Notes .Iteration Statement
Notes .Iteration Statement
Question 1
What do you understand by iterative process? How can it be resolved by using loop?
Iterative process means repeating a set of actions a certain number of times to perform
some task. Loops in programming languages like Java enable us to repeat a single
statement or a set of statements as long as the desired condition remains true.
Question 2
This for loop prints the table of 2 till 12. int i = 1 is the initialization part of the for loop, it
is executed only once when the loop gets executed for the first time. i <= 12 is the condition
part of the for loop, it is executed before the start of each iteration. Loop iterates as long as
this condition remains true. Once it becomes false, execution of the loop is stopped. i++ is
the update part of the for loop. It is executed at the end of each iteration.
Question 3
1. for
2. while
3. do-while
Question 4
Question 5
Define the following with their constructs:
(a) Entry controlled loop
An entry-controlled loop checks the condition at the time of entry. Only if the condition is
true, the program control enters the body of the loop. for and while loops are entry-
controlled loops.
(b) Exit controlled loop
An exit-controlled loop checks the condition after executing its body. If the condition is
true, loop will perform the next iteration otherwise program control will move out of the
loop. do-while loop is an exit-controlled loop.
Question 6
do {
//loop-body
} while (condition);
(c) while loop
while (condition) {
//loop-body
}
Question 7
Question 8
Question 9
What are the different ways to inter-convert the loops? Name them.
1. for loop to while loop
2. for loop to do-while loop
3. do-while loop to while loop
4. do-while loop to for loop
5. while loop to do-while loop
6. while loop to for loop
Question 10
Question 11
Distinguish between:
1. for loop is a suitable choice when we know the number of iterations beforehand.
while loop is helpful in situations where numbers of iterations is not known.
2. Omitting the condition in for loop will lead to an infinite loop whereas if condition is
not provided in while loop, it will cause a compilation error.
Question 12
State one difference and one similarity between while and do-while loop
Similarity — Both while and do-while are suitable in situations where numbers of iterations
is not known.
Difference — while is an entry-controlled loop whereas do-while is an exit-controlled loop
Question 13
State one similarity and one difference between while and for loop.
Similarity — Both for and while are entry-controlled loops
Difference — for loop is a suitable choice when we know the number of iterations
beforehand. while loop is helpful in situations where numbers of iterations is not known.
Question 14
Question 1
class dkl
{
public static void main(String args[])
{
int i;
for(i = -1;i<10;i++)
{
System.out.println(++i);
}
}
}
Output
10
Explanation
This table shows the changes in the value of i as the for loop iterates:
i Remarks
i Remarks
-1 Initial value
Question 2
class dk2
{
public static void main(String args[])
{
int i=2,k=1;
while (++i<6)
k *= i;
System.out.println(k);
}
}
Output
60
Explanation
This table shows the change in values of i and k as while loop iterates:
i k Remarks
i k Remarks
2 1 Initial values
3 3 1st Iteration
4 12 2nd Iteration
5 60 3rd Iteration
Notice that System.out.println(k); is not inside while loop. As there are no curly braces so
only the statement k *= i; is inside the loop. The statement System.out.println(k); is outside
the while loop, it is executed once and prints value of k which is 60 to the console.
System.out.println(x);
Question 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");
}
}
Solution
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");
}
}
Question 4
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);
}
}
Solution
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);
}
}
}
Solutions to Unsolved Java Programs
Question 1
Write the programs in Java to display the first ten terms of the following
series:
(a) 1, 4, 9, 16,
public class KboatSeries
{
public static void main(String args[]) {
for (int i = 1; i <= 10; i++) {
System.out.print(i * i + " ");
}
}
}
Output
(b) 1, 2, 4, 7, 11,
public class KboatSeries
{
public static void main(String args[]) {
for (int i = 0; i < 10; i++) {
int term = 1 + ((i * (i + 1)) / 2);
System.out.print(term + " ");
}
}
}
Output
Question 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
import java.util.Scanner;
Output
Question 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).
import java.util.Scanner;
if (m > n) {
System.out.println("m should be less than n");
}
else {
for (int i = m; i <=n; i++) {
if (i % 2 == 0)
sumEven += i;
else
sumOdd += i;
}
Output
Question 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).
import java.util.Scanner;
Output
Question 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.
import java.util.Scanner;
Output
Question 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.
import java.util.Scanner;
}
}
Output
Question 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.
import java.util.Scanner;
Output
Output
(c) 1 + (1/3) + (1/5) + ...... + (1/19)
public class KboatSeries
{
public static void main(String args[]) {
double sum = 0.0;
for (int i = 1; i <= 19; i = i + 2)
sum += (1.0 / i);
System.out.println("Sum = " + sum);
}
}
Output
(d) (1/2) + (2/3) + (3/4) + ...... + (19/20)
public class KboatSeries
{
public static void main(String args[]) {
double sum = 0.0;
for (int i = 1; i <= 19; i++)
sum += (i / (double)(i + 1));
System.out.println("Sum = " + sum);
}
}
Output
(e) 2 - 4 + 6 - 8 + ...... - 20
public class KboatSeries
{
public static void main(String args[]) {
double sum = 0.0;
for (int i = 1; i <= 10; i++) {
if (i % 2 == 0)
sum -= i * 2;
else
sum += i * 2;
}
System.out.println("Sum = " + sum);
}
}
Output
(f) (1*2) + (2*3) + ...... + (19*20)
public class KboatSeries
{
public static void main(String args[]) {
int sum = 0;
for (int i = 1; i <= 19; i++)
sum += i * (i + 1);
System.out.println("Sum = " + sum);
}
}
Output
Question 9
Write a program to input a number and count the number of digits. The
program further 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.
import java.util.Scanner;
while (n != 0) {
dc++;
n /= 10;
}
if (dc % 2 == 0)
System.out.println("The number contains even number of
digits");
else
System.out.println("The number contains odd number of
digits");
}
}
Output
Question 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 between the original number and the reversed
number.
Sample Input: 194
Sample Output: 491
Absolute Difference= 297
import java.util.Scanner;
while(copyNum != 0) {
int digit = copyNum % 10;
copyNum /= 10;
revNum = revNum * 10 + digit;
}
Output
Question 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 to zero. The last divisor results in GCD.
Sample Input: 45, 20
Sample Output: GCD=5
import java.util.Scanner;
Output
Question 12
Write a program in Java to find the sum of the given series :
(a) S = a2 + a2 / 2 + a2 / 3 + ...... + a2 / 10
import java.util.Scanner;
public class KboatSeries
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter a: ");
int a = in.nextInt();
double sum = 0.0;
for (int i = 1; i <= 10; i++)
sum += Math.pow(a, 2) / i;
System.out.println("Sum = " + sum);
}
}
Output
Output
Output
(d) S = a + a2 + a3 + ...... + an
import java.util.Scanner;
Output
(e) S = 1 + 22 / a + 33 / a2 + ...... to n terms
import java.util.Scanner;
Output
(f) S = 12/a + 32 / a2 + 52 / a3 + ...... to n terms
import java.util.Scanner;
Output
(g) S = 1/a + 1/a2 + 1/a3 + ...... + 1/an
import java.util.Scanner;
Output
(h) S = x/2 + x/5 + x/8 + x/11 + ...... + x/20
import java.util.Scanner;
Output
Question 13
In order to reach the top of a 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
height of the pole. Calculate and display the number of attempts the
monkey makes to reach the top of the pole.
import java.util.Scanner;
Question 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]
import java.util.Scanner;
Output
Question 15
Write a menu driven program to input two positive numbers m and n
(where 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
import java.util.Scanner;
if (m > n) {
switch (choice) {
case 1:
while (n > 0) {
m++;
n--;
}
System.out.println("Sum = " + m);
break;
case 2:
int p = 0;
while (n > 0) {
p += m;
n--;
}
System.out.println("Product = " + p);
break;
case 3:
int q = 0;
while (m >= n) {
m = m - n;
q++;
}
System.out.println("Quotient = " + q);
System.out.println("Remainder = " + m);
break;
default:
System.out.println("Incorrect Choice");
break;
}
}
else {
System.out.println("Invalid Inputs");
}
}
}
Output
Question 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 same as in the right order)
Example: 11, 101, 151 etc.
(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
import java.util.Scanner;
switch (choice) {
case 1:
int copyNum = num;
int revNum = 0;
while(copyNum != 0) {
int digit = copyNum % 10;
copyNum /= 10;
revNum = revNum * 10 + digit;
}
if (revNum == num)
System.out.println(num + " is palindrome");
else
System.out.println(num + " is not palindrome");
break;
case 2:
int sum = 0;
if (num == sum)
System.out.println(num + " is a perfect number");
else
System.out.println(num + " is not a perfect number");
break;
default:
System.out.println("Incorrect Choice");
break;
}
}
}
Output
Question 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)
Example: 3,5,7,11
(b) Automorphic number: (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 as the last two digits.
import java.util.Scanner;
switch (choice) {
case 1:
int c = 0;
for (int i = 1; i <= num; i++) {
if (num % i == 0) {
c++;
}
}
if (c == 2)
System.out.println(num + " is Prime");
else
System.out.println(num + " is not Prime");
break;
case 2:
int numCopy = num;
int sq = num * num;
int d = 0;
/*
* Count the number of
* digits in num
*/
while(num > 0) {
d++;
num /= 10;
}
/*
* Extract the last d digits
* from square of num
*/
int ld = (int)(sq % Math.pow(10, d));
if (ld == numCopy)
System.out.println(numCopy + " is automorphic");
else
System.out.println(numCopy + " is not automorphic");
break;
default:
System.out.println("Incorrect Choice");
break;
}
}
}
Output
Question 18
Write a menu driven program to perform the following tasks by using
Switch case statement:
(a) To print the series:
0, 3, 8, 15, 24, ............ to n terms. (value of 'n' is to be an input by the
user)
(b) To find the sum of the series:
S = (1/2) + (3/4) + (5/6) + (7/8) + ........... + (19/20)
import java.util.Scanner;
switch (choice) {
case 1:
System.out.print("Enter n: ");
int n = in.nextInt();
for (int i = 1; i <= n; i++)
System.out.print(((i * i) - 1) + " ");
System.out.println();
break;
case 2:
double sum = 0;
for (int i = 1; i <= 19; i = i + 2)
sum += i / (double)(i + 1);
System.out.println("Sum = " + sum);
break;
default:
System.out.println("Incorrect Choice");
break;
}
}
}
Output
Question 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.
import java.util.Scanner;
switch (ch) {
case 1:
int a = 0, b = 1;
System.out.print(a + " " + b);
for (int i = 3; i <= 10; i++) {
int term = a + b;
System.out.print(" " + term);
a = b;
b = term;
}
break;
case 2:
System.out.print("Enter number: ");
int num = in.nextInt();
int sum = 0;
while (num != 0) {
sum += num % 10;
num /= 10;
}
System.out.println("Sum of Digits " + " = " + sum);
break;
default:
System.out.println("Incorrect choice");
break;
}
}
}
Output
Question 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 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 product 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".
import java.util.Scanner;
while (num != 0) {
int digit = num % 10;
num /= 10;
digitSum += digit;
digitProduct *= digit;
count++;
}
if (count != 2)
System.out.println("Invalid input, please enter a 2-digit
number");
else if ((digitSum + digitProduct) == orgNum)
System.out.println("Special 2-digit number");
else
System.out.println("Not a special 2-digit number");
}
}
Output
Question 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 the 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 = 5
Sample Output : 5! = 1*2*3*4*5 = 120
For an incorrect choice, an appropriate error message should be
displayed.
import java.util.Scanner;
switch (choice) {
case 1:
System.out.print("Enter number: ");
num = in.nextInt();
for (int i = 1; i < num; i++) {
if (num % i == 0) {
System.out.print(i + " ");
}
}
System.out.println();
break;
case 2:
System.out.print("Enter number: ");
num = in.nextInt();
int f = 1;
for (int i = 1; i <= num; i++)
f *= i;
System.out.println("Factorial = " + f);
break;
default:
System.out.println("Incorrect Choice");
break;
}
}
}
Output
Question 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.
import java.util.Scanner;
int digitSum = 0;
while (num != 0) {
int digit = num % 10;
num /= 10;
digitSum += digit;
}
/*
* digitSum != 0 check prevents
* division by zero error for the
* case when users gives the number
* 0 as input
*/
if (digitSum != 0 && orgNum % digitSum == 0)
System.out.println(orgNum + " is a Niven number");
else
System.out.println(orgNum + " is not a Niven number");
}
}
Output
Question 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
import java.util.Scanner;
if (sum == prod)
System.out.println(orgNum + " is Spy Number");
else
System.out.println(orgNum + " is not Spy Number");
}
}
Output
Question 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.
import java.util.Scanner;
switch (choice) {
case 1:
int sum = 0;
for (int i = 1; i <= 20; i++) {
int term = (int)Math.pow(2, i);
if (i % 2 == 0)
sum -= term;
else
sum += term;
}
System.out.println("Sum=" + sum);
break;
case 2:
int term = 1;
for (int i = 1; i <= 5; i++) {
System.out.print(term + " ");
term = term * 10 + 1;
}
break;
default:
System.out.println("Incorrect Choice");
break;
}
}
}
Output