Answer to Question #335423 in C++ for Wu Celia

Question #335423

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.



1
Expert's answer
2022-04-29T12:46:50-0400
#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);

}
  




Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS