C Program-Loops and Branch
C Program-Loops and Branch
if False
expression
True
Statement 1
Next-Statement
True if False
expression
Statement 1 Statement 2
Next-Statement
if
TRUE FALSE
expr1?
if if
TRUE FALSE TRUE FALSE
expr2? expr3?
Next-Statement
Example: Program to select and print the largest of the 3 numbers using nested
“if-else” statements.
#include<stdio.h>
int main()
{
int a,b,c;
printf(“Enter Three Values: \n”);
scanf(“%d %d %d ”, &a, &b, &c);
printf(“Largest Value is: ”) ;
if(a>b)
{
if(a>c)
printf(“ %d ”, a);
else
printf(“ %d ”, c);
}
else
{
if(b>c)
printf(“ %d”, b);
else
printf(“ %d”, c);
}
return 0;
}
Output:
Enter Three Values:
17 18 6
Largest Value is: 18
if
FALSE
expression1?
TRUE
if
FALSE
expression2?
Statement1
TRUE
if
expression3?
Statement2
Statement3
Next-Statement
Example: Program to select and print the largest of the 3 numbers using
“else…if ladder” statements.
#include<stdio.h>
int main()
{
int a,b,c;
printf(“Enter Three Values: \n”);
scanf(“%d %d %d ”, &a, &b, &c);
printf(“Largest Value is: ”) ;
if ( a>b && a>c )
printf(“ %d ”, a);
else if ( b>a && b>c )
printf(“ %d ”, b);
else
printf(“ %d”, c);
return 0;
}
Output:
Enter Three Values:
17 18 6
Largest Value is: 18
e. switch Statement:
This is a multi-branch statement similar to the else…if ladder (with limitations) but
clearer and easier to code. This is used when we must choose among many
alternatives. This statement is to be used only when we have to make decision using
integral values (i.e., either integer values or characters).
Why we should use Switch statement?
1. One of the classic problems encountered in nested if-else / else-if ladder is
called problem of Confusion.
2. It occurs when no matching else is available for if.
3. As the number of alternatives increases the Complexity of program increases
drastically.
To overcome these, C Provides a multi-way decision statement called „Switch
Statement‟
Syntax:
switch ( expression )
{
case label1 :
statement1 ;
break ;
case label2 :
statement2 ;
break ;
...
default : statement ;
}
Where,
Expression can be either arithmetic expression that reduces to integer value,
character constant, integer constant or an identifier of type integer.
Labels can be either arithmetic expression that reduces to integer value,
character constant or integer constant. But it cannot be an identifier.
The value of expression is tested for equality against the values of each of the labels
specified in the case statements in the order written until a match is found. The
statements associated with that case statement are then executed until a break
statement or the end of the switch statement is encountered.
When a break statement is encountered execution jumps to the statement immediately
following the switch statement.
The default section is optional -- if it is not included the default is that nothing
happens and execution simply falls through the end of the switch statement.
if
expression
Next-Statement
8. WACP to find a given year is leap year or not using ternary operator.
Program:
#include<stdio.h>
int main()
{
int year;
printf(“Enter a year\n”);
scanf(“%d” , &year);
(year%4 = = 0 && year%100 != 0 || year%400 = = 0) ? printf(“%d is a Leap
Year\n” , year) : printf(“%d is Not a Leap Year\n” , year);
return 0;
}
In example 1, since the first statement is goto label1 it jumps to label1 and starts
executing the statement4 as shown with arrows. Hence the jump is made in
forwarding direction.
In example 2, it first executes statements 1, 2 and 3 in sequence then because of the
statement goto label2, it jumps to label2 and starts executing the statements 1, 2, and
3 and repeats the same process as shown with arrows. Hence the jump is made in
backward direction and forms a loop.
From the example 2, we can understand one of the main drawback of using goto
statement is that it forms infinite loop (i.e., loop that never ends) since it is
unconditional jump statement.
Another drawback of using goto statement is that it is used to transfer the control only
within the function but cannot be used to jump between functions.
NOTE: Try to avoid using goto statement. It‟s a bad practice of using goto in a
program.
Example: Program to detect the entered number is even or odd using goto statement.
#include<stdio.h>
int main()
{
int x;
printf(“Enter a Number: \n”);
scanf(“%d”, &x);
if(x % 2 = = 0)
goto even;
else
goto odd;
even : printf(“%d is Even Number” , x);
return 0;
odd : printf(“ %d is Odd Number” , x);
return 0;
}
Output 1:
Enter a Number: 5
5 is Odd Number.
Output 2:
Enter a Number: 8
8 is Even Number.
b. break statement
The break statement can be used in any looping statements and switch
statement.
When a break statement is encountered inside a while, for, do…while statement, then
break statement immediately terminates the entire loop and jumps out of the loop and
resumes execution at the next statement following the loop (if any).
When a break statement is encountered inside a switch statement case, then break
statement will terminate the corresponding switch case and transfers the control out of
switch statement and resumes the execution at the next statement following the switch
statement (if any).
Example 1:-
...
for ( x = 1 ; x <= 10 ; x++ )
{
if ( x > 4 )
break ;
printf( “%d “ , x ) ;
}
printf( "Next Statement\n" );
Example 2:-
switch (ch)
{
case 1: s1;
break;
…………
…………
}
Next-Statement;
In the above example, if value of ch matches with case 1 then it executes statement s1
followed by break statement. After executing break statement the control is
transferred to out of switch statement i.e. Next-Statement.
c. continue statement
The continue statement can be used only in looping statements.
The continue statement terminates the current iteration of a while, for or
do…while statement and resumes execution of next iteration of the loop.
For Example :-
...
for ( x = 1; x <= 5; x++ )
{
if ( x = = 3 )
continue ;
printf( “%d “, x ) ;
}
In this flowchart, the action is repeated over and over again. It never stops.
Since the loop never stops, the action or actions will be repeated forever. We don‟t
want this to happen; we want our loop to end when the work is done. To make sure that it
ends, we must have a condition that controls the loop. The condition which is used to control
the loop is called as loop control expression.
Based on the placement of loop control expression, the loops are classified as TWO types
i. Entry controlled loop or Pre-Test Loop:
In the entry controlled loop or Pre-Test loop, the loop control expression is
checked before we start and at the beginning of each iteration of the loop. If the
control expression is true, we execute action or actions; if the control expression is
false, we terminate the loop.
Examples:
while statement and for statement
ii. Exit controlled loop or Post-Test Loop
In the exit controlled loop or Post-Test loop, the loop control expression is
checked after or at the end of each iteration of the loop. If the control expression is
true, we repeat action or actions; if the control expression is false, we terminate the
loop.
Examples:
do…while statement
The flowchart of entry controlled and exit controlled loops and other differences between
the two are given below.
Entry Controlled or Pre-Test Loop Exit Controlled or Post-Test Loop
The loop control expression is checked The loop control expression is checked after
before we start and at the beginning of each or at the end of each iteration of the loop
iteration of the loop
Flowchart: Flowchart:
Control Expression
TRUE FALSE
An Action or Series of
An Action or Series of Actions
Actions
TRUE
Control Expression
False
Minimum Iterations: Atleast ZERO Times Minimum Iterations: Atleast ONE Times
If the control expression is TRUE for N If the control expression is TRUE for N
times, then action or actions are executed for times, then action or actions are executed for
N times N+1 times
Examples: for loop and while loop Example: do…while loop
Prints numbers from 1 to 10 Prints numbers from 1 to 10
i=1; i=1;
while( i<=10) do
{ {
printf(“%d\n”, i); printf(“%d\n”, i);
i++; i++;
} }while(i<10);
Initialization: Before a loop can start, some preparation is usually required. We call this
preparation as initialization. Initialization must be done before the execution of the loop
body. Initialization sets the variable which will be used in control expression to control the
loop.
Updating: how can the control expression that controls the loop be true for a while and then
change to false? The answer is that something must happen inside the body of the loop to
change the control expression. Otherwise, the loop leads to infinite loop. Hence, the actions
that cause these changes are known as update.
a. while statement
The while statement is typically used in situations where it is not known in advance
how many iterations are required.
Syntax:
while ( control expression )
{
An action or Series of Actions ; //body of loop
}
Here, first the control expression is evaluated to TRUE or FALSE. If it is evaluated to
TRUE, then an action or series of action i.e. body of loop is executed. The process of
executing the body of loop is repeated until the control expression is FALSE. Once control
expression is evaluated to FALSE, then the control is transferred out of the loop. The
execution resumes from the statement following the loop (if any).
Generally, when initialization and updating is included in the while loop, it looks as
follows.
Initialization // initialization is used before the start of loop and sets
// the variable(s) to control the loop
while ( control expression )
{
An action or Series of Actions ; //body of loop
Updating // causes the variable(s) to update that helps to repeat
// the loop or to stop the loop
}
The flow of while statement is shown below.
Initialization
Control Expression
TRUE FALSE
An Action or Series of
Actions
Updating
b. for statement
The for statement is most often used in situations where the programmer knows in
advance how many times a particular set of statements are to be repeated. The for
statement is sometimes termed as counter controlled loop.
Syntax :
for ( expression1 ; expression2 ; expression3 )
{
An action or series of actions ; // body of loop
}
Where,
expression1:- This is usually an assignment/initialization statement to set a loop
control variable(s) for example. But it is not restricted to only initialization, it can be
any valid C statement.
expression2:- This is usually a control expression which determines when loop will
terminate. But, this can be any statement of C that evaluates to TRUE or FALSE.
expression3:- This usually defines how the loop control variable(s) will change each
time the loop is executed i.e. updating.
Body of loop:- Can be a single statement, no statement or a block of statements.
NOTE: All three expressions are optional. But semicolons must be present as in
syntax in the loop.
Curly braces are used in C to denote block whether in a function as in main() or as the
body of a loop. It is optional if body of loop is a single statement or no statement.
The for statement executes as follows:
Example 1: Program to sum all numbers from 1 to 100.
#include <stdio.h>
int main()
{
int x, sum=0 ;
for ( x = 1; x <= 100; x++ )
sum = sum + x;
printf(“Sum = %d\n”, sum);
return 0;
}
Expression1
Expression2
TRUE FALSE
An Action or Series of
Actions
Expression3
Initialization
An Action or Series of
Actions
Updating
TRUE
Control Expression
FALSE
10. WACP to print alternate uppercase letters starting with letter „A‟.
Program:
#include<stdio.h>
int main()
{
char ch;
printf(“Alternate Uppercase letters starting with letter A are:\n”);
for(ch=‟A‟; ch<=‟Z‟; ch= ch + 2)
printf(“%c\n”, ch);
return 0;
}
11. WACP to find the GCD of two numbers using while and ternary
operator.
Program:
#include<stdio.h>
int main()
{
int M, N, GCD, P,Q;
printf(“Enter the value of M and N\n”);
scanf(“%d%d” , &M, &N);
P=M;
Q=N;
while (M != N)
(M>N) ? M = M – N : N = N – M ;
GCD=M;
printf(“ GCD ( %d, %d) = %d\n”, P,Q, GCD);
return 0;
}
12. WACP to find the GCD of two numbers using while and if else
statement.
Program:
#include<stdio.h>
int main()
{
int M, N, GCD, P,Q;
printf(“Enter the value of M and N\n”);
scanf(“%d%d” , &M, &N);
P=M;
Q=N;
while ( M != N )
{
if (M>N)
M = M – N;
else
N=N–M;
}
GCD=M;
printf(“ GCD ( %d, %d) = %d\n”, P, Q, GCD);
return 0;
}