In: Computer Science
Could you modify the code make output arranged into 5x5, like this:
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
16 17 18 19 20
21 22 23 24 25
The code is:
import java.util.*;
public class RandomGen {
public static void main(String[] args) {
int[][] ArrayRand = new int [5][5];
Random rand = new Random();
int sum = 0;
System.out.println("The generated random matris is: ");
for(int i = 0; i < ArrayRand.length;i++){
for(int j = 0; j < ArrayRand[i].length;j++){
ArrayRand[i][j] = rand.nextInt(100)+1;
System.out.print(" "+ ArrayRand[i][j]);
sum += ArrayRand[i][j];
}
}
System.out.println("\nThe sum is: "+ sum);
System.out.println();
}
}
We just have to add a System.out.println() statement after it finishes printing a row outside the inner for loop
import java.util.*;
public class RandomGen {
public static void main(String[] args) {
int[][] ArrayRand = new int [5][5];
Random rand = new Random();
int sum = 0;
System.out.println("The generated random matris is: ");
for(int i = 0; i < ArrayRand.length;i++){
for(int j = 0; j < ArrayRand[i].length;j++){
ArrayRand[i][j] = rand.nextInt(100)+1;;
System.out.print(ArrayRand[i][j]+" ");
sum += ArrayRand[i][j];
}
System.out.println();//add a new line before next row
}
System.out.println("\nThe sum is: "+ sum);
System.out.println();
}
}
The output is
DO give thumbs up and in case there are doubts leave a comment.