For While Loops: 10 Practice Problems and Solutions
This is the solution for the practice question set on the concept of iteration statements (for and while loops). You can find the corresponding list of questions here. Try solving the questions yourself before you go through the solutions.
Problem: Write a program that calculates the sum of the following series up to `n` terms:
S = 1 + 1/1! + 1/2! + 1/3! + … 1/n!
Condition: Use loops to calculate each factorial term and sum them. Allow the user to input the value of `n`.
CODE :
import java.io.*;
import java.util.*;
class Main
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
//declaring all variables
int n,i,j;
double S=1.0;
//S = 1 as we will start a loop from 1/1! till 1/n!
System.out.print("Enter value of n for series : ");
n=sc.nextInt();
//performing calculations
for(i=1;i<=n;i++)
{
//calculating factorial for each value
int fact=1;
for(j=1;j<=i;j++)
{
fact=fact*j;
}
//incrementing S
S=S+(1.0/fact);
}
//printing output
System.out.println("S = "+S);
}
}
Problem: Write a program that takes an integer as input and reverses its digits. For example, if the input is `1234`, the output should be `4321`.
Condition: Use loops to extract each digit and build the reversed number. Ensure the solution handles both positive and negative integers.
CODE :
import java.io.*;
import java.util.*;
class Main {
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
//declaring all variables
int n,rem,rev=0;
//taking input
System.out.print("Enter the number : ");
n=sc.nextInt(); //eg. 1253
while(n>0){
rem=n%10; //eg. 3 -> 5 -> 2 -> 1
rev=rev*10+rem; //eg. 3 -> 30+5 -> 350+2 -> 3520+1
n=n/10; //eg. 125 -> 12 -> 1
}
//printing output
System.out.println("Reversed number : "+rev); //eg. 3521
}
}
Problem: Write a program that generates the first `n` terms of the Fibonacci sequence.
Condition: Use a loop to generate the terms without using recursion. Allow the user to input the value of `n` and print the sequence.
CODE :
import java.io.*;
import java.util.*;
class Main {
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
//declaring all variables
int n,a=-1,b=1,c=0;
//taking input
System.out.print("Enter 'n' for n terms of Fibonacci : ");
n=sc.nextInt();
while(n>0){
// a = -1, b = 1
c=a+b; // c = -1 + 1 = 0
//printing output
System.out.print(c+" ");
a=b; // a = 1
b=c; // b = 0
n--;
}
}
}
Problem: Write a program that counts how many prime numbers are in a given range `[a, b]`, where `a` and `b` are inputs.
Condition: Use nested loops to check each number in the range for primality and count the total prime numbers.
CODE :
import java.io.*;
import java.util.*;
class Main {
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
//declaring all variables
int a,b,i,factorCount=0,primeCount=0;
//taking input
System.out.print("Enter lower limit : ");
a=sc.nextInt();
System.out.print("Enter upper limit : ");
b=sc.nextInt();
while(a<=b){
factorCount=0;
if(a==1) // 1 is not prime
{
a++; // go to next number
continue;
}
for(i=1;i<=a;i++)
{
if(a%i==0)
factorCount++; // increment factorCount for each factor
}
if(factorCount==2) // 1 and number itself
{
primeCount++; // increment primeCount only if number is prime
}
a++;
}
//printing output
System.err.println("Number of primes in range : "+primeCount);
}
}
Problem: Write a program to print the series 25,49,121,169,289 till `n` terms after figuring out the calculation pattern.
CODE :
import java.io.*;
import java.util.*;
class Main {
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
//declaring all variables
int i=5,n,counter=0;
//taking input
System.out.print("Enter value of 'n' : ");
n=sc.nextInt();
// pattern is as follows
// i = 5, counter = 0, next value = i + 2
// i = 7, counter = 1, next val = i + 4
// i = 11, counter = 2, next val = i + 2
// i = 13, counter = 3, next val = i + 4
// i = 17, counter = 4, next val = i + 2
// for every even counter value, add 2 to i
// for every odd counter value, add 4 to i
while(n>0)
{
if(counter>0)
{
// to print a comma before the numbers
System.out.print(",");
}
//printing the output number
System.out.print(i*i);
// increment counter
counter++;
// find if counter is odd or even
if(counter%2==0)
i+=4; // increment i accordingly
else
i+=2;
n--;
}
}
}
Problem: Write a program to print the series 4, 18, 48, 100, 180, 294, 448 till `n` terms after figuring out the calculation pattern.
CODE :
import java.io.*;
import java.util.*;
class Main {
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
//declaring all variables
int i=2,n;
//taking input
System.out.print("Enter value of 'n' : ");
n=sc.nextInt();
// pattern is as follows
// i = 2, output = 2^3 - 2^2 = 8 - 4 = 4
// i = 3, output = 3^3 - 3^2 = 27 - 9 = 18
// for every i, print (i^3 - i^2)
while(n>0)
{
if(i>2)
{
// to print a comma before all numbers except the first
System.out.print(",");
}
System.out.print((int)(Math.pow(i,3)-Math.pow(i,2)));
i++;
n--;
}
}
}
Problem: For any positive integer `n`, the Collatz sequence is defined as:
- If `n` is even, divide it by 2.
- If `n` is odd, multiply it by 3 and add 1.
- Repeat until `n` becomes 1.
Condition: Write a program that takes a starting integer and prints each term in the Collatz sequence until reaching 1. Use a loop to calculate each term.
CODE :
import java.io.*;
import java.util.*;
class Main {
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
//declaring all variables
int n;
//taking input
System.out.print("Enter value of 'n' : ");
n=sc.nextInt();
while(n>=1)
{
if(n>1)
{
// if n > 1, then print n
System.out.print(n+",");
}
else
{
// if n = 1, print 1 and exit loop
System.out.print(n);
break;
}
// if n is even, n = n / 2
if(n%2==0)
{
n=n/2;
}
//if n is odd, n = 3 * n + 1
else
{
n=3*n+1;
}
}
}
}
Problem: Write a program that converts a given decimal number into binary without using built-in conversion functions.
Condition: Use a loop to repeatedly divide the number by 2, recording the remainder each time. Print the binary representation by collecting the remainders in reverse order.
CODE :
import java.io.*;
import java.util.*;
class Main {
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
//declaring all variables
int n,num=0;
//taking input
System.out.print("Enter value of 'n' : ");
n=sc.nextInt();
while(n>0)
{
// creating a number with all remainders
num = num * 10 + (n % 2);
n = n / 2;
}
while(num>0)
{
// printing the output as 'num' in reverse
System.out.print(num%10);
num=num/10;
}
}
}
Problem: Write a program that takes an integer and repeatedly calculates the sum of its digits until a single digit is obtained. For example, for `9875`, the output should be `2` (`9+8+7+5 = 29`, `2+9 = 11`, `1+1 = 2`).
Condition: Use a loop to calculate the sum of digits and continue looping until the result is a single digit.
CODE :
import java.io.*;
import java.util.*;
class Main {
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
//declaring all variables
int n,rem,sum;
//taking input
System.out.print("Enter the number : ");
n=sc.nextInt(); //eg. 9875
while(n>9) //eg. 9875 -> 29 -> 11 -> 2
{
sum=0;
while(n>0)
{
rem=n%10;
sum+=rem; //eg. 9+8+7+5 = 29 -> 2+9 = 11 -> 1+1 = 2
n=n/10;
}
n=sum; //eg. 29 -> 11 -> 2; loop breaks when n = 2
}
//printing output
System.out.println("Sum of digits until a single digit : "+n); //eg. 2
}
}
Problem: Write a program to print the series -10, -8, 6, 40, 102, 200 till `n` terms after figuring out the calculation pattern.
CODE :
import java.io.*;
import java.util.*;
class Main {
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
//declaring all variables
int n,i=2,num=-10;
//taking input
System.out.print("Enter value of 'n' : ");
n=sc.nextInt();
while(n>0)
{
// printing first value
System.out.print(num);
// to print a comma for all values except the last
if(n>1)
{
System.out.print(",");
}
// performing calculations
num = num +(int)(Math.pow(i,2)-2);
// updating values
i+=2;
n--;
}
}
}
Numbers In Java : 10 Practice Problems a...
This is the solution for the practice question set on different numbers (like Harshad, Armstrong, Perfect, and so on).
Read More
Switch Case Simplified: 5 Solved Practic...
This is the solution for the practice question set on the concepts of switch case and fall through.
Read More
Mastering If-Else Statements: 8 Solved P...
This is the solution for the practice question set on conditional (if else) statements.
Read More