0% found this document useful (0 votes)
67 views43 pages

Understanding Loop Constructs in Java

The document discusses iterative processes in programming, particularly focusing on loops such as for, while, and do-while loops. It explains the structure and purpose of these loops, including examples and differences between them. Additionally, it includes Java programming exercises related to loops and series calculations.

Uploaded by

saritasharma0807
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
67 views43 pages

Understanding Loop Constructs in Java

The document discusses iterative processes in programming, particularly focusing on loops such as for, while, and do-while loops. It explains the structure and purpose of these loops, including examples and differences between them. Additionally, it includes Java programming exercises related to loops and series calculations.

Uploaded by

saritasharma0807
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Question

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
Explain for loop with an example.
for loop is an entry-controlled loop. Below is an example of for loop:
for (int i = 1; i <= 12; i++) { int
a = 2 * i;
[Link]("2 x " + i + "\t= " + a);
}
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
Name the different types of loop statements.
1. for
2. while
3. do-while
Question 4
What are the parameters needed to create a for loop?
The following parameters are commonly used in a for loop:
1. An initial value for the loop control variable.
2. A condition—loop will iterate as long as this condition remains true.

3. An update expression to modify the loop control variable after every


iteration.
4. Body of the loop which consists of the statements that needs to be
repeatedly executed.
Question
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
Write down the general format of:
(a) for loop for
(initialization;
condition; update) {
//loop-body
}

(b) do - while do {
//loop-body
} while (condition);

(c) while loop while


(condition) {
//loop-body
}
Question
What is the purpose of using: (a) break statement break statement is
used to unconditionally jump out of the loop
(b) continue statement
continue statement is used to unconditionally jump to the next iteration of the loop,
skipping the remaining statements of the current iteration.
Question
Define the following:
(a) Finite loop
A loop which iterates for a finite number of iterations is termed as a finite loop.
(b) Infinite loop
A loop which continues iterating indefinitely and never stops is termed as infinite
loop.
(d) Null loop
A loop which has an empty loop body is termed as a null loop.
Question
Distinguish between:
(a) for and while loop
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.
(b) while and do-while loop
1. while is an entry-controlled loop whereas do-while is an
exitcontrolled loop
2. while loop is helpful in situations where numbers of iterations is
not known. do-while is suitable when we need to display a menu to the
user.
Question
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
exitcontrolled loop
Question
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.

Predict the Output of the following


Programs
Question 1 class
dkl
{
public static void main()
{ int
i;
for(i = -1;i<10;i++)
{
[Link](++i);
}
}
}
Output
0
2
4
6
8
10
Question 2 class
dk2
{
public static void main()
{
int i=2,k=1; while
(++i<6)
k *= i;
[Link](k);
}
}
Output
60
Question 3 class
dk3
{
public static void main()
{
int m=2,n=15; for(int
i=1;i<=5;i++)
{
m++;--n;
[Link]("m="+m);
[Link]("n="+n);
}
}
}
Output
m=3
n=14 m=4
n=13 m=5
n=12 m=6
n=11 m=7
n=10
Question
Determine how many times the body of the loop will be executed.
class dk4
{
public static void main()
{
int x=5,y=50; while(x<=y)
{
y=y/x;
[Link](y);
}
}
}
Output
10
2
The loop will execute 2 times

Rewrite the following Programs


Question 1 Using
do while:
class Test
{
public static void main()
{
int x,c;
for(x=10,c=20;c>=10;c=c-2)
{
x++;
[Link](x);
}
}
}
Solution class
Test
{
public static void main()
{
int x=10, c=20; do {
x++;
[Link](x);
c=c-2;
} while (c>=10);
}
}
Question 2 Using
do while: class
Pattern
{
public static void main()
{ int
i,j;
for(i=5;i>=1;i--)
{
[Link](i);
}
[Link]();
}
}
Solution class
Pattern
{
public static void main()
{
int i=5,j;
do { [Link](i);
i--;
} while (i>=1);
[Link]();
}
}
Question 3 Using
do while: class
Number
{
public static void main( )
{
int i,n=191,c=0; for(i=1;i<=n;i++)
{
if(n%i==0) c=c+1;
}
if(c==2)
[Link]("Prime"); else
[Link]("Not Prime");
}
}
Solution
class Number
{
public static void main( )
{
int i=1,n=191,c=0;
do { if(n%i==0)
c=c+1;
i++; } while
(i<=n);
if(c==2)
[Link]("Prime"); else
[Link]("Not Prime");
}
}

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 Series
{
public static void main( ) {
for (int i = 1; i <= 10; i++) {
[Link](i * i + " ");
}
}
}

(b) 1, 2, 4, 7, 11,
public class Series
{
public static void main( ) {
for (int i = 0; i < 10; i++) { int
term = 1 + ((i * (i + 1)) / 2);
[Link](term + " ");
}
}
}

(c) 3, 6, 9, 12,
public class Series
{
public static void main( ) {
for (int i = 3; i <= 30; i = i + 3) {
[Link](i + " ");
}
}
}

(d) 4, 8, 16, 32,


public class Series
{
public static void main( ) {
for (int i = 2; i <= 11; i++) {
[Link]((int)([Link](2, i)) + " ");
}
}
}
(e) 1.5, 3.0, 4.5, 6.0,
public class Series
{
public static void main( ) { float term =
1.5f; for (int i = 1; i <= 10; i++) {
[Link](term + " "); term +=
1.5f;
}
}
}

(f) 0, 7, 26,
public class Series
{
public static void main( ) {
for (int i = 1; i <= 10; i++) { int term
= (int)([Link](i, 3) - 1);
[Link](term + " ");

}
}
}
(g) 1, 9, 25, 49,
public class Series
{
public static void main( ) {
for (int i = 1; i <= 19; i = i + 2) {
[Link]((i * i) + " ");
}
}
}

(h) 4, 16, 36, 64, public class Series


{
public static void main( ) {
for (int i = 2; i <= 20; i = i + 2) {
[Link]((i * i) + " ");
}
}
}

(i) 0, 3, 8, 15,
public class Series
{
public static void main( ) {
for (int i = 1; i <= 10; i++) {
[Link]((i * i - 1) + " ");
}
}
}

(j) 24, 99, 224, 399, public class Series


{
public static void main( ) {
for (int i = 5; i <= 50; i = i + 5) {
int term = (int)([Link](i, 2) - 1);
[Link](term + " ");
}
}
}

(k) 2, 5, 10, 17,


