A triangular number is defined as m(m + 1)/2 for m = 1, 2, …, and so on. Therefore, the first few numbers are 1, 3, 6, 10, … . Write a function with the following header that returns a triangular number:
int getTriangularNumber (int n)
Write a test program that uses this function to display the first 75 triangular numbers with 5 numbers on each line.
#include <iostream>
#include <iomanip>
using namespace std;
int getTriangularNumber (int n);
int main() {
int n = 1,i;
for(i=1; i<=75; i++) {
if((i-1)%5==0)
cout<<endl;
cout <<setw(6)<<getTriangularNumber(i)<<' ';
}
return 0;
}
int getTriangularNumber (int n) {
if (n == 1)
return 1;
return n + getTriangularNumber(n-1);
}
Comments
Leave a comment