// Output the array so that 10 elements per line are printed. for(int r = 0; r <
ID: 3661850 • Letter: #
Question
// Output the array so that 10 elements per line are printed.
for(int r = 0; r < 5; r++)
{ for(int c = 0; c < 10; c++)
System.out.print(alpha[r*10+c]+" ");
System.out.println();
Please explain why this prints 10 elements per row at a time. I don't understand this portion of the code.
Entire code:
public static void main(String[] args) {
// Write a program that declares an array "alpha" of 50 elements of type "double".
double[] alpha = new double[50];
// Initialize the array so that the first 25 elements are equal to the square of the index variable
for(int i = 0; i < 25; i++) alpha[i] = i*i;
// the last 25 elements are equal to three times the index variable.
for(int i = 25; i < 50; i++) alpha[i] = 3*i; //
Output the array so that 10 elements per line are printed.
for(int r = 0; r < 5; r++) { for(int c = 0; c < 10; c++)
System.out.print(alpha[r*10+c]+" ");
System.out.println();
}
}
Explanation / Answer
Rewrite the code with proper indentation, to make it clear as:
//Output the array so that 10 elements per line are printed.
for(int r = 0; r < 5; r++)
{
for(int c = 0; c < 10; c++)
System.out.print(alpha[r*10+c]+" "); //Inner Loop Statement
System.out.println(); //Outet Loop Statement
}
Explanation:
In this piece of code, there are two loops, one outer loop (for(int r = 0; r < 5; r++) { ----- }) and one inner loop (for(int c = 0; c < 10; c++) { ------ }).
1. Outer Loop runs from starting with r=0 to r=5.i.e., 5 times
2. For each value of 'r' , inner loop executes starting with c=0 to c=10 i.e., 10 times.
3. One and only one Statement present in inner loop is System.out.print(alpha[r*10+c]+" ");
4. System.out.print() is a standard ouput function, that prints the data to the console.
5.System.out.print() is different from System.out.println() since it doesn't print a new line after printing the data.
6. So the Statement present in inner loop doesn't print a new line and prints 10 elements in a row at a time and then executes outer loop statement and prints a new line.
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.