Search This Blog

Wednesday, December 29, 2010

ICSE BOARD QUESTION 2008 - program to input a string and print out the text with the uppercase and lowercase letters reversed , but all other characters should remain the same as before.

/**ICSE BOARD QUESTION 2008
 * Write a program to input a string and print out the text
 * with the uppercase and lowercase letters reversed ,
 * but all other characters should remain the
 * same as before.
 * EXAMPLE: INPUT:  WelComE TO School
 *          OUTPUT: wELcOMe to sCHOOL
 *
 */
import java.io.*;
public class questionFIVE2008
{
    public static void main(String args[]) throws IOException
    {
        int ch;
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        System.out.println("ENTER THE STRING ");
        String input=br.readLine();
        int len=input.length();
        int i;
        for(i=0; i<len; i++)
        {
            ch=input.charAt(i);
            if(ch>=65 && ch<=90)
            {
                ch=ch+32;
                System.out.print((char)ch);
            }
            else if(ch>=97 && ch<=122)
            {
                ch=ch-32;
                System.out.print((char)ch);
            }
            else
            {
                System.out.print((char)ch);
            }
        }
    }
}

OUTPUT:
ENTER THE STRING
WelComE TO School

wELcOMe to sCHOOL

FUNCTIONS BASED PROGRAM - void function & function with a return type

class aman
{
    public static void main(String args[])
    {
        func ob=new func();
        int ans=ob.sum(10,20); //function call
        System.out.println("the answer is = " +ans);
       
        ob.product(20,50);  //function call
       
       
    }
}
      

class func
{
    int sum(int a, int b)            //function with return type
    {
        int c=a+b;
        return c;
       
       
    }
    void product(int a, int b)     // function with no return type
    {
          int c=a*b;
          System.out.println("the product is = " +c);
    }
}

FUNCTIONS BASED PROGRAM - convert celcius into fahrenheit

class display
{
    public static void main(String args[])
    {
        temperature ob= new temperature();
        double temp=ob.convert(25.0);
        System.out.println("The temperature in fahrenheit is = "+temp);
    }
}
class temperature
{
    double convert(double celcius)
    {
        double far=1.8*celcius+32.0;
        return far;
    }
}

FUNCTIONS BASED PROGRAM - convert inches & feet into cm

class distance
{
    double distinches, distfeet;   
    void func(double inches, double feet)
    {
        distinches=inches;
        distfeet=feet;
    }
   
    void compute()
    {
        double cm;
        cm=2.54*distinches + 30.48*distfeet; //1 INCH=2.54 cm &1 feet=30.48 cm
       
        System.out.println("The total distance in centimetres is = " +cm);
    }
}
    

FUNCTIONS BASED PROGRAM

class a
{
    public static void main(String args[])
    {
        five ob1=new five();   //syntax: class_name objectname= new classname();
        five ob2= new five();
       
        ob1.func(100);
        ob2.func(300);
    }
}
class five
{
    void func(int mins)
    {
        int hours=mins/60;
        int minutes=mins%60;
       
        System.out.println("The time in hours and minutes is = " +hours + " hours and " +minutes + " minutes");
    }
}

OBJECTS AS PARAMETERS IN FUNCTIONS

public class time
{
    int hr, min;
    int totalhours, totalminutes;
    void input(int h, int m)
    {
        hr=h;
        min=m;
    }
    void addtime(time t1, time t2)
    {
        totalhours= t1.hr + t2.hr + (t1.min + t2.min)/60;
        totalminutes=(t1.min + t2.min)%60;
    }
   
    void display()
    {
        System.out.println(totalhours + " hrs " + totalminutes +" min " );  
    }
}

Monday, December 27, 2010

Define class employee with given data members & member methods - ICSE BOARD QUESTION 2008

/** Define a class employee   ICSE BOARD QUESTION 2008
 */
