Arrays in Java - Ariharavelava K (ECE - A 012)
Arrays in Java - Ariharavelava K (ECE - A 012)
Program:
public class max_min {
public static void main(String[] args) {
int[] a = {10, 20, 30, 40, 50};
int i, min, max;
min = a[0];
max = a[0];
for (i = 0; i < 5; i++) {
if (a[i] > max) {
max = a[i];
}
if (a[i] < min) {
min = a[i];
}
}
System.out.println("maximum number in an array is " + max);
System.out.println("minimum number in an array is " + min);
}}
output:
2. Insert an array element.
Program:
import java.util.Scanner;
Output:
3. Common elements between two arrays.
Program:
}}
}}
output:
4. Display the elements in odd position.
Program:
output:
5. Print the modified array so that the average of the array is increased by
the size . only one chance is allowed to alter the array value.
Program:
import java.util.Scanner;
output:
6. Display the difference between sum of odd and even position element
in an array.
Program:
import java.util.*;
public class difference_odd_even {
public static void main(String[] args) {
int i, sumodd = 0, sumeven = 0, difference = 0;
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int a[]= new int[n];
for(i=0;i<n;i++)
{ a[i]=sc.nextInt();}
for (i = 0; i <a.length; i++) {
if (i % 2 == 1)
sumodd += a[i];
else
sumeven += a[i];
}
difference=sumodd-sumeven;
System.out.print("difference between odd and even position of an
array is " +difference);
}
}
output:
7. Find the index of the array element.
Program:
import java.util.Scanner;
output:
8. Add the array elements and display the output.
Program:
output:
9. Perform left shifting for ‘K’ times in an array.
Program:
import java.util.*;
public class leftshift_k_times {
public static void main(String[] args) {
int i;
Scanner sc = new Scanner(System.in);
System.out.println("enter the array size :");
int n = sc.nextInt();
System.out.println("enter the number place shift :");
int k = sc.nextInt();
System.out.println("enter the array elements :");
int a[] = new int[n];
for (i = 0; i < n; i++) {
a[i] = sc.nextInt();
}
for (i = 0; i < n - k; i++) {
a[i] = a[i + k];
}
for (i = n - k; i < n; i++) {
a[i] = 0;
}
for (i = 0; i < n; i++) {
System.out.print(a[i] + " ");
}
}
}
output:
10. Perform right shifting for ‘K’ times in an array.
Program:
import java.util.*;
public class rightshift_k_times {
public static void main(String[] args) {
int i;
Scanner sc = new Scanner(System.in);
System.out.println("enter the array size :");
int n = sc.nextInt();
System.out.println("enter the number place shift :");
int k = sc.nextInt();
System.out.println("enter the array elements :");
int a[] = new int[n];
for (i = 0; i < n; i++) {
a[i] = sc.nextInt();
}
for (i = n; i < k; i++) {
a[i] = a[i-k];
}
for (i = 0; i < k; i++) {
a[i] = 0;
}
for (i = 0; i < n; i++) {
System.out.print(a[i] + " ");
}
}
}
output: