Conditional structures and loops are essential elements in C programming for controlling the flow of a program. There are mainly three types of loops used in C programming: `for`, `while`, and `do-while` loops. Here's an introduction to each of them:
For Loop:
- The `for` loop is one of the most commonly used loops in C.
- It provides a compact way to iterate over a range of values.
- The basic structure of a `for` loop is as follows:
for (initialization; condition; increment/decrement) {
// Code to be executed repeatedly
}
Example of for loop
#include <stdio.h>
int main(){
int num,i;
printf("Enter any nymber");
scanf("%d",&num);
for(i = 1;i<=num;i++){
printf("%d",i);
}
}
While Loop:
- The `while` loop is used to execute a block of code as long as a specified condition is true.
- It may not execute at all if the condition is false from the beginning.
- The basic structure of a `while` loop is as follows:
while (condition) {
// Code to be executed repeatedly
}
Example of while loop
#include <stdio.h>
int main() {
int n;
printf("Enter a positive integer n: ");
scanf("%d", &n);
int i = 1;
while (i <= n) {
printf("%d ", i);
i++;
}
printf("\n");
return 0;
}
Do-While Loop:
- The `do-while` loop is similar to the `while` loop, but it guarantees that the code block is
executed at least once.
- It checks the condition after the execution of the block.
- The basic structure of a `do-while` loop is as follows:
do {
// Code to be executed repeatedly
} while (condition);
Example of while loop
#include <stdio.h>
int main() {
int x = 1;
do {
printf("Value of x: %d\n", x);
x++;
} while (x <= 5);
printf("\n");
return 0;
}