Loop Control Structures
Loop Control Structures
• while loop
• do-while loop
• for loop
/** * C program to print all natural numbers from 1
to n using while loop */
main()
{
int i, n; /* * Input a number from user */
printf("Print all natural numbers from 1 to N: ");
scanf("%d", &n); /* * Print natural numbers from 1 to
end */
i=1;
while(i<=n)
{
printf("%d\n", i);
i++;
}
}
main ()
{
int a = 10;
/* while loop execution */
while( a < 20 )
{
printf("value of a: %d\n", a);
a++;
}
}
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
main()
{
int i, n;
printf("Enter the value of n\t");
scanf("%d", &n);
printf("Printing natural numbers from 1 to %d\n", n);
i = 1;
do {
printf("%d\t", i);
i++;
}while(i <= n);
}
Output
Enter the value of n 10
Printing natural numbers from 1 to 10
1 2 3 4 5 6 7 8 9 10
Nested Loop
Syntax of Nested while loop
while (condition1)
{
statement(s);
while (condition2)
{
statement(s);
... ... ...
}
... ... ...
}
Syntax of Nested do while loop
Break Statement in C
Break Statement in C
main ()
{
int i;
for(i = 0; i<10; i++)
{
printf("%d ",i);
if(i == 5)
break;
}
printf("came outside of loop i = %d",i);
}
int main()
{
int i=1,j=1;//initializing a local variable
for(i=1;i<=3;i++)
{
for(j=1;j<=3;j++)
{
printf("%d %d\n",i,j);
if(i==2 && j==2)
{
break;//will break loop of j only
}
}//end of for loop
return 0;
}
Factorial of a given number
int main()
{
int i,fact=1,number;
printf("Enter a number: ");
scanf("%d",&number);
for(i=1;i<=number;i++)
fact=fact*i;
printf("Factorial of %d is: %d",number,fact);
return 0;
}