WAP to print the following series 1 2 3 4 ... n
Objective
Write a C++ program to print the natural number series: 1, 2, 3, 4 ... N.
Algorithm / Approach
- Read an integer
n. - Start a
forloop withi = 1up ton. - Print
ion each iteration. - Print a newline at the end.
main.cpp
#include<iostream>
using namespace std;
int main() {
int n;
cout<<"Enter the Value for N : ";
cin>>n;
for(int i = 1; i<=n; i++) {
cout<< i<<" ";
}
cout<< endl;
return 0;
}
Expected Output
Enter the Value for N : 8 1 2 3 4 5 6 7 8
Explanation of the Program
- This is the most basic loop series.
- The loop counter
inaturally increments by 1 on every iteration, which perfectly matches the sequence of natural numbers.
Complexity
Time Complexity
O(n)
Space Complexity
O(1)