Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 7

Java Array

Arrays are used to store multiple values


in a single variable, instead of declaring
separate variables for each value.
int a[]=new int[10];

0 1 2 3 4 5 6 7 8 9

2 4 6 7 8 1 2 4 5 6
import java.util.*;

public class arr {


public static void main(String args[])
{
Problem #1: Display the sum of all the Scanner sc = new Scanner(System.in);
elements. int sum =0;
int a[] = new int [10];
Problem #2: Add up all the elements
that are odd numbers and less than 5. for(int i=0;i<10;i++)
{
System.out.print("Enter a number:");
a[i]=sc.nextInt();
Problem #3: Display the elements' total
}
if the array's index is an even integer.
sc.close();
for(int i=0;i<10;i++)
sum = sum+a[i];
System.out.print(sum);
} 0 1 2 3 4 5 6 7 8 9
}
2 3 6 7 8 1 2 4 5 6
int a[][]=new int[3][3];

(0,0) (0,1) (0,2) 2 4 1


(1,0) (1,1) (1,2) 3 5 7
(2,0) (2,1) (2,2) 2 9 6
import java.util.*;

public class arr {


public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
Problem #1: Display the sum of all the int sum =0;
elements. int a[][] = new int [3][3];

for(int i=0;i<3;i++)
Problem #2: Total the number of
{
elements larger than 5. for(int j=0;j<3;j++) {
System.out.print("Enter a number:");
a[i][j]=sc.nextInt();
}} //end of outer loop

sc.close();
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++){
sum = sum+a[i][j];
}} //end of outer loop

System.out.print(sum);
}}
Problem #2: Rotate It
  Sample Run
Problem Description: My phone, it’s stuck! It doesn’t seem to Enter the number of rows: 3
rotate anymore. I have this multidimensional array whose Enter the number of columns: 4
values I need to rotate in order to properly decipher. If it doesn’t 3 6 2 4
rotate 90 degrees clockwise, then I’m in big trouble! Help! 9 3 2 1
  5 3 2 1
Input/Output Rotated:
1. Number of rows of the multidimensional array 5 9 3
2. Number of columns of the multidimensional array 3 3 6
3. Elements of the multidimensional array 2 2 2
1 1 4

You might also like