Lets us write a program to check the number is odd and even using java program. so first, what are odd numbers? and what are even numbers? How to write the program.
CONTENT
- What are odd and even numbers?
- logic for the program.
- Program.
- Explanation.
- Output.
- Task.
What are odd numbers?
The numbers which are not divided by 2 or the numbers which has reminder 1, when it is divided by 2 are known as odd numbers
Example:
1,3,5,7,9...
What are even numbers?
The numbers which are divided by 2 or the numbers which has reminder 0, when it is divided by 2 are known as even numbers
Example:
2,4,6,8,10...
Logic for the program.
We have to ways to create program.
01. we are declaring a variable, that variable sound be divided (%) by 2 and that should be equated to 0, so if we have 0 as the reminder then the number is even else odd.
02. In the same way, we are declaring a variable, that variable sound be divided (%) by 2 and that should be equated to 1, so if we have 1 as the reminder then the number is odd else even.
Program to check the number is odd and even.
import java.io.*;
class odd
{
public static void main(String args[]) throws IOException
{
int n;
InputStreamReader read = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(read);
System.out.println("Enter the number");
n=Integer.parseInt(in.readLine());
if(n%2==0)
System.out.println(" n is even");
else
System.out.println(" n is odd");
}
}
Explanation:
- We have given the class name has odd.
- public static void main(String arg[]) refers to add a method i.e array of strong method to the program.
- int n is declaring the variable.
- InputStreamReader read = new InputStreamReader(System.in); we create this object because we need to give the value to variable at the time of execution, this is a one of the way to give value to a variable.
- BufferedReader in = new BufferedReader(read); we create this object because, we need a buffer to store the value of the variable.
- n=Integer.parseInt(in.readLine()) is used to convert array of numbers to primitive integer.
- Now, we have to give condition which satisfies all the above int the logic for the program.
- I choose, if statement to satisfy the condition.
- n%2==0 is the condition.
- System.out.println is used to display the given in output screen(make sure S in System is capital)
Know more about if statement here.
Output:
Compile : javac odd.java
Run : java odd
Enter the number
5
n is odd.
Compile : javac odd.java
Run : java odd
Enter the number
66
n is even.
known how to execute java program here.
Task:
I have did the program is the first way, try to do in the second way and share your answer below in the command.
Comments
Post a Comment