Here's my current code:
Scanner input = new Scanner(System.in);
int n, sum = 0;
System.out.println("Enter n:");
n = input.nextInt();
for (int i = 1; i <= n; i++) {
if (i % 2 == 0){
sum-=input.nextInt();
} else {
sum+=input.nextInt();
}
}
System.out.println("The total sum is:"+sum);
Can someone please help to alternately add and minus an integer?
For example, if I enter n: = 5
and ask the user to enter 4, 14, 5, 6, 1
then it will compute like 4 + 14 - 5 + 6 - 1
You were almost there:
for (int i = 1; i <= n; i++) {
if (i > 2 && i % 2 != 0){
sum-=input.nextInt();
} else {
sum+=input.nextInt();
}
}
The first two numbers contribute to the result with the "plus" sign, their sign does not alternate, hence the additional i > 2
condition.
Side note: I would suggest renaming sum
to result
and changing the output text to something like System.out.println("The result is:"+result);
.
The reason is that it's not the sum being calculated, to the name sum
is a bit confusing.