Tag: java number programs

  • Java Program to Find GCD of Two Numbers

    In this tutorial, we will write a java program to calculate the GCD of two numbers.

    GCD of two numbers in Java:

    GCD(Greatest Common Divisor) or we can say HCF(Highest Common Factor) of two numbers is the largest number(integer) that divides both the number. Or in other words, two numbers that are divisible by the same largest number leaving no remainder.

    For example: GCD of 20 and 28 is 4 as shown in the image below.

    GCD of two numbers

    Java program two calculate GCD of two numbers using for loop and if statement

    In this example, we take the user input for the two numbers whose GCD needs to be found and store it in num1 and num2. Then iterate through for loop for i less than equal num1 and i less than equal to num2

    Inside for loop, we set if statement to check for the divisibility 0f both num1 and num2 by i. If true then we set the value of current i to gcd. This iteration runs until it finds the largest number that divides both num1 and num2.


    Program: GCD of Two Number in Java.

     //calculate the gcd of two number
     
     import java.util.Scanner;
    
     public class GCDJava
     {
       public static void main(String[] args) 
       {
         int num1 , num2, gcd = 1;
         Scanner sc = new Scanner(System.in);
    
         System.out.println("Enter the first number:");
         num1 = sc.nextInt();
            
         
         System.out.println("Enter the second number:");
         num2 = sc.nextInt();
            
            
         for(int i = 1; i <= num1 && i <= num2; ++i)
         {
           // Checks if i is factor of both integers
           if(num1 % i==0 && num2 % i==0)
              gcd = i;
         }
        System.out.printf("G.C.D of %d and %d is %d", num1, num2, gcd);
       }
     }

    The Output of GCD of two numbers in java

    Enter the first number:
    81
    Enter the second number:
    153
    G.C.D of 81 and 153 is 99


  • Java Program to find the Square Root of a Number

    This post shows how to find a square root of a number in java. We will learn two methods to find the square root one by an in-built math method called Math.sqrt() and the other by using do-while loop.
    let’s begin.


    1. Program to find square root using Math.sqrt() in java

    This is a simple and easy method we only need to use Math.sqrt() which returns the square root value when an argument of double is passed to it. For positive or negative zero arguments, it returns the same value as that of the argument.

    Program:

    import java.util.Scanner;
    
    public class SquareRootjava
    {
      public static void main(String args[])
      {
        Scanner sc = new Scanner(System.in);
    
        //user input
        System.out.println("Enter the number");
        double number = sc.nextDouble();
    
        //using method to get square root
        double squareRoot = Math.sqrt(number);
    
        //Display
        System.out.print("Square root of " + number + " is " + squareRoot);
      }
    }

    The output for the square root using Math.Sqrt:

    square root

    2. Program to find square root using do-while in java

    This is another method to find the square root without using Math.sqrt() in java. Here we used the so-while loop. We take the user input passed to squareRootResult() method and run the do-while loop. After the calculation, we return the result back and display it as shown in the program below.

    Program:

    import java.util.Scanner;
    public class SquareRoot
    {
    
      public static double squareRootResult(int n)
      {
        double temp;
    
        double returnResult = n / 2;
    
        do {
          temp = returnResult;
          returnResult = (temp + (n / temp)) / 2;
        } while ((temp - returnResult) != 0);
    
        return returnResult;
      }
    
      public static void main(String[] args)
      {
        Scanner sc = new Scanner(System.in);
    
        System.out.println("Enter the number");
        int number = sc.nextInt();
    
        System.out.print("Square root of " + number + " is: " + squareRootResult(number));
        sc.close();
      }
    }

    Output:

    square root

  • Java Program to check whether the Number is Palindrome or not

    In this tutorial on Java Program to check whether the number is Palindrome or not, we will learn what is palindrome number is and its programming implementation with an explanation.

    What is a palindrome number?

    A number is said to be a Palindrome number if it remains the same when its digits are reversed or are the same as forward. It is also applied to the word, phrase or other sequences of symbols.

    For example: 14141, 777, 272 are palindrome numbers as they remain the same even if reversed. If we take an example of ‘mam’ or ‘madam’, these are also palindrome words.


    Explanation:
    To check the palindrome number we use the logic to create a program. With the help of a while loop and arithmetic operators such as the remainder operator(%) and the division operator(/), we create a java program to check for palindrome numbers.

    First, take the user input and run the while loop until the entered number(n) is not zero. Inside while loop, we take the remainder that returns the remainder in a division of n/10 that is remainder = n % 10;. Then inside rev variable put the following rev = rev * 10 + remainder;. At last, n is divided by 10 and returns the quotient.

    After the end of the while loop, we check if the original number is equal to the reversed number. If true print accordingly as shown in the program.


    Java Program to check whether the number is palindrome or not

     //check the number for palindrome
    
     import java.util.Scanner;
    
     public class PalindromeCheck 
     {
       public static void main(String[] args) 
       {
         int n, rev = 0, remainder, originalNumber;
        
         Scanner sc = new Scanner(System.in);
        
         System.out.print("Enter an integer: ");
         n = sc.nextInt();
            
         originalNumber = n;
            
         // reversing 
         while( n!= 0 )
         {
           remainder = n % 10;
           rev = rev  * 10 + remainder;
           n /= 10;
         }
            
         // Displaying
         if (originalNumber == rev )
            System.out.println(originalNumber + " is a palindrome.");
         else
            System.out.println(originalNumber + " is not a palindrome.");
       }
     }

    Output:

    Enter an integer: 383
    383 is a palindrome.


  • Java Program to check whether a Number is Prime or Not

    In this tutorial, we will write a program to check whether the number is prime or not in java. Before that, you should have knowledge on the following topic in java.

    Prime Number

    A number is said to be a prime number if it is divisible by itself and 1. Example: 3, 5, 7, 11, 13, 17, 19, etc.


    Explanation:
    We take a boolean variable isPrime and assigned it to be true. Then we take the user input and start a for loop for i = 2 end the loop for i less than half of the number entered. i will increase by 1 after each iteration.

    Inside for loop, a temp variable will contain the remainder of each iteration. And then if statement will check for temp to be 0 that is if the remainder is zero, isPrime is set to false. If isPrime is true, the number is Prime number else not.


    Java Program to check whether a Number is Prime or Not

    source code: Java Program to check for the prime number.

     //check for the prime Number
    
     import java.util.Scanner;
     public class PrimrNumberCheck
     {
       public static void main(String args[])
       {
         int temp;
         boolean isPrime = true;
         Scanner scan = new Scanner(System.in);
    
         System.out.print("Enter any number: ");
    
         int num = scan.nextInt();
         scan.close();
    
         for (int i = 2; i <= num / 2; i++)
         {
           temp = num % i;
           if (temp == 0)
           {
             isPrime = false;
             break;
           }
         }
    
         if (isPrime)
           System.out.println(num + " is a Prime Number"); //If isPrime is true 
         else
           System.out.println(num + " is not a Prime Number"); //If isPrime is false 
       }
     }

    Output:

    Enter any number: 13
    13 is a Prime Number


  • Java Program to Check Armstrong Number

    In this tutorial, we will write a Java Program to check Armstrong number. We will write two different programs to check the armstrong number in java.

    1. What is an Armstrong number?
    2. Java program to check the Armstrong Number(for any digit number) using a while and for.
    3. Java program to check the Armstrong Number(using Math.pow() method).


    What is an Armstrong Number?

    A number is said to be an Armstrong Number if even after the sum of its digits, where each digit is raised to the power of the number of digits is equal to the original number. For example 153, 371, 407, 9474, etc are Armstrong Numbers.

    Follow the below calculation.

    Armstrong Number in Java

    Java program to check the Armstrong Number using while and for loops

    import java.util.Scanner;
     
     public class ArmstrongNumber
     {
      public static void main(String[] args)
      {
        int n, num, totalDigits, remainder, result = 0;
     
        System.out.println("Enter the Number:");
        Scanner scanner = new Scanner(System.in);
        
        n = scanner.nextInt();
        scanner.close();
        
        //setting the power to the no. of digits
        totalDigits = String.valueOf(n).length();
        
        num = n;
     
        while (num != 0)
        {
            remainder = num % 10;
            int lastDigits = 1;
            
            for(int i = 0; i < totalDigits; i++)
             {
               lastDigits = lastDigits * remainder;
             }
             
            result = result + lastDigits;
            num /= 10;
        }
     
        if(result == n)
            System.out.println(n + " is an Armstrong number.");
        else
            System.out.println(n + " is not an Armstrong number.");
      }
     }

    Output: You can check for any digit Number.

    Enter the Number:
    9474
    9474 is an Armstrong number.

    Explanation:
    First we create required variables(n, num, totalDigits, remainder, result). Get User Input and store it in n, then we need the number of digits present in that number and store it n totalDigits using code (totalDigits = String.valueOf(n).length();). After that, copy the entered number to num.

    Now start the while loop checking num is not equal to zero. While stops as soon as num becomes zero.
    After each iteration of the while loop, the last digit of num is stored in remainder for the second use. We initiate an int variable lastDigits = 1.

    Now the for loop runs until the totalDigits less than i where is initiated as 0 and increase by 1 after each iteration. Inside for loop lastDigits is multiplied to remainder and the result is added to lastDigits.

    After the end of for loop, the value of lastDigits is assigned to the result variable.
    and at the end, we divide the num by 10 i.e num /= 10; which will remove the last digit from the number.
    This step is continued until the num becomes 0.

    At last, we will check with if-else statement whether the result is equal to the original number or not. If it is found equal,l then the entered number is an Armstrong Number.


    Java program to check the Armstrong Number using Math.pow() method

     //check for armstrong number
      
    import java.util.Scanner;
     
     public class ArmstrongNumber
     {
      public static void main(String[] args)
      {
        int n, num, power, remainder, result = 0;
     
        
        System.out.print("Enter the Number: ");
        Scanner scanner = new Scanner(System.in);
        
        n = scanner.nextInt();
        scanner.close();
        
        //seting the power to the no. of digits
        power = String.valueOf(n).length();
        
        num = n;
     
        while (num != 0)
        {
            remainder = num % 10;
            result += Math.pow(remainder, power);
            num /= 10;
        }
     
        if(result == n)
            System.out.println(n + " is an Armstrong number.");
        else
            System.out.println(n + " is not an Armstrong number.");
      }
     }

    Output: You can check for any digit Number.

    Enter the Number: 370
    370 is an Armstrong number

    Explanation: In the above program we use the inbuilt method (Math.pow()) which makes it easy for us to calculate the raised power to the number.

    The process is the same as explained above, only the difference is instead of for loop we use the method(Math.pow()) as result += Math.pow(remainder, power);.

    If we were to calculate for the only three-digit number then we can simply replace the code:
    result += Math.pow(remainder, power); with
    result = result + remainder*remainder*remainder;


  • Java Program to Generate Fibonacci Series

    In this java program tutorial, we will write a java program to display the Fibonacci series. Let us first understand what is Fibonacci series is and then the Java program to generate them.

    What is Fibonacci Series?

    Fibonacci series is the series of numbers where the next number is achieved by the addition of the previous two numbers. The initial addition of two numbers is 0 and 1.

    For example: 0,1,1,2,3,5,8,13….etc.

    We will see two ways to print the Fibonacci Series.

    • With the help of iteration(for-loop).
    • Using recursion.

    Program Explanation:
    First, we need to initialize the two terms as 0 and 1 as a = 0, b = 0; then get user input for the total number of elements in a series which is stored in an integer variable n.

    After that start iteration up to the number of elements the user inputs. Inside for loop, we assigned the b value in a and the sum value in b and the sum is the addition of a and b. Then we print the value at every iteration as shown in a program.

    At last, the program exits the iteration when integer i is less than or equal to the number of elements as,
    i <= n.


    1. Java program to display Fibonacci series using for loop

    //Fibonacci series in java
    
    import java.util.Scanner;
    
    public class FibonacciJava
    {
      public static void main(String[] args)
      {
        int n, a = 0, b = 0, sum = 1;
    
        Scanner s = new Scanner(System.in);
    
        System.out.print("Enter the Number:");
        n = s.nextInt();
    
        System.out.print("Fibonacci Series of entered number are:");
        for (int i = 1; i <= n; i++)	//display
        {
          a = b;
          b = sum;
          sum = a + b;
          System.out.print(a + " ");
        }
      }
    }

    Output:

    Enter the Number:6
    Fibonacci Series of entered number are:0 1 1 2 3 5


    2. Fibonacci series using Recursion in java

    //Fibonacci Using Recursion
    
    import java.util.Scanner;
    public class FiboSeries
    {
        public static int fiboRecursion(int n)
        {
         if(n == 0)
         {
           return 0;
         }
         if(n == 1 || n == 2)
         {
           return 1;
         }
         return fiboRecursion(n-2) + fiboRecursion(n-1);
        }
    	
      public static void main(String args[]) 
      {
        int number;
        Scanner s = new Scanner(System.in);
            
        System.out.print("Enter the Number:");
        number = s.nextInt();
            
        System.out.print("Fibonacci Series of entered number: ");
    	
        for(int i = 0; i < number; i++)
        {
    	System.out.print(fiboRecursion(i) +" ");
        }
      }
    }

    After executing, the following output will be obtained.

    Enter the Number:8
    Fibonacci Series of entered number: 0 1 1 2 3 5 8 13


  • Java Program to Reverse the Number

    The following Java Program uses the Multiplication and Modulus Operator to reverse the number entered by the User. Something like this,

    If the entered Number is 1234567, then the final result will display 7654321.

    If you do not know about the Operator in Java, click the link below.


    Example: Java Program to Reverse the Number using while loop

    //reverse a number in java
    
     import java.util.Scanner;
    
     public class ReverseNumberJava
     {
       public static void main(String args[])
       {
         int n, rev = 0;
    
         Scanner in = new Scanner(System.in);
    
         System.out.print("Enter an integer to reverse: ");
         n = in .nextInt();
    
         while (n != 0)
         {
           rev = rev * 10;
           rev = rev + n % 10;
           n = n / 10;
         }
    
         System.out.println("Reverse of the entered interger is " + rev);
       }
     }

    Output of reversing a number:

    Enter an integer to reverse: 1234567
    Reverse of the entered interger is 7654321


  • Java Program to Swap Two Numbers using the Third variable

    Here you will learn how Swap two numbers using the third Variable.

    The program declares a temp variable to temporarily store the value of one of the two values. If you want to know how to swap numbers without using a third variable, click the link below.


    Java Program to Swap two numbers using Third Variable

     //swap two number
    
     import java.util.*;
    
     public class SwapTwoNumbersJava
     {
      public static void main(String []s)
      {
        int a, b, temp;
        
        Scanner sc=new Scanner(System.in);
    
        System.out.print("Enter value of a: ");
        a=sc.nextInt();
        
        System.out.print("Enter value of b: ");
        b=sc.nextInt();
    
        System.out.println("Values before swapping - a: "+ a +", b: " + b);
        
        //swap
        temp=a;
        a=b;
        b=temp;
        
        //displaying after swap
        System.out.println("Values after swapping  - a: "+ a +", b: " + b);
      }
     }

    Output:

     Enter value of a: 24
     Enter value of b: 25
     Values before swapping - a: 24, b: 25
     Values after swapping  - a: 25, b: 24

  • Java Exercise: How to Divide in Java

    Division in Java:

    This article will show you the process to divide in Java with output.

    The division is one of the basic operations in java. Others include addition, subtraction, and multiplication. For dividing in java, a division operator (/)is used. This operator takes two operands(the natural numbers to be divided) to divide them.

    We will see two ways for java division:

    • First by declaring the number to be divided inside the program.
    • Second by taking the user input.

    1. Java Program to divide two numbers.

    public class DivisionJava 
    {
     public static void main(String[] args) 
     {
     //declaring operands
     float num1 = 70, num2 = 3;
     
     //division
     float result = num1/num2;
     
     //Display
     System.out.println("The result is: "+result);
     }
    }

    The output of the division in java:

    The result is: 23.333334

    2. Java Program to Divide two Numbers taking User’s Input

    import java.util.Scanner;
    
    public class JavaDivision 
    {
      public static void main(String[] args) 
      {
        Scanner input = new Scanner (System.in);
        
        System.out.print("Enter the first number (Denominator): ");
        int num1 = input.nextInt();
        
        System.out.print("Enter the second number (Numerator): ");
        int num2 = input.nextInt();
        
        //Division
        int result = (num1/num2);
    
        System.out.println("\nThe result of division is:" +result);
      }
    }

    The output of the user input division in Java:

    Enter the first number (Denominator): 70
    Enter the second number (Numerator): 3
    
    The result of division is:23.333334

  • Java Program to Swap Two Numbers Without using the Third Variable

    This post covers the Java Program to swap two numbers without using the third variable. It is easy to swap two numbers using the third variable, we assigned one to a temporary(temp) variable and swap with others.

    Now let us see without using the third variable.


    Explanation:
    With the help of a Scanner class, we take the user input for two integers (a = 5, b = 3).
    Now during the process of swapping, we assigned the value of a equal to the sum of a and b that is,
    a = a + b;
    (a = 5+3 = 8).

    Second, we assigned the value of b equal to the difference between a and b that is,
    b = a - b
    (b= 8 – 3 = 5).

    Lastly, we assigned the value of a equal to the difference between a and b that is,
    a = a - b
    (a= 8 – 5 = 3).

    Then print those swapped values as shown in the program below.


    Java program to swap two numbers without using Third Variable

    //Swapping of two numbers
    
    import java.util.Scanner;
    class SwapTwoNumbers
    {
       public static void main(String args[])
       {
    
        int a, b;
        System.out.println("Enter the two numbers, a and b");
    
        Scanner in = new Scanner(System.in);
    
        a = in.nextInt();
        b = in.nextInt();
      
        System.out.println("Values before Swapping\na = "+a+"\nb = "+b);
        
        a = a + b;
        b = a - b;
        a = a - b;
    
        System.out.println("Values after Swapping without third variable\na = "+a+"\nb = "+b);
       }
    }
    

    Output: