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
|
DO-WHILE
|
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
|
WHILE
|
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 do…while 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);
}
}
}
}
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
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+” “);
}
No comments:
Post a Comment