-1
package firstprogam;
import java.util.Scanner;
public class sample {
public static void main(String[] args){
    int i,j,k=1,c,r;
    Scanner val = new Scanner(System.in);
    System.out.println("Enter Rows & Columns :");
    r = val.nextInt();
    c = val.nextInt();
    int array[][] = new int[r][c];
    for(i=0; i<=r; i++)
        for(j=0; j<=c; j++){
            array[i][j] = k;
            k++;
        }
    for(i=0; i<=r; i++){
        for(j=0; j<=c; j++)
            System.out.print(array[i][j] + "\t");
            System.out.println();
    }
}
}

I Am getting Error will running the code i unable to get the output output what i expected is number in a Matrix i tried another code without user input i got it, But unable to get with this code

1 Answers1

2

Your problem is that your for loops are using <= instead of < and so, are trying to reach an element that is out of bounds of the array.

Fixed Code:

import java.util.Scanner;

public class sample
{
    public static void main(String[] args)
    {
        int i, j, k = 1, c, r;

        Scanner val = new Scanner(System.in);

        System.out.println("Enter Rows & Columns :");

        r = val.nextInt();
        c = val.nextInt();

        int array[][] = new int[r][c];

        for (i = 0; i < r; i++)
        {
            for (j = 0; j < c; j++)
            {
                array[i][j] = k;
                k++;
            }
        }
        for (i = 0; i < r; i++)
        {
            for (j = 0; j < c; j++)
                System.out.print(array[i][j] + "\t");
            System.out.println();
        }
    }
}
Spikatrix
  • 20,225
  • 7
  • 37
  • 83