Q:

C program to print natural numbers from 1 to n

belongs to collection: C Programming on Numbers

0

What are Natural numbers?

Natural numbers are the positive integers or non-negative integers which starts from 1 and ends at infinity, such as:

1,2,3,4,5,6,7,8,9,10,……,∞

In this exercise, we learn how to write a C program to print natural numbers from 1 to n.  We will take the help of iterative statements like for, while or do-while loop to print the natural numbers.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

C program to print natural numbers from 1 to n using For Loop

In the below program, we will ask the user to enter the value of ‘n’. After entering the value of ‘n’ we will print the natural number from 1 to n with the help of for loop.

#include<stdio.h>
int main()
{
    int num, i;
    printf("Please Enter any Integer number = ");
    scanf("%d", &num);
    if(num >0)
    {
        printf("List of Natural Numbers from 1 to %d are \n", num);
        for(i = 1; i <= num; i++)
        {
            printf("%d ", i);
        }
    }
    else
    {
        printf("Enter Valid number\n");
    }
    return 0;
}

Output:

Please Enter any Integer number = 10
List of Natural Numbers from 1 to 10 are
1 2 3 4 5 6 7 8 9 10

-----------------------------------------------------------------------------------------------------------------------

C program to print natural numbers from 1 to n using while Loop

In the below program, we will ask the user to enter the value of ‘n’. After entering the value of ‘n’ we will print the natural number from 1 to n with the help of a while loop.

#include<stdio.h>
int main()
{
    int num, i = 0;
    printf("Please Enter any Integer number = ");
    scanf("%d", &num);
    if(num >0)
    {
        printf("List of Natural Numbers from 1 to %d are \n", num);
        while(i <= num)
        {
            printf("%d ", i++);
        }
    }
    else
    {
        printf("Enter Valid number\n");
    }
    return 0;
}

Output:

Please Enter any Integer number = 10
List of Natural Numbers from 1 to 10 are
0 1 2 3 4 5 6 7 8 9 10

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

C Programming on Numbers

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
C program to print natural numbers within a range... >>
<< write a program to check and print neon numbers i...