As the name suggests 'Control Flow Statements' enable us to specify the order in which the various instructions in a program are to be executed. They determine the flow of control in a program during execution.
This includes the decision making constructs and using the same for various looping statements to determine when to terminate a program loop.
if Statement
The 'C programming language provides a general decision making construct known as the 'if statement.
The Syntax is
if(expression) program statement;
The expression is evaluated; if it is TRUE (i.e. if it has a non-zero value), the statement is executed, otherwise the statement is skipped.
Example:
if(count > COUNTJJMIT)
printf("count limit exceeded\n");
The if statement can also have an associated else part with it, as follows:
if(expression)
statementi; else
statement;
The expression is evaluated, if it is TRUE (i.e. if it has a non-zero value), statementi is executed, otherwise if it is FALSE (zero) , statement2 is executed.
Example:
if (code == 'd')
amount = amount+money; else
amount = amount - money;
In this example, if the variable code is equal to the character 'd', the first statement
Amount=amount+money
is executed. If the answer is no, the second formula for the amount is used
i.e. amount=amount-money.
Example:
main()
{ intc;
c = getch(); if (c>= 'A' && c <= T)
printf("Upper case letter found\n"); else
printf("Upper case letter not found\n");
}
The statements in the 'if part and the 'else' part of the if else construct could also be a block of statements, enclosed in a set of curly brackets.
If (expression)
{
if_block;
} " else
{
else_block;
}
Example:
main()
{
int c;
c = getchar(); if (c >= 'A' && c <= T)
{
printf ("Upper case letter \n");
printf ("End of program run \n");
} else
{
printf("Upper case letter not found \n");
printf("End of program run \n");
} )
From the above example we can see, an if-else statement can contain simple or compound statements. Any valid C statement can be used, including another if-else statement.
An if within an if statement is called a NESTED IF statement
else-if Statement
When a multipath decision is involved i.e. we want to test a number of conditions based on which separate statements are executed, we can use multiple if statements, each with it's own else statement. We can also use the else-if statement for the same purpose as shown below.
The Syntax is
if(expressionl)
statement else if (expression2)
statement2 else if(expression3)
else
statement.
Here the conditions are evaluated from the top. As soon as a condition is found to be true, the statement associated with it is executed and control is transferred to the statement following the last else i.e. out of the if-elseif block. If all the conditions are false, then the final else block is executed i.e. in this case statementn is executed.
Example:
if (n > 0) if (a > b)
z = a; else
z = b;
Because the else part of an if-else, as shown in the above example, is optional, there is an ambiguity when else is omitted from a nested-if sequence, as shown in the above example. This is resolved in the following way -
The else is associated with the closest previous else-less if, in this case the second if statement.
Example:
In the above example, the else goes with the inner if as follows:
if(n > 0)
{ /* These braces are optional */
if(a>b)z = a;elsez = b;} /* These braces are optional */
If that isn't what you want, braces must be used to force the proper association as follows:
if (n > 0)
{
if (a > b) z = a;
} else
z = b;
Use of proper indentation can make the programs more readable less confusing and the probability of error becomes less.
Example:
main()
{
int a;
scanf("%d", &a); if (a <= 100)
{
if (a <= 10)
printf ("the value is less \n");
} else
printf ("the value is more"); }
What happens when a = 9 a = 30 a = 110
Output:
For a = 9, The value is less For a = 30, nothing is printed For a = 110, The value is more
Now in the same program, if the braces are removed as follows :
Example:
main()
{
int a;
scanf("%d", &a); if (a <= 100)
if (a <= 10)
printf ("the value is less \n");
else
printf ("the value is more");
}
What happens when a = 9 a = 30 a = 110
Output:
For a = 9, The value is less For a = 30, The value is more For a = 110, nothing is printed.
Example:
The following program tests to see if a year is a leap year or not.
/* testing for leap year */ main()
{
int year;
printf("please enter a year:");
scanf ("%d", &year) /*if year is divisible by 4 and divisible
by 100, is divisible by 400, it is a leap
year */ if (year %4 == 0 && year %100!=0 year %400 == 0) printf("%d is a leap year.\n",year); else printf("%d is not a leap yearAn", year);
}
The if-else construct is a very important concept in C and we will look into it in a little more detail. Here is an example:
Example:
if(n > 0)
average = sum / n; else {
printf("can't compute average\n");
average = 0; }
The first statement or block of statements is executed if the condition is true, and the second statement or block of statements (following the keyword else) is executed if the condition is not true. In this example, we can compute a meaningful average only if n is greater than 0; otherwise, we print a message saying that we cannot compute the average.
The general syntax of an if statement can be written as
if( expression )
statement1 else
statement2
(where both statement1 and statement2 may be lists of statements enclosed in braces).
It's also possible to nest one if statement inside another. (It is in general possible to nest any kind of statement or control flow construct within another.) For example, here is a segment of code which decides roughly which quadrant of the compass you're walking into, based on an x value which is positive if you're walking east, and a y value which is positive if you're walking north:
if(x > 0)
{
if(y > 0)
printf("Northeast.\n");
else printf("Southeast.\n");
} else {
if(y > 0)
printf("Northwest.\n"); else printf("Southwest.\n"); }
When we have one if statement (or loop) nested inside another, it's a very good idea to use explicit braces {}, as shown, to make it clear (both to the programmer and to the compiler) how they're nested and which else goes with which if. It's also a good idea to indent the various levels, also as shown, to make the code more readable to humans. Why do we need both? We use indentation to make the code visually more readable to us and other people, but the compiler doesn't pay attention to the indentation (since all whitespace is essentially equivalent and is essentially ignored). Therefore, we also have to make sure that the punctuation is right.
Here is an example of another common arrangement of if and else. Suppose we have a variable grade containing a student's numeric grade, and we want to print out the corresponding letter grade. Here is segment of code that would do the required function:
if(grade >= 90)
printf("A"); else if(grade >= 80)
printf("B"); else if(grade >= 70)
printf("C"); else if(grade >= 60)
printf("D"); else printf("F");
What happens here is that exactly one of the five printf calls is executed, depending on which of the conditions is true. Each condition is tested in turn, and if one is true, the corresponding statement is executed, and the rest are skipped. If none of the conditions is true, we fall through to the last one, printing "F".
In the cascaded if/else/if/else/... chain, each else clause is another if statement. This may be more obvious at first if we reformat the example, including every set of braces and indenting each if statement relative to the previous one:
if(grade >= 90)
{ printf("A");
} else {
if(grade >= 80)
{ printf("B");
} else {
if(grade >= 70)
{ printf("C");
} else {
if (grade >= 60)
{ printf("D");
} else {
printf("F"); } } } }
By examining the code this way, it should be obvious that exactly one of the printf calls is executed, and that whenever one of the conditions is found true, the remaining conditions do not need to be checked and none of the later statements within the chain will be executed. Once we have convinced ourselves of this it's generally preferable to arrange the statements as in the first example, without trying to indent each successive if statement one tabstop further out. (Obviously, we would run into the right margin very quickly if the chain had just a few more cases!)
The while Statement
The while statement functions as follows: The expression is evaluated first. If it evaluates to non-zero, then
statement( or the block of statements) is executed and expression is reevaluated.
This cycle continues until expression becomes false.
The condition is tested first, so it is possible that statement may not be
executed even once.
The Syntax is
while (expression) statement;
Example :
Main()
{
int i = 0;
while (i <= 10)
{
i++;
printf("value of i is %d \n",i);
} }
Output:
Value of i is 1 Value of i is 2 Value of i is 3
Value of i is 11
The same output can be generated by the following code also:
Main()
{
int i = 0;
while(i<= 10)
printffvalue of i is %d \n",++i);
}
Example:
Following program illustrates the use of while loop to echo input characters on the screen, till the user enters the RETURN key.
/*echo input to the screen */ # include
{
int c;
while (c != '\n')
{
c = getchar();
putchar(c);
}
}
or
# include
{
int c;
while ((c = getchar()) != '\n')
putchar(c);
}
Example:
The following program counts the number of characters in the input text. The last character typed RETURN is not included in the count.
/* count characters in input */ #include
{ int nc=0; int c; while((c=getchar()) != '\n') ++nc; printf("number of characters read is %d \n",nc);
}
Example:
This program counts the number of lines in input text. After entering a few lines of text end your data entry by typing Ctrl Z RETURN or by typing F6 RETURN. In DOS Ctrl Z or F6 simulates EOF.
#include
{
int c;
int n=0;
while((c=getchar()) != EOF)
if (c == '\n')
++n;
printf("Number of lines = %d \n", ++n);
} Example:
This program counts the number of characters, number of words and the number of lines in the input text. After entering a few lines of text end your data entry by typing Ctrl Z RETURN or by typing F6 RETURN. It is assumed that there is only one white space between two words. The character count includes the new line characters except the last one.
# include
{
int c;
int nc = 0;
int nl = 0;
int nw=0;
while ((c=getchar()) != EOF)
{
++nc;
if (c == '\n') ++nl;
if(c=="c=='\n'c=='\t') ++nw;
} printf("Number of characters = %d\n ", ++nc); printf("Number of words = %d\n ", ++nw); printf("Number of lines = %d\n", ++nl); }
infinite loop can be constructed easily using 'while' as shown below:
while(1)
{
puts(" I have miles to go before I sleep\n");
} I
For loop
We have just seen that the while loop can be used to perform repetitive execution of a group of statements, with the entry into the loop being controlled by the expression following the while statement. Another entry-controlled loop is the for loop, which we will now discuss. This has certain advantages like the initialization and increment of the loop counter variable. It is also more concise in structure and is more popular with C- programmers than the while loop.
The Syntax is
for (init_expression; loop_condition ; loop_expression) statement_block
Any of the three parts with in the parenthesis can be omitted, although the semicolons must remain.
The for loop functions as explained below:
The init_expression statement is used to set the initial values before the loop begins.
The loop_condition part specifies the condition(s) that are necessary for the loop to continue.
The loop_expression is the statement executed at the end of the statement_block, every time the loop repeats.
Example:
This program illustrates the use of for statement.
/* Program to add the first 10 natural numbers */ main()
{
int i, sum ;
sum = 0
for(i = 0; i<10; i++)
sum = sum+i; printf("The output = %d", sum);
}
Do....While Loop
We have seen the working of the while loop before. The while loop tests the condition before executing any statements within the while loop. So if the condition FAILS in the first pass through the loop, the statements within the loop body are not executed. Sometimes we would like the statements inside the loop body to be executed at least once, even if the condition evaluates to FALSE during the first pass through the loop. In this case we can use the do-while loop.
The Syntax is
do
statement
while (expression);
The do..while construct works similar to the while construct, with the only difference that the loop condition (expression) is evaluated after the execution of the statement block.
So, even if the expression evaluates to FALSE in the very beginning, the statement block is executed atleast once.
This program illustrates the use of do....while loop:
# define ZERO 0
# define RATE .20
main()
{float salestax,price;
do
{printf ("\n Enter a price:");
scanf ("%f", &price);
salestax = RATE*price;
printf ("The salestax is $%5.2f".salestax);
} while (price != ZERO);
}
This program calculates the sales tax on the price of the item, if the price is not zero.
Switch
Switch is a multi-way decision-maker that tests whether an expression matches one of a number of alternate values, and branches accordingly.
switch (integer expression)
{ case constant: statement
case constant : statement
default : statement }
Example:
This program counts the number of digits, white spaces (includes new line! character '\n' and tab characters '\t') and other characters in the input text. Ate j entering a few lines of text end your data entry by typing Ctrl Z RETURN or F6! RETURN. The count for white spaces includes the last RETURN character you typed after F6 or Ctrl Z. The count for the other characters includes the CtrIZ or F6 character you typed.
/* count digits, white spaces, others */
#include
void main()
{
char c;
int ndigits=0;
int nwhite=0;
int nothers=0;
while ((c = getchar()) != EOF)
switch ()
{
case '0';
case '1';
case '2';
case '3';
case '4';
case '5';
case '6';
case '7';
case '8';
case '9'; ++ndigits;
break;
case' ':
case '\n':
case '\t': ++nwhite;
break;
default: ++nothers;
break;
}
printf ("Number of digits = "%d \n", ndigits);
printf ("Number of white spaces = %d \n", ++nwhite);
printf("Number of other characters = %d \n", ++nothers);
}
Note:
The example for switch illustrates how to count the number of digits, white spaces and other characters in the input. To count the number of digits typed from keyboard, the 10 cases have been declared starting from 0 to 9. As soon as the user types any number from 0 to 9, it falls through the switch cases till it meets the statement to increase the ndigits by 1. In this way the number of digits is counted. To count the number of white spaces the nwhite is increased. To count the number of characters, the counter nother in the default statement is increased.
Following are the salient features of a switch construct:
Expression must be an integer expression
Each case is labeled by integer or character constant
Cases and default may occur in any order
Cases must all be different
After the code for one case is done, execution falls through to the next unless you take explicit action to escape.
The break statement causes an immediate exit from the switch
Falling through cases is a mixed blessing
Positive side is to have one code for multiple cases, redundancy avoided
Negative side is to put break after each case
Break and Continue
Break
The break statement allows you to exit a FOR or WHILE loop.
Example:
The following program prints the first 20 characters of an input string. If the string length is less than or equal to 20 characters, it will print the entire string.
#include
{
char c; int i=0;
while((c=getchar())!= '\n')
{ i++;
putchar(c) if(i>=20) break; }
Continue
Continue statement allows you to continue the execution of a FOR or loop from the beginning, making it possible to skip the rest of the statements^ the loop after the continue statement, in that iteration in which the continue''1] statement is executed.
Example:
main()
{ static int marks[5] = {90,80,76,89,-90};
int i, total = 0;
for(i=0;i<5;i++)
{ if(marks[i] <0)
{
printf("negative marks not added \n");
continue;
}
total += marks[i];
}
printf("total marks = %d\n",total);
}
No comments:
Post a Comment