WAP to print the following series. 0 1 3 6 10 15 21... upto n terms
Objective
Write a C++ program to print the Triangular Numbers series: 0, 1, 3, 6, 10, 15, 21...
Algorithm / Approach
- Initialize
j = 0. - Read an integer
n. - Run a loop
ifrom 1 ton. - Print
j. - Add the loop counter to
jfor the next iteration:j = j + i.
main.cpp
#include<iostream>
using namespace std;
int main() {
int i = 0, j = 0, n;
cout<<"Enter the value for N : ";
cin>>n;
for(i = 1; i<=n; i++) {
cout<< j<<" ";
j = j+i;
}
cout<< endl;
return 0;
}
Expected Output
Enter the value for N : 7 0 1 3 6 10 15 21
Explanation of the Program
- This sequence represents the number of dots needed to form equilateral triangles.
- The mathematical gap between each number continuously expands by 1. (0 to 1 is a jump of +1. 1 to 3 is a jump of +2. 3 to 6 is +3). By adding the loop counter
ito our value, we naturally generate this expanding gap.
Complexity
Time Complexity
O(n)
Space Complexity
O(1)