Skip to main content

Conditional Execution in c

Objectives:

Having read this section you should be able to:

1.Program control with if , if-else and switch structures
2.have a better idea of what C understands as true and false.


Program Control:

It is time to turn our attention to a different problem - conditional execution. We often need to be able to choose which set of instructions are obeyed according to a condition. For
example, if you're keeping a total and you need to display the message 'OK' if the value is greater than zero you would need to write something like:

if (total>O) printf("OK");

This is perfectly reasonable English, if somewhat terse, but it is also perfectly good C. The if statement allows you to evaluate a >condition and only carry out the statement, or compound
statement, that follows if the condition is true. In other words the printf will only be obeyed if the condition total > O is true.

If the condition is false then the program continues with the next instruction. In general the if statement is of the following form:

if (condition) statement;

and of course the statement can be a compound statement.

Here's an example program using two if statements:



#include

main()
{
int a , b;

do {

printf("\nEnter first number: ");
scanf("%d" , &a);

printf("\nEnter second number: ");
scanf("%d" , &b);

if (a if (b
} while (a < 999);
}

Here's another program using an if keyword and a compound statement or a block:

#include

main()
{
int a , b;

do {

printf("\nEnter first number: ");
scanf("%d" , &a);

printf("\nEnter second number: ");
scanf("%d" , &b);

if (a printf("\n\nFirst number is less than second\n");
printf("Their difference is : %d\n" , b-a);

printf("\n");
}

printf("\n");

} while (a < 999);
}

The if statement lets you execute or skip an instruction depending on the value of the condition. Another possibility is that you might want to select one of two possible statements - one
to be obeyed when the condition is true and one to be obeyed when the condition is false. You can do this using the


if (condition) statement1;
else statement2;

form of the if statement.

In this case statement1 is carried out if the condition is true and statement2 if the condition is false.

Notice that it is certain that one of the two statements will be obeyed because the condition has to be either true or false! You may be puzzled by the semicolon at the end of the if part
of the statement. The if (condition) statement1 part is one statement and the else statement2 part behaves like a second separate statement, so there has to be semi-colon
terminating the first statement.

Logical Expressions:

So far we have assumed that the way to write the conditions used in loops and if statements is so obvious that we don't need to look more closely. In fact there are a number of
deviations from what you might expect. To compare two values you can use the standard symbols:

> (greater than)

< (less than)

>= (for greater than or equal to )
<= (for less than or equal to)
== (to test for equality).

The reason for using two equal signs for equality is that the single equals sign always means store a value in a variable - i.e. it is the assignment operator. This causes beginners lots of

problems because they tend to write:

if (a = 10) instead of if (a == 10)

The situation is made worse by the fact that the statement if (a = 10) is legal and causes no compiler error messages! It may even appear to work at first because, due to a logical quirk
of C, the assignment actually evaluates to the value being assigned and a non-zero value is treated as true (see below). Confused? I agree it is confusing, but it gets easier. . .

Just as the equals condition is written differently from what you might expect so the non-equals sign looks a little odd. You write not equals as !=. For example:

if (a != 0)

is 'if a is not equal to zero'.

An example program showing the if else construction now follows:


#include

main ()
{
int num1, num2;

printf("\nEnter first number ");
scanf("%d",&num1);

printf("\nEnter second number ");
scanf("%d",&num2);

if (num2 ==0) printf("\n\nCannot devide by zero\n\n");
else printf("\n\nAnswer is %d\n\n",num1/num2);
}

This program uses an if and else statement to prevent division by 0 from occurring.

True and False in C:

Now we come to an advanced trick which you do need to know about, but if it only confuses you, come back to this bit later. Most experienced C programmers would wince at the
expression if(a!=0).

The reason is that in the C programming language dosen't have a concept of a Boolean variable, i.e. a type class that can be either true or false. Why bother when we can use numerical
values. In C true is represented by any numeric value not equal to 0 and false is represented by 0. This fact is usually well hidden and can be ignored, but it does allow you to write

if(a != 0) just as if(a)

because if a isn't zero then this also acts as the value true. It is debatable if this sort of shortcut is worth the three characters it saves. Reading something like

if(!done)

as 'if not done' is clear, but if(!total) is more dubious.


Using break and continue Within Loops:

The break statement allows you to exit a loop from any point within its body, bypassing its normal termination expression. When the break statement is encountered inside a loop, the loop

is imediately terminated, and program control resumes at the next statement following the loop. The break statement can be used with all three of C's loops. You can have as many
statements within a loop as you desire. It is generally best to use the break for special purposes, not as your normal loop exit. break is also used in conjunction with functions and >case
statements which will be covered in later sections.

The continue statement is somewhat the opposite of the break statement. It forces the next iteration of the loop to take place, skipping any code in between itself and the test condition of

the loop. In while and do-while loops, a continue statement will cause control to go directly to the test condition and then continue the looping process. In the case of the for loop, the
increment part of the loop continues. One good use of continue is to restart a statement sequence when an error occurs.


#include

main()
{
int x ;

for ( x=0 ; x<=100 ; x++) {
if (x%2) continue;
printf("%d\n" , x);

}
}


Here we have used C's modulus operator: %. A expression:

a % b

produces the remainder when a is divided by b; and zero when there is no remainder.

Here's an example of a use for the break statement:


#include

main()
{
int t ;

for ( ; ; ) {
scanf("%d" , &t) ;
if ( t==10 ) break ;
}
printf("End of an infinite loop...\n");

}


Select Paths with switch:

While if is good for choosing between two alternatives, it quickly becomes cumbersome when several alternatives are needed. C's solution to this problem is the switch statement. The
switch statement is C's multiple selection statement. It is used to select one of several alternative paths in program execution and works like this: A variable is successively tested against a
list of integer or character constants. When a match is found, the statement sequence associated with the match is executed. The general form of the switch statement is:

switch(expression)
{
case constant1: statement sequence; break;
case constant2: statement sequence; break;
case constant3: statement sequence; break;
.
.
.
default: statement sequence; break;
}


Each case is labelled by one, or more, constant expressions (or integer-valued constants). The default statement sequence is performed if no matches are found. The default is optional.
If all matches fail and default is absent, no action takes place.

When a match is found, the statement sequence asociated with that case are executed until break is encountered.

An example program follows:


#include

main()
{
int i;

printf("Enter a number between 1 and 4");
scanf("%d",&i);

switch (i)
{
case 1:
printf("one");
break;
case 2:
printf("two");
break;
case 3:
printf("three");
break;
case 4:
printf("four");
break;

default:
printf("unrecognized number");
} /* end of switch */

}

This simple program recognizes the numbers 1 to 4 and prints the name of the one you enter. The switch statement differs from if, in that switch can only test for equality, whereas the if
conditional expression can be of any type. Also switch will work with only int and char types. You cannot for example, use floating-point numbers. If the statement sequence includes
more than one statement they will have to be enclosed with {} to form a compound statement.

Comments

Popular posts from this blog

Random post with specific label - Blogger Widget

1. go to blogger dashboard, select template and edit html. 2. search for </head> to add script. - you may download and upload to your site, or just use this link (no download required) script <script src='http://docs.google.com/uc?id=0B7xJbTAja8i0a0ZJbXJ2TkkwSW8&amp;export=download' type='text/javascript'/> 2. search for ]]></b:skin> to add style/css. img.label_thumb{ float:left; padding:5px; border:1px solid #8f8f8f; background:#D2D0D0; margin-right:10px; height:55px; width:55px; } img.label_thumb:hover{ background:#f7f6f6; } .label_with_thumbs { float: left; width: 100%; min-height: 70px; margin: 0px 10px 2px 0px; adding: 0; } ul.label_with_thumbs li { padding:8px 0; min-height:65px; margin-bottom:10px; } .label_with_thumbs a {} .label_with_thumbs strong {} 2. save template. 3. add a widget. 3. edit widget. at this example i use random post with label "blogger", you must replace it with your label. <div s...

Submit your site for free to search engine~SEO TOOL SERACH ENGINE SUBMitt free

free Submit the main page of your site only. The rest of your site will be crawled by the search engines. Only 5 submissions in every 24 hours period are allowed. URL  * Email  * Name  * Business Phone  * Country  *   None Selected   United States   Afghanistan   Albania   Algeria   American Samoa   Andorra   Angola   Anguilla   Antigua and Barbuda   Argentina   Armenia   Aruba   Australia   Austria   Azerbaijan   Bahamas   Bahrain   Bangladesh   Barbados   Belarus   Belgium   Belize   Benin   Bermuda   Bhutan   Bolivia    Bosnia Hercegovina   Botswana   Bouvet Island   Brazil   Brunei Darussalam   Bulgaria   Burkina Faso   Burundi   Cambodia   Cameroon   Canada   Cape Verde   Cayman Islands   Central African Republic   Chad   Chi...

Tips to Enable or Disable Toast Notifications on Windows 8

Windows 8 is among the most incredible and interesting kind of Windows version from Microsoft. It has visually eye catching design, which is found in modern user interface that is meant for redesigning a number of operating systems, worked out for users. If you have used or seen someone using Windows 8 you could have noticed the toast notifications in this modern version of windows, which simply appears the moment you install or uninstall any application. There are many users who are well versed with the bubble notifications, which were found in the earlier versions of Windows seen via the taskbar. The new application platform in Windows 8 comes with an integrated notification system for installing or uninstalling a number of modern applications. The Windows 8 style application can employ a number of notifications types including the traditional toast notifications, live titles and lock screen. These can be managed by either disabling or enabling the notification of your applicatio...

List of all search engine by topics,genre and based on

Tweet General Baidu  (Chinese, Japanese) Bing Blekko Google Sogou  (Chinese) Soso.com  (Chinese) Volunia Yahoo! Yandex.com Yodao  (Chinese) P2P search engines FAROO Seeks  (Open Source) YaCy  (Free and fully decentralized) Metasearch engines See also:  Metasearch engine Blingo Yippy  (formerly Clusty) DeeperWeb Dogpile Excite Harvester42 HotBot Info.com Ixquick Kayak Mamma Metacrawler Mobissimo Otalo PCH Search and Win SideStep Thiv WebCrawler Geographically limited scope Accoona ,  China / United States Alleba , Philippines Ansearch ,  Australia / United States / United Kingdom / New Zealand Biglobe ,  Japan Daum ,  Korea Goo ,  Japan Guruji.com ,  India Leit.is ,  Iceland Maktoob ,  Arab World Miner.hu ,  Hungary Najdi.si ,  Slovenia Naver ,  Korea Onkosh ,  Arab World Rambler ,  Russia Rediff ,  India SAPO ,...

Downloading Windows 8 for Free [Full version]

Tweet Downloading Windows 8 for Free [Full version] Windows 8 is a new version of Windows that focuses on variety of hardware platform and form factors such as slim-type computers and new generation of touch devices. The new version free for download was made available for developers and testers of the new OS. Here’s the download links for the Enterprise version of Windows. How to get and download the latest operating system Thankfully, Microsoft released the new version free for download designed for technological professionals, engineers and IT personnel's for testing and debugging purposes. Download Links of the ISO file (x86 and x64) Windows 8 32-Bit version Windows 8 64-Bit version If you can’t download the file, make sure that you are login to your respected  Hotmail account .

Google Sheet/Google form Script to send automated Email to users

Well many of us want to send especially bloggers sometimes want to send automated replies to user 's ..but as usual, not everyone is a code geek or lovers ... so this is a small guide to How to use Google form with Google sheet to make an automated reply link....so follow the steps accordingly. STEP 1: GOTO google Forms ... and create a form ... in my case I just take users email id and how do they get to my site. 1. GOTO   https://docs.google.com/forms?usp=mkt_forms 2. login with your account. now choose blank form. 3. in Form title write your forms name, for example, let say my form. 4. in Form description write the description let say  A simple form ... 5. now go to setting and in general tab, check collect email address. and  click on save 6. (optional) you can also ask some basic question 7. now goto responses tab now click on create new spreadsheet button. (that green icon ..) in select response, destination cho...

Binary Search Tree in Java implementation (reference based, dynamic memory)

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 import java.util.Scanner ; class BST { static BST . Node root = null ; public void insert ( int num ) { if ( root == null ) { root = new BST . Node ( num ); } else { // root node is not empty BST . Node temp = root ; while ( temp != null ) { if ( num <= temp . getVal ()) { if ( temp . getLeft () != null ) temp = temp . getLeft (); ...

C++ Program to implement Virtual Class by using Multipath Inheritance

Issue the books to various members of library. – Member-Membername, Age, Address – Faculty (derived from member classs)- Department and integer type array for issuing books with upperlimit 10. – Student (derived from member class)- Class, Rollno and integer type array for issuing books with upperlimit 4. Daily Transaction (derived from Faculty and Student classes)- date of issue, date of return (calculated from date of issue as 15 days for students and 45 days for a faculty). #include #include #include #include #include class CDATE{     private:         int dd;         int mm;         int yy;     public:         struct date d;         CDATE(){             getdate(&d);             dd = d.da_day;             mm = d.da_mon;         ...

just more way to disable autorun.inf

Auto run.Inf this is a instruction file associated with the Auto run function. It is a simple text configuration file that instructs the OS (operating system) which executable to start which icon to use which additional menu commands to make available etc Auto run.inf must be located in the root directory of a volume.That is CD,DVD,of Floppy Disk or Pen drive. It is mainly used by the manufacturer on what actions to taken when their CD-ROM when it is inserted. In OS, when autorun.inf is enabled (Normally by default it is enabled ) then by inserting the Cd or DVD the content of the medium is automatically executed. This is to avoid the user intervention and help the low level knowledge of computer literacy people. But Virus programmer taken this as advantage and make virus instruction in autorun.inf text file. TYPICAL AUTORUN.INF A typical autorun.inf file looks like below. [autorun] open=setup.exe icon=setup.exe,0 label=GameProgram SIMPLE METHOD NOT TO GET INFECTED BY AUTORUN.INF:...

python program get union of two list (program to get A union B ) list method .

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Mar 16 17:08:52 2018 @author: beast """ def version1 (): a = [ 'a' , 'b' , 'c' , 'd' , 'e' ] # list 1 b = [ 'a' , 'b' , 'c' , 'd' , 'e' , 'f' , 'g' , 'h' ] # list 2 c = [k for k in (a) if (k in (a) and k not in (b))] # include unique item from list 1 : items are (list1-list2)(set thoery) d = [l for l in (b) if l in (a ) and l in (b) or (l not in (a) and l in (b))] #include all the comman from list 1 and unique from list 2 lst = c + d # append above two comprehensed list to get union of list1 U list2 lst . sort() # not neccessay but makes list easy to understand (sorting in ascending order ) ...