Problem 1: Write a program that initializes an array with ten random integers an
ID: 3569531 • Letter: P
Question
Problem 1:
Write a program that initializes an array with ten random integers and then prints out the following:
Every element at an even index;
Every even element
All elements in reverse order;
Only the first and last elements;
The minimum and maximum element
The sum of all elements
The alternating sum of all elements, where the alternating sum contains all elements at even index added, and the elements at odd index subtracted.
Problem 2:
Write a program that reads a sequence of input values and displays a bar chart of the values in data, using asterisks, like this:
*********************
*************************
*********
**************************
You may assume that all values are positive. First figure out the maximum value in data. That value's bar should be drawn with 40 asterisks. Shorter bars should use proportionally fewer asterisks. Improve your program by adding caption to your bar. Prompt the user for the captions and data values. The output should look like this:
Egypt ********************* France ************************* Norway ********* Germany **************************Explanation / Answer
Answer 1
public class Array1 {
public static void main(String[] args) {
int s=0;
int arr[]=new int[10];
System.out.println("Array elements with index value");
for(int i=0;i<10;i++){
arr[i]=(int)(Math.random()*100);
System.out.print(arr[i]+"("+i+") ");
}
System.out.println();
System.out.println("Every element at an even index");
for(int i=0;i<10;i++){
if(i%2==0)
{
System.out.print(arr[i]+" ");
}
}
System.out.println();
System.out.println("Every even element");
for(int i=0;i<10;i++){
if(arr[i]%2==0)
{
System.out.print(arr[i]+" ");
}
}
System.out.println();
System.out.println("All elements in reverse order");
for(int i=9;i>=0;i--){
System.out.print(arr[i]+" ");
}
System.out.println();
System.out.println("Only the first and last elements");
System.out.print(arr[0]+" "+arr[9]);
System.out.println();
System.out.println("The sum of all elements");
for(int i=0;i<10;i++){
s=s+arr[i];
}
System.out.print("sum="+s);
}
}
Answer 2
import java.util.Scanner;
public class Array {
/**
* @param args
*/
public static void main(String[] args) {
try
{
Scanner sc=new Scanner(System.in);
System.out.println("number of input ");
int n=sc.nextInt();
int c[]=new int[n];
String cap[]=new String[n];
for(int i=0;i<n;i++)
{
System.out.println("Enter caption: ");
cap[i]=sc.next();
System.out.println("Enter value: ");
c[i]=sc.nextInt();
}
for(int k=0;k<c.length;k++)
{
System.out.print(cap[k]+" ");
for(int i=0;i<c[k];i++)
{
System.out.print("*");
}
System.out.println();
}
}
catch(Exception e){
System.out.println("please provide valid input");
}
}
}