Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternate adding and subtracting a number java

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

like image 359
jeiboi Avatar asked Feb 13 '26 15:02

jeiboi


2 Answers

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.

like image 50
Alex Shesterov Avatar answered Feb 16 '26 03:02

Alex Shesterov


int result = 0;
for (int  i = 1; i <= n; i++) {
    int num = input.nextInt();
    result += (i == 1 || i % 2 == 0) ? num : -num;
}
like image 34
patro15 Avatar answered Feb 16 '26 05:02

patro15



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!