List of basic logical programs in Java

Logical programming is a programming paradigm that is largely based on formal logic. Logical programming is mostly asked in the interview by the interviewer to check the logical skills of the candidates. In this article, you will see the very basic and commonly asked logical programs in the interview with clear explanations such as,

  • Fibonacci series
  • Calculate the factorial
  • Check Prime number
  • Check Perfect number
  • Check Armstrong number
  • Reverse a number
  • Check Palindrome number
  • Swap two numbers

Fibonacci Series

Fibonacci series is a special type of series in which the next number is the sum of the previous two numbers. For example, 1 1 2 3 5 8 13 21…. up to a given number.

Solution #1 : Using Recursion

FibonacciSeriesWithRecursion.java

package com.javacodepoint.programs;
 
import java.util.Scanner;
 
public class FibonacciSeriesWithRecursion {
 
    // initiating first two numbers of the Fibonacci series
    static int number1 = 0;
    static int number2 = 1;
 
    public static void main(String[] args) {
 
        // Taking input from the user to print Fibonacci series up to how many numbers
 
        System.out.println("Enter number up to which Fibonacci series to print:");
 
        // Reading user input using Scanner object
        int upto = new Scanner(System.in).nextInt();
 
        // Printing first two numbers
        System.out.print(number1 + " " + number2);
 
        // Calling recursive function by decreasing 2 because two numbers are already printed
        printFibonacci(upto - 2);
 
    }
 
    /*
     * Recursive function
     */
    public static void printFibonacci(int count) {
 
        if (count > 0) {
            int nextNumber = number1 + number2;
            number1 = number2;
            number2 = nextNumber;
 
            System.out.print(" " + nextNumber);
 
            // Call the recursive function again
            printFibonacci(count - 1);
        }
    }
}

OUTPUT:

Enter number up to which Fibonacci series to print:
10
0 1 1 2 3 5 8 13 21 34

Solution #2 : Without Using Recursion

FibonacciSeries.java

package com.javacodepoint.programs;
 
import java.util.Scanner;
 
public class FibonacciSeries {
 
    public static void main(String[] args) {
 
        // Taking input from the user to print Fibonacci series up to how many numbers
 
        System.out.println("Enter number up to which Fibonacci series to print:");
 
        // Reading user input using Scanner object
        int upto = new Scanner(System.in).nextInt();
 
        // Initiating first two numbers of the Fibonacci series
        int number1 = 0;
        int number2 = 1;
 
        // Printing first two numbers
        System.out.print(number1 + " " + number2);
 
        // Start the loop from 3 because first two numbers are already printed
        for (int i = 3; i <= upto; i++) {
            int nextNumber = number1 + number2;
            System.out.print(" " + nextNumber);
            number1 = number2;
            number2 = nextNumber;
        }
    }
}

OUTPUT:

Enter number up to which Fibonacci series to print:
8
0 1 1 2 3 5 8 13

Calculate the factorial

The multiplication of all positive integers which are less than or equal to the given positive number is called the factorial of that given integer number.

Example #1, The factorial of the number 5 can be calculated as follow:

1 * 2 * 3 * 4 * 5 = 120

Example #2, The factorial of the number 8 can be calculated as follow:

1 * 2 * 3 * 4 * 5 * 6 * 7 * 8 = 40320

Solution #1 : Using Recursion

FactorialCalculation.java

package com.javacodepoint.programs;
 
import java.util.Scanner;
 
public class FactorialCalculation {
 
    public static void main(String[] args) {
 
        // Taking input from the user to calculate factorial for a given number
 
        System.out.println("Enter number to calculate factorial:");
 
        // Reading user input using Scanner object
        int number = new Scanner(System.in).nextInt();
         
        if(number < 0) {
            System.out.println("Please enter only positive interger number");
            return;
        }
         
        System.out.println("Factorial of "+number+" is : "+clculateFactorial(number));
 
    }
         
    /* 
     * Method to calculate factorial using recursion
     */
     
    public static int clculateFactorial(int number) {
         
        if(number == 0) {
            return 1;
        }
         
        return number * clculateFactorial(number-1);
    }
}

OUTPUT:

Enter number to calculate factorial:
5
Factorial of 5 is : 120

Solution #2 : Without Using Recursion

FactorialCalculation.java

package com.javacodepoint.programs;
 
import java.util.Scanner;
 
public class FactorialCalculation {
 
    public static void main(String[] args) {
 
        // Taking input from the user to calculate factorial for a given number
 
        System.out.println("Enter number to calculate factorial:");
 
        // Reading user input using Scanner object
        int number = new Scanner(System.in).nextInt();
         
        if(number < 0) {
            System.out.println("Please enter only positive interger number");
            return;
        }
         
        System.out.println("Factorial of "+number+" is : "+clculateFactorial(number));
 
    }
         
    /* 
     * Method to calculate factorial without recursion
     */
     
    public static int clculateFactorial(int number) {
         
        int factorial = 1;
         
        while(number != 0){
             
            factorial = factorial * number ;
            number--;
        }
         
        return factorial;
    }
}

OUTPUT:

Enter number to calculate factorial:
6
Factorial of 6 is : 720

Check Prime number

A Prime number is a number that is divisible by only 1 and itself. A prime number can’t be divided by zero, because numbers divided by zero are undefined. The smallest prime number is 2, which is also the only even prime.

Let’s see the logic to check whether a number is a prime number or not,

Solution

PrimeNumber.java

package com.javacodepoint.programs;

import java.util.Scanner;

public class PrimeNumber {

	public static void main(String[] args) {

		System.out.print("Enter an integer number:");

		// Reading user input using Scanner object
		int number = new Scanner(System.in).nextInt();
		
		if(number > 1 && checkPrime(number)) {
			System.out.println("The given number is a prime number.");
		}else {
			System.out.println("The given number is not a prime number.");
		}

	}
	
	/*
	 * Method to check whether number is prime or not
	 */
	
	public static boolean checkPrime(int number) {
		
		boolean isPrime = true;
		
		for(int i=2; i <= (number/2); i++ ) {
			
			if(number % i == 0) {
				isPrime = false;
				break;
			}
			
		}
		
		return isPrime;
		
	}
}

OUTPUT:

Enter an integer number:13
The given number is a prime number.

Check Perfect number

The Perfect Number is a special type of positive number. When the number is equal to the sum of its positive divisors excluding the number, it is called a Perfect Number.

For example, 28 is the perfect number because when we sum the divisors of 28, it will result in the same number. The divisors of 28 are 1, 2, 4, 7, and 14. 28 = 1 + 2 + 4 + 7 + 14
28 = 28

Let’s see the logic to check it,

Solution

package com.javacodepoint.programs;

public class CheckPerfectNumber {
    
    public static void main (String[] args){   
        
    	System.out.println("All Perfect numbers between 1 - 1000:");   
    	
        for (int i = 1; i < 1000; i++ ){   
            if (isPerfectNumber(i)) {
            	System.out.println( i +" is a perfect number");
            }   
        }  
    } 
    
    
    /*
     * Method that will return true when number will be perfect   
     */
    static boolean isPerfectNumber(int number) {   
        
    	int sum = 1;   
    
        // Finding all the divisors   
        for (int i = 2; i * i <= number; i++) {   
            if (number % i == 0) {   
                if(i * i != number) {   
                    sum = sum + i + number / i;   
                } else { 
                    sum = sum + i;  
                }
            }   
        }    
        
        // Checking whether the sum of all divisors and number both are equal or not  
        if (sum == number && number != 1) {  
            return true;   
        }
        
        return false;   
    }
}

OUTPUT:

All Perfect numbers between 1 – 1000:
6 is a perfect number
28 is a perfect number
496 is a perfect number

Check Armstrong number

A special positive number whose sum of cubes of its individual digit is equal to that number is called an Armstrong Number

Example #1,
The number 153 is an Armstrong number. It can be checked as follow:
(1)3 + (5)3 + (3)3 => 1 + 125 + 27 => 153

Example #2,
The number 371 is also an Armstrong number and It can be checked as follow:
(3)3 + (7)3 + (1)3 => 27 + 343 + 1 => 371

Let’s see the logic to check whether a number is an Armstrong number or not,

Solution

ArmstrongNumber.java

package com.javacodepoint.programs;

import java.util.Scanner;

public class ArmstrongNumber {

	public static void main(String[] args) {
		
		// Taking input from the user to check whether number is Armstrong

		System.out.println("Enter a number to check Armstrong :");

		// Reading user input using Scanner object
		int number = new Scanner(System.in).nextInt();
		
		if(checkArmstrong(number)) {
			System.out.println("The given number is an Armstrong number.");
		}else {
			System.out.println("The given number is not an Armstrong number.");
		}
		
	}
	
	/*
	 * Method to check Armstrong number
	 */
	public static boolean checkArmstrong(int number) {
	    
		int sumOfCube = 0;
		int temp = number;    
	    while(number > 0){
	    	
	    	//Getting last digit 
	        int a = number % 10;  
	        
	        //Removing last digit from number  
	        number = number / 10;  
	        
	        //Calculating sum of cubes of digits    
	        sumOfCube = sumOfCube + (a*a*a); 
	    } 
	    
	    if(temp == sumOfCube) {
	    	return true;
	    }
	    
	    return false;
	}

}

OUTPUT:

Enter a number to check Armstrong :
370
The given number is an Armstrong number.

Reverse a number

