0% found this document useful (0 votes)
6 views

Chapter 8

Chapter 8 covers iterative constructs in Java, including multiple choice questions and explanations of different types of loops such as for, while, and do-while loops. It discusses the characteristics of entry-controlled and exit-controlled loops, as well as the use of break and continue statements. The chapter also includes examples and exercises to illustrate the concepts of loop inter-conversion and the differences between various loop types.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Chapter 8

Chapter 8 covers iterative constructs in Java, including multiple choice questions and explanations of different types of loops such as for, while, and do-while loops. It discusses the characteristics of entry-controlled and exit-controlled loops, as well as the use of break and continue statements. The chapter also includes examples and exercises to illustrate the concepts of loop inter-conversion and the differences between various loop types.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 83

******************************************************************************

******************************************************************************

Chapter 8

******************************************************************************

******************************************************************************

Iterative Constructs in Java

I. Multiple choice questions

Tick the correct answer:

1. When the statements are repeated sequentially a number of times in a program, the construct is
known as:

a) iteration b) sequence

c) selection d) none

2. Which of the following statement is exit controlled loop?

a) for b) while

c) do-while d) if-else

3. Which of the following loop does not execute even once if the condition is false in the beginning?

a) do-while b) while

c) for d) nested loop

4. To execute a loop 10 times, which of the following statement satisfies:


a) for(i=6;i<=26;i=i+2) b) for(i=3;i<=30;i=i+3)

c) for(i=0;i<10;i=i++) d) all of the above

5. Which of the following statement uses multiple branches?

a) loop b) continue

c) switch d) break

6. Which of the following loop checks the condition first and then execution begins?

a) do-while b) do

c) while loop d) for

7. To find the sum of whole numbers upto 10, a loop runs:

a) once b) ten times

c) eleven times d) any number of times

8. How many times the loop, for(i=1; ;i++), will execute, if there is no statement to terminate the
loop?

a) 1 b) 0

c) infinite d) none

9. Which of the following cases uses a case called default?


a) do-while b) while

c) switch d) all of the above

10. A loop statement is given as:

for(i=10; i<10;i++)

Statement

For how many times will the given loop statement be executed:

a) never b) 1 time

c) 10 times d) infinite

Ans.

1. a) iteration

2. c) do-while

3. options b,c and d do not execute even once if the condition if false but option a will execute
atleast once even if the condition is false.

4. b) for(i=3;i<=30;i=i+3)
5. c) switch

6. c) while loop

7. b) ten times

8. c) infinite

9. c) switch

10. a) never

II. Answer the following questions:

1. What do you understand by iterative process? How can it be resolved by using loop?

Ans. Iterative process is a process in which a set of instructions are performed repeatedly till the
condition is satisfied. The programming constructs used for this purpose are known as loops. Once
the control enters the loop, it executes the statements within the loop repeatedly till the condition
becomes false. When the condition becomes false, the control skips and moves to execute the rest
of the program.

2. Explain for loop with an example.

A ‘for’ loop usually has a loop variable. A ‘for’ loop has three parts. They are as follows:

For example, consider the for loop shown below:

for(int p=1; p<4; p++)

{
System.out.print(“Test message”);

System.out.print(p);

System.out.println();

Working of the loop:

The above loop is executed for with an initial value p=1 and ‘Test message1’is printed.

Then the body of the loop is executed again when p=2 and ‘Test message2’ is printed.

Later the loop is executed once again when p=3 and ‘Test message3’ is printed.

Finally, when p=4, the condition becomes false and the control breaks out of the loop. [That is, the
body of the loop is not executed for p=4.]

3. Name the different types of loop statements.

The different type of loop statements used in Java are :

for loop

while loop

do while loop

4. What are the parameters needed to create a for loop?

Ans. A loop must have a condition which results in a boolean value and a loop variable with an initial
value and an update value. Sometime Loops like while(true) which do not involve loop variables
must have a condition within the body of the loop followed by a break statement to terminate the
loop.

5. Define the following with their constructs:


a) Entry controlled loop b) Exit controlled loop

a) Entry controlled loop

In this looping structure, a condition is checked at the beginning of the loop module. If the given
condition is true then the control will enter the loop for execution. The process is repeated under
the condition is false. Since the testing of the condition takes place at the entry point of the loop, it is
termed as ‘Entry Controlled Loop’. Example : for loop, while loop.

Construct of while loop

while(<condition>)

//statements in the body of the loop

Construct of for loop

for(initial value; test condition; update)

b) Exit controlled loop

In this structure, the condition is tested at the end of the looping construct. If the condition is true,
then the control is sent back to the beginning of the loop for the next iteration. As soon as the
condition is false, the control exits the loop. Since the condition is tested at the exit point of the
loop, it is said to be an ‘Exit Controlled Loop’. In this type of loop, even if the condition is false for the
first time, the control will enter the loop at least once. Example: do-while loop.

Construct of do-while loop

do

//statements in the body of the loop

}while(condition);

6. Write down the general format of:

a) for loop b) do-while c) while loop

Ans.

Looping Construct General Format

for loopfor(initial value; test condition; update) { }

do while do { }while(<condition>);

while loop while(<condition>) { }

7. What is the purpose of using

a) break statement

b) continue statement in a program

break
The break statement is used for unusual termination of a block.

This means that as soon as the break statement is executed, the control will come out of the block
by ignoring the rest of the statements of the block and the remaining iterations of the loop.

Sometimes the desired result may be obtained even before the loop has finished all the iterations. In
such a situation, we can use break to terminate the loop.

The break statement is also used in a switch-case block to terminate a case and to avoid ‘fall
through’.

Example

for (i=1; i<=10; i++)

if(i= =5)

break;

System.out.println( );

The above snippet prints the numbers from 1 to 4. When i=5 the break statement is executed and
hence the control comes out of the loop.

continue

When the continue statement is executed, it forces the control to skip the rest of the statements in
the current iteration and continue with the next iteration of the loop.

Example:

for(i=1; i<=10; i++)


{

if(i= =5)

continue;

System.out.println(i);

The above snippet prints all the numbers from 1 to 10 except 5 because of the continue statement.

8. What do you understand by inter-conversion of loops?

Ans. While writing a program, the programmer always has the flexibility to convert one type of loop
to another type of loop based on the programmer’s convenience and requirement.

9. What are the different ways to inter-convert the loops? Name them.

Ans. The various inter-conversion of loops that can be done are given below:

for loop to while loop

for loop to do while loop

while loop to for loop

while loop to do while loop

do while loop to while loop

do while loop to for loop

10. Define the following:

a) Finite loop
b) Delay loop

c) Infinite loop

d) Null loop

Ans.

a) Finite loop : When the statements run for a fixed number of times then the iteration is called as a
‘finite loop’. It can be further categorised as continuous loop and step loop.

Example:

int k=1;

while(k<=5)

System.out.println(k);

k++;

b) Delay loop or Null loop : A loop that does not include any statement to be repeated, is known as
Null loop. Basically, a null loop is used to create a delay in the execution. This can be done to pause
the control (or create a time delay) as needed by the user during programming. The body of the
delay loop does not contain any meaningful operation to perform.

Example:

for(int j=5 ; j<=500 ;j++)

c) Infinite loop: A loop which is executed endlessly is known as ‘Infinite Loop’. This type of loop never
comes to an end. Such ‘Infinite Loops’ are created when there are missing parameters . It may be a
missing condition or it may be a condition which never becomes false.
Example 1:

for(m=1; ;m<=10; )

In the above loop, since the update expression is missing, the condition always evaluates to true and
hence results in an ‘Infinite Loop’.

Example 2:

while(true)

In the above loop, the condition is always true. If there is no break statement in the body of the
loop, this loop becomes an infinite loop.

Example 3:

for (int j=5; j<=10; j–)

In the above loop, due to an incorrect logic the loop is executed endlessly. In this case, suppose if the
update expression was j++ instead of

j- -, the loop would have terminated after five iterations.


d) Null loop – repeated – refer to Question 10 b (Delay loop or Null loop)

11. Distinguish between:

a) for and while loop

for loop:

The for loop is a finite loop which can be used when the number of iterations is fixed.

The initialization of the loop variable and the update expression can be done in the ‘for statement’
itself.

while loop:

The while loop can be used when the number of iterations is fixed as well as unfixed. During an
unfixed iteration, the user may not be aware of the number of iterations during the process.

The initialization and the update expression cannot be given in the while statement. The initialization
must be done before the control enters the loop module and the update expression must be given in
the body of the loop.

b) while and do-while loop

while loop:

A while loop is an entry-controlled loop in which the condition is checked before the control starts
executing the body of the loop.

If the condition is false, the statements within the body of the loop are not executed.

Example:

int p=20;

while(p >0)

{
p = p/2;

System.out.println(p);

The above loop is executed for two iterations i.e. p=20 and p=10

do-while loop:

A do-while loop is an exit-controlled loop in which the condition is checked after executing the body
of the loop.

Even if the condition is false the statements in the body of the loop are executed at least once.

Example:

int p=20;

do

p = p/2;

System.out.println(p);

} while(p >100);

The above loop is executed once for p=20 although the condition p>100 is not satisfied. This is
because the condition was checked at the exit point of the loop.

12. State one difference and one similarity between while and do-while loop?
Difference:

A while loop is a entry-controlled loop in which the condition is checked before the control starts
executing the body of the loop. If the condition is false, the statements within the body of the loop
are not executed.

A do-while loop is an exit-controlled loop in which the condition is checked after executing the body
of the loop. So, even if the condition is false the statements in the body of the loop are executed at
least once.

Similarity:

Both the loops check a logical condition and only when the condition is false, the loop is terminated.

Both the loops are used for repetitive actions.

13. State one similarity and one difference between while and for loop.

Similarity : Both the ‘for’ loop as well as the ‘while ‘ loop are entry controlled or entry restricted
loops because the condition is checked before entering the loop. Only when the condition is true,
the loop is executed. Suppose if the condition is false, the control is transferred to the statement
after the looping construct.

Difference : The for loop is a finite loop which can be used when the number of iterations are fixed

The while loop can be used in both cases i.e. whether the number of iterations are known
or unknown (fixed or unfixed iterations).

14. Give two differences between Step loop and Continuous loop.

When the statements run for a fixed number of times then the iteration is called as a ‘infinite loop’.
It can be further categorised into continuous loop and step loop.

Step loop:

It is a loop in which the loop variable or the control variable is updated (increased or decreased) by a
given value, other than one after each iteration.
Example:

for(int m=1; m<=10;m=m+2)

Continous loop:

It is a loop in which the loop variable or the control variable is updated (increased or decreased) by
one after each iteration.

Example:

for(int m=1; m<=10;m++)

III. Predict the output of the following programs:

1.

class dk1

public static void main(String args[])

int i;
for(i= -1;i<10; i++)

System.out.println(++ i);

}}}

Ans:

Since the print statement also has increment operation (prefix increment operation) the value of ‘i’
is incremented twice. There the output is as follows:

10

2.

class dk2

{
public static void main(String args[])

int i=2, k=1;

while( ++i < 6)

k *=i;

System.out.println(k);

}}

Ans:

Though the i=2 in the beginning during the condition, its value is incremented by 1. So the loop runs
for 3<6, 4<6, 5<6 and therefore the value of k=3*4*5=60. Therefore the output is 60.

3.

class dk3

public static void main(String args[])

int m=2,n=15;
for(int i=1;i<=5;i++)

m++;

–n;

System.out.println(“m=” +m);

System.out.println(“n=”+n);

}}}

Ans:

The initial value of m=2 and n=15. During every iteration the value of ‘m’ is increased by 1 and
printed. Likewise, the value of ‘n’ is decreased and then printed. Since there are 5 iterations (i=1 to
5) , ‘m’ value gets printed as m=3,m=4,m=5,m=6,m=7. Likewise, ‘n’ value gets printed as n=14, n=13,
n=12, n=11, n=10. Hence the output is as follows:

m=3

n=14

m=4

n=13

m=5
n=12

m=6

n=11

m=7

n=10

4. Determine how many times the body of the loop will be executed.

class dk4

public static void main(String args[])

int x=5, y=50;

while( x<=y)

y=y/x;

System.out.println(y);

}}}
Ans. The loop is executed twice.

First iteration

5<=50 condition is true

y= y/x = 50/5 =10. So, the current value of y=10.

Second iteration

5<=10 condition is true

y=y/x=10/5=2. So, the current value of y=2.

Third iteration

5<=2 condition is false. So the control doesn’t enter the body of the loop and the loop terminates.

Hence the output is as follows:

10

IV. Rewrite the following programs:

1. Using do while:

class Test
{

public static void main(String args[])

int x,c;

for(x=10,c=20; c>=10;c=c-2)

x++;

System.out.println(x);

}}}

Ans.

class Test

public static void main(String args[])

int x=10 ,c=20;

do
{

x++;

System.out.println(x);

c=c-2;

}while (c>=10);

}}

2. Using do while:

class Pattern

public static void main(String args[])

int i,j;

for(i=5;i>=1;i –)

System.out.print(i);
}

System.out.println( );

}}

Ans.

class Pattern

public static void main(String args[])

int i=5,j;

do

System.out.print(i);

i–;

}while(i>=1);

System.out.println( );

}}
3. Using do while

class Number

public static void main(String args[])

int i,n=191,c=0;

for(i=1;i<=n;i++)

if(n%i==0)

c=c+1;

if(c==2)

System.out.println(“Prime”);

else

System.out.println(“Not Prime”);
}}

Ans.

class Number

public static void main(String args[])

int i=1,n=191,c=0;

do

if(n%i==0)

c=c+1;

i++;

}while(i<=n);

if(c==2)

System.out.println(“Prime”);

else
System.out.println(“Not Prime”);

}}

4. Using while loop:

import java.io.*;

class Sample

public static void main(String args[]) throws IOException

int n,r;

InputStreamReader read=new InputStreamReader(System.in);

BufferedReader in=new BufferedReader(read);

System.out.println(“Enter a number”);

n=Integer.parseInt(in.readLine( ));

do

{
r=n%10;

n=n/10;

System.out.println(r );

while(n!=0);

}}

Ans.

import java.io.*;

class Sample

public static void main(String args[]) throws IOException

int n,r;

InputStreamReader read=new InputStreamReader(System.in);

BufferedReader in=new BufferedReader(read);

System.out.println(“Enter a number”);
n=Integer.parseInt(in.readLine( ));

while(n!=0)

r=n%10;

n=n/10;

System.out.println(r );

}}

V. Unsolved Java Programs

1) Write the programs in Java to display the first ten terms of the following series:

1, 4, 9, 16………………

1, 2, 4, 7, 11,……………

3, 6, 9, 12………………

4, 8, 16, 32……………..

1.5, 3.0, 4.5, 6.0………..

0, 7, 26…………………

1, 9, 25, 49……………..

4, 16, 36, 64……………

0, 3, 8, 15………………

24, 99, 224, 399………..


2, 5, 10, 17……………..

Solution:
a)

//1,4,9,16……

class Q1

{static void series1()

for(int i=1;i<=10;i++)

System.out.println(i*i);

}}

b)

//1,2,4,7,11…….

class Q1

{static void series2()

{int x=1;

for(int i=1;i<=10;i++ )

{System.out.println(x);
x=x+i;

}}

c)

//3,6,9,12…..

class Q1

{static void series3()

for(int i=1;i<=10;i++ )

System.out.println(i*3);

}}

d)

//4,8,16,32

class Q1

{static void series4()


{int i=2;

for(int p=1;p<=10;p++ )

{i=i*2;

System.out.println(i); }

}}

e)

//1.5,3.0,4.5,6.0……

class Q1

{static void series5()

for(int j=1;j<=10;j++)

System.out.println(j*1.5);

}}

f)

//0,7,26…..

class Q1
{static void series6()

for(int p=1;p<=10;p++ )

System.out.println((int)Math.pow(p,3)-1);

}}

g)

//1,9,25,49

class Q1

