Search code examples
cfor-loopsumconditional-statementsdifference

My solution for a sum-difference function isn't working


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;
}

Solution

  • Because the numbers are consecutives,I removed the if elseif statement ,I use the variable k to reverse '+' to '-',my loop start from 2 to nVal

    Your loop

    for (i = nVal; i <= nVal; i++)
    

    runs just 1 time

    so ,you should changed it to

    for (i = 2; i <= nVal; i++)
    

    and (nResult=1)because in your exercise the sign changed from the third number, not from the second number

    here:

    if (nVal == 1)
    nResult +=i + 1;
    

    If I write as 1 input ,the output is 2 ,I remove this line

    my code:

    #include <stdio.h>
    
    int getValue (nVal)
    {
    int i, nResult = 1;
    int k=1;
    for (i = 2; i <= nVal; i++)
    {
         nResult+=i*k;
         k*=-1;
    }
    return nResult;
    
    }
    
    int main ()
    {
    int nVal, nResult;
    printf ("Enter n value: ");
    scanf ("%d", &nVal);
    
    nResult = getValue (nVal);
    
    printf ("Result: %d", nResult);
    
    return 0;
    
    }