-->

Hello,This is me!

ITEngineer8995

Professional Coder Coding is my passion

About me

Hello

I'mITEngineer8995

Spatial Data Specialist

Do you want all of your codes in one place?? Then you are landed on the right blog... Here you will find varieties of codes of various languages starting from noob to advance with their samples. Do learn, execute and share your knowledge with others. Do visit my YouTube Channel for execution of these codes .

Experience

Video Clone Detector using Hadoop

2017-2018

A detector which differentiates copied videos from the original ones using Hadoop.

Portfolio

Showing posts with label Java Programs. Show all posts
Showing posts with label Java Programs. Show all posts

Java Program To Check Prime Number using While Loop

  

Java Program To Check Prime Number using While Loop

In this java program, we check whether the user input number is prime or not.

A prime number is a natural number greater than 1 that is not a product of two small natural numbers.

E.g. 2, 3, 5 etc are prime numbers.

Steps :

Step 1 : Import Scanner class

Step 2 : Create class PrimeChec

Step 3 : Create main method

Step 4 : Create variable temp

Step 5 : Create object of Scanner 

Step 6 : Ask the user to enter any number by using System.out.print method

Step 7 : Create variable num and store the user entered number in it.

Step 8 : Close the Scanner class

Step 9 : Initialize int i equals to 2

Step 10 : Apply while loop where i is smaller than equal to num divide by 2

Step 11 : Apply if where num mod i is equals equals to zero

Step 12 : Initialize isPrime to False

Step 13 : If isPrime is true then the number is prime else not

Step 14 : Print the number

Program :

import java.util.Scanner;

public class PrimeChecWhile 

    {

        public static void main(String[] args)

        {

            int temp;

            boolean isPrime = true;

            Scanner sc = new Scanner(System.in);

            System.out.println("Enter any number:");

            //capture the input in an integer

            int num = sc.nextInt();

            sc.close();

            int i = 2;

            while(i<=num/2)

            {

                if(num%i==0)

                {

                    isPrime = false;

                    break;

                }

                i++;

            }

            //If isPrime is true then the number is prime else not

        if(isPrime)

        System.out.println(num+"is a Prime Number");

        else

        System.out.println(num+"is not a Prime Number");

        }

        }

Output :

Enter any number:
19
19is a Prime Number

For execution of the same do visit my YouTube Channel :

https://youtu.be/jYxikmPpNb4

Java Program To Break Integer into Digits

 

Java Program To Break Integer into Digits

In this Java Program, we break Integers into Digits

Here we use Scanner class to get input from the user. First While loop is use to count the digits in the input number and second while loop is use to extract the digits from the input number using modulus operator.

Step 1 : Import Scanner Class

Step 2 : Create a Class IntegerToDigit

Step 3 : Create main method

Step 4 : Initialize num, temp, digit and count and store 0 in count

Step 5 : Ask the user to enter any number

Step 6 : Store the user entered number into num variable

Step 7 : Close the Scanner class to avoid memory leaks

Step 8 : Create a copy of input number

Step 9 : Store the num into temp

Step 10 : Count the digits into the input number

Step 11 : Apply While loop where num is greater than zero

Step 12 : Divide num by 10 and store the result into num variable

Step 13 : Increment count by one.

Step 14 : Apply another while loop where temp is greater than zero and store the result of temp % 0 into digit.

Step 15 : Print the Digit

Step 16 : Divide temp by 10 and store the result into temp variable

Step 17 : Decrement count by one.

Program :

import java.util.Scanner;

public class IntegerToDigit {

    public static void main(String[]args)

    {

        int num, temp, digit, count = 0;

        //getting the number from user

        Scanner sc = new Scanner(System.in);

        System.out.print("Enter any number:");

        num = sc.nextInt();

        sc.close();

        //creating a copy of the input number

        temp = num;

        //counting digits int the input number

        while(num > 0)

        {

            num = num / 10;

            count++;

        }

        while(temp > 0)

        {

            digit = temp % 10;

            System.out.println("Digit at place "+count+" is:"+digit);

            temp = temp / 10;

            count --;      

        }

    }    

}

Output :

Enter any number:7891

Digit at place 4 is:1

Digit at place 3 is:9

Digit at place 2 is:8

Digit at place 1 is:7

For execution of the same do visit my YouTube Channel :

https://youtu.be/yYfE4xFPj4s

Java Program to Display Prime Numbers from 1 to n

 

