public class Series
{
public static void main( ) {
for (int i = 1; i <= 10; i++) {
[Link]((i * i + 1) + " ");
}
}
}

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
[Link]; public class MIntegers
{
public static void main( ) { Scanner in = new
Scanner([Link]); int pSum = 0, pCount = 0,
nSum = 0, nCount = 0; [Link]("Enter
50 numbers");
for (int i = 1; i <= 50; i++)
{ int n = [Link](); if (n
>= 0) {
pSum += n; pCount++;
}
else {
nSum += n; nCount++;

}
}
[Link]("Positive Count = " + pCount);
[Link]("Positive Sum = " + pSum);
[Link]("Negative Count = " + nCount);
[Link]("Negative Sum = " + nSum);
}
}

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 [Link];
public class OddEvenSum
{
public static void main( ) {
Scanner in = new Scanner([Link]);
[Link]("Enter m: "); int m =
[Link]();
[Link]("Enter n: "); int n
= [Link]();
long sumOdd = 0, sumEven = 0;
if (m > n) {
[Link]("m should be less than n");
}
else {
for (int i = m; i <=n; i++) {
if (i % 2 == 0)
sumEven += i;
else sumOdd
+= i;
}
[Link]("Even Sum: " + sumEven);
[Link]("Odd Sum: " + sumOdd);
}
}
}

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 [Link]; public
class DivisibleBy5
{
public static void main( ) { final int COUNT =
50;
Scanner in = new Scanner([Link]);
int n, c = 0;
[Link]("Enter " + COUNT + " numbers");
for (int i = 1; i <= COUNT; i++) {
n = [Link]();
if (i % 5 == 0) {
if (i % 10 == 5)
[Link]("Number end with the digit 5");
if (i % 10 == 0) c++;
}
}
[Link]("Count of numbers ending with 0: " + c);
}
}

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 [Link]; public
class BuzzNumber
{
public static void main( ) {
Scanner in = new Scanner([Link]);
[Link]("Enter p: "); int p =
[Link]();
[Link]("Enter q: ");
int q = [Link](); if (p < q) {
[Link]("Buzz Numbers between "
+ p + " and " + q); for (int i
= p; i <= q; i++) { if (i % 10
== 7 || i % 7 == 0)
[Link](i);
}
}
else {
[Link]("Invalid Inputs!!!");
[Link]("p should be less than q");
}

}
}

Question 8
Write a program in Java to find the sum of the given series :
(a) 1 + 4 + 9 + ...... + 400
public class Series
{
public static void main( ) { int sum = 0;
for (int i = 1; i <= 20; i++) sum
+= (i*i);
[Link]("Sum = " + sum);
}
}

(b) 1 + (1/2) + (1/3) + ...... + (1/20) public


class Series
{
public static void main( ) { double sum = 0.0;
for (int i = 1; i <= 20; i++) sum
+= (1.0 / i);
[Link]("Sum = " + sum);
}
}

(c) 1 + (1/3) + (1/5) + ...... + (1/19) public


class Series
{
public static void main( ) { double sum = 0.0;
for (int i = 1; i <= 19; i = i + 2)
sum += (1.0 / i);
[Link]("Sum = " + sum);
}
}
(d) (1/2) + (2/3) + (3/4) + ...... + (19/20)
public class Series
{
public static void main( ) { double sum = 0.0;
for (int i = 1; i <= 19; i++) sum
+= (i / (double)(i + 1));
[Link]("Sum = " + sum);
}
}
Output
(e) 2 - 4 + 6 - 8 + ...... - 20
public class Series
{
public static void main( ) { double sum = 0.0;
for (int i = 1; i <= 10; i++)
{ if (i % 2 == 0) sum -= i *
2;

else sum += i
* 2;
}
[Link]("Sum = " + sum);
}
}

(f) (1*2) + (2*3) + ...... + (19*20) public


class Series
{
public static void main( ) { int sum = 0;
for (int i = 1; i <= 19; i++) sum
+= i * (i + 1);
[Link]("Sum = " + sum);
}
}

Question
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 [Link]; public
class DigitCount
{
public static void main( ) {
Scanner in = new Scanner([Link]);

[Link]("Enter number: ");


int n = [Link]();
int dc = 0; while (n
!= 0) {
dc++; n
/= 10;
}
[Link]("Number of digits = " + dc); if
(dc % 2 == 0)
[Link]("The number contains even number of digits"); else
[Link]("The number contains odd number of digits");
}
}

Question
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 [Link]; public
class GCD
{
public static void main( ) {
Scanner in = new Scanner([Link]);

[Link]("Enter first
number: ");

int a = [Link]();
[Link]("Enter second number: ");
int b = [Link]();
while (b != 0) { int
t = b;
b = a % b;
a = t;
}
[Link]("GCD=" + a);
}
}

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

import [Link]; public


class Series
{
public static void main( ) {
{
public static void main( ) {
Scanner in = new Scanner([Link]);

Scanner in = new Scanner([Link]);


[Link]("Enter a: "); int a =
[Link]();
double sum = 0.0;
for (int i = 1; i <= 10; i++)
sum += [Link](a, 2) / i;
[Link]("Sum = " + sum);
}
}

(b) S = a + a / 2 + a / 3 + ...... + a / 10
2 3 10

import [Link]; public


class Series
{
public static void main( ) {
Scanner in = new Scanner([Link]);
[Link]("Enter a: "); int a =
[Link]();
double sum = 0.0;
for (int i = 1; i <= 10; i++)
sum += [Link](a, i) / i;
[Link]("Sum = " + sum);
}
}

(c) S = 63(a*2) + (a*3) + ...... +


(a*20) import [Link];
public class Series
{
public static void main( ) {
Scanner in = new Scanner([Link]);
[Link]("Enter a: "); int a =
[Link]();
long sum = 0;
for (int i = 2; i <= 20; i++) sum
+= a * i;
[Link]("Sum = " + sum);
}
}
(d) S = a + a + a + ...... + a
2 3 n

import [Link]; public


class Series
{
public static void main( ) {
Scanner in = new Scanner([Link]);
[Link]("Enter a: "); int a =
[Link](); [Link]("Enter n:
"); int n = [Link]();
long sum = 0;
for (int i = 1; i <= n; i++)
sum += [Link](a, i);
[Link]("Sum = " + sum);
}
}

(h) S = x/2 + x/5 + x/8 + x/11 + ...... + x/20


import [Link]; public
class Series
{
public static void main( ) {
Scanner in = new Scanner([Link]);
[Link]("Enter x: "); int x =
[Link]();
double sum = 0.0;
for (int i = 2; i <= 20; i = i+3)
sum += (double)x / i;
[Link]("Sum = " + sum);
}
}

Question
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 [Link]; public


class MonkeyPole

{
public static void main( ) {
Scanner in = new Scanner([Link]);
[Link]("Enter height of the pole: ");
double poleHt = [Link](); double jumpHt
= 5.0; int numAttempts = 1; while (jumpHt <
poleHt) { jumpHt += 5.0; jumpHt -= 2 * jumpHt
/ 100.0;
numAttempts++;
}
[Link]("Number of Attempts = " + numAttempts);
}
}

Question
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 [Link]; public


class NumberOperations
{
public static void main( ) {
Scanner in = new Scanner([Link]);
[Link]("1. Sum without '+' operator");
[Link]("2. Product without '*' operator");
[Link]("3. Quotient and Remainder without '/' & '%' operators");
[Link]("Enter your choice: "); int choice = [Link]();
[Link]("Enter m: "); int m = [Link]();
[Link]("Enter n: ");
int n = [Link](); if (m > n)
{
switch (choice) {
case 1: while (n >
0) {
m++;
n--;
}
[Link]("Sum = " + m);
break; case 2:
int p = 0;
while (n > 0) {
p += m;
n--;
}
[Link]("Product = " + p);
break; case 3: int q = 0;
while (m >= n) {
m = m - n; q++;
}
[Link]("Quotient = " + q);
[Link]("Remainder = " + m);
break; default:
[Link]("Incorrect Choice"); break;
}
}
else {
[Link]("Invalid Inputs");
}
}
}

Question
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 [Link]; public


class PalinOrPerfect
{
public static void main( ) {
Scanner in = new Scanner([Link]);
[Link]("1. Palindrome number");
[Link]("2. Perfect number");
[Link]("Enter your choice: "); int
choice = [Link]();
[Link]("Enter number: "); int
num = [Link]();

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)
[Link](num + " is palindrome"); else
[Link](num + " is not palindrome"); break;

case 2: int
sum = 0;

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


if (num % i == 0) { sum += i;
}
}

if (num == sum)
[Link](num + " is a perfect number"); else
[Link](num + " is not a perfect number"); break;

default:
[Link]("Incorrect Choice"); break;
}
}
}

Question
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 [Link]; public


class PrimeAutomorphic
{
public static void main( ) {
Scanner in = new Scanner([Link]);
[Link]("1. Prime number");
[Link]("2. Automorphic number");
[Link]("Enter your choice: "); int
choice = [Link](); [Link]("Enter
number: "); int num = [Link]();

switch (choice) { case


1:
boolean isPrime = true;
for (int i = 2; i <= num / 2; i++) {
if (num % i == 0) { isPrime =
false; break;
}
}
if (isPrime)
[Link](num + " is Prime"); else
[Link](num + " is not Prime"); break;

case 2:
boolean isAutomorphic = true;
int numCopy = num; int sq =
num * num;

while(num > 0) { if (num


% 10 != sq % 10) {
isAutomorphic = false;
break;
}
num /= 10; sq
/= 10;
}

if (isAutomorphic)
[Link](numCopy + " is automorphic"); else
[Link](numCopy + " is not automorphic"); break;

default:
[Link]("Incorrect Choice"); break;
}
}
}

Question
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 [Link]; public


class SeriesMenu
{
public static void main( ) {
Scanner in = new Scanner([Link]);
[Link]("Type 1 to print series");
[Link]("0, 3, 8, 15, 24,....to n terms");
[Link]();
[Link]("Type 2 to find sum of series");
[Link]("(1/2) + (3/4) + (5/6) + (7/8) +....+ (19/20)");
[Link]();
[Link]("Enter your choice: "); int
choice = [Link]();

switch (choice) { case


1:
[Link]("Enter n: ");
int n = [Link](); for (int i =
1; i <= n; i++)
[Link](((i * i) - 1) + " ");
[Link](); break;

case 2:
double sum = 0;
for (int i = 1; i <= 19; i = i + 2)
sum += i / (double)(i + 1);
[Link]("Sum = " + sum);
break; default:
[Link]("Incorrect Choice"); break;
}
}
}
Question
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 [Link]; public


class FibonacciNDigitSum
{
public static void main( ) {
Scanner in = new Scanner([Link]);
[Link]("1. Fibonacci Series");
[Link]("2. Sum of digits");
[Link]("Enter your choice: "); int
ch = [Link]();

switch (ch) { case


1:
int a = 0, b = 1; [Link](a +
" " + b);
for (int i = 3; i <= 10; i++) {
int term = a + b;
[Link](" " + term); a
= b; b = term;
}
break;

case 2:
[Link]("Enter number: ");
int num = [Link](); int sum = 0;
while (num != 0) {
sum += num % 10; num
/= 10;

}
[Link]("Sum of Digits " + " = " + sum); break;

default:
[Link]("Incorrect choice"); break;
}
}
}
Question
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 [Link]; public


class SpecialNumber
{
public static void main( ) {
Scanner in = new Scanner([Link]);
[Link]("Enter a 2 digit number: ");
int orgNum = [Link](); int num = orgNum;
int count = 0, digitSum = 0, digitProduct = 1;
while (num != 0) { int digit = num % 10; num
/= 10; digitSum += digit; digitProduct *= digit;
count++;
}
if (count != 2)
[Link]("Invalid input, please enter a 2-digit number"); else
if ((digitSum + digitProduct) == orgNum) [Link]("Special
2-digit number"); else
[Link]("Not a special 2-digit number");
}
}
Question
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 [Link]; public


class Menu
{
public static void main( ) {
Scanner in = new Scanner([Link]);
[Link]("1. Factors of number");
[Link]("2. Factorial of number");
[Link]("Enter your choice: "); int
choice = [Link](); int num;

switch (choice) { case


1:
[Link]("Enter number: "); num =
[Link]();
for (int i = 1; i < num; i++) { if
(num % i == 0) {
[Link](i + " ");
}
}
[Link](); break;

case 2:
[Link]("Enter number: "); num =
[Link]();
int f = 1; for (int i = 1; i <=
num; i++)
f *= i;
[Link]("Factorial = " + f);
break; default:
[Link]("Incorrect Choice"); break;
}
}
}

Question
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 [Link]; public
class NivenNumber

{
public static void main( ) {
Scanner in = new Scanner([Link]);
[Link]("Enter number: "); int
num = [Link]();
int orgNum = num;
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)
[Link](orgNum + " is a Niven number"); else
[Link](orgNum + " is not a Niven number");
}
}
Question
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 [Link]; public


class SpyNumber
{
public static void main( ) {
Scanner in = new Scanner([Link]);
[Link]("Enter Number: "); int
num = [Link](); int digit, sum = 0;
int orgNum = num;
int prod = 1; while
(num > 0) { digit =
num % 10; sum +=
digit; prod *=
digit;
num /= 10;
}
if (sum == prod)
[Link](orgNum + " is Spy Number"); else
[Link](orgNum + " is not Spy Number");
}
}

Common questions

Powered by AI

The 'do-while' loop is an exit-controlled loop, meaning the condition is evaluated after the loop body is executed, ensuring the loop runs at least once . In contrast, the 'while' loop is entry-controlled, checking the condition before the body executes; thus, if the condition is false initially, the loop body may not execute at all .

Entry-controlled loops, such as 'for' and 'while' loops, execute based on an initial condition check, which can prevent unnecessary iterations and enhance performance by avoiding execution when unnecessary . This often results in clear and concise logic, as the condition is assessed before the loop body runs. However, this can also be a pitfall if there is an assumption that the loop body should always execute at least once, leading to potential logic issues or missed operations. In contrast, exit-controlled loops like 'do-while' always execute the loop body once, which can simplify cases where at least one execution is required but might unnecessarily execute additional cycles if not carefully implemented .

'Break' and 'continue' statements control loop execution by altering the natural flow. 'Break' exits the loop immediately, bypassing the remainder of the loop's iterations, and is particularly useful for prematurely terminating loops upon meeting a specific condition . 'Continue,' on the other hand, skips the current iteration and proceeds to the next, useful for skipping specific iterations while still continuing with the loop's execution . They simplify handling specific cases or optimizing execution flow, especially when dealing with complex conditions or when certain iterations should be omitted without breaking the entire loop. However, their misuse can lead to less readable code or logical errors if not applied thoughtfully .

The for loop is preferable when the number of iterations is known ahead of time, providing a concise method of initializing, testing the condition, and updating the loop variable . In contrast, a while loop is useful when the number of iterations is uncertain, as it only requires a condition to be checked before each iteration . Omitting the condition in a for loop causes an infinite loop, whereas a missing condition in a while loop leads to a compilation error .

To convert a for loop to a do-while loop, you must manually handle initialization, condition checking, and updates within the do-while structure . This means initializing variables before entering the loop, placing the loop body's statements between the 'do' and 'while' keywords, and incorporating the condition within the 'while' part after completing the loop body to ensure it runs at least once. Challenges in this conversion include maintaining the loop's logic, as do-while loops inherently differ by always executing once, which can alter program behavior if not managed correctly .

When rewriting a for loop as a do-while loop, the loop's control variables must be initialized before entering the loop, as the do-while will execute its body at least once regardless of the condition . The continuation condition must be carefully placed at the end of the loop body to ensure correct logic flow, as opposed to being checked beforehand like in a for loop. Mixing a loop's control within the loop body can lead to unexpected results, especially if conditions change unexpectedly due to operations within the loop body . It is critical to manage the loop's termination carefully, as the inherent difference in execution control could alter program behavior if not anticipated and countered with precise conditions and updates .

A switch-case structure allows a program to execute different code blocks based on specific user input, effectively creating menu-driven programs . For example, a program might prompt the user to select a sequence generation or calculation task, and based on their choice, each case within the switch statement handles the respective tasks. One case might generate the first 'n' terms of a sequence, while another calculates the sum of a series. If the user inputs a number not listed in the menu, a default case handles this by displaying an error message . This approach simplifies decision-making and enhances user interaction by outlining clear options .

A for loop requires an initialization setting the loop control variable, a condition determining the loop's continuation, an update expression modifying the control variable after each iteration, and the loop body comprising statements to execute repeatedly . The loop executes as long as the condition remains true, and each of these components plays a critical role in managing the loop's execution flow .

An infinite loop occurs when the loop's termination condition is never met, either due to a missing condition or an error in the loop's logic, such as not properly updating the control variable . The implication of an infinite loop is that the program becomes unresponsive, as it continuously executes without completion, consuming computational resources until interrupted .

The loop for calculating the GCD using the Euclidean method involves continuously replacing the larger number with its remainder when divided by the smaller number until the remainder becomes zero . Initially, the larger number is divided by the smaller, and the remainder from this operation becomes the new divisor. This process is repeated within a loop structure, typically a while or do-while loop, until zero is achieved as the remainder. At this point, the last non-zero remainder becomes the GCD. This method efficiently narrows down the GCD by progressively reducing the problem size with each division and remainder calculation, ensuring a fast convergence to the correct solution .

You might also like