In: Computer Science
JAVA LANGUAGE
Write a program that declares a 2-Dimensional Array with 4 rows
and 4 columns to store integer values, and then:
fill elements with values as the sum of its column index and row
index, e.g., the element at row index 0 and column index 0 is
(0+0=0), the element at row index 0 and column index 1 is
(0+1=1).
compute the sum of elements at the second row.
compute the sum of elements at the third column.
compute the sum of all elements.
print the array in tabular form.
Write a program that declares an array list to store integers and
fills the elements with users’ inputs from keyboards. Then prints
the following outputs (each in one line):
Every element at an even index.
Every even element (using enhanced for loop).
Every odd element (using common loop, not enhanced for loop).
All elements in reverse order.
Only the first, the middle and the last element.
The largest and smallest element.
The alternating sum of all elements. For example, if your program
reads the values from users: 1 4 9 16 10 7 4 9 11 5, then it
computes 1-4+9-16+10-7+4-9+11-5=-6.
Please find below code for above 2 questions and don't forget to give a like.
1)
package com.example;
public class Main{
public static void main(String[] args) {
int array[][];
int result=0;
array= new int[4][4];
for(int i=0;i<array.length;i++){
for(int j=0;j<array[i].length;j++){
array[i][j]=i+j;
result+=array[i][j];
}
}
System.out.println("The 2nd row values are");
for(int j=0;j<array.length;j++){
int i=1;
System.out.print(array[i][j]+" ");
}
System.out.println();
System.out.println("The third column values are");
for(int i=0;i<array.length;i++){
int j=2;
System.out.print(array[i][j]+" ");
System.out.println();
}
System.out.print("Sum of all the elements is"+result);
System.out.println();
System.out.println("The tabular form is");
for(int i=0;i<array.length;i++){
for(int j=0;j<array[i].length;j++){
System.out.print(array[i][j]+" ");
}
System.out.println();
}
}
}
2)
We use scanner to take the input and asking user to enter size of list and then using that length we will get the input from user.
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
int result=0;
Scanner input1 = new Scanner(System.in);
System.out.print("Enter the size of list");
int number=input1.nextInt();
int numb[]=new int[number];
System.out.println("Enter the the elements");
for(int i=0;i<number;i++){
numb[i]=input1.nextInt();
}
for (int i=0;i<numb.length;i++){
if(i%2==0){
result+=numb[i];
System.out.print(result);
}
else{
result-=numb[i];
}
}
System.out.print("The result is"+result);
}
}