0

If the input is 4 the output should be 2---> f(4) =  - 1  + 2  - 3  + 4  = 2

but the code doesn't give any output

#include <iostream>
using namespace std;

int main() {
    int n; cin>>n;
    int sum = 0;
    for(int i = 1;i<=n;i++){
        if (i%2 != 0){
            i = -i;
        }
        sum += i;
    }
    cout<<sum;
    return 0;
}
  • I think you used the wrong tag (`css`). – LawrenceWebDev Dec 05 '22 at 21:09
  • 2
    Unfortunately, you will discover that the coding puzzle site where this coding puzzle is likely from will still fail this, because of "time limit exceeded" for values of several million. This is because the coding puzzle site is a scam, taking advantage of people who want to learn C++ by promising that all they need to do is solve their silly coding puzzles. This coding puzzle is really a simple mathematical formula, that does not require adding numbers, like that, but just a single, simple, formula. Someone who wants to learn C++ is not going to learn anything by knowing what the formula is. – Sam Varshavchik Dec 05 '22 at 21:15
  • 2
    Hint: you should not modify the loop index `i` inside the loop. – Damien Dec 05 '22 at 21:17
  • 2
    Track the value of `i` in your loop, you will see that `i <= n` is always true, so your loop never finishes and you see no output – john Dec 05 '22 at 21:18
  • 1
    you should not write a loop to solve this in the first place. Do the maths first: `-1 + 2 -3 + 4 == (-1+2) + (-3+4) == 1 + 1 == 4/2`. you only need to check if `n` is odd or even. The rest is trivial. – 463035818_is_not_an_ai Dec 05 '22 at 21:29

3 Answers3

1

We already know the problem:

int sum = 0;
for(int i = 1;i<=n;i++){
   if (i%2 != 0){
       i = -i;      // <-- Bad Idea.
                    // Can you imagine what the sequence of 'i' looks like?
                    // It just keeps alternating between 1, -1 and 0.
   }
   sum += i;
}

There's a possible approach that's only variable away from this snippet. I'll wrap it into a function, so that it can be more easily tested.

#include <iostream>

namespace b {
  constexpr int alternating_sum(int n)
  {
    int sum{};
    for(int i = 1; i <= n; i++)
    {
      int value = i;     // <-- Let's use this, instead of messing with i.
      if ( i % 2 != 0)
      {
        value = -value;  
      }
      sum += value;
    }
    return sum;
  }
}

int main()
{
  // Let's test it:
  using namespace b;
  static_assert(alternating_sum(1) == -1);
  static_assert(alternating_sum(2) == -1 + 2);
  static_assert(alternating_sum(3) == -1 + 2 - 3);
  static_assert(alternating_sum(4) == -1 + 2 - 3 + 4);
  
  std::cout << "So far, so good...\n";
  return 0;
}

I also wrapped it into a namespace, while avoiding using namespace std1, because I'd like to play a little more.

Maybe it helps to see how the sequence "grows", so we can add this snippet to the main function:

for (int i = 1; i <= 10; ++i)
{
    std::cout << alternating_sum(i) << '\n';
}

It outputs the following

-1
1
-2
2
-3
3
-4
4
-5
5

That seems like a pattern. One we can reproduce without a loop, with just a little math:

namespace c
{
  constexpr int alternating_sum(int n)
  {
    if ( n % 2 != 0 )
    {
      return -(n + 1) / 2;
    }
    else
    {
      return n / 2;
    }
  }
}

To test it, we just have to change using namespace b; into using namespace c; in main.


1) Why is "using namespace std;" considered bad practice?

Bob__
  • 12,361
  • 3
  • 28
  • 42
  • You can simplify even more by have a "sign" variable that toggles between -1 and 1. Example: `sum += (sign_variable) * (term);` and then do `sign_variable *= -1;`. Try it! – Thomas Matthews Dec 06 '22 at 00:25
  • @ThomasMatthews Yeah. That would also be the "correct" way of writing "monstrosity" like `pow(-1, i) * i`. – Bob__ Dec 06 '22 at 01:40
0

the problem is in the i = -i, thus the for loop should be changed to something like:

int sum = 0;
for(int i = 1; i <= n; i++) {
    if(i % 2 == 0) {
        sum += i;
    } else {
        sum -= i;
    }
}
Jam
  • 65
  • 7
-1

You need an endl when printing so that the output buffer gets flushed to the console.

cout << sum << endl;

e: In the for loop, you set i = -i. This makes it so that i will never be able to reach n.

for (int i = 1; i <=n; i++) {
    if (i%2 == 0)
        sum += i;
    else
        sum -= i;
}