{static void series7()

for(int p=1;p<=19;p=p+2)

System.out.println(p*p);

}}

h)

//4,16,36,64….
class Q1

{static void series8()

for(int p=2;p<=20;p=p+2)

System.out.println(p*p);

}}

i)

//0,3,8,15…

class Q1

{static void series11()

for(int p=1;p<=10;p++)

System.out.println(p*p-1);

}}

j)

//24,99,224,399,………..
class Q1

{static void series10()

for(int p=5;p<=50;p=p+5 )

System.out.println(p*p-1);

}}

k)

//2,5,10,17,…..

class Q1

{static void series11()

for(int p=1;p<=10;p++)

System.out.println(p*p+1);

}}

2) Write a program to input any 50 numbers (including positive and negative). Perform the following
tasks:
a) Count the positive numbers

b) Count the negative numbers

c) Sum of positive numbers

d) Sum of negative numbers

Solution:

Import java.util.*;

class Q2

static void main()

Scanner sc=new Scanner (System.in);

int x, p=0,n=0,sumpos=0,sumneg=0,count=0;

System.out.println(“Enter 50 numbers positive or negative”);

while(++count<=50)

x=sc.nextInt();

if(x>0)

p++;

sumpos+=x;

else if(x<0)

n++;

sumneg+=x;
}

System.out.println(“Number of positive numbers=”+p);

System.out.println(“Number of negative numbers=”+n);

System.out.println(“Sum of positive numbers=”+sumpos);

System.out.println(“Sum of negative numbers=”+sumneg);

3) Write a program to calculate the sum of all odd numbers and even numbers between a range of
numbers from m to n (both inclusive) where m<n. Input m and n (where m<n).

Solution:

Import java.util.*;

class Q3

static void main()

Scanner sn=new Scanner(System.in);

int m,n,even=0,odd=0;

System.out.println(“Enter the starting value of the range”);

m=sn.nextInt();

System.out.println(“Enter the ending value of the range”);

n=sn.nextInt();

while(m<=n)

if(m%2==0)

even+=m;

else

odd+=m;

m++;

}
System.out.println(“Sum of even numbers=”+even);

System.out.println(“Sum of odd numbers=”+odd);

4) Write a program to enter any 50 numbers and check whether they are divisible by 5 or not. If
divisible then perform the following tasks:

a) Display all the numbers ending with the digit 5.

b) Count those numbers ending with 0 (zero).

Solution:

import java.util.*;

class Q4

static void main()

Scanner ob=new Scanner(System.in);

int i=0,n,count=0;

String s=””;

System.out.println(“Enter 50 numbers”);

while(++i<=50)

n=ob.nextInt();

if(n%5==0)

if(n%10==5)

s=s+”\t”+n;

else if(n%10==0)

count++;

System.out.println(“The numbers ending with 5 are :”+s);


System.out.println(“The count of numbers ending with zero is :”+count);

5) Write a program to display all the numbers between m and n input from the keyboard (where
m<n, m>0, n>0) check and print the numbers that are perfect square. E.g. 25, 36,49……..are said to
be perfect square numbers.

Solution:

import java.util.*;

class Q5

static void main()

Scanner ob=new Scanner(System.in);

int m,n;

String s=””;

System.out.println(“Enter the first value of the range”);

m=ob.nextInt();

System.out.println(“Enter the last value of the range”);

n=ob.nextInt();

if(m>0 && n>0)

while(m<n)

if(m==(int)Math.sqrt(m)*(int)Math.sqrt(m))

s=s+”\n”+m;

m++;

System.out.println(“The perfect square numbers are :”+s);

}
6) Write a program to display all the ‘Buzz Numbers’ between p and q (where p<q). A ‘Buzz Number’
is the number which ends with 7 or is divisible by 7.

Solution:

import java.util.*;

class Q6

static void main()

Scanner ob=new Scanner(System.in);

int p,q;

String s=””;

System.out.println(“Enter the first value of the range”);

p=ob.nextInt();

System.out.println(“Enter the last value of the range”);

q=ob.nextInt();

while(p<q)

if(p%10==7 || p%7==0)

s=s+”\n”+p;

p++;

System.out.println(“The Buzz numbers are :”+s);

7) Write a program to input marks in English, Maths and Science of 40 students who have passed
ICSE Examination 2014. Now, perform the following tasks:

a) Number of students, who have secured 95% or more in all the subjects.

b) Number of students, who have secured 90% or more in English, Maths and Science.
Solution:

import java.util.*;

class Q7

static void main()

Scanner sn=new Scanner(System.in);

int n=0,eng,math,sci,x=0,y=0;

while(++n<=40)

System.out.println(“Enter the marks for 1.Eng 2.Math 3.Science”);

eng=sn.nextInt();

math=sn.nextInt();

sci=sn.nextInt();

if(eng>=95 && math>=95 && sci>=95)

x++;

else if(eng>=90 && math>=90 && sci>=90)

y++;

System.out.println(“Number of students who got more than 95 is:”+x);

System.out.println(“Number of students who got more than 90 is:”+y);

8) Write a program in Java to find the sum of the given series:

1+4+9+……………………………..400

1+ 1/2+ 1/3 +…………………….1/20

1+ 1/3 + 1/5……………………..1/19

1/2 +2/3 +3/4+…………………19/20

2 – 4 + 6 – 8 +……………………-20

(1*2) +(2*3)+……………………(19*20)
Solution:

//1+4+9+……400

class Q8

static void main()

