QP School

Full Version: Looping structures in C (for, while, do-while)
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Loops allow you to execute a block of code repeatedly.

// Using a for loop to print numbers from 1 to 5
for (int i = 1; i <= 5; i++) {
    printf("%d ", i);
}
printf("\n");

// Using a while loop to calculate the sum of numbers from 1 to 10
int sum = 0, i = 1;
while (i <= 10) {
    sum += i;
    i++;
}
printf("Sum: %d\n", sum);

// Using a do-while loop to print numbers from 1 to 5
int num = 1;
do {
    printf("%d ", num);
    num++;
} while (num <= 5);
printf("\n");