Tag: java number programs

  • Perfect Square Program in Java

    In this tutorial, we will write a java program to check if a given number is a perfect square or not. Before that, you should have knowledge of the following topic in Java.

    We will look at two java perfect square programs:

    1. With sqrt() function
    2. Without sqrt() funciton

    Both of the programs below take the number as user input and process it. The first program uses the math function sqrt() to check for perfect square and the second program uses if..else statement to check.

    In this java program, both programs have a user-defined boolean function that returns true or false to the main function.


    Using sqrt() function

    import java.util.Scanner;
    
    public class Main
    {
      public static void main(String[] args)
      {
        int num;
        boolean result = false;
    
        Scanner scan = new Scanner(System.in);
    
        System.out.print("Enter the number: ");
        num = scan.nextInt();
    
    
        result = isPerfectSquare(num);
    
        // check the returned result
        if (result)
          System.out.println(num + " is a Perfect Square");
        else
          System.out.println(num + " is NOT a Perfect Square");
      }
    
      //user-defined function
      public static boolean isPerfectSquare(int num)
      {
        double root = Math.sqrt(num);
        return (root - Math.floor(root) == 0);
      }
    }

    Output:

    Enter the number: 16
    16 is a Perfect Square


    Java Program to check for Perfect Square without using sqrt

    import java.util.Scanner;
    
    public class Main
    {
      public static void main(String[] args)
      {
        int num;
        Scanner scan = new Scanner(System.in);
    
        System.out.print("Enter the number: ");
        num = scan.nextInt();
    
        // check the result with condition
        if (isPerfectSquare(num))
          System.out.println(num + " is a Perfect Square");
        else
          System.out.println(num + " is NOT a Perfect Square");
      }
    
     //user-defined function
      public static boolean isPerfectSquare(int num)
      {
        for (int i = 1; i * i <= num; i++)
        {
          if ((num % i == 0) && (num / i == i))
            return true;
        }
    
        return false;
      }
    }

    Output:

    Enter the number: 25
    25 is a Perfect Square

    Enter the number: 21
    21 is NOT a Perfect Square


  • Java Program to Find the LCM of Two Numbers

    Here, we will write a program to calculate the LCM of two numbers in java. LCM stands for Lowest Common Factor. The Numbers will be taken as input from the user using the scanner class.

    Before we start, click on the links below to have a proper working idea of the if statement and break statement that this program uses.


    Program to Find the LCM of Two Numbers in Java

     //find the lcm of two number in java
      
     import java.util.Scanner;
    
     public class LCM 
     {
        public static void main(String[] args) 
        {
          int num1, num2, lcm;
            
          Scanner s = new Scanner(System.in);
          System.out.print("Enter the first number: ");
          num1 = s.nextInt(); 
            
          Scanner sc = new Scanner(System.in);
          System.out.print("Enter the second number: ");
          num2 = sc.nextInt();
            
          // maximum number between n1 and n2 is stored in lcm
          lcm = (num1 > num2) ? num1 : num2;
            
          while(true)
          {
            if( lcm % num1 == 0 && lcm % num2 == 0 )
            {
              System.out.printf("The LCM of %d and %d is %d.", num1, num2, lcm);
              break;
             }
            ++lcm;
          }
        }
     }

    Output:

    Enter the first number: 81
    Enter the second number: 27
    The LCM of 81 and 27 is 81.


  • Java Program to Find the Greatest of Three Numbers

    The following program takes three integers from the user and finds the largest of those three numbers. The program uses if..elseif statement to check the greatest of three and print them accordingly.

    Before we start, click on the links below to have a proper working idea of if..elseif statement that this program uses.


    Program to Find the Greatest of Three Numbers in Java

     //find the greatest of three numbers in java
    
     import java.util.Scanner;
    
     public class GreatestNumber 
     {
       public static void main(String[] args) 
       {
         int num1, num2, num3;
            
         Scanner s = new Scanner(System.in);
         System.out.println("Enter the first number:");
         num1 = s.nextInt();
            
         System.out.println("Enter the second number:");
         num2 = s.nextInt();
            
         System.out.println("Enter the third number:");
         num3 = s.nextInt();
            
            
         if(num1 > num2 && num1 > num3)
         {
           System.out.println("Largest number is:"+num1);
         }
         else if(num2 > num3)
         {
           System.out.println("Largest number is:"+num2);
         }
         else
         {
           System.out.println("Largest number is:"+num3);
         }
        
       }
     }

    Output:

    Enter the first number:
    34
    Enter the second number:
    89
    Enter the third number:
    23
    Largest number is:89


  • Java Program to Display the Odd Numbers

    The following program takes the value for n that is the max limit of n from the user. The program starts checking for odd numbers between this range 1 to n and it displays all the odd numbers lying within that range.

    Before we start, click on the links below to have a proper working idea of for loop and if statement that this program uses.


    Program to display the Odd Numbers within the range in Java

    //display the odd number in java
    
     import java.util.*;
    
     public class DisplayOddNumbers
     {
        public static void main(String args[]) 
        {
      int n;
      Scanner sc=new Scanner(System.in);
      
      System.out.print("Enter the number: ");
        n=sc.nextInt();
        
      System.out.print("Odd Numbers between 1 to "+n+" are: ");
      
        for (int i = 1; i <= n; i++) 
        {
          // if the number is not divisible by 2 then it is even
          if (i % 2 != 0) 
          {
            System.out.print(i + " ");
          }
        }
      }
     }

    Output:

    Enter the number: 10
    Odd Numbers between 1 to 10 are: 1 3 5 7 9


  • Java Program to Check Positive or Negative Numbers

    In this tutorial, we will write a program to check whether the number is positive or negative in java. The program takes the user input for the number to be checked and performs the calculation.

    Before, we begin you need to have the idea of the proper working of if-else..if statement. Click the link below.:


    Java Program to Check for Positive and Negative Numbers

     //check for positive or negative of a number in java
    
     import java.util.Scanner;
    
     public class PositiveNegativeNumber
     {
        public static void main(String[] args) 
        {
          int num;
          Scanner s = new Scanner(System.in);
          System.out.print("Enter the number: ");
            
          num = s.nextInt();
          if(num > 0)
          {
            System.out.println(num+" is a positive number");
          }
          else if(num < 0)
          {
            System.out.println(num+" is a negative number");
          }
          else
          {
            System.out.println(num+" is neither positive nor negative");
          }
        }
     }

    Output:

    Enter the number: -5
    -5 is a negative number


  • Java Program to Find the Sum of the Digits of a Number

    In this example, we will calculate the sum of the Digits of a Number in java taking the value from the user. Before we begin, you should have knowledge on the following topic in Java:

    Explanation: This is an easy program if you have the working technique of the operator. Suppose the entered number is 123, we will create a program in a loop that will add these three digits such as 1 + 2 + 3. And display the result.


    Java Program to Find a Factorial of a Number Using for loop

     //calculate the sum of the digits of a number in java
    
     import java.util.Scanner;
    
     public class SumOfDigits 
     {
        public static void main(String args[])
        {
           int num, temp, sum = 0;
            
           Scanner s = new Scanner(System.in);
            
           System.out.print("Enter the number: ");
           num = s.nextInt();
            
           while(num > 0)
           {
              temp = num % 10;
              sum = sum + temp;
              num = num / 10;
           }
            
           System.out.println("Sum of the entered Digits:"+sum);
        }
     }

    Output:

    Enter the number: 4567
    Sum of the entered Digits:22


  • Java Program to Find a Factorial of a Number using Recursion

    In this example, we will calculate the factorial of a number taking the value from the user.
    You can also learn to find the Factorial of a Number in Java Using for loop.

    Recursion refers to the function calling itself inside its function in a program.

    Before we begin, you should have the knowledge of the following:

    Factorial of n number: Factorial of n number is the product of all the positive descending integers and is denoted by n!.
    Example:

    factorial of n (n!) = n * (n-1) * (n-2) * (n-3)….1
    factorial of 5 (n!) = 5 * 4 * 3 * 2 * 1
    NOTE: Factorial of 0 (0!) = 1


    Factorial Program using Recursion in java.

     //find the factorial of a number using recursion in java
    
     import java.util.Scanner;
    
     public class FactorialRecursion
     {
       public static void main(String args[])
       {
    
         Scanner scanner = new Scanner(System.in);
         System.out.print("Enter the number: ");
    
         int num = scanner.nextInt();
    
         //Called the user defined function fact
         int factorial = fact(num);
    
         System.out.println("Factorial of entered number is: " + factorial);
       }
    
       //function
       static int fact(int n)
       {
         int output;
         if (n == 1)
         {
           return 1;
         }
         output = fact(n - 1) *n; //recursion
         return output;
       }
     }

    Output:

    Enter the number: 4
    Factorial of entered number is: 24


  • Java Program to Find a Factorial of a Number

    In this example, we will calculate the factorial of a number taking the value from the user. You may also learn to find Factorial of a Number in Java Using recursion.

    Before we begin, you should have the knowledge of the following:

    Factorial of n number: Factorial of n number is the product of all the positive descending integers and is denoted by n!.

    Example:

    factorial of n (n!) = n * (n-1) * (n-2) * (n-3)….1
    factorial of 5 (n!) = 5 * 4 * 3 * 2 * 1
    NOTE: Factorial of 0 (0!) = 1


    Java Program to Find a Factorial of a Number Using for loop.

     //find the factorial of a number in java
    
     import java.util.Scanner;
    
     public class FactorialOfANumber
     {
      public static void main(String args[])
      {
        int fact=1;
        Scanner scanner = new Scanner(System.in);
    
        System.out.print("Enter the number: ");
        int num = scanner.nextInt();
    
        for(int i=1;i<=num;i++)
        {
         fact = fact * i;
        }
        System.out.println("Factorial of entered number is: "+fact);
      }
    
     }

    Output:

    Enter the number: 5
    Factorial of entered number is: 120


  • Java Program to Find the Sum of Natural Numbers

    It is the Basic Java Program to find the sum of N natural numbers. The program below uses the While loop, if you want to learn about the while loop click below.

    Example: If you want to find the sum of 5 natural numbers, the process will be executed in this manner:
    1 + 2 + 3 + 4 + 5
    The result will be: 15


    Java Program to Find the Sum of Natural Numbers using While Loop

    //Sum of Natural numbers in java
      
    public class SumNaturalNumbers 
    {
      public static void main(String[] args) 
       {
    
       int n = 100, count = 1, sum = 0;
    
       while(count <= n)
       {
           sum = sum + count;
           count++;
       }
    
       System.out.println("Sum: "+sum);
       }
    }

    Output:

    Sum: 5050

    In the above program, n is already defined in the program but if you wish to take the input of n from the user, just use the scanner class.


  • Java Program to Generate Random Numbers

    Generating Random numbers in java is quite easy as it provides various classes to do that. It comes in handy when needed to apply to any kind of application development that might require random number generation. Let start by knowing random numbers.

    What is Randon Number?

    We can define Random as something that happens without any conscious decision. Similarly, a random number is a number that is chosen unpredictably or randomly from the set of numbers.

    Random Number can be generated using two ways.

    • java.util.Random class
    • Math.random() method

    We will also learn to generate between the range, at last.


    Java Program to generate Random Number

    1. Using java.util.Random class:

    java.util.Random class allows us to generate random numbers of type integers, doubles, floats, longs, and booleans. In the example below, we will see to generate numbers of type Integers and booleans. Then you can apply to other data-types.

    Program:

    import java.util.Scanner;
    import java.util.Random;
    
    public class JavaRandomNumber
    {
      public static void main(String[] args)
      {
        Scanner sc = new Scanner(System.in);
    
        //user Input
        System.out.println("How many random Numbers do you want?");
        int num = sc.nextInt();
    
        Random random = new Random();
    
        //Interger Random Numbers
        System.out.println(num + " Random Integers are:");
        for (int i = 0; i < num; i++)
        {
          System.out.println(+random.nextInt());
        }
    
        System.out.println("\n");
    
        //Booleans Random Numbers
        System.out.println(num + " Random Booleans are:");
        for (int i = 0; i < num; i++)
        {
          System.out.println(random.nextBoolean());
        }
      }
    }

    The output of generating random numbers using java.util.Random class:


    2. Using Math.random() method:

    Math.random() method allows you to create only a random number of type doubles as shown below.

    Program:

    import java.util.Scanner;
    
    public class JavaRandomNumber
    {
      public static void main(String[] args)
      {
        Scanner sc = new Scanner(System.in);
        
        //user Input
        System.out.println("How many random Numbers do you want?");
        int num = sc.nextInt();
        
        //Doubles Random Numbers
        System.out.println(num+" Random Doubles are:");
        for(int i = 0; i < num; i++)
        {
            System.out.println(+Math.random());
        }
      }
    }

    The output of generating random numbers using Math.random() method:


    Java Program to generate Random Number within the range

    import java.util.Scanner;
    import java.util.Random; 
    
    public class JavaRandomNumber
    {
      public static void main(String[] args)
      {
        Scanner sc = new Scanner(System.in);
        
        //user Inputs
        System.out.println("How many random Numbers do you want?");
        int num = sc.nextInt();
        
        System.out.println("What is the last range of number starting from 0 to _?");
        int lastNum = sc.nextInt();
        
        Random random = new Random();
        
        //Doubles Random Numbers
        System.out.println("\n"+num+" Random integers within 0 to "+lastNum+ " are : ");
        for (int i = 0; i < 5; i++)
        {
            System.out.println(+random.nextInt(lastNum));
        }
      }
    }

    The output to generate random numbers between the range in java:

    How many random Numbers do you want?
    4
    What is the last range of number starting from 0 to _?
    30

    4 Random integers within 0 to 30 are :
    1
    15
    9
    28
    4

    This random generation of numbers within range can be applied to Math.random() method, we only need to replace the code inside the for loop to System.out.println((int)(Math.random() * lastNum));.