Array and 2 D Array in Java
Array is an object in java, which contains similar type of data in a contiguous memory location.
new keyword is used to allocate space in memory.type[] arrayName = new type[size];int[] marks = new int[10];
Simple Example
class HelloWorld {public static void main(String[] args) {int myArray[] = {1,2,3,4,5};for(int i = 0; i<myArray.length; i++){System.out.println(myArray[i]);}}}
1
2
3
4
5
import java.util.*;class HelloWorld {public static void main(String[] args) {Scanner sc = new Scanner(System.in);System.out.print("Enter size: ");int n = sc.nextInt();int myArray[] = new int[n];for(int i= 0; i<n; i++){System.out.print("Enter value: ");myArray[i] = sc.nextInt();}System.out.print("Output: ");for(int j = 0; j<n; j++){System.out.println(myArray[j]);}}}
Enter size: 5
Enter value: 1
Enter value: 2
Enter value: 3
Enter value: 4
Enter value: 5
Output: 1
2
3
4
5
Take an array as input from the user. Search for a given number x and print the index at which it occurs.
import java.util.Scanner;public class MyClass {public static void main(String args[]) {System.out.print("Enter Size: ");Scanner sc = new Scanner(System.in);int n = sc.nextInt();int myArray[] = new int[n];System.out.print("Enter Array value: ");for(int i = 0; i<n; i++){myArray[i] = sc.nextInt();}System.out.print("Show Values : ");for(int j = 0; j<myArray.length; j++){System.out.println(myArray[j]);}System.out.print("Enter Value for search: ");int search = sc.nextInt();for(int k = 0; k<myArray.length; k++){if(myArray[k] == search){System.out.println("Value found in:" +k+" position");}}}}
Enter Size: 5
Enter Array value: 1
2
3
4
5
Show Values : 1
2
3
4
5
Enter Value for search: 4
Value found in:3 position
Post a Comment