Loop Control Instructions
while (condition) {
// instructions to be repeated
}
For example, the following code will print the numbers 1 through 10:
int i = 1;
while (i <= 10) {
printf("%d\n", i);
i++;
}
The for loop is similar to the while loop, but it is more compact and is often used for counting or iterating through arrays. The syntax for a for loop is as follows:
for (initialization; condition; increment) {
// instructions to be repeated
}
For example, the following code will also print the numbers 1 through 10:
for (int i = 1; i <= 10; i++) {
printf("%d\n", i);
}
The do-while loop is similar to the while loop, but it guarantees that the instructions within the loop will be executed at least once. The syntax for a do-while loop is as follows:
do {
// instructions to be repeated
} while (condition);
For example, the following code will ask the user for a number and continue to ask until the number is greater than 0:
int num;
do {
printf("Enter a number greater than 0: ");
scanf("%d", &num);
} while (num <= 0);
In conclusion, loop control instructions are an important part of C programming and are used to repeat a set of instructions multiple times. The while loop, for loop, and do-while loop are all useful tools that can be used to accomplish this task, and each has its own unique advantages and use cases. Understanding and using these loops correctly can help you write more efficient and readable code.
.jpg)