Java Program to Display Prime Numbers from 1 to n

In this Java Program, prime numbers from 1 to n are displayed to the user.

A prime number is a natural number greater than 1 that is not a product of two small natural numbers.

E.g. 2, 3, 5 etc are prime numbers.

Step 1 : Create main method and create the object of  Scanner.

Step 2 : Initialize i to zero and num to zero.

Step 3 : Create an empty String named primeNumbers

Step 4 : Ask the user to enter the value of n using System.out.print method

Step 5 : Store the object of Scanner class in  variable n

Step 6 : Close the Scanner 

Step 7 : Apply For loop where i is equal to 1,  i is less than equal to n and increment i by 1

Step 8 : Initialize counter to 0

Step 9 : Apply another for loop where num is equal to i, num is greater than equal to 1 and decrement num by 1 

Step 10 : Apply if statement where i % num == 0

Step 11 : Increment counter by 1 and store it in variable counter

Step 12 : Close both the for loops

Step 13 : Apply if statement where counter == 2

Step 14 : Append the Prime number to the String

Step 15 : Print the output

Program :

import java.util.Scanner;
public class PrimeNumbersTwo 
    {
        public static void main(String[]args)
        {
            Scanner sc = new Scanner(System.in);
            int i = 0;
            int num = 0;
            //Empty String
            String primeNumbers = "";
            System.out.println("Enter the value of n:");
            int n = sc.nextInt();
            sc.close();
        for(i = 1; i <= n; i++)
        {
            int counter = 0;
            for(num = i; num>=1; num--)
            {
                if(i%num == 0)
                {
                    counter = counter + 1;
                   
                }
            }
            if (counter == 2)
                
            {
                //Appended the Prime number to the String
                primeNumbers = primeNumbers + i + " ";
            }
        }
            System.out.println("Prime numbers from 1 to n are:");
            System.out.println(primeNumbers);
    
}
}

Output:

Enter the value of n:
150
Prime numbers from 1 to n are:
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 101 103 107 109 113 127 131 137 139 149 

For execution of the same do visit my YouTube Channel :


Java Program to Display Prime Numbers from 1 to 100

  

















Java Program to Display Prime Numbers from 1 to 100

In this Java Program, prime numbers from 1 to 100 are displayed to the user.

A prime number is a natural number greater than 1 that is not a product of two small natural numbers.

E.g. 2, 3, 5 etc are prime numbers.

Step 1 : Initialize i to zero

Step 2 : Initialize num to zero

Step 3 : Create an empty string named as primeNnumbers

Step 4 : Apply for loop where num is equal to i, num is greater than equal to 1 and decrement num

Step 5 : Apply if statement inside for loop where i mod num is equal equal to zero

Step 6 : Increment counter by one and store it in counter variable

Step 7 : Close the for loop

Step 8 : Apply if statement where counter is equal equal to 2

Step 9 : Append the prime number to the string

Step 10 : Print the output by using System.out.println method

Program :

public class PrimeNumbers {
    
    public static void main (String[] args)
    {
        int i =0;
        int num =0;
        //Empty String
        String primeNumbers = "";
        
        for(i = 1; i<=100; i++)
        {
            int counter = 0;
            for(num = i; num>= 1; num--)
            {
                if(i%num==0)
                {
                    counter= counter + 1;
                }
            }
            if(counter == 2)
            {
                //Appended the Prime number to the String
                        primeNumbers = primeNumbers + i + "";
               
            }
        }
        System.out.println("Prime numbers from 1 to 100 are:");
        System.out.println(primeNumbers);
    }
    
}

Output:

Prime numbers from 1 to 100 are:
2357111317192329313741434753596167717379838997

For execution of the same do visit my YouTube Channel :





Java Program to Display First 100 Prime Numbers

 

















Java Program to Display First 100 Prime Numbers 

In this Java Program, first 100 prime numbers are displayed to the user.

A prime number is a natural number greater than 1 that is not a product of two small natural numbers.

E.g. 2, 3, 5 etc are prime numbers.

Step 1 : Create main method 

Step 2 : Initialize variables n, status and num

Step 3 : Print "First 100 prime numbers are:" using System.out.println method 

Step 4 : Apply for loop in which i is equal to 2 and i should be greater and equal to 100

Step 5 : Apply nested for loop in which j is equal to 2 and j is less than equal to Math.sqrt(num)                          and increment j by 1.

