Skip to main content

Control Flow: Practice

Basic Loops 2

Time to step it up with some more challenges!


Program1: Write a java program to enter a number and print its reverse.

Input

12345

Output

54321

Approach

Explanation

We now know how to get hold of each digit of a number. But the point is how can we reverse the number?

Let me demonstrate how to do that with the help of an example:

  • Let a number be 123. You start with an empty space for the reverse number.
  • Take the last digit of 123, which is 3, and place it in the empty space. So, now, you have 3.
  • Next, take the next digit, which is 2, and place it next to the 3. So, now, you have 32.
  • Finally, take the first digit, which is 1, and place it at the end. Now, you have 321 which is the reverse of 123.

Fine! But how can we place a digit next to what we already have in the result? Isn't it like shifting all the digits of result to higher place? Like if we multiply what we have in the result by 10, that will allow us to make space for the next digit, which we can include by adding it to the result.

So, for the number 123, the reverse would be calculated like this:

  • reverse = (0 * 10) + 3 = 3
  • reverse = (3 * 10) + 2 = 32
  • reverse = (32 * 10) + 1 = 321

Therefore, the reverse of 123 is 321.

Solution
import java.util.*;

public class main {
    public static void main(String[] args) {
        // Input a number from the user
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter any number to find reverse: ");
        int num = scanner.nextInt();

        int currentNo = num, reverse = 0;
        // Repeat until 'currentNo' becomes 0
        while (currentNo != 0) {
            // Increase place value of reverse and add last digit to reverse
            reverse = (reverse * 10) + (currentNo % 10);

            // Remove the last digit from 'currentNo'
            currentNo /= 10;
        }

        System.out.println("Reverse: " + reverse);
    }
}

Program2: Write a java program to input number from user and check number is palindrome or not.

A number is palindrome if it can be read the same in both forward and backward direction. That means a palindromic number is a number equal to its reverse.

Input

121

Output

121 is palindrome

Approach

Hint

Since palindromic numbers are equal to their reverse, with the help of the previous question, we can easily check if a number is palindrome.

Solution
import java.util.*;

public class main {
    public static void main(String[] args) {
        // Input a number from the user
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter any number to find reverse: ");
        int num = scanner.nextInt();

        int currentNo = num, reverseNo = 0;
        // Repeat until 'currentNo' becomes 0
        while (currentNo != 0) {
            // Increase place value of reverse and add last digit to reverse
            reverseNo = (reverseNo * 10) + (currentNo % 10);

            // Remove the last digit from 'currentNo'
            currentNo /= 10;
        }

        if(num == reverseNo){
          System.out.println(num + " is a palindromic number.");
        }
        else{
          System.out.println(num + " is not a palindromic number.");
        }
    }
}

Program3: Write a java program to find power of a number using for loop.

Input

Base: 2
Exponent: 5

Output

32

Approach

Hint

Imagine you have a plant named "Double" which doubles its size every next day.

On the zeroth day, its height is 1cm(2^0 = 1).

The next day, it doubles to 2cm(2^1 = 2).

And on the second day, it again doubles to 4cm(2^2 = 2 * 2).

The next day it again doubles to 8cm(2^3 = 2 * 2 * 2) and so on.

It's like you need to find its size on the sixth day now.

Solution
import java.util.*;

public class main {
    public static void main(String[] args) {
        long power = 1;

        // Input base and exponent from the user
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter base: ");
        int base = scanner.nextInt();
        System.out.print("Enter exponent: ");
        int exponent = scanner.nextInt();

        // Multiply base, exponent times
        for (int i = 1; i <= exponent; i++) {
            power = power * base;
        }

        System.out.println(base + " ^ " + exponent + " = " + power);
    }
  }

Program4: Write a java program to input a number from user and find all factors of the given number using for loop. 

Input

12

Output

Factors of 12: 1, 2, 3, 4, 6, 12

Approach

Explanation

Any number which divides the given number is a factor of it.

That means we can simply loop from 1 to the given number, and checks if on dividing the given number, the remainder is 0. If it is, then the number we divided with is the factor of given number.

But do you remember:

1 * 16 = 16 * 1

2 * 8 = 16 = 8 * 2

4 * 4 = 16 = 4 * 4

What I mean to say is that, if I know 2 is factor of 16, automatically, 8 (= 16 / 2) will be also a factor of 16. From the above examples, it is clear that I can check only till the square root of given number (sqrt(16) = 4) to find all factors of it.

Solution
import java.util.*;

public class main {
    public static void main(String[] args) {
        // Input base and exponent from the user
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter number: ");
        int num = scanner.nextInt();

        System.out.println("Factors of " + num + " are: ");
        for (int i = 1; i <= Math.sqrt(num); i++){ 
            if (num % i == 0){ 
                // If divisors are equal, print only one 
                if (num / i == i) 
                    System.out.print(" "+ i); 
                else // Otherwise print both 
                    System.out.print(i + " " + num / i + " " ); 
            } 
        } 
    }
  }

Same concept can be used to check whether a number is prime or not.

And since we know how to check whether a number is prime or not, we can even get the prime factors of a number.

import java.util.*;

public class main {
    public static boolean isPrime(int num){
      for (int j = 2; j <= Math.sqrt(num); j++) {
          if (num % j == 0) {
              return false;
          }
      }
      return true;
    }
    public static void main(String[] args) {
        // Input a number from the user
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter any number to print Prime factors: ");
        int num = scanner.nextInt();

        System.out.println("All Prime Factors of " + num + " are: ");

        // Find all Prime factors
        for (int i = 2; i <= Math.sqrt(num); i++) {
            // Check 'i' for a factor of num
            if (num % i == 0) {
                // If 'i' is a Prime number and factor of num
                if (isPrime(i)) {
                    System.out.print(i + ", ");
                }
                //If the otherFactor is Prime
                int otherFactor = num / i;
                if((otherFactor != i) && isPrime(otherFactor)){
                  System.out.print(otherFactor + ", ");
                }
            }
        }
    }
}

Program5: Write a java program to input a number and calculate its factorial using for loop. 

Factorial of a number n is product of all positive integers less than or equal to n and greater than 0. It is denoted as n!.

For example factorial of 5 = 1 * 2 * 3 * 4 * 5 = 120

Input

5

Output

120

Approach

Hint

Since the factorial is the product of all positive integers that are less than or equal to n, we can compute the product by iterating through all of the numbers between 1 and n. And we already know how to do that!

Solution
import java.util.Scanner;

public class main {
    public static void main(String[] args) {
        long factorial = 1L;

        // Input number from user
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter any number to calculate factorial: ");
        int num = scanner.nextInt();

        // Run loop from 1 to num
        for (int i = 1; i <= num; i++) {
            factorial = factorial * i;
        }

        System.out.println("Factorial of " + num + " = " + factorial);
    }
}

Program6: Write a java program to input two numbers from user and find the LCM using for loop. 

LCM(Lowest Common Multiple), also known as LCD(Least Common Divisor ),  is a smallest positive integer that exactly divides two or more numbers. It is also the least number which has the given numbers as factors.

Input

Number1: 12
Number2: 30

Output

60

Approach

Hint

We know how to calculate factors of a number. And LCM is the least number who has the given numbers as factors.
We know for both the numbers to be the factor of LCM, the maximum of both numbers could be one possible option. So, we can start checking with the maximum of both numbers. If it has both the given numbers as factor, our job is done.
Else, we have to check on further numbers. We can check all the numbers one by one until we find one.
Isn't that such a slow process? Do you have any ideas on how we can calculate the LCM more quickly?
Let's try to think on these lines! Since LCM is the the least number which has the given numbers as factors, the number we are checking should be a multiple of both the numbers. So, we can simply check multiples of the larger number and we can continue checking until we find a number which is a multiple of smaller number too. And yaah, that's it!

Solution
import java.util.*;

public class main {
    public static void main(String[] args) {
        int lcm = 1;

        // Input two numbers from the user
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter any two numbers to find LCM: ");
        int num1 = scanner.nextInt();
        int num2 = scanner.nextInt();

        // Find the maximum between num1 and num2
        int max = (num1 > num2) ? num1 : num2;

        // First multiple to be checked
        int i = max;

        // Run loop indefinitely until LCM is found
        while (true) {
            if (i % num1 == 0 && i % num2 == 0) {
                // If 'i' divides both 'num1' and 'num2', then 'i' is the LCM
                lcm = i;

                // Terminate the loop after LCM is found
                break;
            }

            // If LCM is not found, generate the next multiple of max between both numbers
            i += max;
        }

        System.out.println("LCM of " + num1 + " and " + num2 + " = " + lcm);
    }
}
Let's explore HCF hand-in-hand with LCM! 🤓

Since we now know how to calculate the LCM of 2 numbers, we can calculate the HCF too.

HCF (Highest Common Factor), also known as GCD (Greatest Common Divisor) or GCF (Greatest Common Factor), is the greatest number that divides exactly two or more numbers. That means it is the greatest number which is the factor of both the given numbers.

import java.util.*;

public class main {
    public static void main(String[] args) {
        int hcf = 1;

        // Input two numbers from the user
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter any two numbers to find HCF: ");
        int num1 = scanner.nextInt();
        int num2 = scanner.nextInt();

        // Find the minimum between two numbers
        int min = (num1 < num2) ? num1 : num2;

        for (int i = 1; i <= min; i++) {
            // If 'i' is a factor of both numbers
            if (num1 % i == 0 && num2 % i == 0) {
                hcf = i;
            }
        }

        System.out.println("HCF of " + num1 + " and " + num2 + " = " + hcf);
    }
}

Let's move on to the next article, eagerly awaiting for us to master loops!