java program to input the limit and print all the even and odd number up to the given limit
Answers
import java.util.*;
class Limit
{
public static void main ( )
{
Scanner sc=new Scanner (System.in);
int limit,i;
System.out.println("Enter the limit");
limit=sc.nextInt( );
System.out.println("Even number");
for(i=0;i<=limit;i++)
{
if(i%2==0)
System.out.print(i+" ");
}
System.out.println("Odd numbers");
for(i=0;i<=limit;i++)
{
if(i%2!=0)
System.out.print(i+" ");
}
}
}
I m first to answer,mark me brainlest.
And follow me for more java related doubts.
I am java lover and learner.
Program:
import java.io.*;
import java.util.*;
public class Main{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String even = "", odd = "";
System.out.println("Enter limit: ");
int limit = scan.nextInt();
for(int i=limit ; i>=0 ; i--){
if(i%2==0){
even = "["+i+"]"+even;
}else{
odd = "["+i+"]"+odd;
}
}
System.out.println("Even numbers upto "+limit+" are :"+even+"\nOdd numbers upto "+limit+" are :"+odd);
}
}
Ouput:
Enter limit:
20
Even numbers upto 20 are [0][2][4][6][8][10][12][14][16][18][20]
Odd numbers upto 20 are [1][3][5][7][9][11][13][15][17][19]
Explanation:
- First i initialized 2 strings even and odd
- i took input into a int variable "limit"
- then i started loop from behind
- and for every iteration i check whether the number is even or odd
- if even even string is over-written by that even number
- else odd string is over written by odd number
- after loop breaks i printed both the string in a single out statement
NOTE:
You are thinking why did u start loop in reverse,
i'll tell you why, for suppose if i started loop in normal way then my even and odd strings are over written by the recent value
for suppose recent even value is 12 then my string will start from 12
to override that problem i started reverse string
so now the recent value will be 0 then my string starts with 0 and it makes some sense.
----Hope this Helps you :)