Step 6 : Apply if statement inside nested for loop in which num mod of j should be equal to zero

Step 7 : Store zero in the status variable and break the if statement and close the nested for loop.

Step 8 : Apply if statement in which status is not equal to zero

Step 9 : Print the num and increment the i by 1

Step 10: Store 1 in the status variable and increment num by 1

Program :

public class PrimeNumberDemo2 {

    public static void main (String[] args)
    {
        int n;
        int status = 1;
        int num = 3;
        System.out.println("First 100 prime numbers are:");
        System.out.println(2);
        for(int i = 2; i <= 100;)
        {
            for(int j = 2; j <= Math.sqrt(num);j++)
             {
               if(num%j == 0)
                 {
                status = 0;
                break;
                 }
               
             }
            if(status !=0)
            {
                System.out.println(num);
                i++;
            }
            status = 1;
            num++;
        }
    }
}

Output :

First 100 prime numbers are:

2
3
5
7
11
13
17
19
23
29
31
37
41
43
47
53
59
61
67
71
73
79
83
89
97
101
103
107
109
113
127
131
137
139
149
151
157
163
167
173
179
181
191
193
197
199
211
223
227
229
233
239
241
251
257
263
269
271
277
281
283
293
307
311
313
317
331
337
347
349
353
359
367
373
379
383
389
397
401
409
419
421
431
433
439
443
449
457
461
463
467
479
487
491
499
503
509
521
523
541

For execution of the same do visit my You Tube Channel :

https://youtu.be/seUJ8P4dNqM






Java Program to Display First n Prime Numbers using Scanner

















Java Program to Display First n Prime Numbers using Scanner

In this Java Program, first n prime numbers are displayed using scanner.

A prime number is a natural number greater than 1 that is not a product of two small natural numbers.

E.g. 2, 3, 5 etc are prime numbers.

Step 1 : Import Scanner class

Step 2 : Create main method 

Step 3 : Initialize variables n, status and num for capturing the value of n

Step 4 : Create object of Scanner

Step 5 : Ask the user to enter the value of n

Step 6 : Store the enter value in the variable n

Step 7 : Apply if statement

Step 8 : Apply for loop of i & j

Step 9 : Print the Results

Program :

import java.util.Scanner;

public class PrimeNumberDemo {
    public static void main(String args[])
    {
        int n;
        int status = 1;
        int num = 3;
        //for capturing the value of n
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the value of n:");
        //The entered value is stored in the var n
        n = sc.nextInt();
        if( n >= 1)
        {
            System.out.println("First "+n+" prime numbers are:");
            // 2 is prime number
            System.out.println(2);
            
        }
        for (int i = 2; i <= n;)
        {
            for (int j = 2; j <= Math.sqrt(num); j++)
            {
                if (num % j == 0)
                {
                    status = 0;
                    break;
                }
            }
            if( status != 0)
            {
                System.out.println(num);
                i++;
                
            }
            status = 1;
            num++;
        }
           
       
    }
    
}

Output :

Enter the value of n:

15

First 15 prime numbers are:

2
3
5
7
11
13
17
19
23
29
31
37
41
43
47

For execution of the same do visit my You Tube Channel :







Java Program To Find The Factorial Of A Number Using Recursion

  

Java Program To Find The Factorial Of A Number Using Recursion

In this Java Program, we calculate the factorial of the number using recursion.

Factorial of n is the product of all the positive descending integers. It is denoted by n!

For example : 4! = 4 * 3 * 2 * 1 = 24

Logic : fact = fact * i;

Step 1 : Create main method

Step 2  : Create variable factorial and store factorial of 4 in it.

Step 3  : Print the number

Step 4 : Create a static function which returns 1

Step 5 : Create recursion function which calls itself

Program :

public class FactorialDemo2 {

    public static void main(String[] args){

        int factorial = fact(4);

        System.out.println("Factorial of 4 is:"+factorial);

    }

    static int fact(int n)

    {

    int output;

    if(n==1){

        return 1;

    }

    //Recursion : Function calling itself

    output = fact(n-1)*n;

    return output;

    }

}

Output :

Factorial of 4 is : 24

For execution of the same do visit my YouTube Channel :

https://youtu.be/xGJ2VBxZuRc


Java Program To Find The Factorial Of A Number Using Recursion Entered By The User

 

Java Program To Find The Factorial Of A Number Using Recursion Entered By The User

In this Java Program, we calculate the factorial of the number using recursion entered by the user.

Factorial of n is the product of all the positive descending integers. It is denoted by n!

For example : 4! = 4 * 3 * 2 * 1 = 24

Logic : fact = fact * i;

Step 1 : Import Scanner Class

Step 2 : Create main method

Step 3 : Create scanner object for capturing the user input

Step 4 : Ask the user to enter the number

Step 5 : Store the entered value in the variable num

Step 6 : Call the user defined function fact

Step 7 : Print the number

Step 8 : Create a static function which returns 1

Step 9 : Create recursion function which calls itself

Program :

import java.util.Scanner;

public class FactorialDemo {

    public static void main(String[] args)

    {

        //Scanner object for capturing the user input

        Scanner sc = new Scanner(System.in);

        System.out.println("Enter the number:");

        //Store the entered value in variable

        int num =sc.nextInt();

        //Call the user defined function fact

        int factorial = fact(num);

        System.out.println("Factorial of entered number is:"+factorial);

    }

    static int fact(int n)

    {

        int output;

        if(n==1){

            return 1;

        }

                //Recursion: Function calling itself

        output = fact(n-1)*n;

        return output;

    }    

}

Output :

Enter the number:

5

Factorial of entered number is:120

For execution of the same do visit my YouTube Channel :

https://youtu.be/IBSxhMDbMrw


Java Program To Reverse a String Entered by the User

  

Java Program To Reverse a String Entered by the User

In this Java Program, we reverse a string entered by the user

Logic :  String reversed = reverseString(str);

Step 1 : Import Scanner Class

Step 2 : Create main method

Step 3 : Create variable str

Step 4 : Ask user to enter the username

Step 5 : Create the object of the Scanner Class

Step 6 : Store the user entered username in the variable str

Step 7 : Close the scanner class to avoid memory lea

Step 8 : Apply the logic

Step 9 : Print the reversed string

Step 10 : Create reversedString method

Step 11 : Apply if condition which says if str is empty then reverse string

Step 12 : Call the function recursively 

Program :

import java.util.Scanner;

public class JavaExample2 {

    public static void main(String[] args)

    {

        String str;

        System.out.println("Enter your username:");

        Scanner sc = new Scanner(System.in);

        str = sc.nextLine();

        sc.close();

        String reversed = reverseString(str);

        System.out.println("The reversed string is:"+reversed);

    }

    public static String reverseString(String str)

    {

        if(str.isEmpty())

            return str;

        //calling function recursively

        return reverseString(str.substring(1))+str.charAt(0);

    }

}

Output :

Enter your username:

how are you doing?

The reversed string is:?gniod uoy era woh

For execution of the same do visit my Youtube Channel :

https://youtu.be/GUoz8dR5d1E


Java Program To Reverse a String using Recursion

 

Java Program To Reverse a String using Recursion

In this Java Program, we reverse a string using recursion.

The process in which the function calls itself directly or indirectly is called recursion and the corresponding function is called as recursive function

Logic :

 String reversed = reverseString(str);

Step 1 : Create obj str of String class and store the output string in it.

Step 2 : Create another object as reversed and apply the logic of the reverse string in it.

Step 3 : Output the reversed string using the System.out.println method.

Step 4 : Create reverseString method

Step 5 : Apply if statement, if str.isEmpty then return str.

Step 6 : Call function recursively.

Program :

public class JavaExample {

    public static void main(String []args)

    {

        String str = "Welcome To my Channel";

        String reversed = reverseString(str);

        System.out.println("The reversed string is : "+reversed);

    }

    public static String reverseString(String str)

    {

        if(str.isEmpty())

            return str;

        //Calling function recursively

        return reverseString(str.substring(1)) + str.charAt(0);

  }

}

Output :

The reversed string is : lennahC ym oT emocleW

For execution of the same do visit my YouTube Channel :

https://youtu.be/0XA6NlNoIQA




Java Program To Reverse a Number using Recursion

 

Java Program To Reverse a Number using Recursion

In this Java Program, we reverse a number using Recursion.

The process in which the function calls itself directly or indirectly is called recursion and the corresponding function is called as recursive function

Step 1 : Import Scanner Class

Step 2 : Create a method for reverse

Step 3 : Apply if condition in which the number should be smaller than 10

Step 4 : Print the number

Step 5 : Apply else condition in which number should mod by 10 and print the result

Step 6 : Apply reverse method condition in which number should be divided by 10

Step 7 : Create main method

Step 8 : Initialize num to 0

Step 9 : As the user to enter the number and press enter

Step 10 : Create Scanner object

Step 11 : Store the user entered number into num

Step 12 : Print Reverse of the input number is.

Step 13 : Call the reverseMethod method

Program :

import java.util.Scanner;

public class RecursionReverseDemo 

    {   

        //A method for reverse

        public static void reverseMethod(int number)

        {

            if(number < 10)

            {

                System.out.println(number);

                return;

            }

            else

            {

                System.out.print(number % 10);

                //Method is calling itself : recursion

                reverseMethod(number / 10);

            }

        }

        public static void main(String args[])

        {

            int num = 0;

            System.out.println("Input your number and press enter:");

            Scanner sc = new Scanner(System.in);

            num = sc.nextInt();

            System.out.println("Reverse of the input number is:");

            reverseMethod(num);

            System.out.println();

        }        

}

Output :

Input your number and press enter:

5678901

Reverse of the input number is:

1098765

For execution of the same do visit my YouTube Channel : 

https://youtu.be/uu50BfxfhjA



Java Program To Reverse a Number using For Loop

 

Java Program To Reverse a Number using For Loop

In this Java Program, we reverse a number using For loop.

Logic :

   for (;num != 0;)

            {

                reversenum = reversenum * 10;

                reversenum = reversenum + num%10;

                num = num/10;

            }

Step 1 : Import the Scanner Class

Step 2 :  Create the main method

Step 3 : Initialize num and reversenum equals to zero

Step 4 : Ask the user to enter the number by using System.out.println() method

Step 5 : Create Scanner object.

Step 6 : Store the captured input in num

Step 7 : Apply for loop logic to reverse the number

Step 8 : In for loop, num should be not equal to zero

Step 9 : Multiply reversenum with 10 and store its result in reversenum.

Step 10 : Add num%10 to reversenum and store the result into reversenum

Step 11 : Divide num by 10 and store the result in num.

Step 12 : Print the reversenum

Program :

import java.util.Scanner;

public class ForLoopReverseDemo 

    {

        public static void main(String args[])

        {

            int num=0;

            int reversenum = 0;

            System.out.println("Input your number and press enter:");

            //This statement will capture the user input

            Scanner sc = new Scanner(System.in);

            //Captured input would be stored in the number num

            num = sc.nextInt();

            //For loop: No initialization part as num is already initialized.

            //No increment/decrement part as logic

            //num = num/10 already decrements the value of num

            for (;num != 0;)

            {

                reversenum = reversenum * 10;

                reversenum = reversenum + num%10;

                num = num/10;

            }

         System.out.println("Reverse of specified number is:"+reversenum);                    

        }

}

Output :

Input your number and press enter:
56789111
Reverse of specified number is:11198765

For execution of the same do visit my YouTube Channel :

Java Program To Reverse a Number using While Loop

Java Program To Reverse a Number using While Loop

In this Java Program, we reverse a number using while loop.

Logic :

  while (num != 0)

             {

                reversenum = reversenum * 10;

                reversenum = reversenum + num%10;

                num = num/10;                

             }

Step 1 : Import the Scanner Class

Step 2 :  Create the main method

Step 3 : Initialize num and reversenum equals to zero

Step 4 : Ask the user to enter the number by using System.out.println() method

Step 5 : Create Scanner object.

Step 6 : Store the captured input in num

Step 7 : Apply while loop logic to reverse the number

Step 8 : In while loop, num should be not equal to zero

Step 9 : Multiply reversenum with 10 and store its result in reversenum.

Step 10 : Add num%10 to reversenum and store the result into reversenum

Step 11 : Divide num by 10 and store the result in num.

Step 12 : Print the reversenum

Program :

import java.util.Scanner;

public class ReverseNumberWhile 

    {

        public static void main(String args[])

        {

            int num =0;

            int reversenum = 0;

            System.out.println("Input your number and press enter:");

            //This statement will capture the user input

            Scanner sc = new Scanner(System.in);

            //Captured input would be stored in number num

            num = sc.nextInt();

            //While loop: Logic to find out the reverse number

            while (num != 0)

             {

                reversenum = reversenum * 10;

                reversenum = reversenum + num%10;

                num = num/10;                

             }

            System.out.println("Reverse of input number is : "+reversenum);

        }

}

Output :

Input your number and press enter :
145689

Reverse of input number is : 
986541

For execution of the same do visit my YouTube Channel :




Java Program to add two given Matrices

 

Java Program to add two given Matrices

In this Java Program, we add two given matrices. 

Array is a data structure consisting of collections of elements each identified by atleast one array index or key. 

E.g. If you want to store 5 numbers in an array,

        datatype arrayname [arraysize];

         int a[5];

A matrix is a multidimensional array which consists of columns and rows.

For the addition of two matrices, we need two matrices of same dimension, which means they should have same number of rows and columns.

For this Program, we declare the matrix as a 2D array.

| 1 1 1 1 |
| 2 3 5 2 |

Declaration of matrix as 2D array :

int [][] MatrixA = { {1, 1, 1, 1}, {2, 3, 5, 2}};

We use for loop for addition of the two matrices and store the addition values into the sum matrix.

For E.g.

sum[0][0] = MatrixA[0][0] + MatrixB[0][0], similarly,

sum[0][1] = MatrixA[0][1] + MatrixB[0][1] and so on.

Program :

public class AddTwoMatrix {
    
    public static void main(String [] args)
    {
        int rows = 2, columns = 4;
        
        //Declaring the two matrices as multi-dimensional arrays
        int[][] MatrixA = { {1, 1 , 1, 1}, {2, 3, 5, 2} };
        int[][] MatrixB = { {2, 3, 4, 5,}, {2, 2, 4, -4} };
        
        //Declaring a matrix sum, that will be the sum of MatrixA and MatrixB
        //The sum matrix will have the same rows and columns as the given matrices.
        
        int[][] sum = new int[rows][columns];
        for(int i = 0; i < rows; i++)
        {
            for(int j = 0; j < columns; j++)
            {
                sum[i][j] = MatrixA[i][j] + MatrixB[i][j];
            }
        }
        //Displaying the sum matrix
        System.out.println("Sum of the given matrices is:");
        for(int i =0; i < rows; i++)
        {
            for(int j =0; j < columns; j++)
            {
                System.out.print(sum[i][j] + "   ");
                
            }
            System.out.println();
        }
    }
    
}

Output :

Sum of the given matrices is:
3   4   5   6   
4   5   9   -2  

For Execution of the same, do visit my YouTube Channel :




Java Program To Convert Char Array To String

 


Java Program To Convert Char Array To String

In this Java Program, we convert the char array to String. 

Array is a data structure consisting of collections of elements each identified by atleast one array index or key. 

E.g. If you want to store 5 numbers in an array,

        datatype arrayname [arraysize];

         int a[5];

Logic : 1. Using String object: 
                 String str = new String(ch);

             2. Using ValueOf method.
                 String str2 = String.valueOf(ch);

Step 1 : Create an array of char and store the characters in it.

Step 2 : Create an object of String as str and store the characters of ch in it.

Step 3 : Output the object str.

Step 4 : Create object of String str and store characters in it by using ValueOf() method.

Step 5 : Output the object str.
              
Program :

public class CharArrayToString 
    {
        public static void main(String args[])
        {
        //Method 1 : Using String object
         char[] ch = { 'h', 'a','v','e','á','g', 'o', 'o', 'd', 'd', 'a', 'y'};
         String str = new String(ch);
         System.out.println(str);
         
         //Method 2 : Using valueOf method
         String str2 = String.valueOf(ch);
         System.out.println(str2);
        }
}

Output :

haveágoodday
haveágoodday

For execution of the same do visit my YouTube Channel :


Java Program To Reverse The Array

 


Java Program To Reverse The Array

In this Java Program, we reverse the array. In this program if a user enters numbers 1, 2, 3, 4, 5 then the program will reverse the array and the elements will be 5, 4, 3, 2, 1.  

Array is a data structure consisting of collections of elements each identified by atleast one array index or key. 

E.g. If you want to store 5 numbers in an array,

        datatype arrayname [arraysize];

         int a[5];

Step 1 : Import java.util.Scanner Class

Step 2 : Create and initialize variable i and j to 0, counter and temp.

Step 3 : Create an array named number and store value 100 in it.

Step 4 : Create the object of the Scanner class

Step 5 : Ask the user to the enter the number of elements he want to enter.

Step 6 : Store the user entered numbers in the variable counter

Step 7 : Apply for loop where i is equal o 0, i should be less than counter and increment i.
              This loop stores all the elements that we enter in an array number. First element is at number[0], second at number[1] and so on.

Step 8 : Print the enter array element by adding  1 int the i.

Step 9 : Store the user entered number in the array of number[i]

Step 10 : Decrement i by 1 and store it in j. Here we are writing the logic to swap first element with last element, second last element with the second element and so on. On the first iteration of the while loop i is the index of first element and j is the index of last. On the second iteration i is the index of the second and j is the index of the second last.

Step 11 : Initialize i to 0

Step 12 : Close the Scanner class to avoid any memory leak.

Step 13 : Apply while loop where i should be less than j

Step 14 : Store array number[i] in the temp variable

Step 15 : Store array of number[i] in array of number[j]

Step 16 : Store array of number [j] in variable temp.

Step 17 : Increment i & decrement j

Step 18 : Print reversed array

Step 19 : Apply for loop where i should be equal to 0, i should be less than counter and increment i

Step 20 : Print the array of number [i]

Program :

import java.util.Scanner;

public class ReverseArray 
    {
        public static void main(String args[])
        {
            int counter, i = 0, j = 0, temp;
            int number[] = new int[100];
            Scanner sc = new Scanner(System.in);
            System.out.print("How many elements you want to enter:");
            counter = sc.nextInt();
            
            for(i = 0; i < counter; i++)
            {
                System.out.print("Enter Array Element"+(i + 1)+": ");
                number[i] = sc.nextInt();
                
            }
            j = i - 1;
            i = 0;
            sc.close();
            while(i < j)
            {
                temp = number[i];
                number[i] = number[j];
                number[j] = temp;
                i++;
                j--;
                
            }
            
            System.out.print("Reversed array:");
            for(i = 0; i < counter; i++)
            {
                
                System.out.print(number[i]+" ");
            }
            
            
        }
    
}

Output: 

How many elements you want to enter:5
Enter Array Element1: 11
Enter Array Element2: 22
Enter Array Element3: 33
Enter Array Element4: 44
Enter Array Element5: 55
Reversed array:55 44 33 22 11

For execution of the same do visit my You Tube Channel :



Java Program To Sum the elements of the Array Entered By The User


Java Program To Sum the elements of the Array Entered By The User

In this Java Program, we sum up all the elements of the array entered by the user.

Array is a data structure consisting of collections of elements each identified by atleast one array index or key. 

E.g. If you want to store 5 numbers in an array,

        datatype arrayname [arraysize];

         int a[5];

Step 1 : Import java.util.Scanner Class

Step 2 : Create the object of the Scanner Class

Step 3 : Create and Initialize array

Step 4 : Create variable sum and initialize it to zero

Step 5 : Ask the user to enter the elements by using println method 

Step 6 : Apply for loop where i is equal to 0, i is less than 10 and increment i

Step 7 : Store the user entered elements in the array of i

Step 8 : Apply advanced for loop where num : array

Step 9 : Add sum and num and save its result in the variable sum

Step 10 : Print the Sum of the array elements.

Program :

import java.util.Scanner;
public class SumArray2 
    {
        public static void main(String[] args)
        {
            Scanner sc = new Scanner(System.in);
            int[] array = new int[10];
            int sum = 0;
            System.out.println("Enter the elements:");
            for(int i = 0; i<10; i++)
            {
                array[i] = sc.nextInt();
            }
            for(int num : array)
            {
                sum = sum + num;
            }
                System.out.println("Sum of array elements is:"+sum);
           
        }
    
}

Output :

Enter the elements:
1
2
3
4
5
6
7
8
9
10
Sum of array elements is:55

For Execution of the same do visit my YouTube Channel :





Java Program To Sum the elements of the Array


Java Program To Sum the elements of the Array

In this Java Program, we sum up all the elements of the array.

Array is a data structure consisting of collections of elements each identified by atleast one array index or key. 

E.g. If you want to store 5 numbers in an array,

        datatype arrayname [arraysize];

         int a[5];

Step 1 : Create and Initialize array

Step 2 : Create variable sum and initialize it to zero

Step 3 : Apply advanced for loop where int number : array

Step 4 : Add sum to num and store it in the variable sum

Step 5 : Print the Result

Program :

public class SumArray 
    {
        public static void main(String[] args)
        {
            int[] array = {10, 20, 30, 40, 50, 10};
            int sum = 0;
            //Advanced for loop
            for(int num : array)
            {
                sum = sum + num;
            }
            System.out.println("Sum of array elements is: "+sum);
        }
    
}