Scanner sn=new Scanner(System.in);

int sum=0;

for(int j=1;j<=20;j++)

sum+=j*j;

System.out.println(“Sum of the series=”+sum);

//1+ 1/2+ 1/3 +…….1/20

import java.util.*;

class Q8

static void main()

Scanner sn=new Scanner(System.in);

double sum=0;

for(int p=1;p<=20;p++)

sum+=1.0/p;

System.out.println(“Sum of the series=”+sum);

//1+ 1/3 + 1/5…….1/19

import java.util.*;

class Q8

static void main()


{

Scanner sn=new Scanner(System.in);

double sum=0;

for(int p=1;p<=19;p=p+2)

sum+=1.0/p;

System.out.println(“Sum of the series=”+sum);

//1/2 +2/3 +3/4+……19/20

import java.util.*;

class Q9

static void main()

Scanner sn=new Scanner(System.in);

double term,sum=0;

for(int p=1;p<=19;p++)

term=p/(p+1.0);

sum+=term;

System.out.println(“Sum of the series=”+sum);

//2-4+6-8+…….-20

import java.util.*;

class Q8

static void main()

Scanner sn=new Scanner(System.in);


int sum=0;

for(int i=2;i<=20;i=i+2)

if(i%4==0)

sum-=i;

else

sum+=i;

System.out.println(“Sum of the series=”+sum);

//(1*2) +(2*3)+……..(19*20)

import java.util.*;

class Q8

static void main()

Scanner sn=new Scanner(System.in);

int sum=0;

for(int p=1;p<=19;p++)

sum+=p*(p+1);

System.out.println(“Sum of the series=”+sum);

9) Write a program to input a number and count the number of digits. The program checks whether
the number contains odd number of digits or even number of digits.

Sample Input: 749

Sample Output: Number of digits =3

The number contains odd number of digits.


Solution:

import java.util.*;

class Q9 {

static void main()

Scanner sn=new Scanner(System.in);

System.out.println(“Enter a number”);

int n,y=0;

n=sn.nextInt();

while(n>0)

{y++; //y represents number of digits

n=n/10;

System.out.println(“Number of digits=”+y);

if(y%2==0)

System.out.println(“Even number of digits”);


else

System.out.println(“Odd number of digits”);

}}

10) Write a program to input a number and display the new number after reversing the digits of the
original number. The program also displays the absolute difference the original number and the
reversed number.

Sample Input: 194

Sample Output: 491

Absolute difference = 297

Solution:

import java.util.*;

class Q10 {

static void main()

Scanner sn=new Scanner(System.in);

System.out.println(“Enter a number”);

int n,n1,n2,y=0,rev=0;
double d;

n=sn.nextInt();

n1=n2=n;;

while(n>0)

{y++;

n=n/10;

while(n1>0)

{ d=n1%10;

d=d*Math.pow(10,–y);

rev+=d;

n1=n1/10;

System.out.println(“The reversed number is :”+rev);

System.out.println(“The absolute difference is:”+Math.abs(n2-rev));


}}

11) The Greatest Common Divisor (GCD) of two integers is calculated by the continued division
method. Divide the larger number by the smaller, the remainder then divides the previous divisor.
The process repeats unless the remainder reaches zero. The last divisor results in GCD.
[ICSE 2009]

Sample Input : 45, 20

Sample Output: GCD=5

Solution:

import java.util.*;

class Q11 {

static void main()

Scanner sn=new Scanner(System.in);

int a,b,a1,b1,c=0;

System.out.println(“GCD of two numbers”);

System.out.println(“Enter the two numbers”);

a1=sn.nextInt();

b1=sn.nextInt();
a=Math.max(a1,b1);

b=Math.min(a1,b1);

while(true)

System.out.println(“***New iteration”);//OPTIONAL

c=a%b;

a=b;

System.out.println(“a=”+a);//OPTIONAL

b=c;

System.out.println(“b=”+b);//OPTIONAL

if(a%b==0)break;

System.out.println(“HCF=”+c);

}}

12) Write a program in Java to find the sum of the given series:
S=a2 + a2/2 + a2/3 + …………….+ a2/10

S= a1 + a2/2 + a3/3 + …………….+ a10/10

S=(a*2) + (a*3) +…………………+ (a*20)

S= a1 + a2 + a3 + ………………….+ an

S= 1 + 22/a + 33/a2 + …………….to n terms

S= 12/a + 32/a2 + 52/a3…………… to n terms

S=1/a + 1/a2 + 1/a3 + ……………+ 1/an

S=x/2 + x/5 + x/8 + x/11…………+ x/20 [ICSE 2008]

Solution:

a)

// S=a2 + a2/2 + a2/3 + …………….+ a2/10

