Author: admin

  • Hollow Inverted Right Triangle Star Pattern in Java

    Hollow Inverted Right Triangle Star Pattern in Java

    In this tutorial, we will write a java program to print hollow inverted right triangle star pattern. Before that, you may go through the following topic in java.

    We will display the hollow inverted right triangle pattern of stars in java using different loops. We will use for loop and while and write two different codes.

    The programs however take the number of rows as an input from the user and print the hollow pattern. There is a use of if..else statement in the program to check the boolean condition. It is placed inside the for loop and while loop.


    Hollow Inverted Right Triangle Star Pattern in Java

    Using For Loop

    import java.util.Scanner;
    
    public class Main
    {
      public static void main(String args[])
      {
        int rows, i, j, k;
        Scanner sc = new Scanner(System.in);
    
        System.out.print("Enter the no. of rows: ");
        rows = sc.nextInt();
    
        for (i = rows; i > 0; i--)
        {
          if (i == 1 || i == rows)
          {
            for (j = 1; j <= i; j++)
              System.out.print("*");
          }
          else
          {
            for (k = 1; k <= i; k++)
            {
              if (k == 1 || k == i)
                System.out.print("*");
              else
                System.out.print(" ");
            }
          }
          System.out.println();
        }
      }
    }

    Output:

    Hollow Inverted Right Triangle Star Pattern in Java

    Using While Loop

    import java.util.Scanner;
    
    public class Main
    {
      public static void main(String args[])
      {
        int rows, i, j;
        Scanner sc = new Scanner(System.in);
    
        System.out.print("Enter the no. of rows: ");
        rows = sc.nextInt();
        i = rows;
    
        while (i > 0)
        {
          j = 1;
          while (j <= i)
          {
            if (j == 1 || j == i || i == 1 || i == rows)
              System.out.print("*");
            else
              System.out.print(" ");
            j++;
          }
          System.out.println();
          i--;
        }
      }
    }

    Output:

    Hollow Inverted Right Triangle Star Pattern in Java

  • Reverse an Array in Java using Recursion

    In this java program tutorial, we will write a java program to reverse an array using recursion. Before that, you may go through the following topic in java.

    Explanation: In this java program we will take user input for the size of an array and array elements. The elements are reversed using a recursive function in the program below.


    Reverse an Array in Java using Recursion

    import java.util.Scanner;
    
    public class Main
    {
      public static void main(String args[])
      {
        int size, i;
        int arr[] = new int[50];
        Scanner scan = new Scanner(System.in);
    
        System.out.print("Enter the size of a first array: ");
        size = scan.nextInt();
    
        System.out.println("Enter " + size + " elements in first Array:");
        for (i = 0; i < size; i++)
          arr[i] = scan.nextInt();
    
        System.out.print("Original array: ");
        for (i = 0; i < size; i++)
          System.out.print(arr[i] + " ");
    
        //calling a function
        reverseFunc(arr, 0, size - 1);
    
        System.out.print("\nReversed array: ");
        for (i = 0; i < size; i++)
          System.out.print(arr[i] + " ");
      }
    
      static void reverseFunc(int arr[], int start, int end)
      {
        int temp;
        if (start >= end)	//base condition
          return;
    
        temp = arr[start];
        arr[start] = arr[end];
        arr[end] = temp;
        reverseFunc(arr, start + 1, end - 1);
      }
    }

    Enter the size of a first array: 5
    Enter 5 elements in first Array:
    1
    2
    3
    4
    5
    Original array: 1 2 3 4 5
    Reversed array: 5 4 3 2 1


  • Reverse an Array in Java

    In this java program tutorial, we will write a java program to reverse an array. Before that, you may go through the following topic in java.

    Explanation: In this java program we will take user input for the size of an array and array elements. The elements are reversed using for loop and while loop.

    We will write two programs:

    1. Using for loop
    2. Using while loop

    Java program to reverse an array without using another array

    Source Code: reverse the array using for loop.

    import java.util.Scanner;
    
    public class Main
    {
      public static void main(String args[])
      {
        int size, i;
        int arr[] = new int[50];
        Scanner scan = new Scanner(System.in);
    
        System.out.print("Enter the size of a first array: ");
        size = scan.nextInt();
    
        System.out.println("Enter " + size + " elements in first Array:");
        for (i = 0; i < size; i++)
          arr[i] = scan.nextInt();
    
        System.out.println("Original array: ");
        for (i = 0; i < size; i++)
        {
          System.out.print(arr[i] + " ");
        }
    
        System.out.println("\nArray in reverse order: ");
        for (i = size - 1; i >= 0; i--)
        {
          System.out.print(arr[i] + " ");
        }
      }
    }

    Output:

    Enter the size of a first array: 5
    Enter 5 elements in first Array:
    10
    20
    30
    40
    50
    Original array:
    10 20 30 40 50
    Array in reverse order:
    50 40 30 20 10


    Reverse the Array using while loop

    In this program, we will create a separate user-defined function to reverse the array, and then we will print the reversed array.

    Source Code: reverse an array using a while loop.

    import java.util.Scanner;
    
    public class Main
    {
      public static void main(String args[])
      {
        int size, i;
        int arr[] = new int[50];
        Scanner scan = new Scanner(System.in);
    
        System.out.print("Enter the size of a first array: ");
        size = scan.nextInt();
    
        System.out.println("Enter " + size + " elements in first Array:");
        for (i = 0; i < size; i++)
          arr[i] = scan.nextInt();
    
        System.out.print("Original array: ");
        for (i = 0; i < size; i++)
          System.out.print(arr[i] + " ");
    
        //calling a function
        reverseFunc(arr, 0, size - 1);
    
        System.out.print("\nReversed array: ");
        for (i = 0; i < size; i++)
          System.out.print(arr[i] + " ");
      }
    
      static void reverseFunc(int arr[], int start, int end)
      {
        int temp;
        while (start < end)
        {
          temp = arr[start];
          arr[start] = arr[end];
          arr[end] = temp;
          start++;
          end--;
        }
      }
    }

    Output:

    Enter the size of a first array: 5
    Enter 5 elements in first Array:
    1
    2
    3
    4
    5
    Original array: 1 2 3 4 5
    Reversed array: 5 4 3 2 1


  • Java Program to Merge Two Arrays

    In this java program tutorial, we will write a program to merge two arrays in java. Before that, you may go through the following topic in java.

    Explanation: In merge programming in C, we will take two arrays and merge them in a third array. We will take user input for the size of an array and elements of an array for both arrays. The final element is stored in a mergeArray[].


    Java Program to Merge Two Arrays

    Source Code: Program to merge arrays in java.

    import java.util.Scanner;
    
    public class Main
    {
      public static void main(String args[])
      {
        int size1, size2, size, i, j, k;
        int arr1[] = new int[50];
        int arr2[] = new int[50];
        int mergeArray[] = new int[100];
        Scanner scan = new Scanner(System.in);
    
        System.out.print("Enter the size of a first array: ");
        size1 = scan.nextInt();
    
        System.out.println("Enter " + size1 + " elements in first Array:");
        for (i = 0; i < size1; i++)
          arr1[i] = scan.nextInt();
    
        System.out.print("Enter the size of a second array: ");
        size2 = scan.nextInt();
    
        System.out.println("Enter " + size2 + " elements in Second Array:");
        for (i = 0; i < size2; i++)
          arr2[i] = scan.nextInt();
    
        //merging...
        for (i = 0; i < size1; i++)
          mergeArray[i] = arr1[i];
    
        size = size1 + size2;
    
        for (i = 0, k = size1; k < size && i < size2; i++, k++)
          mergeArray[k] = arr2[i];
    
        System.out.println("After Merging, the array becomes:");
        for (i = 0; i < size; i++)
          System.out.print(mergeArray[i] + "  ");
      }
    }

    Output:

    Enter the size of a first array: 4
    Enter 4 elements in first Array:
    10
    20
    30
    40
    Enter the size of a second array: 3
    Enter 3 elements in Second Array:
    70
    80
    90
    After Merging, the array becomes:
    10 20 30 40 70 80 90


  • Java Program to Copy one Array to another

    In this java program tutorial, we will write a program to copy the array in java. Before that, you may go through the following topic in java.

    We will look at two programs:

    • Using loop
    • Using System.arraycopy()

    Explanation: In this program, we will copy the elements of one array to another and display the copied array. We will iterate the array using one of the lops in java and copy each element at every iteration.

    Array 1  
    1  2  3  4  

    Copied Array
    1  2  3  4

    Deep Copy Array Java

    public class Main
    {
      public static void main(String[] args)
      {
        int[] arr1 = new int[]
        { 10, 20, 30, 40, 50 };
        int arr2[] = new int[arr1.length];
    
        for (int i = 0; i < arr1.length; i++)
          arr2[i] = arr1[i];
    
        System.out.print("Original Array: ");
        for (int i = 0; i < arr1.length; i++)
        {
          System.out.print(arr1[i] + " ");
        }
    
        System.out.print("\nCopied Array: ");
        for (int i = 0; i < arr2.length; i++)
        {
          System.out.print(arr2[i] + " ");
        }
      }
    }

    Output:

    Original Array: 10 20 30 40 50
    Copied Array: 10 20 30 40 50


    Copy Array to another array in java using System.arraycopy()

    Syntax of the arraycopy() method:

    System.arraycopy(Object src, int srcPos, Object dest, int destPos,int length);

    • src: Source of copying array.
    • srcPos: Starting position of the source array.
    • dest: Destination, where the array is to copied.
    • destPos: Position of the destination array.
    • length: Number of elements to be copied.

    Program source:

    import java.util.Arrays;
    
    public class Main
    {
      public static void main(String[] args)
      {
        int[] arr1 = new int[]
        { 10, 20, 30, 40, 50 };
        int arr2[] = new int[arr1.length];
    
        System.arraycopy(arr1, 0, arr2, 0, arr1.length);
    
        System.out.println("Original Array = " + Arrays.toString(arr1));
        System.out.println("Copied Array = " + Arrays.toString(arr2));
    
      }
    }

    Output: It will produce the same output as the above program.


  • 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 Distance between Two Points

    In this tutorial, we will write a program to find the distance between two given points in java. Before that, you should have knowledge of the following topic in Java.

    Distance Formula:

    The distance between two coordinates or points is calculated using the following formula.

    First point: (x1, y1)
    Second point: (x2, y2)
    Distance (MN): √((x2 – x1)2 + (y2 -y1)2)

    Here x1, y1 are the coordinates of the first point and x2, y2 are the coordinates of the second point. These points indicate the x-axis and y-axis values.

    Example:

    First Points: (4, 8)
    Seecond Points: (12, 14)
    Then distance between them √((12-4)2 + (14-8)2) = √(64 + 36) = √(100) = 10


    Java Program to Find the Distance between Two Points

    import java.util.Scanner;
    
    public class Main
    {
      public static void main(String[] args)
      {
        Scanner scan = new Scanner(System.in);
    
        int x1, x2, y1, y2, x, y;
        double distance;
    
        System.out.println("Enter first coordinates (x1, y1): ");
        x1 = scan.nextInt();
        y1 = scan.nextInt();
    
        System.out.println("Enter second coordinates (x2, y2): ");
        x2 = scan.nextInt();
        y2 = scan.nextInt();
    
        //calculation
        x = x2 - x1;
        y = y2 - y1;
        distance = Math.sqrt(x * x + y * y);
    
        System.out.println("Distance between the two coordinates: " + distance);
      }
    }

    Output:

    Enter first coordinates (x1, y1):
    5
    3
    Enter second coordinates (x2, y2):
    2
    3
    Distance between the two coordinates: 3.0


  • C Program to Read the First Line From a File

    In this tutorial, we will write a program to read the first line of the file in C. Before that, you should have knowledge on the following topic in C.

    To read from a text file in C, you will need to open a file stream using the fopen() function. And then check if the file exists or not. Then read the file.


    C Programming Read First line of File

    #include <stdio.h>
    #include <stdlib.h>
    
    int main()
    {
      char c[1000];
      FILE * fptr;
    
      fptr = fopen("test.txt", "r");
    
      if (fptr == NULL)
      {
        printf("Error occured!");
        exit(1);
      }
    
      // read the first line
      fscanf(fptr, "%[^\n]", c);
      printf("First line of the file:\n%s", c);
    
      fclose(fptr);
      return 0;
    }

    Output:

    The file test.txt contains the following information.

    This is simple2code.com.
    This is a programming website to learn programming languages.

    After successful execution of the above program, the following output will be displayed.

    First line of the file:
    This is simple2code.com.


  • Bouncy Number Program in Java

    In his tutorial, we will learn how to write a java program to check bouncy number. Before we code, let us understand what is a bouncy number.

    Bouncy Number

    A number is said to be a bouncy number if the digits of that number are in random order that is not sorted. Example: 121575, 521634, etc.

    In other words, a number that is neither an increasing number nor a decreasing number is called a bouncy number.

    • Increasing number: The number whose current digit is greater than or equal to the previous digit is called an increasing number. Example: 12345, 45678, etc.
    • Decreasing number: The number whose current digit is less than the previous digit is called an decreasing number. Example: 54321, 98765, etc.

    Bouncy Number Program in Java

    import java.util.*;
    
    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();
    
        //calling function and checking condition
        if (isIncreasing(num) || isDecreasing(num) || num < 101)
          System.out.println(num + " is NOT a Bouncy number");
        else
          System.out.println(num + " is a Bouncy number");
      }
    
      //user-defined function to check for incresing number
      public static boolean isIncreasing(int num)
      {
        String str = Integer.toString(num);
        char digit;
        boolean flag = true;
    
        for (int i = 0; i < str.length() - 1; i++)
        {
          digit = str.charAt(i);
          if (digit > str.charAt(i + 1))
          {
            flag = false;
            break;
          }
        }
    
        return flag;
      }
    
      //user-defined function to check for decreasing number
      public static boolean isDecreasing(int num)
      {
        String str = Integer.toString(num);
        char digit;
        boolean flag = true;
        for (int i = 0; i < str.length() - 1; i++)
        {
          digit = str.charAt(i);
          if (digit < str.charAt(i + 1))
          {
            flag = false;
            break;
          }
        }
    
        return flag;
      }
    }

    Output:

    //Run 1
    Enter the number: 12345
    12345 is NOT a Bouncy number

    //Run2
    Enter the number: 23561
    23561 is a Bouncy number


  • Three Dimensional Array Program in Java

    Let us go through a three dimensional array in java language. Before that, you may go through the following topic in java.

    Three Dimensional (3D) Array program

    3D arrays are the multidimensional array in java. They are quite complicated as they run on three loops. In order to initialize or display the array, we need three loops. The inner loop is for one dimensional array, the second one is for the two dimensions and the outer loop makes the third dimensional array.

    The program below is an example of 3d array in java. We will initialize the 3D array and display the output on the screen.


    Three Dimensional Array Program in Java

    import java.util.Scanner;
    
    public class Main
    {
      public static void main(String args[])
      {
        int i, j, k, index_1, index_2, index_3;
        Scanner sc = new Scanner(System.in);
    
        System.out.print("Enter the Index 1 for Array: ");
        index_1 = sc.nextInt();
        System.out.print("Enter the Index 2 for Array: ");
        index_2 = sc.nextInt();
        System.out.print("Enter the Index 3 for Array: ");
        index_3 = sc.nextInt();
    
        int arr[][][] = new int[index_1][index_2][index_3];
    
        System.out.print("\nEnter the elements: \n");
        for (i = 0; i < index_1; i++)
        {
          for (j = 0; j < index_2; j++)
          {
            for (k = 0; k < index_3; k++)
            {
              System.out.print("arr[" + i + "][" + j + "][" + k + "]: ");
              arr[i][j][k] = sc.nextInt();
            }
          }
        }
    
        //Display the elements
        System.out.print("\nThe enetered elements are: \n");
        for (i = 0; i < index_1; i++)
        {
          for (j = 0; j < index_2; j++)
          {
            for (k = 0; k < index_3; k++)
              System.out.print("arr[" + i + "][" + j + "][" + k + "]: " + arr[i][j][k] + "\n");
          }
        }
      }
    }

    Output:

    Enter the Index 1 for Array: 2
    Enter the Index 2 for Array: 2
    Enter the Index 3 for Array:

    Enter the elements:
    arr[0][0][0]: 1
    arr[0][0][1]: 2
    arr[0][1][0]: 3
    arr[0][1][1]: 4
    arr[1][0][0]: 5
    arr[1][0][1]: 6
    arr[1][1][0]: 7
    arr[1][1][1]: 8

    The enetered elements are:
    arr[0][0][0]: 1
    arr[0][0][1]: 2
    arr[0][1][0]: 3
    arr[0][1][1]: 4
    arr[1][0][0]: 5
    arr[1][0][1]: 6
    arr[1][1][0]: 7
    arr[1][1][1]: 8