Computer Science, asked by mosam05, 1 year ago

java program to input the limit and print all the even and odd number up to the given limit​


amannishad0512p5zxh6: i is absolutely right

Answers

Answered by amannishad0512p5zxh6
1

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.


rakeshchennupati143: your program gets error you that?
amannishad0512p5zxh6: okk
amannishad0512p5zxh6: let me check
rakeshchennupati143: did you checked?
rakeshchennupati143: i know the error but try to know on your own
amannishad0512p5zxh6: I also know
Answered by rakeshchennupati143
1

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:

  1. First i initialized 2 strings even and odd
  2. i took input into a int variable "limit"
  3. then i started loop from behind
  4. and for every iteration i check whether the number is even or odd
  5. if even even string is over-written by that even number
  6. else odd string is over written by odd number
  7. 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   :)


amannishad0512p5zxh6: don't tell me how to answer
amannishad0512p5zxh6: You are beggar
amannishad0512p5zxh6: you beg.for batch
Similar questions