Displaying number sequences is a simple way to practice for loops, step values and formatting. The first example prints 1 to 100 with a line break after every ten numbers.
#include <stdio.h>
int main(void) {
for (int i = 1; i <= 100; i++) {
printf("%3d ", i);
if (i % 10 == 0) {
putchar('\n');
}
}
return 0;
}
The integer remainder operator % is enough here; fmod() is for floating-point values.
#include <stdio.h>
int main(void) {
for (int i = 2; i <= 10; i += 2) {
printf("%d ", i);
}
putchar('\n');
return 0;
}
#include <stdio.h>
int main(void) {
for (int i = 1; i <= 10; i++) {
printf("%03d\n", i);
}
return 0;
}
%03d requests a field width of 3 and fills unused leading positions with zeros.
#include <stdio.h>
int main(void) {
for (int i = 1; i <= 10; i += 2) {
printf("%d ", i);
}
putchar('\n');
return 0;
}
#include <stdio.h>
int main(void) {
for (int i = 10; i >= 1; i--) {
printf("%d ", i);
}
putchar('\n');
return 0;
}
#include <stdio.h>
int main(void) {
for (int i = -1; i >= -10; i--) {
printf("%d ", i);
}
putchar('\n');
return 0;
}
Continue with Fibonacci numbers or review the for loop.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.