C Workshop · Print 1 to N
Lesson C

Print 1 to N

Read n, then print every integer from 1 through n, each on its own line.

What it is

You read n, then print every integer from 1 through n, each on its own line. The loop variable i is both the counter and the thing you print.

Approach

  1. scanf n.
  2. for (i = 1; i <= n; i++).
  3. printf each i with a newline.

Where this is used in the real world

Diagram

1

scanf n

sample n is 3

A while version would still start i at 1.
2

i = 1; i <= n ?

for header test

do-while would print once even if n were 0 — different kind.
3

printf i

body

One number per line.
4

i++

step

Same role as i++ at the end of a while body.

Run algorithm

Each step highlights the matching C line. Program output appears only when a line that prints actually runs.

Ready
C code
1#include <stdio.h>
2int main(void) {
3    int n, i;
4    scanf("%d", &n);
5    for (i = 1; i <= n; i++) {
6        printf("%d\n", i);
7    }
8    return 0;
9}
What this line does
Press Run algorithm. The highlight will move through the C code.
Program output
(no output yet)

Check your understanding

Five questions. Pick one answer each, then Check answers. The correct choice turns green.

1. n = 3 prints:

i from 1 to n.

2. The test i <= n is checked:

for test.

3. A while version needs you to:

while has no built-in step.

4. do-while would print at least:

Body first.

5. When i becomes n+1:

Leave for.