Part-2 Conditional Branching and Loops
Part-2 Conditional Branching and Loops
Part-2 Conditional Branching and Loops
LOOPING STATEMENTS
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
~ - 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
I
int count; I
r
. - - - - - - - - - Checks for condition
Increments count by 1
~ 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
-
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.
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);
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)
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.
. .
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.
True Continue
False
Example to find the product of 4 integers entered by a us~r. If user enters Oskip
program . .,t.
# 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()
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
\ ,1
'I
'I
.,I