**C++ program to print all the natural numbers from 1 to N** can be written in both iterative and recursive methods. In the iterative method, the task can be performed by using for loop, while loop and do-while loop. Here, all the C++ programs using different loops have been covered to print the natural numbers from 1 to N (1, 2, 3, ..., N).

#### Page content(s):

#### Additional content(s):

## 1. C++ Program & output to Print First N Natural Numbers

/************************************ alphabetacoder.com C++ program to print all natual numbers from 1 to n using for loop **************************************/ #include <iostream> using namespace std; int main() { // declare variables int n, i; //take input of the number upto which // natural numbers will be printed cout << "Enter the upper limit = "; cin >> n; // iterate from 1 to n and print the number cout << "First " << n << " natural numbers are : "; for (i = 1; i <= n; i++) cout << i << " "; return 0; }

Output

**Case 1:**

Enter the upper limit = 10

First 10 natural numbers are : 1 2 3 4 5 6 7 8 9 10

**Case 2:**

Enter the upper limit = 5

First 5 natural numbers are : 1 2 3 4 5

/************************************** alphabetacoder.com C++ program to print all natual numbers from 1 to n using while loop ***************************************/ #include <iostream> using namespace std; int main() { // declare variables int n, i; //take input of the number upto which // natural numbers will be printed cout << "Enter the upper limit = "; cin >> n; // iterate from 1 to n and print the number cout << "First " << n << " natural numbers are : "; i = 1; while (i <= n) { cout << i << " "; i++; } return 0; }

Output

**Case 1:**

Enter the upper limit = 10

First 10 natural numbers are : 1 2 3 4 5 6 7 8 9 10

**Case 2:**

Enter the upper limit = 5

First 5 natural numbers are : 1 2 3 4 5

/***************************************** alphabetacoder.com C++ program to print all natual numbers from 1 to n using do - while loop ******************************************/ #include <iostream> using namespace std; int main() { // declare variables int n, i; //take input of the number upto which // natural numbers will be printed cout << "Enter the upper limit = "; cin >> n; // iterate from 1 to n and print the number cout << "First " << n << " natural numbers are : "; i = 1; do { cout << i << " "; i++; } while (i <= n); return 0; }

Output

**Case 1:**

Enter the upper limit = 10

First 10 natural numbers are : 1 2 3 4 5 6 7 8 9 10

**Case 2:**

Enter the upper limit = 5

First 5 natural numbers are : 1 2 3 4 5

## No comments:

## Post a Comment

If you have any doubts or suggestions, please leave a note.