The reverse of a given number is simply called as when the number is 123, the reverse number should be 321. In java, there are multiple ways to calculate the reverse of a given number. Here we will discuss a simple way using a while loop.

Follow the below steps to calculate the reverse of a number,

  1. First find the last digit of given number (calculating the remainder by dividing the number by 10).
  2. Now multiply the variable reverse by 10 and add the calculated remainder of previous step.
  3. Remove the last digit from the number by dividing the number by 10.
  4. Repeat the above 3 steps inside while loop until the number become 0.

Let’s see the complete logic to calculate the reverse of a given number,

Solution

ReverseNumber.java

package com.javacodepoint.programs;

import java.util.Scanner;

public class ReverseNumber {

	public static void main(String[] args) {

		// Taking input from the user to reverse
		
		System.out.print("Enter an integer number:");

		// Reading user input using Scanner object
		int number = new Scanner(System.in).nextInt();
		
		//Initiating reverse variable with 0 
		int reverse = 0;
		int tempNumber = number;
		
		// while loop will continue until the number become 0
		while(number > 0) {
			
			//Finding the last digit of the number
			int remainder = number % 10;
			
			//Calculating the reverse by multiplying it with 10 and adding remainder (last digit) 
			reverse = reverse * 10 + remainder;
			
			//Removing the last digit from the number
			number = number / 10;
		}
		
		System.out.print("The reverse of the given number is = "+reverse);

	}

}

OUTPUT:

Enter an integer number: 12345
The reverse of the given number is = 54321

Check Palindrome number

A Palindrome number is a special type of number. After reversing a number, if the number will be the same as the original number then that number will be called a Palindrome number.

For example, some Palindrome number is as follow:

121, 242, 12321, 515, 8448, 2345432, etc.

Let’s see the logic to check whether a given number is a Palindrome number or not,

Solution

CheckPalindromeNumber.java

package com.javacodepoint.programs;

import java.util.Scanner;

public class CheckPalindromeNumber {

	public static void main(String[] args) {
		
		// Taking input from the user to check Palindrome number

		System.out.print("Enter an integer number:");

		// Reading user input using Scanner object
		int number = new Scanner(System.in).nextInt();
		
		// Calling method to check Palindrome
		if(isPalindromeNumber(number)) {
			System.out.print("The given number is a Palindrome number.");
		}else {
			System.out.print("The given number is not a Palindrome number.");
		}

	}
	
	/*
	 * Method to check number is Palindrome number or not
	 */
	public static boolean isPalindromeNumber(int number) {
		int remainder, reverse=0;      
        
		//Storing number into a temporary variable  
        int temp = number;      
          
        //Reversing the number  
        while(number > 0){
        	//calculating remainder
        	remainder = number % 10;  
        	
        	//calculate reverse of the number when loop ends.
        	reverse = (reverse*10) + remainder;
        	
        	//removing last digit from the number
            number = number/10;      
        }   
  
        //Checking whether the reversing number is equal to the number or not  
        if(temp == reverse) {
        	return true;
        }
        return false;
	}

}

OUTPUT #1:

Enter an integer number:121
The given number is a Palindrome number.

OUTPUT #2:

Enter an integer number:123
The given number is not a Palindrome number.

Swap two numbers

Swapping two numbers can be also known as exchanging the numbers between two variables. The swapping of two numbers without using a third variable or a temporary variable can be done by following the below simple steps:

For example, let’s take two numbers x=20 (first variable) and y=30 (second variable),

  1. Add both number (x+y) and store it in first variable (x). ie x = x + y
  2. Now Substract the second number from the first, and store it in y variable. ie. y = x – y
  3. Now to the step two again but store the value in x variable. ie. x = x – y

Let’s see the calculation steps:

x = x + y => x = 20 + 30 => 50
y = x – y => y = 50 – 20 => 30
x = x – y => x = 50 – 30 => 20

Let’s see the logic to do the same,

Solution

SwapTwoNumbers.java

package com.javacodepoint.programs;

public class SwapTwoNumbers {

	public static void main(String[] args) {
		
		//Initiating two integer numbers
		
		int x = 20, y=30;
		
		//Print both number before swapping
		System.out.println("x = "+x+", y= "+y);
		
		//Logic to swap these numbers without using a third variable
		
		x = x + y;		
		y = x - y;		
		x = x - y;
		
		//Printing the both number again after swapping
		System.out.println("x = "+x+", y= "+y);

	}

}

OUTPUT:

x = 20, y= 30
x = 30, y= 20

Summary

In this article, you have seen the basic logical programs which are commonly asked in interviews by the interviewer.

Hope you like it. If you have any doubts or questions about the above programs you can ask by writing in the comment below.

Java logical programs list


Java Basic Programs

Java Programs based on the Collection Framework

Leave a Reply

Your email address will not be published. Required fields are marked *