class Q12a {

static void main(double a)

{double term,sum=0;

for(int i=1;i<=10;i++)

{term=a*a/i;

sum+=term;

System.out.println(“Sum=”+sum);

}}
// S= a1 + a2/2 + a3/3 + …………….+ a10/10

class Q12b {

static void main(double a)

{double term,sum=0;

for(int i=1;i<=10;i++)

{term=Math.pow(a,i)/i;

sum+=term;

System.out.println(“Sum=”+sum);

}}

// S=(a*2) + (a*3) +…………………+ (a*20)

class Q12c {

static void main(double a)

{double term,sum=0;

for(int i=2;i<=20;i++)
{term=a*i;

sum+=term;

System.out.println(“Sum=”+sum);

}}

// S= a1 + a2 + a3 + ………………….+ an

import java.util.*;

class Q12d {

static void main()

{Scanner sn=new Scanner(System.in);

int a,n;

double sum=0;

System.out.println(“Enter the value of a”);

a=sn.nextInt();

System.out.println(“Enter the value of n ie (power of the last term)”);

n=sn.nextInt();
for(int i=1;i<=n;i++)

sum+=Math.pow(a,i);

System.out.println(“Sum=”+sum);

}}

//S= 1 + 22/a + 33/a2 + …………….to n terms

import java.util.*;

class Q12e {

static void main()

{Scanner sn=new Scanner(System.in);

int a,n;

double sum=0,term;

System.out.println(“Enter the value of a”);

a=sn.nextInt();

System.out.println(“Enter the number of terms”);

n=sn.nextInt();
for(int i=1;i<=n;i++)

{term=Math.pow(i,i)/Math.pow(a,(i-1));

sum+=term;

System.out.println(“Sum=”+sum);

}}

S= 12/a + 32/a2 + 52/a3…………… to n terms

import java.util.*;

class Q12f {

static void main()

{Scanner sn=new Scanner(System.in);

int a,n;

double sum=0,term;

System.out.println(“Enter the value of a”);

a=sn.nextInt();

System.out.println(“Enter the number of terms”);


n=sn.nextInt();

for(int i=1,x=1;x<=n;i=i+2,x++)

{term=Math.pow(i,2)/Math.pow(a,x);

sum+=term;

System.out.println(“Sum=”+sum);

}}

// S=1/a + 1/a2 + 1/a3 + ……………+ 1/an

import java.util.*;

class Q12g {

static void main()

{Scanner sn=new Scanner(System.in);

int a,n;

double sum=0;

System.out.println(“Enter the value of a”);


a=sn.nextInt();

System.out.println(“Enter the value of n ie (power of the last term)”);

n=sn.nextInt();

for(int i=1;i<=n;i++)

sum+=1.0/Math.pow(a,i);

System.out.println(“Sum=”+sum);

}}

// S=x/2 + x/5 + x/8 + x/11…………+ x/20

import java.util.*;

class Q12h {

static void main()

{Scanner sn=new Scanner(System.in);

int x;

double sum=0;

System.out.println(“Enter the value of x”);

x=sn.nextInt();
for(double i=2.0;i<=20;i=i+3)

sum+=x/i;

System.out.println(“Sum=”+sum);

}}

13) In order to reach the top of pole, a monkey in his first attempt reaches to a height of 5 feet and
in the subsequent jumps, he slips down by 2% of the height attained in the previous jump. The
process repeats and finally the monkey reaches the top of the pole. Write a program to input the
height of the pole. Write a program to input height of the pole. Calculate and display the number of
attempts the monkey makes to reach the top of the pole.

Solution:

import java.util.*;

class Q13

{static void monkeyJump()

{Scanner sn=new Scanner(System.in);

double ht,x,y,cnt=0,sum=0;

System.out.println(“Enter the height of the pole”);

ht=sn.nextDouble();

x=5;
while(sum<ht)

{y=98/100.0 * x;

sum+=y;

System.out.println(sum); //OPTIONAL

x=y;

cnt++;

System.out.println(“\n\n”+sum); //OPTIONAL

System.out.println(“No.of attempts made by the monkey”+cnt);

}}

14) Write a program to input Principal (P), Rate (R ) and Time (T).Calculate and display the amount,
which is compounded annually for each year by using the formula:

Simple Interest (si)=prt/100;

p=p+si;

[Hint : The amount after each year is the Principal for the next year.]

Solution:
import java.util.*;

class Q14 {

static void main()

Scanner sn=new Scanner(System.in);

double p,r,t,si,amt=0;

System.out.println(“Enter the principal \n rate\n time”);

p=sn.nextDouble();

r=sn.nextDouble();

t=sn.nextDouble();

for(int i=1;i<=t;i++)

{si=p*r*t/100.0;

amt=p+si;

p=amt; //This year’s amount is next year’s principal

}
System.out.println(“The amount after “+t+”years =”+amt);

}}

15) Write a menu driven program to input two positive numbers m and n (when m>n) and perform
the following tasks:

a) Find the sum of two numbers without using ‘+’ operator

b) Find the product of two numbers without using ‘*’ operator

c) Find the quotient and remainder of two numbers without using ‘/’ and ‘%’ operator.

[Hint: The last value obtained after each subtraction is the remainder and the number of iterations
results in quotient.]

Sample Input: m=5, n=2

5-2=3

3-2=1, thus quotient =2 and remainder=1

Solution:

import java.util.*;

class Q15 {

static void main()

{
Scanner sn=new Scanner(System.in);

int m,n,p=0,sum=0,cnt=0,i;

System.out.println(“MENU”);

System.out.println(“1. Sum of two numbers”);

System.out.println(“2. Product of two numbers”);

System.out.println(“3. Quotient and remainder”);

System.out.println(“Enter your choice 1/2/3”);

int choice=sn.nextInt();

System.out.println(“Enter the value of m”);

m=sn.nextInt();

System.out.println(“Enter the value of n”);

n=sn.nextInt();

if(m>0 && n>0 && m>n)

switch(choice)

{
case 1: //Addition by repeated increment

sum=m;

for(i=1;i<=n;i++)

sum++;

System.out.println(“Sum=”+sum);

break;

case 2: //Multiplication by repeated addition

for(i=1;i<=n;i++)

p+=m;

System.out.println(“Product=”+p);

break;

case 3: //Division by repeated subtraction

for(i=m;i>0;i=i-n)

{if(i-n<0)

break;
cnt++;

System.out.println(“Quotient=”+cnt);

System.out.println(“Remainder=”+i);

break;

default: System.out.println(“Invalid choice”);

} //end of switch block

} //end of if statement

else

System.out.println(“Enter 2 positive numbers such that first number>second number”);

}}

