Part-2 Conditional Branching and Loops

Download as pdf or txt
Download as pdf or txt
You are on page 1of 11

5.4.

LOOPING STATEMENTS

A loop is a sequence of instructions that is repeated until a certain condition is reached.

A useful task in programming is to repeatedly execute a block of code. Many programs that produce
extremely complex output are only executing a single task many times. A loop lets the programmer
write a very simple statement to produce a significantly greater result simply by repetition.
A loop is used with a condition. The repetition is done till the condition is true.
A loop declaration and execution can be done in the following ways.
• Initialize loop with declaring a variable
• Check condition to start a loop
• Executing sta.tements inside loop.
• Increment or decrement the value of a variable.
_ _ _ _ _ _ _ _ _ _ _ _ _ _.....,.._ _ _ Programming for Problem Solving

5.4.1. Types of looping statements


Basically, the types of looping statements depend on the condition checking method. Condition
checking can be made in two ways: Before loop and after loop. So, there are two types of looping
statements.
(a) Entry controlled loop
(b) Exit controlled loop

(a) Entry Controlled Loop


In such type of loop, the test condition is checked first before the loop is executed.
Examples of this looping statements are :
• while loop
• for loop

(b) Exit Controlled Loop


In such type ofloop, the loop is executed first. Then condition is checked after the blocks of statements
· are executed. The loop is executed atleast once.
Example of this looping statement is:
• do-while loop

~ - for statement
This is an entry controlled looping statement.
The syntax of the for statement is,
for(initialization; expression; update)
{
Set of statements;, Body of for loop
}
Set of statements;~ Statements after for
In this loop structure, more than one variable can
be initialized. The for foop can be more concise and
flexible than that of while and do-while loops.The Initialization
initialization allows the program to either declare a
variable and give it a value or give a value to an already Update
existing variable. Second, the condition tells the
program that while the conditional expression is true,
the loop should continue to repeat itself. The update Body of for loop
allows the updation of a variable. That is, the variable
may be incremented or decremented. ·
False

Example Statements after for


Program using for statement
#include ~stdio.h>
OP~
I
precedence and Control Statements _ _ _ _ _ _ _ _ _ _ _ ___. -:--1 ,
void main() /* Program introduces the for statement, counts to ten*/

I
int count; I

for( count= 1; count<= 10; count= count+ 1)


{
printf("%d ", count);
printf ( 11 \n");

,-----------+ Initializes count to 1

r
. - - - - - - - - - Checks for condition

Increments count by 1

for( count = 1; count <= 1O; count = count + 1)


Each time the condition is checked and the count is incremented until it reaches 10.

~ hile statement ·
This is an entry controlled looping statement. It is used to repeat a block of statements till the
condition is true. Its syntax is,
while( condition
{
Set of statements;~ Body of while loop
}
Set of statements;~ Statements after while
Somewhere within the body of the while loop, a statement must alter the value of the variable used
in the condition to allow the loop to finish. The following diagram depicts the working of while statement.

False

Body of while loop

-
Statements after while
.__ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ Programming for Problem Solving

Example
Program using while statement
/* Sample program using while*/
#include <stdio.h>
void main ()
{
int loop= O;
while( loop<= 10)
{
printf( 11 %d\n 11 , loop);
++loop;
}
}
The above program uses a while loop to repeat the statements
printf( 11 %d\n 11 , loop);
++loop;
The variable upon which the while is dependant is initialized prior to the while statement (in this
case the previous line), and also that the value of the variable is altered within the loop, so that eventually
the conditional test will succeed and the while loop will terminate once the condition fails.
This program is functionally equivalent to the earlier program which counted to ten.

Sifdo-while statement
This is an exit controlled looping statement. Sometimes, there is a need to execute a block of statements
first and then to check the condition. At that time this type of a loop is used. In this, block of statements
is executed first and then condition is checked.
The Syntax of this statement is,
do
{
Set of statements;
}
.
while(condition);
\

In the above syntax, the block of statements is executed first. At the end ofloop, condition is evaluated.
If the result is true then program control goes to execute the body of a loop once again. This process
continues till condition is true. When it becomes false, the loop is terminated. Even if the condition is
false, the loop is executed as least once whereas in while, the loop will be executed only when the
condition is true. ·
Example
Program using while statement
#include <Stdio.h>
p
tor precedence and Control Statements
opera

void main()

int X = 0; I I
do
{
printf( "%d\n", x);
x++; /* Update x so the condition can be met eventually*/
} while ( X<= 10); /* While xis less than 10 */
}
I,
This program is also functionally equivalent to the earlier for and while programs which counted to
ten.

S.S. BREAK AND CONTINUE

5.5.1. break statement


In C programming, break is used in terminating the loop·immediately after it is encountered. The
l.
break statement can be used in terminating all three loops: for, while and do while loops. In general, the
break statement is used with if statement inside loops.

The syntax of break statement


break;
The working of the break statement is shown below: ·

True
Break

lI I
_________......;._ _ _ _ _ _ _ _ _ Programming.for Problem Solving

The following diagram illustartes the working of bre.:ik statement in all three types ofloops,

do {
while (test expres3ion) { Statement/s
statement/s if (test expression) {
if (test expression) { break;
break; }
) statement/s
statement/s }
} while (test expression);

for (initial expression; test expression; updata expression) {


Statement/s
if (test expression) {
break;
}
statements/

Example
Program to find average of maximum of 'n' positive numbers entered by user. But, if the input
is negative, display the average (excluding the. average of negative input) and end the program.

# include <stdio.h>
void main(){
float num,average,sum;
int i,n;
printf("Maximum no. cf inputs\n");
scanf ( 11 %d 11 , &n);
printf ( "Enter numbers \n") ;
for(i=l;i<=n;++i)

scanf ( "%f", &num) ;


if(num<O.O)
break;//for loop breaks if num<O.O
sum=sum+num;
}
}
operator precedence and Control Statem~nts

When the above ~ode is.compiled and executed, it produces the following result:
Maximum no. of mputs
4
Enter numbers
1
2
3
4
Average=Z.500000
In this program, when the user inputs a number Jess than zero, the loop is terminated using break
statement with executing the statement below it, that is, without executing sum=sum+num.
. .

In C, break statement is also used in switch case statement.

s.s.2. continue
It is sometimes desirable to skip some statements inside the loop and continue with the next iteration
of the loop. In such cases, continue is used.

The syntax of continue statement


continue;
Just like break, continue is also used with if statement.
.,

True Continue

False

Remaining part of loop

Example to find the product of 4 integers entered by a us~r. If user enters Oskip
program . .,t.

//program to demonstrate the working of continue statement m C programmmg

# include <stdio.h>
void main(}{
inti,num,product;
& ('-1 product=l·i<=4;++i)
~or 1 - , '
- - - - - - - - - - - - - - - - - - - Programming for Problem Solving

{
printf("Enter num%d:",i);
scanf("%d",&num);
if (num==O)
continue;
/*In this program, when num equals to zero, it skips the following
st
atement and control transfer to the beginning of the loop. */
product*=num;
}
printf ( "product=%d", product) ;
}
When the above code is compiled and executed, it produces the following result:
Enter numl :3
· Enter num2:0
Enter num3:-5
Enter num4:2
product=-30

Additional Programs

1. Suppose, you are interested in how many ways the word "kongu" may be scrambled. There
are 5 choices for the first letter, once we have chosen the first letter there are 4 choices for the
second letter, and then three choices for the third letter, two for the fourth letter, and only one
choice for the last letter. Write a program to find the number of choices for the above five letter
word.
#include<stdio.h>
#include<conio.h>
void main ()
{
long resul t=l;
int n,i;
clrscr();
printf("\n Number of lefters to be scrambled(without repeating
letters");
scanf ( "%d", &n);
for(i=n;i>=l;i--)
result=result*i;
printf ( "\n the number of possible scrambled words : %ld 11 , result);
getch();
}
. precedence and Control Statements
operator
Write a program to find the number of ways to scramble the word "program".
~ote: Jf there is no duplicate letters, the solution would be 51, but this is not the case. There
, then the solution is 51/21.
are"r'5
1

#include<stdio.h>
void main()

long resultl=l,result2=1 , res;


int n,i,rep;
clrscr();
printf("\n Number of letters to be scrambled (one letter
repeating)\n");
scanf ( "%d", &n) ;
printf("\n how many times the letter repeats\n");
scanf( 11 %d 11 ,&rep);
for(i=n;i>=l;i - -)
resultl=resultl*i;
for(i=rep;i>=l;i--)
result2=result2*i;
res=resultl/result2;
printf("\n the number of possible scrambled words :%ld.",res);
}
3. Kavin is working for a departmental store on a constraint. The constraint is that he s_hould
sell an item of quantity which is equivalent to the number of same items sold in previous two days.
Calculate the minimum quantity he should sell in each day of one week? The number of items he
sold on first two days is Oand 1.
#include<stdio.h>
void main()
{
int i,no~soldl,no_sold2,no_sold3,no_of_days;
no_soldl=O;
no_sold2=1;
printf ( 11 \n Number of days worked ... \n");
scanf( 11 %d 11 ,&no_of_days);
i=3;
while(i<=no of days)
{
no_sold3=no_soldl+no_sold2;
printf("\n Number of items sold on %dth day is
%d",i,no_sold3);
.__ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ Programming for Problem Solving

i++;
no soldl=no sold2;
no sold2=no sold3;
}
}
4. Write a program to print a checker board (8 -by-8 grid).
#include<stdio.h>
void main ()
{
int i,j,k;
for(i=l;i<=8;i++)
{
for(j=l;j<=8;J++)
printf( 11 - - - 11 ) ;
printf( 11 \n 11 ) ;
for(k=l;k<=9;k++)
printf ( 11 I 11 ) ;
printf ( 11 \n 11 ) ;
for(k=l;k<=9;k++)
· printf ( 11 I 11 ) ;
for(j=l;j<=8;j++)
printf( 11 - - - 11 ) ;
printf( 11 \n 11 ) ;
}
}

5. Determine the maximum number of circular stampings of specified size that can be cut in a
rectangular metal sheet. Find the amount of sheet wasted. Write a program to test it.
#include<stdio.h>
#include<conio.h>
void main ()
I
l

fl~at hgt,width,radius,rect_area,circle_area,rem_area,waste;
int no_stampings=O,rwidth,rhgt;
11
printf ( \nEnter the height and width of the rectangle metal
sheet .... \n 11 ) ;
scanf( 11 %f%f 11 ,&hgt,&width);
rect_area=hgt*width;
rem area=rect_area;
~ e n c e and Control Statements - - - - - - - - - - - - - - -
operator 11
, ntf ( 11 \n enter the radius of stamping placed inside the rectangle ) ;
prl f(11%f 11 ,&radius);
9 ca n
•rcle area=3.14*radius*radius·
Cl - '
wnile(rem_area>=circle_area)
{
rem area=rem area-circle area·
- - - • I

no_stampings++;
}
printf("\n Number of circular stampings .... :%d 11 ,no_stampings);
printf ( 11 \n The amount of sheet wasted .... : %f 11, rem_area);
get ch() ;
}
6. Write a program to find the largest ellipse that can be drawn inside a rectangular area
#include<stdio.h>
#include<conio.h>
void main ()
{
float hgt,width,ellipse_area,rect_area,major_axis,~inor_axis;
,
clrscr () ;
printf( 11 \nEnter the height and width of the rectangule ... \n");
scanf( 11 %f%f 11 ,&hgt,&width);
rect_area=width*hgt;
major_axis=width/2;
minor_axis=hgt/2; I
ellipse_area=3.14*major_axis*minor_axis; I
printf("\n the area of the rectangle :%f",rect_area); I
printf("\n area of the 1grgest ellipse that can be ·fit i~
:%f",ellipse_area);
·getch();

I
In this chapter, you have studied about overview of operator precedence, decision making and \1

branching and looping statements. I

\ ,1
'I

'I
.,I

You might also like