Loops In C Programming Language

Loops In C Programming Language

Why use loops?

To simplify the complex problems into the easy ones, there we need to use loop. In other words repeating the same process multiple times until a specific condition satisfies, there we need to use looping. In C programming, there are 3 types of loop.

Advantage of loops

1) Provides code reusability.

2) Need to write the same code again and again.

2) Traverse over the elements of data structures (array or linked lists).

Types of Loops

There are three types of loop:

do-while Loop In C Programming Language

do-while Loop also called post tested loop. This loop continues until a given condition is satisfied. This loop is used when it is necessary to execute the loop at least once


Syntax:

    do{  
//code to be executed
}while(condition);

Flowchart of do while loop

Loops In C Programming Language

Example 1

    #include<stdio.h>  
#include<stdlib.h>
void main ()
{
char c;
int choice,dummy;
do{
printf("n1. Print Hellon2. Print Javatpointn3. Exitn");
scanf("%d",&choice);
switch(choice)
{
case 1 :
printf("Hello");
break;
case 2:
printf("Javatpoint");
break;
case 3:
exit(0);
break;
default:
printf("please enter valid choice");
}
printf("do you want to enter more?");
scanf("%d",&dummy);
scanf("%c",&c);
}while(c=='y');
}

After executing the above code, our output looks like

1. Print Hello
2. Print Javatpoint
3. Exit
1
Hello
do you want to enter more?
y

1. Print Hello
2. Print Javatpoint
3. Exit
2
Javatpoint
do you want to enter more?
n

Example 2

    #include<stdio.h>  
int main(){
int i=1;
do{
printf("%d n",i);
i++;
}while(i<=10);
return 0;
}

The above program prints 1 to 10. After executing the above code, our output looks like

1
2
3
4
5
6
7
8
9
10

Example 3

    #include<stdio.h>  
int main(){
int i=1,number=0;
printf("Enter a number: ");
scanf("%d",&number);
do{
printf("%d n",(number*i));
i++;
}while(i<=10);
return 0;
}

After executing the above code, our output looks like

Enter a number: 5
5
10
15
20
25
30
35
40
45
50

Infinitive do while loop

By this loop we can pass any non-zero value as the conditional expression. This loop will run infinite times.

Syntax:

    do{  
//statement
}while(1);
Post a Comment