16) Write a Menu Driven class to accept a number from the user and check whether it is a
Palindrome or a Perfect number.

a) Palindrome number – (A number is a Palindrome which when read in reverse order is the same as
in the right order.)

b) Perfect Number – (A number is called Perfect if it is equal to the sum of its factors other than the
number itself.)

Example : 6 =1+2+3
Solution:

import java.util.*;

class Q16

static void check()

Scanner sn=new Scanner(System.in);

int n,n1,d,rev=0,sum=0,var;

System.out.println(“**MENU**”);

System.out.println(“Enter 1 for Palindrome number, 2 for perfect number”);

var=sn.nextInt();

System.out.println(“Enter the number”);

n=sn.nextInt();

n1=n;

switch(var)
{case 1: //PALINDROME NUMBER

while(n>0)

d=n%10;

rev=rev*10+d;

n=n/10;

if(n1==rev)

System.out.println(“It is a Palindrome number”);

else

System.out.println(“Not a Palindrome number”);

break;

case 2: //PERFECT NUMBER

for(int j=1;j<n1;j++)

if(n1%j==0)
sum+=j;

if(n1==sum)

System.out.println(“It is a Perfect number”);

else

System.out.println(“Not a Perfect number”);

break;

default:System.out.println(“Invalid choice”);

}}

17) Write a Menu Driven program to accept a number from the user and check whether it is a Prime
number or an Automorphic number.

a) Prime number – A number is said to be Prime if it is only divisible by 1 and itself.

b) Automorphic number – An Automorphic number is the number which is contained in the last
digit(s) of its square.

Example: 25 is an automorphic number as its square is 625 and 25 is present in the last digit(s) of its
square.
Solution:

import java.util.*;

class Q17

static void check()

Scanner sn=new Scanner(System.in);

int var,n,cnt=0,p;

boolean flag=true;

System.out.println(“**MENU**”);

System.out.println(“1.Prime number”);

System.out.println(“2.Automorphic number”);

System.out.println(“Enter your choice 1 or 2”);

var=sn.nextInt();

System.out.println(“Enter the number”);

n=sn.nextInt();
switch(var)

{case 1: //PRIME NUMBER

for(int i=1;i<=n/2;i++)

{if(n%i==0)

cnt++;

if(cnt==1) System.out.println(“It is a Prime number”);

else System.out.println(“Not a Prime number”);

break;

case 2: //AUTOMORPHIC NUMBER

p=n*n;

while(n>0)

if(p%10 !=n%10)

{flag=false;
break;

else

{n=n/10;

p=p/10;

if(flag==false) System.out.println(“Not a Automorphic number”);

else System.out.println(“It is an Automorphic number”);

break;

default:System.out.println(“Invalid choice”);

}}

18) Write a menu driven program to perform the following tasks by using the ‘switch case’
statement. [ICSE 2011]

a) To print the series:


0,3,8,15, 24………………..to n terms (value of n to be input by the user)

b) To find the sum of the series:

S=1/2 + 3/4 + 5/6 + 7/8 +………………+ 19/ 20.

Solution:

import java.util.*;

class Q18 {

static void main(){

int n,j=1;

double sum=0.0;

Scanner ob=new Scanner(System.in);

System.out.println(“***MENU***”);

System.out.println(“1.To print the series….0,3,8,15,24….”);

System.out.println(“2.To print the SUM of the series …1/2 + 3/4 + 5/6….”);

System.out.println(“Enter your choice..1 or 2”);

switch(ob.nextInt())

{case 1: System.out.println(“Enter the number of terms in the series”);


n=ob.nextInt();

for(int i=1;i<=n;i++)

System.out.print(i*i-1+” ,”);

break;

case 2: System.out.println(“Enter the number of the terms in the series”);

n=ob.nextInt();

for(int i=1;i<=n;i++)

{sum+=j/(j+1.0);

j=i+2;

System.out.println(“Sum of the series=”+sum);

break;

default: System.out.println(“Invalid entry”);

}}}

19) Using a switch statement, write a menu driven program to :


a) Generate and display the first 10 terms of the Fibonacci series

0,1,1,2,3,5

The first two Fibonacci numbers are 0 and 1 and each subsequent number is the sum of the previous
two.

b) Find the sum of the digits of an integer that is input.

Sample Input: 15390

Sample Output: Sum of the digits =18

For an incorrect choice, an appropriate error message should be displayed.

Solution:

import java.util.*;

