Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a complete program in C++, including the function, with separate declarati

ID: 3595396 • Letter: W

Question

Write a complete program in C++, including the function, with separate declaration and definition. Test your function int main() as follows.

Write a function to compute the sum of the first (n > 0) positive integers. The function takes an integer as input and returns the sum as output. If a positive integer is not input, the function should return 0 after printing a polite message.

Here is an example run.

Enter a positive integer: 5 The sum of the first 5 positive integers is 15 Here's another run Enter a positive integer: 0 Sorry, 0 is not a positive integer.

Explanation / Answer

#include<iostream>
using namespace std;

// declaration
int sum(int);

main()
{
// DRIVER that takes input and get's sum of numbers
int n;
cout << "Enter a positive integer: ";
cin >> n;
sum(n);
}

// definition
int sum(int n)
{
if(n>0)
{
int sum = 0;
  
// this loops for n times and adds sum
for(int i=1;i<=n;i++)
{
sum = sum + i;
}
cout << "The sum of the first 5 positive integers is " << sum;
return sum;
}
cout << "Sorry, " << n << "is not a positive integer." << endl;
return 0;
  
}

/*SAMPLE OUTPUT
Enter a positive integer: 0
Sorry, 0is not a positive integer.

Enter a positive integer: 10
The sum of the first 5 positive integers is 55
*/

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote