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

Using C++ Write a programmer defined function with void return type that calcula

ID: 3863562 • Letter: U

Question

Using C++

Write a programmer defined function with void return type that calculates the sum of integers from 1 to a user defined integer. For example, if the user defined integer is 10, the function needs to add from 1 to 10. Your function will accept two parameters: an integer to compute the sum up to and a long integer to store the calculated sum. You need to ask the user for the value of the integer, pass it to your function and compute the sum in your function. Display the sum in your main function.

HINT: Think whether you need to pass by value or reference.

Explanation / Answer

#include<iostream>
using namespace std;
void add(long int *sum,long int n )
{
   while(n>=1)
   {
       *sum=*sum+n;//adding 1 to given number n
       n--;  
   }
  
}
int main()
{
   long int sum,n;
   cout<<"Enter number:";
   cin>>n;
   add(&sum,n);//function calling
   //printing output
   cout<<"The sum from 1 to given number n:"<<n<<" is "<< sum<<endl;
   return 0;
}

ouput:-

Enter number:5
The sum from 1 to given number n:5 is 15


Process exited normally.
Press any key to continue . . .

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