Full Range

Call me (USA Free)

Monday 14 April 2014

Simple programs for beginner's

Leave a Comment

Q.Write a java program to add two numbers.

     public class  addNum
    {
        public void sum(int x,int y) // creates the instance of a class
       {
   
           int z=x+y;
           System.out.print(z);
       }
 
   }
 
  Q.Write a java program to subtract two numbers.

      public class Difference
       {
           public void diff(int x,int y)
            {
              int z=x-y;
              System.out.println("The difference between "+x+" and "+y+" is "+z);
            }
      }
 Q.Write a java program to check whether the entered number is prime or composite...
     
      import java.io.*;
     public class Prime
    {
         public static void main(String args[])throws Exception
          {
             BufferedReader stdin =new BufferedReader(new InputStreamReader(System.in));
             System.out.print("Enter the number: ");
             int n=Integer.parseInt(stdin.readLine());
             int flag=0;
              for(int i=2;i<n;i++) //used to get the vales less than the entered number in loop
               {
                   if(n%i==0) //checks if the number is divisble by i
                    {
                       flag=1;
                       break; //exits from the loop
                    }
       
               }
               if(flag==0)
               {
                  System.out.println(n+" is a prime number");
               }
             else
             {
                System.out.println(n+" is a composite number");
            }
    } //method
} //class

Q.Write a java program to reverse the entered number

    import java.io.*;
   public class Reverse
    {
        public static void main(String args[])throws Exception
        {
          BufferedReader stdin =new BufferedReader(new InputStreamReader(System.in));
          System.out.print("Enter the number: ");
          int n=Integer.parseInt(stdin.readLine());
          int nr=0;
         while(n>0) //loop used to reverse the number
         {
          nr=(nr*10)+(n%10); //(n%10):extracts the last digit of the number
          n=n/10;
         }
         System.out.print(nr);
      } //method
 } //class

If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment