Java Program to Print Square of Given Array Elements

CodeForHunger
2 min readJul 26, 2024

--

Arrays in Java is a very important concept when it comes to Java interview questions because arrays in Java is a base for many classes in the collections framework like ArrayList, Vector, and Stack.

In the previous post, we learned how to print the multiplication of given array elements. In this post, we will learn how to print squares of given array elements. So let’s get started… :)

Java Program to Print Square of Given Array Elements, Java programming examples, Java Arrays examples and solutions

Step-by-step logic of the given program:

1. Accept the array limit from the user and store it in a variable say lim.

2. Accept elements from the user. Run a for loop from 0 to arr.length-1 and store elements one by one in the array:

for(int i =0;i<arr.length;i++) {
arr[i]=sc.nextInt();
}

3. After that store Square of the array elements one by one in a variable called square and print it.

for(int i=0;i<arr.length;i++) { 
square = arr[i]*arr[i];
System.out.println("Square of "+ arr[i] +" is: "+square);
}

Java Program to Print Square of Given Array Elements :

import java.util.Scanner;

public class ArraySquareExample {

public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int square=0;
//Accept limit
System.out.println("How many elements you want to enter: ");
int lim = sc.nextInt();
int[] arr= new int[lim];
//Accepting elements
System.out.println("Enter "+lim+" elements: ");
for(int i =0;i<arr.length;i++) {
arr[i]=sc.nextInt();
}
//Logic to print square of array elements
for(int i=0;i<arr.length;i++) {
square = arr[i]*arr[i];
System.out.println("Square of "+ arr[i] +" is: "+square);
}

}
}

OUTPUT:

How many elements you want to enter: 7

Enter 7 elements:

5

3

8

7

9

15

21

Square of 5 is: 25

Square of 3 is: 9

Square of 8 is: 64

Square of 7 is: 49

Square of 9 is: 81

Square of 15 is: 225

Square of 21 is: 441

To know more about arrays in Java 👉 Click Here.

Originally published at https://codeforhunger.blogspot.com.

--

--

CodeForHunger

Here, I will share tips & tricks to learn programming languages, Learn C and Java with lot of exercises, coding examples & interview questions. Follow for more.