C program to print all natural numbers from 1 to n

Write a C program to print all natural numbers from 1 to n using loop. C program to print first n natural numbers using loop. How to print natural numbers in a given range using loop.

Example:
Input upper limit to print natural number: 10
Output natural numbers from 1 to 10: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10

Also view this program through other programming methods
C program to print all natural numbers from 1 to n using while loop.
C program to print all natural numbers from 1 to n using recursion.

Required knowledge:

Basic C programming, Loop, Natural numbers

Program to print natural numbers using loop

/**
 * C program to print all natural numbers from 1 to n
 */

#include <stdio.h>

int main()
{
    int i, n;

    /*
     * Reads the value of n from user
     */
    printf("Enter any number: ");
    scanf("%d", &n);

    printf("Natural numbers from 1 to %d : \n", n);

    /*
     * Starts loop counter from 1 (i=1) and goes till n (i<=n)
     * And in each repetition prints the value of i
     */
    for(i=1; i<=n; i++)
    {
        printf("%d\n", i);
    }

    return 0;
} 

Note: If you want to print natural numbers in range then you need to initialize the loop counter with some variable such as: for(i=start; i<=n; i++) { ... } .

Output
X
_
Enter any number: 10
Natural numbers from 1 to 10 :
1
2
3
4
5
6
7
8
9
10

Happy coding ;)


Any doubt or suggestion write here. I will try my best to help. Before posting your code you must escape it to view. To format your source code and use format highlighting, post your source code inside
< code >< pre > -- Your source code -- < /pre >< /code > (Remove spaces from pre and code tags).

No comments:

Post a Comment