You are given the sum 1 - 3 + 5 - 7 + 9 - 11 + 13... You should compile a program that (given integer N) finds and displays the value of the sum to the N-th addend.
I don't even have an idea how this program should be. I've written some code but don't know what to add. Please, can you help me? :)
Here is my code:
Scanner input = new Scanner(System.in);
System.out.print("n = ");
int n = input.nextInt();
int sum = 0;
for (int i = 1; i <= n; i++) {
if (i % 2 != 0) {
sum = sum + i;
}
}
System.out.println(sum);
May be you want this
If I enter i/p 7 this will produce -4 as o/p
for (int i = 1; i <= n; i+=2) {
if( i % 4 == 1 )
sum = sum + i;
else
sum = sum - i;
}
in @fafl style (Using Ternary operator), correct me if I'm wrong
sum += (i % 2 != 0) ? ( i % 4 == 1 ) ? + i : - i;
If I enter i/p 7 this will produce 7 as o/p
int n = input.nextInt();
int sum = 0;
int addOrDedduct = 1;
for (int i = 1; i <= n; i++ ) {
if( addOrDedduct % 4 == 1 )
sum = sum + addOrDedduct;
else
sum = sum - addOrDedduct;
addOrDedduct+=2;
}
System.out.println(sum);
Update:
fafl's statement sum = n % 2 == 0 ? -n : n
producing same o/p, Here you don't need to use loop
Forget about the loop and use fafl's answer.