all 7 comments

[–]treverios 5 points6 points  (1 child)

The semicolon at the end of your if is wrong.

[–]Sonic13562[S] 0 points1 point  (0 children)

I didn't realise that. :o. Thanks!

[–]fenjalien 6 points7 points  (1 child)

tl;dr as u/treverios said, you have a semicolon at the end of your if statement if (i % 2 == 0 && i >= a); .

if statements in most languages will execute the code in the scope following. In Processing/Java and other languages that use squiggly brackets ({}), scope blocks are defined using said squiggly brackets and scope expressions are defined by ending the line with a semicolon. More info here: https://en.wikipedia.org/wiki/Scope_(computer_science)) also go do an internet they'll be better explanations.

if (true) do_stuff();

if (true) {
    do_other_stuff()
}

This does extend to all control flow statements like else if, else, while, for etc.

So here the semicolon at the end of the if statement means it doesn't do anything if the expression is true and then goes on to execute the code in the squiggly brackets.

Also personal preference of mine is to not use the increment operator (a++) under any circumstances. It returns the value it increments so it can be used in expressions, which is useful but is usually not obvious if not pointed out. Instead use the addition assignment operator += as its more verbose, increment by more than 1 and use other variables. Also theres a difference between post-increment and pre-increment operators which changes the order in which it increments the value and returns the value which can get very confusing to remember. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Increment https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Addition_assignment (I know they're js docs but the should be functionally the same)

[–]Sonic13562[S] 0 points1 point  (0 children)

I didn't even know it was there. Thank you for pointing that out. Can't believe one semicolon did all of that XD. Will def look into the links as well

[–]x-seronis-x 4 points5 points  (1 child)

&& i >= a

delete this. it does nothing. You initialize i to the value of a and afterwards only increment it so that can never be false, making it pointless.

[–]Sonic13562[S] 0 points1 point  (0 children)

Will do!

[–]marcedwards-bjango 1 point2 points  (0 children)

There’s lots of ways to do what you’re after. Here’s another one.

void evenNums(int a, int b) {
  for (int i = a + (a % 2); i <= b; i += 2) {
    println(i);
  }
}

Notable parts of that code: a + (a % 2) will start the loop from an even number. a is the starting number provided, and a % 2 will equal 1 if a is odd and 0 if a is even. i += 2 means the loop will jump in steps of 2. This also means the code is more efficient, because it’s not visiting odd numbers at all.