class Q19 {

static void main(){

int n,sum=0,a=0,b=0,c=1;

Scanner ob=new Scanner(System.in);

System.out.println(“***MENU***”);

System.out.println(“1.First ten terms of the Fibonacci series”);


System.out.println(“2.Sum of the digits of the number entered”);

System.out.println(“Enter your choice..1 or 2”);

switch(ob.nextInt())

{case 1: System.out.println(“**Fibonacci Series***”);

for(int i=1;i<=10;i++) //FIRST 10 TERMS

{a=b;

b=c;

c=a+b;

System.out.print(a +”, “);

break;

case 2: System.out.println(“***Sum of Digits*** \n Enter the number”);

n=ob.nextInt();

while(n>0)

{sum+=n%10;

n=n/10;
}

System.out.println(“The sum of the digits is “+sum);

break;

default: System.out.println(“Invalid entry”);

}}

20) A special two-digit number is such that when the sum of its digits is added to the product of its
digits, the result is equal to the original two-digit number.

Example: Consider the number 59,

Sum of digits=5 + 9 = 14

Product of digits = 5* 9 = 45

Sum of the sum of the digits and product of digits = 14+ 45= 59

Write a program to accept a two-digit number. Add the sum of its digits to the products of its digits.
If the value is equal to the number input, then display the message “Special 2 digit number”
otherwise display the message “Not a special two digit number”.

Solution:

import java.util.*;
class Q20 {

static void Sp2Digit()

{Scanner sn=new Scanner(System.in);

int n,ld,rd,sum=0,pdt;

System.out.println(“Enter a two digit number”);

n=sn.nextInt();

rd=n%10;

ld=n/10;

sum=ld+rd;

pdt=ld*rd;

if(n==(sum+pdt))

System.out.println(“It is a Special two digit number”);

else

System.out.println(“It is not a Special two digit number”);

}}

21) Using switch statement, write a menu driven program to:


a) find and display all the factors of a number input by the user (including 1 and excluding the
number itself)

Example : Sample Input n=15

Sample Output: 1,3,5

b) Find and display the factorial of a number input by the user (the factorial of a non-negative
integer n, denoted by n! is the product of all integers less than or equal to n.

Example: Sample Input : n=15

Sample Output : 5! = 1*2*3*4*5 = 120

For an incorrect choice, an appropriate error message should be displayed.

Solution: [ICSE 2015]

import java.util.*;

class Q21 {

static void main(){

int n,fact=1;

Scanner ob=new Scanner(System.in);

System.out.println(“***MENU***”);

System.out.println(“1.Factors of a number”);
System.out.println(“2.Factorial of a number”);

System.out.println(“Enter your choice..1 or 2”);

switch(ob.nextInt())

{case 1: //FACTORS OF THE NUMBER EXCLUDING THE NUMBER ITSELF

System.out.println(“Enter a number”);

n=ob.nextInt();

for(int i=1;i<n;i++) //FIRST 10 TERMS

{ if(n%i==0)

System.out.print(i+”,”);

break;

case 2: //FACTORIAL OF THE GIVEN NUMBER

System.out.println(“Enter a non-negative number”);

n=ob.nextInt();

for(int j=1;j<=n;j++)
fact=fact*j;

System.out.println(“The Factorial of the number is :”+fact);

break;

default: System.out.println(“Invalid entry”);

}}

22) Write a program to input a number. Check and display whether it is a Niven number or not. ( A
number is said to be Niven which is divisible by the sum of its digits)

Example: Sample Input: 126

Sum of its digits = 1+2+6 =9 and 126 is divisible by 9.

Sample Output : It is a Niven number. [ICSE 2016]

Solution:

import java.util.*;

class Q22 {

static void NivMethod()

{
Scanner sn=new Scanner(System.in);

int sum=0,num,n,d;

System.out.println(“Enter the number”);

n=sn.nextInt();

num=n;

while(n>0)

{d=n%10;

sum+=d;

n=n/10;

if(num%sum==0)

System.out.println(“The number is a Niven number”);

else

System.out.println(“Not a Niven number”);

}}
23) Write a program to accept a number and check whether it is a ‘Spy number’ or not. ( A number is
Spy if the sum of its digits equals the product of its digits)

Example : Sample Input 1124

Sum of the digits = 1+1+2+4 = 8

Product of the digits=1*1*2*4=8

Solution:

import java.util.*;

class Q23 {

static void main()

Scanner sn=new Scanner(System.in);

int sum=0,pdt=1,n,d;

System.out.println(“Enter the number”);

n=sn.nextInt();

while(n>0)

{d=n%10;
sum+=d;

pdt*=d;

n=n/10;

if(sum==pdt)

System.out.println(“The number is a Spy number”);

else

System.out.println(“Not a Spy number”);

}}

24) Using switch statement, write a menu driven program for the following:

a) To find and display the sum of the series given below:

S=x1 – x2 +x3 – x4 + x5 -………………………………-x20 where x=2

b) To display the series:

1,11,111,1111,11111

For an incorrect option, an appropriate error message should be displayed. [ICSE 2017]

Solution:
import java.util.*;

class Q24 {

static void main(){

int x,s;

double term,sum=0;

Scanner ob=new Scanner(System.in);

System.out.println(“***MENU***”);

System.out.println(“1.To find the sum of the given series”);

System.out.println(“2.To display the series 1,11,111,1111….”);

System.out.println(“Enter your choice..1 or 2”);

switch(ob.nextInt())

{case 1: //SUM OF THE SERIES

x=2;

for(int i=1;i<=20;i++)

{term=Math.pow(x,i);
if(i%2==1)

sum+=term;

else

sum-=term;

System.out.println(“Sum of the series=”+sum);

break;

case 2: //PRINT THE SERIES 1,11,111…..

s=0;

for(int j=1;j<=5;j++)

{s=s*10+1;

System.out.print(s+”,”);

if(s==0)

s++;

break;
default: System.out.println(“Invalid entry”);

}}}

*************

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy