0% found this document useful (0 votes)
77 views33 pages

Unit II - Branching and Looping

Uploaded by

arshlankhan7860
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
77 views33 pages

Unit II - Branching and Looping

Uploaded by

arshlankhan7860
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 33

UNIT - 2 BRANCHING AND LOOPING

STRUCTURE

2.0 learning Objectives

2.1 Introduction

2.2 Branching Constructs

2.2.1 If-Else

2.2.2 Switch

2.2.3 Conditional Operator & Goto Statements

2.3 Looping Constructs

2.3.1 While

2.3.2 Do-While

2.3.3 For And Jumping Statements

2.4 Summary

2.5 Keywords

2.6 Learning Activity

2.7 Unit End Questions

2.8 References

2.0 LEARNING OBJECTIVES

After studying this unit, you will be able to:

 Describe the structure of decision making with if statement


 Identify Switch Case statement
 Explain the Ternary ?: Operator Describe the Structure of goto Statement

55
2.1 INTRODUCTION

In C language support the following decision-making capabilities, they are,

1. If statement

2. Switch statement

3. Conditional operator 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

A loop is a process of the program to be executed repeatedly until condition is satisfied.


When condition becomes false, the loop terminates and the control passes on the statement
following the loop. A Loop consists of two segments, one is known as the control statement
and the other is the body of the loop.

They are three kinds of looping statement in C,

1. The for…loop statement

2. The while statements

3. The do…while statement

2.2 BRANCHING CONSTRUCTS

2.2.1. if else

The if statement allows the programmer to execute a statement or series of statements


Conditionally. If the condition supplied to the statement is logically true, then the statement
that follows it is executed. Else it simply transfers control the next statement.

The condition may be any valid C language expression including constants, variables,
logical comparisons etc. The condition must be placed with parentheses.

Some examples of decision making using if statements are,

56
1. if (student average greater
than 60) grade first
class

2.if(age is more than 58)

person is retired

3.if(employee salary greater than


250000)pay with tax

The if statement may be implemented of conditions to be tested. The control statements are
fourtypes:

1. Simple if statement

2. if…else statement

3. Nested if…else statement

4. else if ladder

SIMPLE IF STATEMENT

The syntax of a simple if statement is,

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

Fig 2.1 If Statement Using Flowchart

Consider the following statement of program that is written for calculating marks
obtained in auniversity examination.

EXAMPLE 1

Write a program whether the given number is positive or not.

#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

Write a program to enter integer number between 1…10.

#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

Fig 2.2 If Else Construct


The program given below illustrate the use of the IF…ELSE construct

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
;

printf(“\n Area of the square=%f”,area);


}
}

EXAMPLE 2

Write a program to generate magic(random) number.

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*****”); }}

NESTING OF IF…ELSE STATEMENT

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

Fig 2.3 Nested If Construct

EXAMPLE 1

Write a program to check whether the integer number is positive or negative.

#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

Write a program to find the largest of three numbers.

#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

Fig 2.4 Else If Ladder Construct

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)
{

printf(“End of file uncounted \n”);


}
else if (char>‟a‟ && char<=‟z‟)
{
printf(“lower case character \n”);
}
else if(char>=‟A‟ && char<=‟Z‟)
{
printf(“upper case character \n”);
}
else if(char>=‟0‟ && char<=‟9‟)
{
printf(“number \n”);
}
else
{
printf(“Alpha Numeric”);
}
}

EXAMPLE 2

Write a program to check find a grade of students in a university examination.

#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

The Switch Case Statement causes a particular group of statements to be


selected from a group of options. The selection is based upon the current value of the
expression which is specified with the SWITCH statement.

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

Figure 2.5 Switch Case Statement

Write a program to find a grade of students in a university examination using switch


casestatement.

#include<stdio.h> void main()


{
int marks; string grade;case 10:
case 9:
case 8:
grade=”Honors”break;
case 7:

71
case 6:
grade=”First Class”;break;

case 5:
grade=”Second Class”
case 4:
grade=”Third Class”;break;
case else grade=”fail”;break;
}

2.2.3. Conditional operator & goto statements

THE TERNARY? OPERATOR

An expression that evaluates conditions is called as conditional expressions. The operator


used to evaluate conditional expressions is called as a conditional operator (? :) . It is a simple
form of on if-else statement. The conditional operator also referred to as a ternary operator.

SYNTAX

Expression 1? Expression 2:Expression 3;

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.

#include<stdio.h> void main()

72
{

int number1, number2, result;

printf(“Enter the value of number1 and


number2”); scanf(“%d
%d”,&number1,&number2);
result=number1>number2)?:number1:number2;
printf(“The largest number is %d”,result);

THE GOTO STATEMENT

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

#include<stdio.h> void main()

int x,y; x=16; y=12;

if(x==y) x++;

else

goto error; error:

printf(“Fatal Error, exiting \n”);

EXAMPLE 1

Write a program to find square of given number.

#include<stdio.h> void main()

double x,y; read:

scanf(“%f”,&x);

if(x<0)

goto read;

y=sqrt(x);

2.3 LOOPING CONSTRUCTS

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.

The flowchart of the while loop are given below:

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

Write a program to find the average of the marks.

#include<stdio.h>

void main()

int i,num=0;

float sum=0,average;

printf(“Enter the marks of student”);

scanf(“%d”,&i);

sum=sum+1; num++;

scanf(“%d”,&i);

average=sum/num;

printf(“The average is % 2f”,average);

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

Figure 2.6 Do While Statement

EXAMPLE 1

Write a program to find the sum of first natural numbers using for-loop.

#include<stdio.h> #include<conio.h> void main()

77
int n,i,sum; clrscr();

printf(“Enter a number \n”); scanf(“%d”,&n);

i=1;

sum=0; do

sum=sum+i; i++ ;

while(i<=n) printf(“Sum=%d \n”,sum);

EXAMPLE 2

Write a program to print numbers from 1 to 5.

#include<stdio.h> void main()

int x=5; int i=0; do

i++;

printf(“%d \n”,i); while(i<=x);

2.3.3 for and Jumping statements

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

Executions of statement in for…loop as follows;

1. Initialization statement is executed.

2. Test-Expression is evaluated.

3. If the test-expression evaluates true, the statements in the body of the loop executed.

4. Next, control goes to incremented or decremented value.

5. If its condition is true, again the statement of the body of the loop is executed.

6. Otherwise, it exits from the statements.

Write a program to find sum of first N natural numbers.

#include<stdio.h> void main()

int i,n,sum;

printf(“Enter a Number \n”);

scanf(“%d”,&n);

sum=0; for(i=1;i<=n;i++)

sum=sum+i;

printf(“The sum of first n number is %d”,sum);

79
EXAMPLE 2

Write a program to generate multiplication of a number.

#include<stdio.h> void main()

int number,i,product; printf(“Enter a number \n”); scanf(“%d”,&number); for(i=1;i<=10;i++)

product=number*i;

printf(“%d * %d=%d \n”,number,i,product);

JUMPS IN LOOPS

Break and Continue statement are represented as jump in looping statement.

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

Write a program to loop exits only when „Q‟ is pressed.

#include <stdio.h>

int main() char c; for(;;)

printf( "\nPress any key, Q to quit: " ); scanf("%c", &c);

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

Write programs to loop continue again when the value of i is 3.

#include<stdio.h> void main()

int i; for(i=1;i<=5;i++)

if(i==3)

continue; printf(“%d”,i);

2.4 SUMMARY

 In C programs are is a set of statements which normally executed sequentially in the


order there are several instances where we have to make decision by changing
execution order
 The If statement allows the programmer to execute statement or series of statement
sequentially.
 The simple if statement the statement-block may be a single statement or group of
statement.
 When if…else statement taking a decision there are always two faces is to do or not
do to.

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.

2.6 LEARNING ACTIVITY

1. Write a program to generate Armstrong numbers up to 1000.

___________________________________________________________________________
_______________________________________________________________________

2. Write a program to reverse a number.

___________________________________________________________________________
_______________________________________________________________________

2.7 UNIT END QUESTIONS

A. Descriptive Questions

Short Questions

1. Mention the three necessary things required to construct a loop.

2. Explain for loop with its syntax.

3. Explain while loop with its syntax.

84
4. Difference between while loop and do-while loop

5. Define control statements with an example.

6. Explain the used of if statement with an example.

7. Explain the used of if-else statement with an example.

8. Multiple-if statements. Explain with necessary examples.

9. Nested-if statements. Explain with necessary examples.

Long Questions

1. Explain do-while with an example.

2. What is the need for looping?

3. Difference between selection and looping.

4. Difference between break and continue statement.

5. Explain the syntax and use of the switch statement with an example.

6. Explain the various keywords used in a switch statement with an example.

7. Define fall through in a switch statement with an example

B. Multiple Choice Questions

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

3. The continue statement cannot be used with ________

a. for

b. while

c. do while

d. switch

4. Which keyword can be used for coming out of recursion?

a. return

b. break

c. exit

d. both A and B

5. Switch statement accepts

a. int

b. char

c. long

d. All of these

86
Answers

1-a, 2-c, 3-d, 4-a, 5-d

2.8 REFERENCES

References book

 The C Programming Language, B.W. Kernighan, Dennis M. Ritchie, PHI/Pearson


Education
 C Programming with problem solving, J.A. Jones & K. Harrow, Dreamtech Press
 Programming in C - Stephen G. Kochan, III Edition, Pearson Education
 C – programming E. Bal Guruswamy Tata McGray Hill
 How to solve it by Computer: Dromey, PHI
 Schaums outline of Theory and Problems of programming with C: Gottfried

87

You might also like