In C programming there are 3 types of loop and they are while loop, for loop and do while loop.
While loop
In while loop the body is executed until the test condition become false.
Syntax:
while (conditiuon){
//statement inside while.
}
Example:
#include <stdio.h>
int main() {
int count = 1;
while (count < 5){
printf("While loop in c\n");
count = count + 1;
}
return 0;
}
Multiplication table using while loop:
#include <stdio.h>
int main() {
int number;
printf("Enter the number: ");
scanf("%d", &number);
int count = 1;
while(count <= 10){
int product = number * count;
printf("%d x %d = %d \n", count, number, product);
count = count + 1;
}
return 0;
}
do while loop
Here the body of the loop is executed and then the condition is evaluated, if the condition is true the body of the loop is executed again.
syntax:
do {
//body of loop
} while(condition);
Example:
int main(){
int count = 5;
do{
printf("%d\n", count);
count = count + 1;
} while(count < 5);
return 0;
}
for loop
Syntax:
for(initializationExpression; testExpression; updateExpression){
//codee inside for loop.
}
Example:
int main() {
for(int i=0; i<10; i++){
printf("%d ", i);
}
return 0;
}
Sum of whole numbers from 1 to 100:
int main() {
int sum=0;
for(int i=1; i<=100; i++){
sum=sum+i;
}
printf("%d", sum);
return 0;
}
Sum of even numbers:
int main() {
int sum=0;
for(int i=2; i<=100; i=i+2){
sum=sum+i;
}
printf("%d", sum);
return 0;
}
Top comments (0)