In: Computer Science
Write a function called alter_sum(n)that returns the alternating sum of all the numbers from 1 to n so that the first number is added, the second number is subtracted, the third number added, the fourth subtracted, and so on: 1-2+3-4+5-6+7… until you reach n. If n is 0 or less then return 0.
code in c++
#include <iostream>
using namespace std;
// creating function
int alter_sum(int n)
{
// if n is less than or equal to 0 return 0
if(n<=0)
return 0;
int sum=0; //initializing int sum to 0
// calculating alternate sum
for (int i = 1; i <= n; i++)
{
if(i%2!=0) //if i is odd then add it to sum
sum+=i;
else //if i is even then subtract it from sum
sum-=i;
}
return sum;
}
int main()
{
// testing our function
cout<<alter_sum(5);
}
ss for reference: