Tuesday, 28 July 2015

FUNCTION



 FUNCTION
Ques 1 what is function ?Write advantage of using function
Ans :- Functions are methods that contain codes to perform a specific task and returns values for further computation .
                        OR
Functions are the modules from which java programs are built. Modular code is easy to debug and maintain.
Function provides as
1.      Reusability of the code
2.      they hide low level details
3.      They make program easy to debug and maintain.
Ques 2- What are actual and formal parameters of a functions?
Ans :- Arguments are known as actual parameters. Parameters are the variables defined by a method that receives values known as formal parameters.
Actual parameter appears in function call where as formal parameters appears in function signature.
Ques 3:- What is the role of a return statement in a function?
Ans :-public int add(int n, int m)
            {
             return n+m;
            }
The return statement will send the sum of n and m to the calling body.
Ques 4:- What is the role of void keyword in declaring functions.
Ans :- a void keyword signifies that the method does not return any value to its caller.
Ques 5:- Give difference between call by value and call by reference.
Ans :- Call By Value:- this method copy the entire arguments passed to the function. It copies the value of an argument into the formal parameter of the subroutine. As a copy of the argument is being made and passed to the function, any changes made to the parameter inside the function do not effect the original argument.
Call By Reference:- When we pass a reference data type as argument to a function. It is called pass by reference.
Ques 6:-What is function overloading? 2006
Ans :- the process of having two or more methods or functions with in a class, with same name but different parameters declaration is known as function overloading.
Ques 7:- What is function signature?
Ans :- Parameter of the function along with function name. It is also known as function signature.
Ques 8- What is parameters?
Ans :- List of variable that recives the value of the arguments passed to the function when is  called. This can be empty is there are no parameters.
Ques 9;- what do you understand by early binding and static binding?
Ans :- the compiler at compile time knows the number and type of arguments. The compiler selects the appropriate function for a call at the compile time itself. This is known as early binding or static binding.
Ques 10- What is the role of static keyword in function prototype
Ans:- the keyword static signifies that function can be called without creating its object.
Ques 11:- What is ‘this’ keyword?
Ans :- ‘this’ is a reference to the object on which the function was invoked. In other word ‘this ‘ keyword is used to refer to the current object.
Ques 12. Give the difference between pure and impure function ?
Ans:- Pure :- These types of functions uses the object received for various process but do not changes the state of the object.
Impure:- this type of functions uses the object received for various processes as well as changes the state of the object.
 Quest 13. How does a function declaration different form a function call?
Ans:- Type specifier is mentioned in function declaration which is absent in function call.
Function declaration should not end with a semicolon but function statement should end with a semicolon.
Ques 14:- What is function prototype?
Ans :- A function prototype is and interface to the compiler. It is the first line of  the function definition that tells the program about the type of the value returned by the function and the number and type of parameters.
Ques 15:- What do you mean by the term “access specifier”?
Ans:- It means the type of access to the function .i.e. from where and how the function can be called.
Ques 16:- Name any two library function which implements function overloading? [2006]
Ans  :-  indexOf() and substring().
Ques 17 What are the condition which must satisfy to implement function overloading?
Ans:- To implement function overloading function signature must be different in either of three ways
i.                    Number of the arguments
ii.                  Data type of the arguments
iii.                Sequence of the arguments

Ques 18 Define an impure function. [2006]
 An impure function takes primitive data types or object as arguments and modifies the state of the received data or object .
Ques 19 Explain the function of return statement.                                                [2006]
There are two functions performed by the return statement.
i.                    It causes the termination of the execution of the function in which it is written.
ii.                  It may also return a value to the calling function.

POINT TO REMEMBER
  1. Functions are methods that contain codes to perform a specific task and returns values for further computation.
  2. Functions may be categorized as pure and impure functions.
  3. Pure functions, also called accessors, are used for getting data for an object.
  4. Accessors begin with term get to indicate that they receive values.
  5. Impure functions, also called mutators or updaters are used for changing the object’s state.
  6. Mutators usually begin with the term set to indicate that they reset the values of the object.
  7. Every function has a unique signature: its name, return type and a list of parameters.
8.      More than one function bearing same name with different parameters is called function overloading.
  1. Primitive variables store the values directly in the memory.
  2. Object variables also called reference variables store only the reference (value of the memory location).
  3. Values are passed though arguments to the function.
  4. When the values passed are of primitive type it is termed as pass-by-value.
  5. When the values passed are of class type it is called pass-by-reference.
  6. If a variable has no objects to refer to, it is called null reference.
15.  Inaccessible objects can be garbage collected in Java.
  1. Function, which has its parameter variable name same as that of class variables, the key word this is used to specify the current instant variable.
  2. Method this()can be useful for calling a constructor within another constructor.

Ques 1 write a program to display all prime number between 1 to 1000
class dispprime
{
static boolean isprime(int n)
{
int i;
for(i=2;i<n;i++)
{
if(n%i==0)
return false;
}
return true;
}
public static void main(String args[])
{
int num;
for(num=1;num<=1000;num++)
{
if(isprime(num))
System.out.println( num);
}
}
}
Ques 2 program to find sum of the series using function int fact(int);
X-X3/3!+X5/5!-X7/7!.................XN/N!
import java.util.*;
class seriessum
{
static int factorial(int x)
{
int i,fact=1;
for(i=1;i<=x;i++)
{
fact=fact*i;
}
return fact;
}
public static void main(String a[]) throws Exception
{
int x,n,f,sign,i;
double sum,term;
Scanner Sn=new Scanner(System.in));
System.out.println( "enter x and n");
x=Sn.nextInt();
n=Sn.nextInt();
sum=0.0;
sign=1;
for(i=1;i<=n;i=i+2)
{
f=factorial(i);
term =Math.pow(x,i)/f;
sum=sum+term*sign;
sign=sign*-1;
}
System.out.println( sum);
}
}
Ques 3-Write a menu driven program to find volume of a cube/cubiod/sphere using overloaded function                     [2008]
import java.util.*;
class overload
{
static int volume(int s)
{
return s*s*s;
}
static int volume(int l, int b,int h)
{
return l*b*h;
}
static double volume(double r)
{
return  4*3.14*r*r*r/3;
}
public static void main(String args[]) throws Exception
{
Scanner Sn=new Scanner(System.in));
int side,len,wid,hei,choice;
double red;
choice=1;
while(choice!=0)
{
System.out.println( "1 . volume of cube");
System.out.println( "2.  volume of cubiod ");
System.out.println( "3. volume of sphere");
System.out.println( "0. exit");
System.out.println( "enter your choice");
choice =Sn.nextInt();
switch(choice)
{
case 1: System.out.println( "enter side");
            side=Sn.nextInt();
            System.out.println( volume(side));
            break;
case 2 : System.out.println( " enter l,b,h");
             len=Sn.nextInt();
             wid=Sn.nextInt();
            hei=Sn.nextInt();
     System.out.println( volume(len,wid,hei));
            break;
case 3 :System.out.println( "enter radius");
      red=Sn.nextDouble()
      System.out.println( volume(red));
case 0 : break;
default:            System.out.println( "invalid input");
                        break;
}
}
}
}
PROGRAM FOR PRACTICE
Ques1 write a program to input principal, rate and time and calculate simple interest using function int simple_interest(int p,int r, int t) which calculates and returns simpleinterest.
Ques 2 write a program to input principal, rate and time and calculate compound  interest using function int compound_interest(int p,int r, int t) which calculates and returns compoundinterest.
Ques 3. Write a program to input two numbers and display maximum of two number using function . int max(int, int) which returns maximum out of 2 numbers.
Ques 4. Write a program to input two numbers and display maximum of three number using function . int max(int, int,int ) which returns maximum out of 3 numbers.
Ques 5 Write a program to input 2 number and display highest common factors. Using function int hcf(int,int) which returns highest common factor of 2 numbers.
Ques 6 A number is said to be perfect number if its sum of factors is equal to itself. write a program to input a number and display it is perfect number or not. Using function int sum_of_factor(int) which returns sum of factors of a number.
Ques 7 Write a program to number and display number of digits and sum of digit of the number using function    void number(int) calculates and display number of digit and sum of digit.
Ques 8 Create a class education and a function double calculate() with three parameters velocity u, time t and acceleration acc all of double types, find and return the value of ‘v’ from the following relation: where v=u+at
Write a main function to input value for ‘u’, ‘a’, ‘t’and by calling function calculate() print the value of u,a,t and v.
Ques 9 Create a class interchange and a function change(interchange s) which receives two strings by refrence. Interchange the strings stored in the object s.
Write a another function  to input two strings and interchange these strings by invoking function by reference. Print strings before and after interchange.          
Ques 10. Write a program to display all  palindrome number between 1 to 1000. Use the function int reverse(int n) which returns reverse of n..
Ques 11 Write a program to  display all prime numbers between 1 ti 1000 .  use the function int isprime(int n) which returns 1 if  n is prime number otherwise return 0. 
Ques 12 Write a program to find sum of prime number of an array of 20 elements. use the function int isprime(int n) which returns 1 if  n is prime number otherwise return 0. 
Ques 13 Write a program to display all twin prime number between 1 to 1000. Using isprime(). Twin prime numbers are consecutive odd prime number. as (1,3) , (11,13)
Ques 14 Write a program to store all non-prime numbers in an array of 25 elements. Using isprime().
Ques 15 Write a program to input a string and display the character stored at prime position. E.g Input :- INTERNATIONAL
Output:- I,N,T,R,A,N,L
Ques 16 Write a program to input a sentence and display number of vowels in it. Using int isvowel(char) return 1 of character supplied to it is vowel otherwise returns 0.
Ques 17 Write a program to input a sentence and count vowel pairs in it. Using int isvowel(char) return 1 of character supplied to it is vowel otherwise returns 0.
Ques 18 Create a function int GCD_FINDER(int m, int n) to find and return HCF/GCD of m and n, using subtraction method. Write a main function to input two numbers and prin their HCF.
Ques 19 Create a function int GCD_FINDER(int m, int n) to find and return HCF/GCD of m and n, using LONG DIVISION method. Write a main function to input two numbers and prin their HCF.
Ques 20 define following functions:
i.                    int cube(int x) to return the cube of integer z.
ii.      void Armstrong()- by invoking function cube() find and print  only Armstrong numbers between 50 to 300.
Write a program to print only Armstrong numbers from 100 to 500 by using above functions.
Ques 21.   Write a program  to print all perfec numbers between two limits entered by the user with the help of  following functions:
boolean isperfect(int num) to retrun ‘true’ if num is perfect, otherwise ‘false’
void showperfectnumbers(int start, int end) – to print all perfect numbers between sta and end limitby using function isperfect()
Ques 22:-  Design a class sample for the following function to print cash memo for  a product.
void product(): create this function wht product code(integer), unit price of product(int decimal) and quantity fo product(in decimal) as parameters. Calculate total cost of product discount as 12% on total cost and net price to be paid for the product.
Write a main function to invoke function product() by passing required values and print all the data members including total, discount and net price of product with suitable message.

Ques 23  create a class distance with function double distance() with three parameters u, time and acc all of double types, find and return the value of d from the following relation:
d=ut +1/2 a t2
Write a main function to input velocity (v) , time (t) and acceleration (a) and by invoking function distance() print the value of d,v,t and a.

Ques 24  Write a progam to define overloaded function sum()
void sum() which takes an array of 10 element as argument and returns sum of its elements
void sum() whick takes an array of 10 element and a character. If character is O the it returns sum of odd numbers if character is E the returns sum of even number otherwise return zero.
Ques 25   Write a progam to generate the sum of given series
            S= 1+x2/2! + x3/3! + x4/4!.........................xn/n!
Make use of user define function
power() which takes two integer argument x and n and returns x to the power n and
factorial() which takes an integer and returns factorial of the number.
Ques 26   Specify the class finder with the following overloaded function:
int findmax(int n1, int n2) – to decide and return largest from n1 ,n2. If both the numbers are same the return 0.
int findmax(int n1,int n2,int n3) –to decide and return largest from n1,n2,n3. If all the numbers are same then return 0.
Write main function to call above function depending upon user’s choice.

Question 27    int factorial(int x) returns the factorial of x
int power(int p,int q) calculates and returns p to the power q (without using pow().
Write a program to display the sum of given series.
Sum= X2/2! – X4/4! + X6/6!-X8/8! …………… XN/N!

Question 28 Design following functions:
Int fact(int q) – to find and return the factorial of q.
Void printnumber() by invoking function fact() find and print special numbers between 1 to 500.
[ if sum of factorial of each digits of a numbers is equal to the given number itself. Then the number is a special number.]

Ques 29 Create a function int countletters(Strings nam, char ch) – to get a string in nam and a character in ch . count and return the occurance of ch in nam if ch is present in nam otherwise return a value -1.
Write a main function to input a string and a character. Print occuremce of ch  in nam by invoking the function countletters()
Ques 30 Write a program to print all prime numbers between two numbers entered by the user with the help of following function:
Boolean isprime(int n) – to return
‘true’ if  n is prime, otherwise ‘false’
Void showprime(int s,int e) – to print all prime numbers between start(s) and end(e) limits by invoking function isprime(). Makes sure s<e otherwise print suitable message.

Ques 31 Write a java class that contains a method compound() and a main method. The 'compound' method computes the compound interest, based on the following conditions if time is less than or equal to 1 yr then r=3%, if time is between 1 and 2 yrs then r=5% and if time>2yr, r=7%.
The method returns the interest to main( ), where the result is displayed. Assume principal amount (P) and time (T) to be inputted from the console. The interest should be calculated for 10 investors.

Ques 32 Write a program using a function called area() to compute area of a
(i) circle (pi*r*r) where pi=3.14
(ii) square(side*side)
(iii) rectangle( length*breadth)
Display the menu to output the area as per User's Choice.                                         [2005]

Sunday, 17 May 2015

LOOPING

LOOPING
4.1 Basic element of Loop-there are three basic elements of the loop:-
Initializations , test expression, update expressions
Initialization are the statement which specify what should be the initial value of the variable which is been used to control the loop
Test expression is the condition which specifies that loop will continue or not.
Update expression is the statement which changes the value of the control variable as per requirement of the program.

4.2 Explain While statement
The while is a looping statement. Looping statements control execution of a series of other statements, causing  part of a program to execute repeatedly as long as a certain statement is met.
while(test expression)
{
 // program statement(s)
}

Ex1:-     num=1;
            while(num<=5)
            {
             System.out.print(num+”  “);
             num --
}
Output :- 1  2  3  4  5

Pragram 1.
 program to input a number and display factorial of it.
import java.util.*;
class check8
{
public static void main(String args[]) throws Exception
{
Scanner Sn=new Scanner(System.in));
int n,fact,i;
System.out.println(“enter a number”);
n=Sn.nextInt();
fact=1;
i=1;
while(i<=n)
{
fact=fact*i;
i=i+1;
}
System.out.println(“factorial of “+n+” is “+fact);
}
}
Pragram 2.
program to input a number and find its sum of digit, number of digit, reverse of number
import java.util.*;
class check7
{
public static void main(String args[]) throws Exception
{
Scanner Sn=new Scanner(System.in));
int dig,num,rev,len,sum,cp;
System.out.println(“enter a number”);
num=Sn.nextInt();
cp=num;
sum=0;
rev=0;
len=0;
while(cp!=0)
{
dig=cp%10;
sum=sum+dig;
len++;
rev=rev*10+dig;
cp=cp/10;
}
System.out.println(“length of number ”+len);
System.out.println(“sum of digits ”+sum);
System.out.println(“sum of digits ”+rev);
}
}

4.3 DO- WHILE STATEMENT:-
This loop is similar to the while loop except the test expression occurs at the bottom of the loop. this ensures that the body executes at least one time.
Syntax:-           do
                        {
                        Statement(s);
                        }while(test expression);
It will repeat statements given in the loop till condition given with it is true.
Exmple
int num=10;
do
{
System.out.println(num);
num--;
}while(num>=1);
This loop will print numbers from 10 to 1.

4.4 Explain the term the for loop  with an example [2005]
THE FOR LOOP:- The for loop is easy to use, normally we use for loop when number of times statements is to be repeated is known. The for loop has initialization, test expression, update statement at the beginning of the loop.
Syntax:-
            for(initialization;condition;increment)
            {
            Statement(s)
            }
In for loop all these three loop control statements are optional.
Example
            for(i=1;i<=10;i++)
            {
            System.out.println(i);
            }
it will display numbers from 1 to 10.

Example 2
            for(i=1,j=2;;i<=5;i++,j++)
            {
            System.out.print(i+”/”+j+”+”);
            }
            System.out.print(“\b”);
Above given loop will display
1/2+2/3+3/4+4/5+5/6

Example 3
            for(i=1;i<=10;i++);
            System.out.print(i);
It will display 11

Example 4
            for( ; ; )
            {
            System.out.println(“hello”);
}
It will display hello infinite times

4.5 EMPTY LOOP /TIME DELAY LOOP
The loop which do not have body with it is called empty loop this type of loop are used to give some interval before starting some process.
Example
for(i=1;i<=1000000;i++);
System.out.println(“computer “);
Here it will keep counting 1to 1000000 then display given message .

4.6  State one similarity and one difference between while loop and do while loop.                   [2005]
Similarity:- Both are looping statement they execute given statement till given condition is satisfied.
Difference:- While is an entry control loop. condition is checked first then body of the loop get executed. Do-while is exit control loop. Body of the loop executes first then condition is checked

4.7 Break: The break statement is used in many programming languages such as c, c++, java etc. Some times we need to exit from a loop before the completion of the loop then we use break statement and exit from the loop and loop is terminated. The break statement is used in while loop, do - while loop, for loop and also used in the switch statement.
Example
for(i=1;i<100;i++)
{
if(i%9==0)
break;
System.out.println(i)
}
It will display number from 1 to 8 as soon as i will become 9 loop will terminate.


4.8 Continue: The continue statement is used in many programming languages such as C, C++, java etc. Sometimes we do not need to execute some statements under the loop then we use the continue statement that stops the normal flow of the control and control returns to the loop without executing the statements written after the continue statement. There is the difference between break and continue statement that the break statement exit control from the loop but continue statement keeps continuity in loop without executing the statement written after the continue statement according to the conditions
Example
for(i=1;i<100;i++)
{
if(i%9==0)
continue;
System.out.println(i)
}
It will display number from 1 to 99 except numbers which are divisible be 9 because  as soon (i%9==0) condition will be true it will skip display statement.

4.9 RETURN STATEMENT: The return statement can be used to cause execution back to the caller to the method. Thus the return statement immediately terminates the method in which it is executed.


4.10  Explain break and continue statements. [2005] [2008]
break statement sends the control out of the loop. continue statement skips part of loop and goes for next iteration.
for(i=1;i<10;i++
{
if(i%2==0)
continue;
if(i==9)
break;
System.out.print(i);
}
in above example when i is even number then it will skip part of program and go for next iteration and when i is 9 it will terminate loop.
output will be 1357

4.11 DIFFERENCE BETWEEN WHILE AND DO-WHILE
WHILE LOOP
DO-WHILE LOOP
The while loop will not execute at all if the condition is not satisfied
The do while loop will execute at least once.

The while loop checks the condition first and then the execution begins
The do-while check the condition after executing the loop once

4.12 DIFFERENCE BETWEEN    FOR AND WHILE LOOP

FOR LOOP
WHILE LOOP
It is used when we know in advance how many repetitions are to be done
It is used when we do not know the number of repetitions are to be done.
The initialization, condition check and update is done at one line.
Here initialization, condition check and update is done at difference places.

Find and correct the errors in the following program segment:-                         [2006]
int n[]=(2,4,6,8,10);
for(int i=0;i<=5;i++)
System.out.println(“n[“+i+”]=”+n[i]);
The corrected program segment is:-
int n[]={2,4,6,8,10};
for(int i=0;i<5;i++)
System.out.println(“n[“+i+”]=”+n[i]);

Find the output of the following program segment, when:                                   [2006]
i)val=500
ii) val=1600
int val,sum,n=550;
sum=n+val>1750?400:200;
System.out.println(sum);
Output:- 200 for val =500
IMPORTANT  POINTS

ü  The statement within the block is executed one after the other. This type of structure is called sequential structure.

ü  Use of goto statement creates an unconditional jump within program.
ü  Control structure is used when tranfer of control takes place to the other part of the program depending on some conditon. 
ü  Java offers three selection statements: if, if...else and switch.
ü  While if statement checks only for the condition that evaluates true, if...else structure checks for both truth and falsity of a condition.
ü  The switch structure in Java consists of series of case keyword.
ü  Each of the case value must be a unique literal constant and not a variable.
ü  break statement  is used to skip out of switch structure.
ü  Switch structure is an efficient way of writing multiple if statements that contains only equality conditions of integral values.
ü  Repetitive statements in programming are called iteration or looping.
ü  In Java the looping statements for, while and do...while are used for performing iteration.
ü  Initialization part of the loop  contains assignment of value to a  control variable.
ü  Condition part of the loop is to test whether a boolean expression evaluates to true or false.
ü  Modification part is used for updating the initial value of the control variable.
In nested loops the iteration of innermost loop is done first and the Pragram 2.
ü  outermost at the end.
ü  For executing a statement or a block of codes repeatedly a specified number of times for loop is used.
ü  while and dowhile loops can be used where the number of iteration is not known before hand.
ü  break statement skips the rest of the statement of the body of the loop and exits the loop before the iteration is completed.
ü  continue statement forces to skip the rest of the statement of the body of the loop before the loop finishes the  iteration and passes control to execute the next  iteration of the loop.
ü  break and continue statements used with label can transfer control to any part of the program.
ü  When break and continue statements are used within nested loops the inner loop gets affected.

EXAMPLE PROARAMS
Program 3.
program to display first 10 terms of fabonacci series:-
0,1,1,2,3,5,8,13,21,34
class febo
{
public static void main(String args[])
{
int i,fn,sn,cu;
fn=0;
sn=1
System.out.print( fn+”\t”+sn+”\t”);
for(i=3;i<=10;i++)
{
cu=fn+sn;
System.out.print( cu+”\t”);
fn=sn;
sn=cu;
}
}
}


Program 4.
 program to input a number and display it is prime or not.
import java.util.*;
class checkprime
{
public static void main(String args[]) throws Exception
{
Scanner Sn=new Scanner(System.in));
int num,i,ctr;
ctr=0;
System.out.println( “enter a number”);
num=Sn.nextInt();
for(i=1;i<=num;i++)
{
if(num%i==0)
ctr++;
}
if (ctr<=2)
System.out.println( num+”is prime);
else
System.out.println( num+”is not prime);
}
}

Program 5
program to check a number is Armstrong or not
import java.util.*;
class armstrong
{
public static void main(String args[]) throws Exception
{
Scanner Sn=new Scanner(System.in));
int num,sum,i,dig;
System.out.println( “enter a number”);
num=Sn.nextInt();
sum=0;
for(i=num;i!=0;i=i/10)
{
dig-i%10;
sum=sum+dig*dig*dig;
}
if(sum==num)
System.out.println( num+”is Armstrong”);
else
System.out.println( num+”is not Armstrong “);
}
}
Program 6
program to input Two numbers and display highest common factors of the numbers using long division method.
import java.util.*;
class high
{
public static void main(String args[]) throws Exception
{
Scanner Sn=new Scanner(System.in));
int a,b,x,y,r;

System.out.println( “enter two number”);
a=Sn.nextInt();
b=Sn.nextInt();
if(a<b)
{
x=a;
y=b;
}
else
{
x=b;
y=a;
}
while(true)
{
r=y%x;
if(r==0)
break;
y=x;
x=r;
}
System.out.println(“hcf of “+a+” and “+b+              ” is    “+x);
}
}
Program 7
 program to input Two numbers and display highest common factors of the numbers using long division method.
import java.util.*;
class high
{
public static void main(String args[]) throws Exception
{
Scanner Sn=new Scanner(System.in));
int a,b,h;
System.out.println( “enter two number”);
a=Sn.nextInt();
b=Sn.nextInt();
for(i=1;i<=a;i++)
{
if(a%i==0 && b%i==0)
h=i;
}
System.out.println(“hcf of “+a+” and “+b+              ” is    “+h);
}
}
Program 8
program to input Two numbers and display Least common Mutiple(LCM) of the numbers using long division method.
import java.util.*;
class high
{
public static void main(String args[]) throws Exception
{
Scanner Sn=new Scanner(System.in));
int a,b,lcm;
System.out.println( “enter two number”);
a=Sn.nextInt();
b=Sn.nextInt();
lcm=a;
while(lcm%b!=0)
{
lcm=lcm+a;
}
System.out.println(“lcm of “+a+” and “+b+              ” is    “+lcm);
}
}
Program 9
program to input numbers till the users choice find sum of even, odd numbers.
import java.util.*;
class user
{
public static void main(String args[]) throws Exception
{
Scanner Sn=new Scanner(System.in));
int num,ev=0,od=0
char ch=’y’;
while(ch==’y’ || ch==’Y’)
{
num=Sn.nextInt();
if(num%2==0)
ev=ev+num;
else
od=od+num;
System.out.println( “press y to continue”);
ch=Sn.next().charAt(0);
}
System.out.println( “sum of even”+ev);
System.out.println( “sum of odd”+od);
}
}
Program 10
Program to display prime number between 1 to 50
public class Break{
public static void main(String[] args){
int i,j;
System.out.println("Prime numbers between 1 to 50 : ");
for (i = 1;i < 50;i++ ){
for (j = 2;j < i;j++ ){
if(i % j == 0)
{
break;
}
}
if(i == j)
{
System.out.print(" " + i);
}
}
}
}
//output
 The Prime number in between 1 - 50 :
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47
Program 11

 menu driven program to input a number and display is perfect or not , palindrome or not.
import java.util.*;
class menu
{
public static void main(String args[]) throws Exception
{
Scanner Sn=new Scanner(System.in));
int num,i,dig,rev,sum,choice=1;
while(choice!=0)
{
System.out.println( “1 . perfect number”);
System.out.println( “2. palindrome number”);
System.out.println( “0. exit”);
System.out.println( “enter your choice”);
choice =Sn.nextInt();
switch(choice)
{
case 1: System.out.println( “enter a number”);
            num=Sn.nextInt();
            sum=0;
           
for(i=1;i<num;i++)
{
if(num%i==0)
sum=sum+i;
}
if (sum==num)
System.out.println(num+” is perfect no.”);
else
System.out.println(num+” is not perfect no.”);
 Break;
case 2: System.out.println( “enter a number”);
            num=Sn.nextInt();
            rev=0;
            for(i=num;i!=0;i=i/10)
            {
            dig=i%10;
            rev=rev*10+dig;
            }
            if(rev==num)
System.out.println( num+” is palindrome”);
else
System.out.println( num+” is not palindrome”);
            break;
case 0  : break;
default: System.out.println( “invalid option”);
            break;
}
}
}
}
Program 12

 menu driven program convert temperature from Fahrenheit to Celsius and Celsius to Fahrenheit [2007]
import java.util.*;
class menu
{
public static void main(String args[]) throws Exception
{
Scanner Sn=new Scanner(System.in));
int choice=1;
double cel,fah;
while(choice!=0)
{
System.out.println( “1 . Fahrenheit to Celsius”);
System.out.println( “2. Celsius to Fahrenheit”);
System.out.println( “0. exit”);
System.out.println( “enter your choice”);
choice =Sn.nextInt();
switch(choice)
{
case 1: System.out.println( “enter temp in       Fahrenheit”);
       feh=Sn.nextDouble()
cel=(feh-32)*5/9;
System.out.println(cel+” celsius”);
break;
case 2: System.out.println( “enter temp in       Celsius”);
       cel=Sn.nextDouble()
feh=(feh*9/5)+32;
System.out.println(feh+“Fahrenheit”);
 break;

case 0  : break;
default: System.out.println( “invalid option”);
            break;
}
}
}

Program 13
 program to find sum to given series using menu driven program
1+(1+2)/(1*2)+(1+2+3)/(1*2*3)+…….n terms
X+X2/3!+X3/3!+X4/4!..........................XN/N!
import java.util.*;
class menu
{
public static void main(String args[]) throws Exception
{
Scanner Sn=new Scanner(System.in));
int X,N,choice.i,p,q,f;
double sum,term;
while(choice!=0)
{
System.out.println( “1 . Series 1”);
System.out.println( “2. Series 2”);
System.out.println( “0. exit”);
System.out.println( “enter your choice”);
choice =Sn.nextInt();
switch(choice)
{
case 1: System.out.println( “enter a number”);
            n=Sn.nextInt();
            p=0;     q=1; sum=0.0;
for(i=1;i<=n;i++)
            {
            p=p + i ;
            q=q * i;
            sum=sum+ p/q;
            }
            System.out.println( “sum =”+sum);
            break;
case 2 : System.out.println( “enter x and n”);
            x=Sn.nextInt();
            n=Sn.nextInt();
            f=1; sum=0.0;
            for(i=1;i<=n,i++)
            {
            f=f* i;
            term=Math.pow(x,i)/f;
            sum=sum+term;
            }
            System.out.println(sum);
            break;
case 0: break;
default: System.out.println( “invalid choice”);
             break;
}
}
}
}
Program 14

 program to display given pattern
            55555
54444
            54333
            54322
            54321
class pattern
{
public static void main(String args[])
{
int x,y,z;         
for(x=5;x>=1;x--)
{
for(y=5;y>=x;y--)
System.out.print( y);
for(z=1;z<x;z++)
System.out.print(x);
System.out.println( );
}
}}
Program 15

//program to display  given pattern
             1
           212
         32123    
       4321234
     543212345
class pattern
{
public static void main(String args[])
{
int x,y,z,sp,s;  
for(i=1,sp=4;i<=5;i++,sp--)
{
  for(s=1;s<=sp;s++)
            System.out.print(“ “);
 for( y=i;y>=1;y++)
            System.out.print( y);
 for(z=2;z<=i;z++)
            System.out.print( z);
System.out.println( );
}
}}

Program 16

Write a program to print the sum of negative number, sum of positive even and sum of positive odd number from a list of number(N) entered by the user. the list is terminates when the user enter a zero.                               [2005]
import java.util.*;
class check
{
public static void main(String args[]) throws Exception
{
buffer
int n,sn=0,se=0,so=0;
for(;;)
{
System.out.println"enter a number 0 to stop");
n=Sn.nextInt();
if(n==0)
break;
if(n<0)
sn+=n;
else if(n %2==0)
se+=n;
else
so+=n;
}
           
System.out.println("sum of negative\t"+sn);
System.out.println("sum of positive even\t"+se);
System.out.println("sum of positive odd\t"+so);
}
}
Program 17

Write a program to calculate and print the sum of odd numbers and the sum of even numbers for the first n natural numbers.[2006]
The integer n is to be entered by the user.
import java.util.*;
class prog1
{
public static void main(String args[]) throws Exception
{
Scanner Sn=new Scanner(System.in));
int even=0,odd=0,i,n;
System.out.println(“Enter a number”);
n=Sn.nextInt();
for(i=1;i<=n;i++)
{
if(i%2==0)
   even=even+i;
else
      odd=odd+i;
}
System.out.println(“Sum of Even “+even);
System.out.println(“Sum of Odd “+odd);
}
}
}
Program 18

Write a program that outputs the results of the following evaluations based on number entered by the       [2006]
User:-
i.                    Natural Logarithm of the number.
ii.                  Absolute value of the number.
iii.                Square root of the number.
iv.                Random numbers between 0 and 1.
import java.util.*;
class menu
{
public static void main(String args[]) throws Exception
{
Scanner Sn=new Scanner(System.in));
int choice=1,n;
double cel,fah;
while(choice!=0)
{
System.out.println( “1 Natural Logarithm of the number.”);
System.out.println( “2. Absolute value of the number”);
System.out.println( “3. Square root of the number”);
System.out.println( “4. Random numbers between 0 and 1”);
System.out.println( “0. exit”);
System.out.println( “enter your choice”);
choice =Sn.nextInt();
switch(choice)
{
case 1: System.out.println( “Enter a number”);
            n =Sn.nextInt();
System.out.println(“Natural Logarithm =\t”+Math.log(n));
break;
case 2: System.out.println( “Enter a number”);
            n =Sn.nextInt();
System.out.println(“Absolute value =\t”+Math.abs(n));
break;
case 3: System.out.println( “Enter a number”);
            n =Sn.nextInt();
System.out.println(“Square Root =\t”+Math.sqrt(n));
break;
case 4: System.out.println(“Random Number =”+Math.random());
            break;
case 0  : break;
default: System.out.println( “invalid option”);
}
}
}
}


Program 19:- . Write a program to calculate and print the sum of each of the following series
Sum(S)= 2-4+6-8+……..20
Sum(S)= x/2+x/5+x/8+x/11….. +x/20
(value of x to be input by the user.) [2008]

import java.io.*;
class  abc
{
public static void main(String[] args) throws Exception
            {
DataInputStream d=new DataInputStream(System.in);
            int x,s,i;
                        s=0;
            for(i=2;i<=20;i=i+2)
            {
                        if(i%4==0)
                        s=s-i;
                        else
                        s=s+i;
            }
System.out.println("Sum is series 1 is "+s);
System.out.println("Enter a number");
x=Integer.parseInt(d.readLine());
double sum=0.0;
for(i=2;i<=20;i=i+3)
{
sum=sum+(double)x/i;
}
System.out.println("Sum is series 2 is "+sum);
}
}
Program 20:- Write a menu driven program to accept a number form the user and check whether it is a palindrome or a perfect number.
Palindrome number:- a number is a palindrome which when read in reverse order is same as read in the right order. E.g 11,101,151 etc.
Perfect number:- a number is called perfect if it is equal to the sum of its factors other than the number itself. E.g – 6=1+2+3

import java.util.*;
class menu
{
public static void main(String[] args)throws Exception
            {
Scanner Sn=new Scanner(System.in));
int ch=1,i,num=0,r;
while(ch!=0)
{
System.out.println("1. Palindrome number\n2. Perfect number");
System.out.println("0. exit\n Enter your choice");
ch=Sn.nextInt();
if(ch==1 || ch==2)
{
System.out.println("Enter a number");
            num=Sn.nextInt();
}
switch(ch)
{
case 1  :           r=0;    
                        for(i=num;i!=0;i=i/10)
                        r=r*10+i%10;
                        if(r==num)
            System.out.println("Palindrome");
                        else
            System.out.println("Not Palindrome");
                        break;
case 2:             r=0;
                        for(i=1;i<num;i++)
                        {
                        if(num%i==0)
                        r=r+i;
                        }
                        if(r==num)
                        System.out.println("Perfect no");
                        else
            System.out.println("Not perfect");
                        break;
case 0:             break;

default: System.out.println("invalid option");
            break;
}
}
}
}

Ques Convert the following segment into equivalent for loop.                             [2008]
            int i=1;
            while(i<=20)
            {
            System.out.println(i+" ");
            i++;
            }
Ans;- int i;
            for(i=1;i<=20;i++)
            {
              System.out.println(i+” “);

            }