I'm trying to write a loop function that returns the result of a computation given a positive integer nVal.
Given nVal, the function computes for 1 + 2 - 3 + 4 - 5 + ... + nVal. So for example if nVal = 4, the function returns the result of 1 + 2 - 3 + 4. The solution I made isn't looping nVal properly and I don't know how to fix it.
Any fixes that I can try?
Here's my code so far (Btw I'm using C language):
#include <stdio.h>
int getValue (nVal)
{
int i, nResult = 0;
for (i = nVal; i <= nVal; i++)
{
if (i % 2 == 0)
{
nResult += i;
}
else if (i % 2 == 1)
{
nResult -= i;
}
}
if (nVal == 1)
nResult +=i + 1;
return nResult;
}
int main ()
{
int nVal, nResult;
printf ("Enter n value: ");
scanf ("%d", &nVal);
nResult = getValue(nVal);
printf ("Result: %d", nResult);
return 0;
}