Output :

Sum of array elements is: 160

For the execution of the same do visit my YouTube Channel :


Java Program To Calculate Average of the Number using Array Entered by the User.


Java Program To Calculate Average of Number using Array Entered by the User.

In this Java Program, we calculate average of number using array entered by the user.

Average is a number that is calculated by adding all the numbers together and dividing the total by the number of quantities. It is also known as mean.

E.g. Average of 5 numbers :

       Average = 1 + 2 + 3 + 4 + 5 = 15 / 5 = 3

Array is a data structure consisting of collections of elements each identified by atleast one array index or key. 

E.g. If you want to store 5 numbers in an array,

        datatype arrayname [arraysize];

         int a[5];

Step 1 : Import java.util.Scanner

Step 2 : Ask user how many number he want to enter by using System.out.println method.

Step 3 : Create object of Scanner class

Step 4 : Create variable n and store the entered number of the user.

Step 5 : Create an array arr and store the contents of n in it.

Step 6 : Create a variable total and initialize it to 0

Step 7 : Apply for loop, where i is equal to zero, i should be less than length of the array and increment i.

Step 8 : Print the entered element number by adding 1 in it.

Step 9 : Store value of sc.nextDouble() into array of i.

Step 10 : Close the Scanner.

Step 11 : Apply another for loop, where i is equal to zero, i should be less than length of the array and increment i.

Step 12 : Add total + array of i and store it in total.

Step 13 : Display the Result.

Program :

import java.util.Scanner;

public class AverageArray2 
    {
        public static void main (String []args)
        {
            System.out.println("How many numbers you want to enter?");
            Scanner sc = new Scanner(System.in);
            int n = sc.nextInt();
            //Declaring array of n elements, the value of n is provided by the user
            
            double[] arr = new double[n];
            double total = 0;
            
            for(int i = 0; i<arr.length; i++)
            {
                System.out.print("Enter Element No."+(i+1)+": ");
                arr[i] = sc.nextDouble();
            }
            sc.close();
            for(int i = 0; i<arr.length; i++)
            {
                total = total + arr[i];
                
            }
            
            double average = total / arr.length;
            
            System.out.format("The average is : %.3f", average);
        }
    
}

Output :

How many numbers you want to enter?
5
Enter Element No.1: 12.7
Enter Element No.2: 18.9
Enter Element No.3: 20
Enter Element No.4: 13.923
Enter Element No.5: 16.225
The average is : 16.350

For execution of the same do visit my YouTube Channel :




Java Program To Calculate Average of Number using Array


Java Program To Calculate Average of Number using Array

In this Java Program, we calculate average of number using array.

Average is a number that is calculated by adding all the numbers together and dividing the total by the number of quantities. It is also known as mean.

E.g. Average of 5 numbers :

       Average = 1 + 2 + 3 + 4 + 5 = 15 / 5 = 3

Array is a data structure consisting of collections of elements each identified by atleast one array index or key. 

E.g. If you want to store 5 numbers in an array,

        datatype arrayname [arraysize];

         int a[5];

Logic :  double[] arr = {19, 12.89, 16.5, 200, 13.7};
              double total = 0;
            
                  for(int i = 0; i<arr.length; i++)
                    {
                       total = total + arr[i];
                    }

Step 1 : Create an array of data type double named arr and store the numbers in it.

Step 2 : Create a variable total with data type double and initialize it to 0.

Step 3 : Apply for loop, where i should be equal to zero, i should be less than the length of the array and increment i. arr.length returns the number of elements present in the array.

Step 4 : Add total and the a[i] and store it in the variable total.

Step 5 : Create a variable average and store the result of the division of total and arr.length.

Step 6 : Print the output. 

Program :

public class AverageArray 
    {
        public static void main (String[] args)
        {
            double[] arr = {19, 12.89, 16.5, 200, 13.7};
            double total = 0;
            
            for(int i = 0; i<arr.length; i++)
            {
                total = total + arr[i];
            }
            
            //arr.length returns the number of elements present in the array
            
            double average = total / arr.length;
            
            //This is used for displaying the formatted output
            //If you give %.4f then the output would have 4 digits after decimal point
            System.out.format("The average is : %.3f", average);
        }
}


Output :

The average is : 52.418

For execution of the same do visit my Youtube Channel :




ITEngineer8995
India

SEND ME A MESSAGE

Search This Blog

Powered by Blogger.

Pages