In C programming language, the Control statements are used to repeat a set of statements.
They are as follows −
- for loop
- while loop
- do-while loop
In for loop and while loop, the condition specifies the number of times, in which a loop can be executed.
Example for the for loop
for (k = 1; k<=5; k++)
Here, the loop will execute until k<=5, when ever k>5 the control come out of the loop.
So, here the for-loop condition specifies the number of times a loop can be executed i.e 5 times the loop executes.
Example
Following is the C program for the for loop −
main( ){ int k; for (k = 1; k<=5; k++){ printf ("%d",k); } }
Output
When the above program is executed, it produces the following output −
1 2 3 4 5
Example for the while loop
while (k< = 5)
Here, the loop will execute until k<=5, when ever k>5 the control come out of the loop.
So, here also, the while-loop condition specifies the number of times in which a loop can be executed i.e. 5 times the loop executes.
Example
Following is the C program for the while loop −
main( ){ int k; k = 1; while (k<=5){ printf ("%d",k); k++; } }
Output
When the above program is executed, it produces the following output −
1 2 3 4 5
Odd loops
Sometimes a user may not know about how many times a loop is to be executed. If we want to execute a loop for unknown number of times, then the concept of odd loops should be implemented. This can be done using for-loop, while-loop or do-while-loops.
Example
Following is the C program for the odd loop −
#include<stdio.h> int main(){ int number; number=1; while(number==1) // odd loop don’t know how many times loop executes{ printf("enter a number:\n"); scanf("%d",&number); if((number%2)==0) printf("number is even\n"); else printf("number is odd\n"); printf("do you want to test any number\n"); printf("if yes then press '1'\n");// if press 1 loop executes again printf("else press '0'\n");//if press 0 exist from loop scanf("%d",&number); } return 0; }
Output
When the above program is executed, it produces the following output −
enter a number: 3 number is odd do you want to test any number if yes then press '1' else press '0' 1 enter a number: 4 number is even do you want to test any number if yes then press '1' else press '0' 1 enter a number: 9 number is odd do you want to test any number if yes then press '1' else press '0' 0