Week 7-8 Array Tutorial Exercise - Preparartion Te - 240806 - 092425
Week 7-8 Array Tutorial Exercise - Preparartion Te - 240806 - 092425
Exercise 1.
Write a java program to prompts the user to input the size of an array, takes input values
from the user, and then prints out the values of the array.
Answer
import java.util.Scanner;
public class Array_Size
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter the Array Limit :");
int l =input.nextInt();
int [] a =new int[l];
for(int i=0;i<l;i++)
{
System.out.printf("Element of a[%d] :",i);
a[i]=input.nextInt();
}
System.out.println("\n Display Array Elements...\n");
for(int i=0;i<l;i++)
{
System.out.println(a[i]);
}
}
}
Exercise 2
Write a Java program that prompts the user to input the size of an array, takes input values
from the user, calculates the sum of the values in the array, and then prints out the sum
import java.util.Scanner;
public class Sum_Array
{
public static void main(String[] args)
{
Scanner input =new Scanner(System.in);
System.out.print("Enter the Array Limit :");
int l =input.nextInt();
int [] a =new int[l];
int sum = 0;
for(int i=0;i<l;i++)
{
System.out.printf("Element of a[%d] :",i);
a[i]=input.nextInt();
}
for(int i=0;i<l;i++)
{
sum = sum + a[i];
}
System.out.println("Sum of Array Elements : "+sum);
}
}
Exercise 3
Write a Java program that takes user input for the size of an array, then prompts the user to
enter the elements of the array. It then prints the elements of the array in reverse order
import java.util.Scanner;
public class Array_Reverse
{
public static void main(String[] args)
{
Scanner input =new Scanner(System.in);
System.out.print("Enter the Array Limit :");
int l =input.nextInt();
int [] a =new int[l];
for(int i=0;i<l;i++)
{
System.out.printf("Element of a[%d] :",i);
a[i]=input.nextInt();
}
System.out.println("\nDisplay Reverse Order in Array Elements...\n")
;
for(int i=l-1;i>=0;i--)
{
System.out.println(a[i]);
}
}
}
Exercise 4
Write a Java program that takes user input for the size of an array, then prompts the user to
enter the elements of the array. It then finds and prints the maximum and minimum
elements of the array
import java.util.Scanner;
public class Array_Max_Min
{
public static void main(String[] args)
{
Scanner input =new Scanner(System.in);
System.out.print("Enter the Array Limit :");
int l =input.nextInt();
int [] a =new int[l];
int max=0,min=0;
for(int i=0;i<l;i++)
{
System.out.printf("Element of a[%d] :",i);
a[i]=input.nextInt();
}
max=a[0];
min=a[0];
for(int i=0;i<l;i++)
{
if(max<a[i])
max=a[i];
if(min>a[i])
min=a[i];
}
System.out.println("Maximum Element of Array : "+max);
System.out.println("Minimum Element of Array : "+min);
}
}