Natural numbers from 1 to N

C program to print natural numbers from 1 to N.

Program

#include<stdio.h>
#include<conio.h>
void main()
{
   int n, i;

    printf("Enter the value of N\t:");
    scanf("%d",&n);

    printf("Natural number from 1 to %d are\n",n);
    for(i=1;i<=n;i++)
    {
        printf("%d ",i);
    }
    getch();
}

Output

Enter the value of N    :8
Natural number from 1 to 8 are
1 2 3 4 5 6 7 8

Explanation

In the above program, we have to print 'n' natural numbers, where 'n' is entered by the user at run time. So, we have to repeat the task of printing natural numbers until we reach to the value of 'n'. For this purpose, where repetition of a task is needed, loops are used.

In Loops a counter variable is required, which take care of how many times the loop will be executed. In this case, lets say that it is 'i'.
Loops consist of three parts
initialization
condition
increment/decrement

In the above task, we have to start printing the numbers from 1. So, value of i is initialized to 1. We have to print the natural numbers upto 'n', so condition will be i<=n. The difference between two natural numbers is 1. Therefore, if x is one natural number then next natural number is given by x+1. So, counter 'i' is increased by 1. i.e. i++
Inside the loop body, we will print the value of i. Because we need to print natural numbers from 1 to 'n' and from loop structure it is clear that 'i' will iterate from 1 to n. So to print from 1 to 'n' print the value of i.
for(i=1;i<=n;i++) // for(initialization;condition;increment)
{
printf("%d ",i);
}

Here i is initialized to 1 and incremented by 1 for each iteration, instructions inside the for block are executed unless i becomes greater than n. So, value of i will be printed like 1 2 3 .... n using printf statement.

The above program can be rewritten using while and do-while loop using the following constructs
i = 1; //initialization
while(i<=n) //condition
{
printf("%d ",i);
i++; //increment
}

i = 1; //initialization
do
{
printf("%d ",i);
i++; //increment
}while(i<=n); //condition