C Loops
The looping can be defined as repeating the same process multiple times until a specific condition satisfies. There are three types of loops used in the C language.
Why use loops in C language?
The looping simplifies the complex problems into the easy ones. It enables us to alter the flow of the program so that instead of writing the same code again and again, we can repeat the same code for a finite number of times. For example, if we need to print the first 10 natural numbers then, instead of using the printf statement 10 times, we can print inside a loop which runs up to 10 iterations.
Advantage of loops in C
1)It provides code reusability.
2)Using loops, we do not need to write the same code again and again.
3)Using loops, we can traverse over the elements of data structures (array or linked lists).
Do while loop in C
The syntax of the C language do-while loop is given below:
1. do{
2. //code to be executed
3. }while(condition);
Example 1
1. #include<stdio.h>
2. #include<stdlib.h>
3. void main ()
4. {
5. char c;
6. int choice,dummy;
7. do{
8. printf("\n1. Print Hello\n2. Print C Programming\n3. Exit\n");
9. scanf("%d",&choice);
10. switch(choice)
11. {
12. case 1 :
13. printf("Hello");
14. break;
15. case 2:
16. printf("C Programming ");
17. break;
18. case 3:
19. exit(0);
20. break;
21. default:
22. printf("please enter valid choice");
23. }
24. printf("do you want to enter more?");
25. scanf("%d",&dummy);
26. scanf("%c",&c);
27. }while(c=='y');
28. }
Output
1. Print Hello
2. Print C Programming
3. Exit
1
Hello
do you want to enter more?
y
1. Print Hello
2. Print C Programming
3. Exit
2
C Programming
do you want to enter more?
n
Do while example
There is given the simple program of c language do while loop where we are printing the table of 1.
1. #include<stdio.h>
2. int main(){
3. int i=1;
4. do{
5. printf("%d \n",i);
6. i++;
7. }while(i<=10);
8. return 0;
9. }
Output
1 4 7
2 5 8
3 6 9
While loop in C
The syntax of while loop in c language is given below:
1. while(condition){
2. //code to be executed
3. }
Let's see the simple program of while loop that prints table of 1.
1. #include<stdio.h>
2. int main(){
3. int i=1;
4. while(i<=10){
5. printf("%d \n",i);
6. i++;
7. }
8. return 0;
9. }
Output
1
2
3
4
5
6
7
8
9
10
For loop in C
The for loop in C language is used to iterate the statements or a part of the program several times. It is frequently used to traverse the data structures like the array and linked list.
The syntax of for loop in c language is given below:
1. for(Expression 1; Expression 2; Expression 3){
2. //code to be executed
3. }
Let's see the simple program of for loop that prints table of 1.
1. #include<stdio.h>
2. int main(){
3. int i=0;
4. for(i=1;i<=10;i++){
5. printf("%d \n",i); 6. }
7. return 0; 8. }
Output
1
2
3
4
5
6
7
8
9
10
0 Comments