C++ ?Please read the question carefully and match the output given at the end! W
ID: 3788895 • Letter: C
Question
C++
?Please read the question carefully and match the output given at the end!
Write a program that computes the summation between 1 and a given number. For example, if the user inputs 5 the function should add 1 + 2 + 3 + 4 + 5, and return 15. The program should compute the summation in two dierent ways which are described bellow and compare if the functions produce the same result.
1. Write a function that computes the summation between 1 and a given number using a loop.
2. Write a function that computes the summation between 1 and a given number n using the following formula:
Thank you in advance!!
Example of program execution:
Input a number: 5
Using a loop , the result of the summation is: 15
Using Gauss 's formula , the result of the summation is: 15
Both methods give the same answer
Explanation / Answer
#include <iostream>
using namespace std;
int getSumByFormula(int n){
int sum = (n * (n + 1) )/ 2;
return sum;
}
int getSum(int n){
int sum = 0;
for(int i=1; i<=n; i++){
sum = sum + i;
}
return sum;
}
int main(){
int n;
cout<<"Input a number: ";
cin >> n;
int sum = getSum(n);
cout<<"Using a loop , the result of the summation is: "<<sum<<endl;
sum = getSumByFormula(n);
cout<<"Using Gauss 's formula , the result of the summation is: "<<sum <<endl;
return 0;
}
Output:
Input a number: 5
Using a loop , the result of the summation is: 15
Using Gauss 's formula , the result of the summation is: 15
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.