Thursday 23 June 2011

Java Program take no from user and print the sum of even and odd nos.

Open notepad or any text editor and type this code.

import java.io.*;

class sumeo
   {
     public static void main(String args[]) throws IOException
      {
        BufferedReader ob=new BufferedReader(new InputStreamReader(System.in));
        String a;
        System.out.print("Enter a No: ");
        a=ob.readLine();
        int b=Integer.parseInt(a);
            int even=0,odd=0;
        for(int i=1;i<=b;i++)
        {
                        int c=i%2;
            if(c==0)
                        {
                        even=even+i;
                        }       
                        else
                        {
                        odd=odd+i;
                        }
            }
         System.out.println("Sum of even nos. is:  "+even);
           System.out.println("Sum of odd nos. is:  "+odd);
  }
}



and save this file as sumeo.java in the bin directory (c:\j2sdk1.4.2\bin).

Now open command prompt and go to your Java directory.
Now compile your  program by typing  javac sumeo.java
Now the program will be compiled.
Now Run your program by typing  java sumeo
The output of the above program will be like this.





No comments:

Post a Comment