import java.io.*;
class questionFOUR2008
{
    public static void main(String args[]) throws IOException
    {
        employee ob=new employee();
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        System.out.println("Enter the PAN NUMBER");
        int pan=Integer.parseInt(br.readLine());
       
        System.out.println("Enter the NAME ");
        String name=br.readLine();
       
        System.out.println("Enter the TAX INCOME");
        double taxincome=Double.parseDouble(br.readLine());
       
       ob.input(pan, name, taxincome);
       ob.calc();
       ob.display();
    }
}
    


class employee  
{
    int pan;
    String name;
    double taxincome;
    double tax;
   
    void input(int p, String n, double ti)
    {
        pan=p;
        name=n;
        taxincome=ti;
    }
    void calc()
    {
        if(taxincome <= 100000)
        {
            tax =0;
        }
        else if(taxincome<=150000)
        {
            tax=(taxincome-100000)*0.10;
        }
        else if(taxincome<=250000)
        {
            tax=5000+(taxincome-150000)*0.20;
        }
       
        else
        {
            tax=25000+(taxincome-250000)*0.30;
        }
    }
    void display()
    {
        System.out.println("PAN NUMBER \t NAME \t TAX-INCOME \t TAX");
        System.out.println("===============================================");
        System.out.println(+pan +"\t" + name +"\t" + taxincome+"\t"+ tax);
    }
}


 OUTPUT:

Enter the PAN NUMBER
123456789
Enter the NAME
AMAN
Enter the TAX INCOME
300000


 
PAN NUMBER      NAME      TAX-INCOME      TAX
===============================================
123456789              AMAN         300000.0             40000.0

Define class salary with given data members & member methods - ICSE BOARD QUESTION 2007

/**
 * Define a class salary  - ICSE BOARD QUESTION 2007
 */ 
import java.io.*;   
class questionFOUR2007
{
    public static void main(String args[]) throws IOException
    {
        salary ob=new salary();
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
       
        System.out.println("Enter the NAME of the teacher ");
        String name=br.readLine();
       
        System.out.println("Enter the ADDRESS of the teacher ");
        String address=br.readLine();
       
        System.out.println("Enter the PHONE number");
        int phone=Integer.parseInt(br.readLine());
       
        System.out.println("Enter the SUBJECT SPECIALISATION ");
        String subject=br.readLine();
       
        System.out.println("Enter the monthly salary ");
        double salary=Double.parseDouble(br.readLine());
       
        ob.accept(name, address, phone, subject, salary);
        ob.compute();
        ob.display();
    }
}
class salary
{
    String name,address, subject;
    int phone;
    double salary;
    double tax=0.0;
    void accept(String n, String add, int ph, String sub, double sal)
    {
        name=n;
        address=add;
        phone=ph;
        subject= sub;
        salary=sal;
      
    }
    void compute()
    {
        double annualsalary=salary*12;  //annual salary
        tax=0.05*(annualsalary-175000);
    }
    void display()
    {
        System.out.println("NAME \t ADDRESS \t PHONE \t SUBJECT SPECIALISATION \t MONTHLY SALARY \t INCOME TAX ");
        System.out.println( name + "\t" + address + "\t" + phone + "\t" + subject + "\t" + salary + "\t" + tax);
    }
}
   
OUTPUT:
Enter the NAME of the teacher
AMAN
Enter the ADDRESS of the teacher
CHANDIGARH
Enter the PHONE number
98157
Enter the SUBJECT SPECIALISATION
MBA FINANCE
Enter the monthly salary
90000
NAME      ADDRESS      PHONE      SUBJECT SPECIALISATION    SALARY     INCOME TAX
AMAN    CHANDIGARH    98157    MBA FINANCE                           90000.0          45250.0

Saturday, December 25, 2010

Board questions : OUTPUT BASED 2 marks

class boards
{
    void outputbasedquestions()
    {
        int x=5;
        System.out.println(5*++x);  //ICSE 2005
        x=5;
        System.out.println(5*x++);  //ICSE 2005
       
        int m=5;
        int n=2;
        m-=n;
        System.out.println("m is = " +m);
        m=5;
       n=2;
        n=m+m/n;
        System.out.println("n is =" +n);
       
        int a=0, b=30, c=40;
        a=--b+c+ ++b;                    //ICSE 2006
        System.out.println("a = " +a);
       
       
        int val=500;
        int sum;
        n=550;
        sum=n+val>1750?400:200;    //ICSE 2006
        System.out.println("sum is =" +sum);
       
        val=1600;
        sum=n+val>1750?400:200;   //ICSE 2006
        System.out.println("sum is =" +sum);
       
        System.out.println("four:" +4+2);   // ICSE 2007
        System.out.println("four:" +(2+2)); //ICSE 2007
       
       
        a=2;
        b=3;
        c=9;
        int out=a-(b++)*(--c);                //ICSE 2007
        System.out.println("OUTPUT:"  +out); 
       
        a=2;
        b=3;
        c=9;
        out=a*(++b)%c;                         //ICSE 2007
        System.out.println("OUTPUT:"  +out);
       
               
    }
    void morequestions()
    {
        double x=-9.99;
        System.out.println(Math.abs(x));     //ICSE 2008
       
        x=9.0;
        System.out.println(Math.sqrt(x));    //ICSE 2008
       
       
       
    }
   
   
}


OUTPUT ON THE TERMINAL WINDOW:

30
25
m is = 3
n is =7
a = 99
sum is =200
sum is =400
four:42
four:4
OUTPUT:-22
OUTPUT:8

9.99
3.0

Friday, December 17, 2010

Nested Loops - to print a pattern

/*
 * Write a program to print the following pattern:


ABCDCBA
ABC   CBA
AB        BA
A             A      
AB        BA
ABC   CBA
ABCDCBA

 */
class aman
{
    void pattern(int n)
    {
        int j,i,k=0;
        int num=n;
        for(j=65+num;j>=65;j--)
        {
            for(i=65;i<j;i++)
            {
                System.out.print((char)i);
            }
            for(i=1;i<k;i++)
            {
                System.out.print(" ");
            }
            for(i=j-1;i>64;i--)
            {
                if(i!=65+num-1)
                {
                    System.out.print((char)i);
                }
            }
            k=k+2;
            if(j!=66)
            {
            System.out.print("\n");
        }
        }
        k=num-1;
        for(j=67;j<=65+num;j++)
        {
            for(i=65;i<j;i++)
            {
                System.out.print((char)i);
            }
            for(i=k;i>0;i--)
            {
                System.out.print(" ");
            }
            for(i=j-1;i>64;i--)
            {
               
                    if(i!=65+num-1)
                {
                    System.out.print((char)i);
                }
               
            }
            k=k-2;
            System.out.print("\n");
        }
   
   
    }
}

       
          

Thursday, December 16, 2010

Sorting of city names in alphabetical order using the Bubble Sort technique - ICSE BOARD QUESTION 2008

/**
 * Define a class and store the given city names in a single dimensional array. Sort these names in alphabetical order
 * using the Bubble Sort technique only.
 * INPUT: Delhi, Bangalore, Agra, Mumbai, Calcutta
 * OUTPUT: Agra, Bangalore, Calcutta, Delhi, Mumbai
 */
import java.io.*;
class question2008
{
    public static void main(String args[]) throws IOException
    {
        String words[]= {"Delhi", "Bangalore", "Agra", "Mumbai", "Calcutta"};
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));       
       
        int len=words.length;
        int i,j;
        String t;
       
        for(i=0; i<len-1; i++)
        {
            for(j=0; j<len-1-i; j++)
            {
                if(words[j].compareTo(words[j+1])>0)
                {
                    t=words[j+1];
                    words[j+1]=words[j];
                    words[j]=t;
                }
            }
        }
        System.out.println("The cities in alphabetical order are : ");
        for(i=0; i<len; i++)
        {
            System.out.print(words[i]+ " ");
        }
    }
}

Tuesday, December 14, 2010

Arrays based program - ICSE BOARD QUESTION 2009

/*
 * The annual examination results of 50 students in a class is tabulated as follows:
 * Roll no.         Subject A            Subject B           Subject C
 * ......           .......              .......             .......
 *
 * Write a program to read the data, calculate & display the following:
 * a) Average marks obtained by each student
 * b) Print the roll no. & average marks of the students whose average mark is above 80
 * c) Print the roll no & average marks of the students whose average marks is below 40
 */
import java.io.*;
public class questionNINE2009
{
    public static void main(String args[]) throws IOException
    {
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        int roll[]=new int[50];
        int marksA[]=new int[50];
        int marksB[]=new int[50];
        int marksC[]=new int[50];
        float avg[]=new float[50];
        int i,j;
        for(i=1; i<=50; i++)
        {
            System.out.println("Enter roll number of the student");
            roll[i]=Integer.parseInt(br.readLine());
            System.out.println("Enter marks of the student in Subject A");
            marksA[i]=Integer.parseInt(br.readLine());
            System.out.println("Enter marks of the student in Subject B");
            marksB[i]=Integer.parseInt(br.readLine());
            System.out.println("Enter marks of the student in Subject C");
            marksC[i]=Integer.parseInt(br.readLine());
           
            avg[i]=(marksA[i]+marksB[i]+marksC[i])/3;
        }
        System.out.println("----------------------------------RESULT----------------------------------------------");
        System.out.println("Roll no. \t Subject A \t Subject B \t Subject C \t Average ");
       
        for(j=1; j<=50; j++)
        {
       System.out.println(roll[j] +"\t \t" + marksA[j] +"\t \t" + marksB[j] +"\t \t" + marksC[j] +"\t \t" + avg[j] );
        }
       
        System.out.println("\n roll no. & average marks of the students whose average mark is above 80");
        System.out.println("Roll no. \t  Average ");
        for(j=1; j<=50; j++)
        {
           if(avg[j]>80)
            System.out.println(roll[j] +"\t \t" +  avg[j]);
            else
            System.out.println("N.A. \t \t   N.A.");
        }
       
        System.out.println("\n roll no. & average marks of the students whose average mark is below 40 ");
        System.out.println("Roll no. \t  Average ");
        for(j=1; j<=50; j++)
        {
           if(avg[j]<40)
            System.out.println(roll[j] +"\t \t" +  avg[j] );
            else
            System.out.println("N.A. \t \t   N.A.");
        }
           
    }
}

Menu driven program to accept a number from the user and check * whether it a BUZZ number or to accept any two numbers & print GCD of them - ICSE BOARD QUESTION 2009

/**
 * Write a menu driven program to accept a number from the user and check
 * whether it a BUZZ number or to accept any two numbers & print GCD of them.
 */
import java.io.*;
class questionEIGHT2009
{
    public static void main(String args[]) throws IOException
    {
        int i,j;
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        System.out.println("**************MENU*************");
        System.out.println("Type 1 to check if a number is a BUZZ number or not");
        System.out.println("Type 2 to print GCD of any two numbers");
       
        System.out.println("Enter your choice");
        int ch=Integer.parseInt(br.readLine());
       
        switch(ch)
        {
            case 1:
            System.out.println("Enter the number to check if it is buzz number or number");
            int n=Integer.parseInt(br.readLine());
           
            if(n%7==0 || n%10==7)
            {
                System.out.println("The number " +n+ " is a BUZZ number");
            }           
            else
            {
                System.out.println("The number " +n+ " is NOT a BUZZ number");
            }
            break;
           
            case 2:
            System.out.println("Enter any two numbers to print their GCD");
            int n1=Integer.parseInt(br.readLine());
            int n2=Integer.parseInt(br.readLine());
           
            int divisor, dividend;
            if(n1>n2)
            {
                dividend=n1;
                divisor=n2;
            }
            else
            {
                dividend=n2;
                divisor=n1;
            }
           
            int rem=1;
            while(rem!=0)
            {
                rem=dividend%divisor;
                if(rem==0)
                {
                    System.out.println("GCD is = " +divisor);
                }
                else
                {
                    dividend=divisor;
                    divisor=rem;
                }
            }
            break;
           
            default:
            System.out.println("Wrong choice");
        }
    }
}

Program to generate a triangle or an inverted triangle till n terms based upon the user's choice of triangle to be displayed - ICSE BOARD QUESTION 2009

/**
 * Write a program to generate a triangle or an inverted triangle
 * till n terms based upon the user's choice of triangle to be displayed.
 *
 * Example 1:
 * Input: Type 1 for a triangle and
 *        Type 2 for an inverted triangle
 *       
 *        1
 *        Enter the number of terms
 *        5
 *        OUTPUT:
 *        1
 *        2 2
 *        3 3 3
 *        4 4 4 4
 *        5 5 5 5 5
 *       
 */
import java.io.*;
class questionFIVE2009
{
    public static void main(String args[]) throws IOException
    {
        int i,j;
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        System.out.println("**************MENU*************");
        System.out.println("Type 1 for a triangle and ");
        System.out.println("Type 2 for an inverted triangle");
       
        int ch=Integer.parseInt(br.readLine());
        System.out.println("Enter the number of terms");
        int terms=Integer.parseInt(br.readLine());
       
        switch(ch)
        {
            case 1:          
            for(i=1; i<=terms; i++)
            {
                for(j=1; j<=i; j++)
                {
                    System.out.print(i);
                }
                System.out.println("");
            }
            break;
    
            case 2:
            for(i=terms; i>=1; i--)
            {
                for(j=1; j<=i; j++)
                {
                    System.out.print(i);
                }
                System.out.println("");
            }
            break;
           
            default:
            System.out.println("Wrong choice");
        }
    }
}

Function Overloading - ICSE BOARD QUESTION 2009

/**
 * Design a class to overload a function num_calc() as follows:
 *
 * void num_calc(int num, char ch) with one integer argument and one char
 * argument, computes the square of integer argument if choice ch is 's'
 * otherwise find its cube.
 *
 * void num_calc(int a, int b, char ch) with two integer arguments and
 * character argument. It computes the product of integer arguments if ch
 * is 'p' else adds the integers.
 *
 * void num_calc(String s1, String s2) with two string arguments, which
 * prints whether the strings are equal or not
 *
 */
public class questionSEVEN2009
{
   public void num_calc(int num, char ch)
   {
       if(ch=='s')
       {
           int square=num*num;
           System.out.println("The square of the number is = "+ square);
        }
        else
        {
            int cube=num*num*num;
            System.out.println("The cube of the number is =  "+ cube);
        }
    }
    public void num_calc(int a, int b, char ch)
   {
       if(ch=='p')
       {
           int product=a*b;
           System.out.println("The product of the two numbers is = "+ product);
        }
        else
        {
            int sum=a+b;
            System.out.println("The sum of the two number is = "+ sum);
        }
    }
    public void num_calc(String s1, String s2)
   {
       if(s1.equals(s2))
       {
           System.out.println("The two strings are equal");
        }
        else
        {
          System.out.println("The two strings are not equal"); 
        }
    }
}

Input a sentence & print the number of characters found in the longest word of the given sentence - ICSE Board Question 2009

/**
 * Write a program to input a sentence & print the number of characters
   found in the longest word of the given sentence.
   For example if S= "India is my country" then the output should be 7
 */
import java.io.*;
class questionSIX2009
{
    public static void main(String args[]) throws IOException
    {
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        System.out.println("Enter a sentence :");
        String s=br.readLine();
       
        char ch;
        s=s+" ";
        int array[]=new int[50];
        int lenword=0;
        int lenstr=s.length();
        int j=0;
       
        System.out.println("The string entered by you is: " +s);
        for(int i=0; i<lenstr; i++)
        {
            ch=s.charAt(i);
            if(ch!=' ')
            {
                lenword++;
               
                System.out.print(ch);
            }
           
            if(ch==' ')
            {
                array[j]=lenword;
                j++;
                System.out.println("   The size is " + lenword + "characters");
                lenword=0;
                System.out.print("\n");
            }
        }
         int m=0;
        for(j=0; j<lenstr; j++)
        {
            if(array[j]>m)
            {
                m=array[j];
            }
        }
        System.out.println("The length of the longest word is = " +m);
    }
   
}

Sunday, December 12, 2010

STRING - To enter a string & display all its words in reverse individually

import java.io.*;
class revwords
{
    public static void main(String args[]) throws IOException
    {
        BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
            System.out.println("Enter the string");
            String str=br.readLine();
            int i, a1, l,p,j;
            p=0;
            l=str.length();
            System.out.println("The original string is:    " +str);
            System.out.println("The string after reversing of words is : ");
            for(i=0; i<l; i++)
            {
                char a=str.charAt(i);
                a1=(int) a;
                if(a1==32||i==l-1)
                {
                    for(j=i; j>=p; j--)
                    {
                        char b=str.charAt(j);
                        System.out.print(b);
                    }
                    System.out.print(" ");
                    p=i;
                }
            }
    }
}     





OUTPUT:

Enter the string
yadavindra public school

The original string is:    yadavindra public school
The string after reversing of words is :
                                  ardnivaday  cilbup  loohcs 

BCD addition & subtraction - Menu based program (switch case) taking input from user

import java.io.*;
class bcd
{

    void m()throws IOException
    {
        char c; // used to store 'y' or 'n' for continuing or terminating the program
        do
        {

            BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

            System.out.println("\n \n *************** MENU ******************\n");

           
            System.out.println("Enter 1 to perform BCD Addition of Two Numbers\n ");
            System.out.println("Enter 2 to perform BCD Subtraction of Two Numbers\n");
            System.out.print(" Enter your choice : ");
            int y=Integer.parseInt(br.readLine());
            switch(y)

            {
               
                case 1: System.out.print("Enter First No. : ");
                int n=Integer.parseInt(br.readLine());
                System.out.print("Enter Second No. : ");
                int m=Integer.parseInt(br.readLine());

                int z = n+m;
               
                System.out.println(" \n\t\tBCD Addition : \n");
                disp(z);

                break;
           
                case 2: System.out.print("Enter First No. : ");
                int x=Integer.parseInt(br.readLine());
                System.out.print("Enter Second No. : ");
                int a=Integer.parseInt(br.readLine());

                int w = x-a;
               
                System.out.println(" \n\t\tBCD Subtraction : \n");
                disp(w);

                break;


                default : System.out.println("Invalid choice");
            } // closing of switch case
            System.out.print("\nDo you want to continue ? Press y/n :\t");
            c=(char)br.read();
        }
        while(c!='n'); // closing of do-while loop
    } // closing of m function
   
    void disp(int num) // method to display the results after BCD ADDITION & BCD SUBTRACTION
    {
        int x[]=new int[32]; // To represent 32 bits positive BCD numbers
        if(num>99999999 || num<0)
        {
            System.out.println("Number should only be of eight digits and it should be positive");
            return;
        }
        int rem,r;
        int y[]={0,0,0,0}; // array of size 4 taken to store a digit when converted into binary
        int z=0;

        System.out.print(num+" = ");
        while(num>0)
        {
            rem=num%10; //Extracting the digits from decimal number
            num=num/10;
            for(int i=0;i<4;i++)
            {
                r=rem%2; // Converting the extracted digit into Binary
                rem=rem/2;
                y[i]=r;
            }
            for(int j=0;j<4;j++)
            {
                x[z]=y[j];

                z++;
            }
        }

        for(int j=31;j>=0;j--)
        {
            System.out.print(x[j]);
            if(j%4==0)
                System.out.print(" ");
        } // closing of for loop

       
    } // closing of disp method

   
} // closing of class


 OUTPUT:


 *************** MENU ******************

Enter 1 to perform BCD Addition of Two Numbers

Enter 2 to perform BCD Subtraction of Two Numbers

 Enter your choice : 1
Enter First No. : 15
Enter Second No. : 1

        BCD Addition :

16 = 0000 0000 0000 0000 0000 0000 0001 0110
Do you want to continue ? Press y/n :    n

MENU BASED PROGRAM: SUM OF FACTORS OF A NUMBER, CHECK IF NO. IS PERFECT OR NOT - USING SWITCH CASE & TAKING INPUT FROM THE USER

import java.io.*;
class NumberProblems
{
    int SumOfFactors(int n)
    {
        int s=0;   //to store the sum of all the factors
        int i;
        for(i=1;i<n;i++)
        {
            if(n%i==0)
            {
                s=s+i;
            }
        }
        return s;
    }


    boolean isPerfect(int n)
    {
        int s=0;
        int i;
        for(i=1;i<n;i++)
        {
            if(n%i==0)
            {
                s=s+i;
            }
        }

        if(s==n)    //condition for checking whether the number is perfect or not
        {
            return true;
        }
        else
        {
            return false;
        }
    }
    void perfectNosBelow(int lim)
    {
        int n,i,s;
        for(n=1; n<lim; n++)
        {
            s=0;
            for(i=1;i<n;i++)
            {
                if(n%i==0)
                {
                    s=s+i;
                }
            }

            if(s==n)
            {
                System.out.print(n+"=(");
                for(i=1;i<n;i++)            //additional loop to print factors in the given format
                {
                    if(n%i==0)
                    {
                        System.out.print(i+", ");
                        if(i!=3)
                        {
                            System.out.print(",");
                          }
                    }
                }
                System.out.println(")"); //backspace
            }
        }
    }


    void m() throws IOException
    {
       
        System.out.println("***********************MENU***************************");
        System.out.println("Enter 1 to calculate sum of all the factors of a number");
        System.out.println("Enter 2 to check if a number is perfect or not");
        System.out.println("Enter 3 to find all perfect numbers below a limit");
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));   //required for taking input
        int ch=Integer.parseInt(br.readLine());
        switch(ch)
        {
           

        case 1:

        System.out.println("\n Enter the number for which you require the sum of all its factors \n");
        int num=Integer.parseInt(br.readLine());       
        int s=SumOfFactors(num);
        System.out.println("\n Sum of factors of " +num +" is = "+s);
        break;
       
        case 2:       
        System.out.println("\n Enter the number for which you need to check if it is perfect or not \n");
        int number=Integer.parseInt(br.readLine());
        boolean ans=isPerfect(number);
        if(ans==true)
        {   
            System.out.println("\n Number " +number+ " is perfect");
        }
        else
        {
            System.out.println("\n Number " +number+ " is not perfect");
        }
        break;
       
        case 3:

        System.out.println("\n Enter the limit below which you need to find all the perfect numbers \n");
        int limit=Integer.parseInt(br.readLine());
        perfectNosBelow(limit);
        break;
       
        default:
        System.out.println("Wrong choice");
}   
    }
}


Output:
***********************MENU***************************
Enter 1 to calculate sum of all the factors of a number
Enter 2 to check if a number is perfect or not
Enter 3 to find all perfect numbers below a limit
1

 Enter the number for which you require the sum of all its factors

6

 Sum of factors of 6 is = 6

INPUT A NUMBER FROM USER - CHECK EVEN OR ODD

import java.io.*;
class aman
{
    public void trial()throws IOException
    {
        InputStreamReader abc = new InputStreamReader(System.in);
        BufferedReader br = new BufferedReader(abc);
        int num;
       
            System.out.println("Enter Number");
            num = Integer.parseInt(br.readLine());
            if(num%2==0)
            {
            System.out.println("even");
            }
            else
            {
                System.out.println("odd");
            }
        }
    }

PARAMETERISED FUNCTION - sum

class aman
{
    public void sum(int a, int b)//parameterised function
    {
        float c=a+b;
        System.out.println("The sum of two numbers is = " +c);
    }
}

FUNCTIONS - simple : sum & product

class aman
{
    public void sum() //simple function
    {
        int a=10;
        int b=100;
        int c=a+b;
        System.out.println("The sum of two numbers is = " +c);
    }
    public void prod()
    {
        int m = 1987;
        int n = 4;
        int p = m*n;
       
        System.out.println("the product of 2 numbers = " +p);
    }
}

String functions with output- length, charAt, compareTo, equals, concat, indexOf, substring

class strings
{
    void str()
    {
        String name1="Aman";
        String name2="Tania";
        String name3="Aman";
        String name4="aman";
       
       
        System.out.println("length of "+ name1 + " is = " + name1.length());
        System.out.println("length of "+ name2 + " is = " + name2.length());
       
        System.out.println("character at 3 in "+ name1 + " is = " + name1.charAt(3));
       System.out.println("character at 4 in "+ name2 + " is = " + name2.charAt(4));
      
      
       System.out.println("comparison of the 2 names is  " + name1.compareTo(name2));
       System.out.println("comparison of the 2 names is  " + name2.compareTo(name1));
       System.out.println("comparison of the 2 names is  " + name3.compareTo(name1));
       System.out.println("comparison of the 2 names is  " + name4.compareTo(name1));
      
       System.out.println("equality comparison of the 2 names is  " + name2.equals(name1));
       System.out.println("equality comparison of the 2 names is  " + name3.equals(name1));
      
       System.out.println("concatenation of the 2 names is  " + name1.concat(name2));
       System.out.println("concatenation of the 2 names is  " + name1+name2);
      
       System.out.println("First occurence of 'a' in " + name2 + "is at index " + name2.indexOf('a'));
      
       System.out.println("Last occurence of 'a' in " + name2 + " is at index " + name2.lastIndexOf('a'));
       System.out.println("First occurence of 'x' in " + name2 + " is at index " + name2.indexOf('x'));
       System.out.println("Substring 1 onwards  in " + name2 + " is = " + name2.substring(1));
      
      
      
    }
}


Output:
length of Aman is = 4
length of Tania is = 5
character at 3 in Aman is = n
character at 4 in Tania is = a
comparison of the 2 names is  -19
comparison of the 2 names is  19
comparison of the 2 names is  0
comparison of the 2 names is  32
equality comparison of the 2 names is  false
equality comparison of the 2 names is  true
concatenation of the 2 names is  AmanTania
concatenation of the 2 names is  AmanTania
First occurence of 'a' in Taniais at index 1
Last occurence of 'a' in Tania is at index 4
First occurence of 'x' in Tania is at index -1
Substring 1 onwards  in Tania is = ania



Note:
if
System.out.println("character at 5 in "+ name1 + " is = " + name1.charAt(5));
is also added to the above program, it ll throw an error:

java.lang.StringIndexOutOfBoundsException: String index out of range: 5
    at java.lang.String.charAt(String.java:686)
    at strings.str(strings.java:16)

This is so because charAt(5) points to 5th character which is beyond the length of the string = 4

Saturday, December 11, 2010

Sample Java program II - Accept two numbers & print the greater one using if else

class aman
{
       public void greater(int a, int b)
      {
             if(a>b)
            {
                  System.out.println("The greater number is = " +a);
            }
            else if(b>a)
           {
                   System.out.println("The greater number is = " +b);
           }
           else
           {
                    System.out.println("Both are equal");
            }
     }
}

Sample Java program I- Addition of two numbers

class add
{
        public void sum(int a, int b)
        {
         int ans= a+b;
         System.out.println("The sum is = "+ans);
        }
}

// The above program is as per Blue J environment