C Program to Print all Natural Numbers from 1 to N Using While Loop

Hey coders, today you will learn how to print all natural numbers from 1 to N using a While loop.

As you already know, natural numbers are all positive integers ranging from 1 to infinity. They are also known as counting numbers because they are used to count different objects.

Don’t forget that natural numbers do not include zero or negative integers.

In this tutorial, we will learn to write a C program which prompts the user to enter the upper limit or value of N, then this program will automatically print all natural numbers from 1 to N. This can be done using many approaches, but for this tutorial, we will go with the While loop approach.

So, without further ado, let’s begin this tutorial.

C Program to Print all Natural Numbers from 1 to N Using While Loop

C Program

// C Program to Print ALl Natural Numbers from 1 to N Using While Loop
#include <stdio.h>

int main()
{
    int i = 1, N;

    // Asking for input
    printf("Enter the value of N: ");
    scanf("%d", &N);

    // Printing all natural numbers from 1 to N
    while (i <= N)
    {
        printf("%d\n", i);
        i++;
    }

    return 0;
}
C Program to Print all Natural Numbers from 1 to N Using While Loop

Output 1

Output 2

Output 3

How does this Program Work?

    int i = 1, N;

In the first line of the program, we have declared two variables i and N. We have assigned a value of 1 to i variable.

    // Asking for input
    printf("Enter the value of N: ");
    scanf("%d", &N);

Then, we take input from the user using the scanf() function. The scanf() function is used to read input from the input. Here, the user is asked to enter the upper limit up to which the user wants to print the numbers. The entered number gets stored in the N variable.

    // Printing all natural numbers from 1 to N
    while (i <= N)
    {
        printf("%d\n", i);
        i++;
    }

After that, we defined a while loop which checks whether the value of i is less than or equal to N or not, if it is less than N, then this loop is executed, and it prints the value of i and then increments the value of i. This loop keeps on iterating until the value of i is greater than the value of N.

Conclusion

I hope you all understand how to print all natural numbers from 1 to N using a While loop in the C programming language.

You can also use the same logic to print the natural numbers in the for loop and do-while loop approach.

Leave a Comment

Your email address will not be published. Required fields are marked *