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;
}
CodePudding user response:
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;
}
}
CodePudding user response:
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;
}