Unit II - Branching and Looping
Unit II - Branching and Looping
STRUCTURE
2.1 Introduction
2.2.1 If-Else
2.2.2 Switch
2.3.1 While
2.3.2 Do-While
2.4 Summary
2.5 Keywords
2.8 References
55
2.1 INTRODUCTION
1. If statement
2. Switch statement
4. Goto statement
These statements are popularly known as decision-making statements. Since these statements
„control‟ the flow of execution, they are also known as control statements
2.2.1. if else
The condition may be any valid C language expression including constants, variables,
logical comparisons etc. The condition must be placed with parentheses.
56
1. if (student average greater
than 60) grade first
class
person is retired
The if statement may be implemented of conditions to be tested. The control statements are
fourtypes:
1. Simple if statement
2. if…else statement
4. else if ladder
SIMPLE IF STATEMENT
SYNTAX
if(condition)
{
Statement-block;
}
Statement-x;
57
The „statement-block‟ may be a single statement or a group of statements. If the condition is
true, the statement-block is executed; otherwise, statement-block will be jumped and
execution will get to the statement-x. When the condition is true both the statement block and
statement-x also executed in the sequence. The control flow of the “simple if statement” can
be represented using flow chart as follows.
Entry
T
test expression
statement-block
F
statement-x
next statement
Consider the following statement of program that is written for calculating marks
obtained in auniversity examination.
EXAMPLE 1
#include
<stdio.h>
void
58
main ()
{
float x;
printf(“\n Enter a positive
number:”);scanf(“%f”,&x);
{
print(“\n Positive Number:%f”,x);
}
}
EXAMPLE 2
#include
<stdio.h>
void
main()
{
int number=0;
printf (“\n Enter an integer between 1
and 10:”);scanf(“%d”,&number);
if(number>7)
printf(“you enter %d which is greater than 7 \n”,
number);if(number<3)
printf(“you entered %d which is less than 3 \n”,number);
}
IF…ELSE STATEMENT
When if…else statement taking a decision there are always two faces that is to do
or not to do. Similarly, when programming there are two faces to a condition it may
evaluates as TRUE or FALSE. To implement such a decision has provided you with the
IF…ELSE construct. This construct carries out a logical test and then takes one of the
two possible cases of actions, depending on the outside of the condition.
59
SYNTAX
if(condition)
{
Statement 1;
}
else
{
Statement 2;
}
Statement-x;
If the condition with in the parentheses evaluates to TRUE, then the statement
immediately following it is executed; otherwise, the statement following the ELSE
clauses is executed. Givenbelow is flowchart description of the “ if…else” construct.
Entry
T F
test expression
Statement1 Statement2
Statement-x
EXAMPLE 1
Write a program given below illustrate the use of the IF…ELSE construct.
60
#include
<stdio.h>
void
main()
{
int flg;
float side,area;
printf(“\n enter for 1 for circle and and 0 for
square:”);scanf(“%d”,&flg);
if(flg)
{
printf(“\n Enter
Radius:”);
scanf(“%f”,&rad)
;
area=3.14*rad*ra
d;
printf(“\n Area of Circle=%f”,area);
}
else
{
printf(“\n Enter
Side:”);
scanf(“%f”,&s
ide);
area=side*side
;
EXAMPLE 2
61
#include<
stdio.h>
#include<
stdlib.h>
void
main()
{
it magic;int guess;
magic=rand();
printf(“Guess the magic
number:”);
scanf(guess=magic)
{
printf(“***** Right ***** “);
}
else
{
printf(“*****Wrong*****”); }}
The else clause like the IF clause can contain compound statements. More ever,
a clause of the statement may contain another if statement. This feature is known as
nesting of if statements. There are several forms that nested if-else statement can take.
62
if(Condition1)
{
if(Condition2)
{
Statement 1;
}
else
{
Statement 2;
}
else
{
Statement 3;
}
Statement-x;
If the condition within the parentheses evaluates to TRUE, if the statement immediately
following another condition is evaluated if the condition is true is evaluated with the clause
else, if evaluated else part if the first part of the condition is else executed statement.
Otherwise executed statement-x.
63
Given below is a flowchart description of nested if construct
Entry
Condition1
Statement-3 Condition2
Statement-2 Statement-1
Statement-x
Next Statement
EXAMPLE 1
#include
<stdio.h>
void
64
main()
{
int num;
printf(“Enter an integer:”);
scanf(“%d”
,&num);
if(num<0)
printf(“number is
negative”);if(num>-1)
printf(“number is positive”)
}
EXAMPLE 2
#include
<stdio.h>
void
main()
{
float a,b,c,large;
printf(“Enter the value for a,b
and c \n”);scanf(“%f %f
%f”,&a,&b,&c);
large=a;
if(b>big)
large=b;
if(c>big)
large=c;
printf(“The largest of three number=%7.2 \n”,large);
}
65
ELSE IF LADDER STATEMENT
They are another way of writing nested if statement using elseif ladder statement.
A multipath decision is a chain associated with each else is an if.
SYNTAX
if(condition 1)
statement 1;
else if(condition 2)
statement 2;
else
statement 3;
statement-x;
This type of statements is known as “else if ladder”. It checks the condition, if the condition
is true the control is transferred to a corresponding n number of statement otherwise control
transferred to the else part statement.
66
Given be is a flowchart description of the else if ladder construct.
Entry
Condition1
Statement 1
F
T
Condition2 Statement 2
T
Condition3
Statement 3
Statement-x
Next Statement
EXAMPLE 1
Write a program to check whether the given character is upper case or lower case.
#include
<stdio.h>
void
main()
{
67
int char;
printf(“Enter
Character”);
char=getchar();
if(char!==EOF)
{
EXAMPLE 2
#include
<stdio.h>
void
main()
68
{
int marks;
scanf(“%d”,
&marks);
if(marks>=7
5)
printf(“Honors \n”);
else if(marks>=60 &&
marks<75)
printf(“First Class”);
else if(marks>=50 &&
marks<60)
printf(“Second
Class”);
else if(marks>=40 &&
marks<50)
printf(“third class”);
else
printf(“fail \n”);
printf(“\n\n Grade of university Examinations”);
}
2.2.2. Switch
SYNTAX
69
Switch(expression)
{
Case Label 1
Statements;
break;
Case Label 2
Statements;
break;
default:
Statements;
break;
}
The expression whose value is being compared may be valid expression, including the value
of a variable as an arithmetic expression in a logical comparison etc., but not a floating- point
expression.
The expression value is checked against each of the specified cases and when a match occurs
the statements following that case is executed. When a break statement is encounter, control
proceeds to the end of the switch case statement.
The break statement should be included in each case. If the break statement is omitted then
the statement for subsequent cases will also be executed. Even through a match has already
take place.
The values that follow the keyword „case‟ can only be labels; they cannot be expressions.
Case labels cannot be repeated within a switch statement. The last case default is selected and
the statement following this case is executed if none of cases mentioned earlier are matched.
The default case anywhere may or may not be included depending on the program’s needs.
The default group may appear anywhere within the switch statement.
70
Given below is a flow chart description of a Switch Case Statement
Entry
Expression?
Block-1
Block-2
Block-3
Statement-x
71
case 6:
grade=”First Class”;break;
case 5:
grade=”Second Class”
case 4:
grade=”Third Class”;break;
case else grade=”fail”;break;
}
SYNTAX
The expression1 is the condition for evaluation when evaluating a conditional operator,
exression1 is evaluated first. If expression is true, expression 2 is alone evaluated. If
expression is false, expression 3 is alone evaluated.
result=number<5?10:6;
EXAMPLE 1
Write a program to find the largest of three numbers using a conditional operator.
72
{
The goto statement is used to alter the normal sequence of program execution by
unconditionally transferring control to some other part of the program
SYNTAX
goto Label;
.
.
.
Label Statement;
where,
Label1 is an identifier used to transfer the control whether label occurs. The Label must
follow a colon (:).
EXAMPLE 1
73
Write a program using goto statement
if(x==y) x++;
else
EXAMPLE 1
scanf(“%f”,&x);
if(x<0)
goto read;
y=sqrt(x);
2.3.1 While
The while statements are used to carry out looping operation. Hence, the loop is executed
until the expression evaluates be TRUE.
74
Syntax
The condition can be valid C language expression including the value of a variable, a unary
or binary expression an arithmetic expression etc. In a “while construct” the condition is
evaluated first. The statements given will be continuously executed until the value of the
expression is not zero. This cycle continues until the condition evaluates to zero.
The “while statements” may be a simple statement or a compound statement. The group of
statements usually contain one such statement which determents the value of the expression
and ultimately leads to termination of loop. Once the condition evaluates to zero (false), the
control is transferred to the statement following this loop.
Entry
F
Condition1 Exit
Body of Loop
FIGURE 1.13
The condition in the while statement evaluates to false and the statement inside the loop are
not executed. The condition in the while statement evaluates to true, and the statement inside
the loop are executed.
EXAMPLE 1
Write a program to displays the integer number between 1 to 10 using while loop
75
#include<stdio.h> void main()
int digit=1;
while(digit<=10)
printf(“%d \n”,digits++)
EXAMPLE 2
#include<stdio.h>
void main()
int i,num=0;
float sum=0,average;
scanf(“%d”,&i);
sum=sum+1; num++;
scanf(“%d”,&i);
average=sum/num;
76
}
2.3.2 Do-While
The do…while loop sometimes referred to as “do loop” differs from its counterpart the while
loop in checking the condition. The condition of the loop is not tested until the body of the
loop has been executed once. If the condition is false, after the first loop iteration the loop
terminates. If the test expression evaluates to true then the body of the loop gets executed.
This process repeated as long as the test-expression evaluates to true. Once the test-
expression evaluates to false, the loop is exited and the control goes to the first statement
following looping construct.
Start
Initialization
Statements
F
Text
Expression
EXAMPLE 1
Write a program to find the sum of first natural numbers using for-loop.
77
int n,i,sum; clrscr();
i=1;
sum=0; do
sum=sum+i; i++ ;
EXAMPLE 2
i++;
The for…loop allows us to specify three things about the loop in a single line to construct a
loop, initialization, text expression and incrementing or decrementing the value, each
represented separated by semicolons and enclosed within a pair of parentheses. The
initialization, test-expression and increments or decrementing can be used in different places
78
like the way used in while and do-while loop. The “for loop” allows us to specify three things
about in a single line.
SYNTAX
2. Test-Expression is evaluated.
3. If the test-expression evaluates true, the statements in the body of the loop executed.
5. If its condition is true, again the statement of the body of the loop is executed.
int i,n,sum;
scanf(“%d”,&n);
sum=0; for(i=1;i<=n;i++)
sum=sum+i;
79
EXAMPLE 2
product=number*i;
JUMPS IN LOOPS
Break Statement
A break statement is used to terminate or to exit for, switch, while or do-while statement and
the execution continues following the break statement.
SYNTAX
break;
The break statement does not have any embedded expressions or arguments. The break
statement usually used at the end of each (in a switch statement) and before the start of the
80
next case statement. The keyword “break” breaks the control only from the loop in which it is
placed.
EXAMPLE
#include <stdio.h>
if (c == 'Q') break;
Continue Statement
The continue statement is used to transfer the control the beginning of loop, there by
terminating the current iteration of the loop and starting again form the next iteration of the
same loop. The continue statement can be used within a while or a do-while or a for loop.
SYNTAX
continue;
The continue statement does not have any expression or arguments. Unlike break, the loop
does not terminate when a continue statement is encounter, but it terminates the current
iteration of the loop by skipping the remaining part of the loop and resumes the control to the
81
start of the loop for the next iteration. The continue statement applies only to loops and not
for switch statement.
EXAMPLE 1
int i; for(i=1;i<=5;i++)
if(i==3)
continue; printf(“%d”,i);
2.4 SUMMARY
82
Nesting of if…else statement the else clause like the “if clause” can contain
compound statement.
The else…if ladder statement there are another way of writing result if statement
using else if cases.
The switch case statement causes a particular group of statements to be selected
from a group of option.
A loop is a process the program to be executed repeatedly until condition stratified.
The while loop executed until the expression evaluates be TRUE.
The for…loop allows us to specify three things about the loop in a single line.
The do-while loop sometimes referred to as do…loop the condition of the loop is
not tested until the body of the loop has been execute.
A break statement is used to terminate or to exit a for, switch, while or do-while
statement.
The continue statement is used to transfer the control to the beginning of loop.
The for…loop can be nested within a while loop or another loop are represented
with another manner called nesting of loops
2.5 KEYWORDS
Branching: One of several possible action will be carried out depending upon the
outcome of the logical test is referred as branching.
If: C uses the keyword if to implement decision control statement.
If-Else Statement: The if-else statement is an extension of an ordinary if statement.
The “If statement” by default will execute a single statement or a group of
statements when the condition is false.
Multiple If-Else Statements: When a series of decisions are involved, we have
to use morethan one “if-else statement” called as multiple ifs.
Nested If-Else Statement: One of more if or if-else statements inside an if or if-else
statement(s) is called as nested if statements.
Switch-Case Statement: The switch statement allows us to make a decision from a
number of choices. It is usually referred as the switch-case statement.
Sequence: All the statements from the beginning till the end get executed
without fail in theserial order is called sequence.
83
Selection: Selection was sometimes some statements are executed and some are
skippeddepending on some condition.
Looping: The repeat is one of a block of statements as long as some condition is
true is called looping.
Iteration: Looping is also called iteration.
Valid Loop: To execute a block of statements repeatedly as long as some
condition is true i.e.,to construct a valid loop.
Entry-controlled or pre-tested looping construct: The test-expression is first
evaluated before entering into the body of the loop, the looping construct is called
entry-controlled or pre-tested looping construct.
Break statement: A break statement is used to terminate or to exit a for, switch,
while or do- while statement and the execution continues following the break
statement.
Continue statement: The continue statement is used to transfer the control to the
begging ofthe loop.
___________________________________________________________________________
_______________________________________________________________________
___________________________________________________________________________
_______________________________________________________________________
A. Descriptive Questions
Short Questions
84
4. Difference between while loop and do-while loop
Long Questions
5. Explain the syntax and use of the switch statement with an example.
1. Which of the following operator reverses the result of expression its operators on?
a. !
b. ||
c. &&
d. All of these
2. If you have to make decision based on multiple choices, which of the following is best
suited?
a. if
b. if-else
85
c. if-else-if
d. All of these
a. for
b. while
c. do while
d. switch
a. return
b. break
c. exit
d. both A and B
a. int
b. char
c. long
d. All of these
86
Answers
2.8 REFERENCES
References book
87