nPrint the numbers from 1 to n using a while loop.
while, counters, and formatted output.
A while loop repeats as long as a condition is true. Here, we start with i = 1 and keep printing while i <= n. After each print, we increase i by 1. This ensures the loop stops after reaching n.
#include <stdio.h>
int main() {
int n, i = 1;
printf("Enter a number: ");
scanf("%d", &n);
while (i <= n) {
printf("%d ", i);
i++;
}
printf("\n");
return 0;
}
Input: 5
Output: 1 2 3 4 5
Print the odd numbers from 1 to n using a while loop.
while, incrementing, and odd-number checks.
We start from i = 1 and continue until i <= n. In each iteration, we check whether i is odd using i % 2 != 0. If it is odd, we print it. Then we increase i by 1. This prints only the odd numbers.
#include <stdio.h>
int main() {
int n, i = 1;
printf("Enter a number: ");
scanf("%d", &n);
while (i <= n) {
if (i % 2 != 0) {
printf("%d ", i);
}
i++;
}
printf("\n");
return 0;
}
Input: 7
Output: 1 3 5 7
Print the multiplication table of a number using a while loop.
while, counters, and multiplication.
The loop starts with i = 1 and continues until i <= 10. In each iteration, we multiply the chosen number by i and print the result. This generates the multiplication table for that number.
#include <stdio.h>
int main() {
int num, i = 1;
printf("Enter a number: ");
scanf("%d", &num);
while (i <= 10) {
printf("%d x %d = %d\n", num, i, num * i);
i++;
}
return 0;
}
Input: 3
Output:
3 x 1 = 3
3 x 2 = 6
3 x 3 = 9
3 x 4 = 12
3 x 5 = 15
3 x 6 = 18
3 x 7 = 21
3 x 8 = 24
3 x 9 = 27
3 x 10 = 30