Infolinks

Breaking

Adsense

Thursday, January 28, 2016

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

PHP loops execute a block of code a specified number of times. There are four (4) types of loops in PHP. The for loop, foreach loop, do while loop and the while loop. In this tutorial, we will be focusing on the while loop which I often used in creating iterations to save code and memory space.

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 Odd or EVen

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 Odd or Even




















Thank you for visiting and hope this helps you. Feel free to leave a comment below for any questions. I got some other articles related to php and mysql here in my blog. Watch out for more upcoming tutorials related to blogging and programming. Good day! ^_^

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

No comments:

Post a Comment

Adbox