1.Create a class called Lab6 with one private field called lab that is a primiti
ID: 3674539 • Letter: 1
Question
1.Create a class called Lab6 with one private field called lab that is a primitive array of 100 integers.
2.Create a constructor that populates the primitive array lab with even numbers beginning at 2.
3.Create a method called printReverse that prints the contents of the primitive array lab to a terminal window in reverse order.
4.Create a method called printArray that uses a while loop to print the contents of the primitive array lab to a terminal window.
5.Create a method called sumArray that uses a for-loop to return the sum of all the elements in the primitive array lab.
Explanation / Answer
/* package codechef; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Lab6
{
int lab[] = new int[100];
Lab6(){
for(int i = 0;i<100;i++)
lab[i] = 2*(i+1);
}
public void printReverse(){
for(int i=99;i>=0;i--)
System.out.print(lab[i] + " ");
}
public void printArray(){
int i = 0;
while(i<100){
System.out.print(lab[i] + " ");
i++;
}
}
public int sumArray (){
int sum =0;
for(int i=0;i<100;i++)
sum += lab[i];
return sum;
}
public static void main (String[] args) throws java.lang.Exception
{
Lab6 myObj = new Lab6();
myObj.printReverse();
System.out.print(" ");
myObj.printArray();
System.out.print(" Sum ="+myObj.sumArray());
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.