Professional Documents
Culture Documents
C Loops
C Loops
C- Control statements
for(i=1;i<=10;i++)
{
printf(“Hello”);
}
Dr. Deepika Bhatia 3
Dr. Deepika Bhatia 4
Dr. Deepika Bhatia 5
Important points related to for loop
for(i=0;i<3;i++)
{
for(j=0;j<2;j++)
printf(“i=%d\t j=%d\n”,i,j);
}
1 1
12 2 3
123 4 5 6
1234
a=10; //part1
while(a !=1) //part2
{
printf(“%d”,a);
a- -; //part3
}
Dr. Deepika Bhatia 9
Do-While Loop –in the statement inside do is executed at least
once before condition is tested. So, it is an exit controlled
loop.
The syntax of do while loop
do
{
//set of statements
} while(condn);
Example:
i=1;
do
{
printf(“%d”,i); //1
i--; //0
}while(i!=0);
1)Do-while will be executed minimum once, but while loop can have
minimum execution as 0 times.
2)Do-while is an exit control loop, but while are entry control loop.
3)While loop is not terminated by semi colon. But do-while is
terminated by semicolon.
4)Variable initialisation happens before the loop in case of while
loop,but may be done inside the loop body in case of do-while loop.
Syntax:
while(condition) do {
{
}while(condition);
}
Dr. Deepika Bhatia 11
Comparison of three loops
int j; int j;
for(j=1;j<=3;j++) for(j=1;j<=3;j++)
{ {
if(j==2) if(j==2)
continue; break;
printf(“%d”,j); printf(“%d”,j);
} }
output is: 13 output is: 1
Dr. Deepika Bhatia 18
exit() – exit(int status)
• exit() is a C library function to jump out of a program.
• Integer value as argument
• Zero indicate normal termination
#include <stdio.h>
• Non-zero indicate abnormal termination #include <stdlib.h>
• Prototype in <stdlib.h>
int main () {
• Syntax: void exit(int status) printf("Start of the program....\n");
• //status is the value returned to
parent process printf("Exiting the program....\n");
exit(0);
return(0);
}
Output is
Start of the program....
Exiting the program....
Dr. Deepika Bhatia 19
Decision making and Branching in C
C program follows a normal sequence for statements execution.
But there are cases where we have to change order of execution/ to use
repeated statements/go to some other statements. For this we use
decision control statements like: (conditional operator ?: is done
earlier)
Example: simple if
if( a < 20 )
{
printf("a is less than 20\n" );
}
Dr. Deepika Bhatia 21
Simple if statement
if( a < 20 )
{
printf("a is less than 20\n" );
} else {
printf("a is not less than 20\n" );
Dr. Deepika Bhatia 23
}
Nesting of if…else statements
END
if (a > b)
{
printf("\n a is greater than b");
}
else if (b > a)
{
printf("\n b is greater than a");
}
else
{
printf("\n Both are equal");
} Dr. Deepika Bhatia 28
Switch Statement in C
• Switch statement in C When you want to solve multiple option
type problems, for example: Menu like program, where one
value is associated with each option and you need to choose only
one at a time, then, switch statement is used.
• Switch statement is a control statement that allows us to choose
only one choice among the many given choices.