07-25-2023, 10:54 AM
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");
// 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");