Thursday, January 28, 2016

JAVA ODD OR EVEN: Display Numbers in a Loop and Identify if Odd or Even

This example uses Java looping statement specifically the while loop but you can also use the different looping statements. The example below will display numbers from 1 to 15 and will use a conditional statement (if else) to identify if the number is odd or even.

Feel free to visit Odd or Even Code in PHP here.

Java Code

import java.util.Scanner; 
public class Square {

public static void main(String[] args) {

// solve for the area of a rectangle
int i=1;
int a = 15;
while (i<=a)
{
if (i%2==0)
System.out.printf("%d is an even number\n",i);
else
System.out.printf("%d is an odd number\n",i);
i++;
}
}
}

Refer to the previous article about the while loop for explanation on how to use it. I'll just jump into the conditional statement if which contains the condition wherein we get the remainder of the i. If the remainder is 0, then it will display even. Otherwise, it will display odd. Just add a line break which is the \n to insert new line after each value.

Output


















JAVA ODD OR EVEN: Display Numbers in a Loop and Identify if Odd or Even

JAVA ODD OR EVEN: Display Numbers in a Loop and Identify if Odd or Even Rating: 4.5 Diposkan Oleh: Emoblazz

0 comments:

Post a Comment