user12929063
user12929063

Reputation:

How to create (m) columns and (n) rows for a rectangular pattern using nested for loops in java?

I just learned how to use nested loops today and the task I am required to do is quite simple but I am not able to execute it properly, although with the same idea.

The task is to input a character, an integer that is the rows**(n), and another integer that is the columns **(m)

It should display the rectangular pattern with n rows and m columns

Sample input:

*
3
2

Here the number of rows is 3 and the number of columns is 2

Sample output:

**
**
**

This has to be done using nested for loops only

My code:

import java.util.Scanner;

class Example {
    public static void main (String[] args) {

        Scanner keyboard = new Scanner(System.in);
        String character = keyboard.next();
        int n = keyboard.nextInt();
        int m = keyboard.nextInt();

        for (int x = m; x <= m; x++) {
            for (int y =n ; y <= n; y++) {
                System.out.print(character);
            }
            System.out.println("");
        }
    }
}

The output I am getting:

*

Upvotes: 0

Views: 1005

Answers (3)

Majed Badawi
Majed Badawi

Reputation: 28434

You should start from 0 in both loops until reaching < m and < n as follows:

Scanner keyboard = new Scanner(System.in);
String character = keyboard.next();
int n = keyboard.nextInt();
int m = keyboard.nextInt();
for (int x = 0; x < m; x++){
    for (int y = 0; y < n; y++){
        System.out.print(character);
    }
    System.out.println("");
}      

A sample input/output would be:

*
3
2
***
***

Upvotes: 1

Shubhanshu
Shubhanshu

Reputation: 11

what is wrong in your code is that you are starting loop from m itself instead you should think it like how many times you want to run the loop. With that in mind try running the code from 0 to m and inner loop from 0 to n. This mindset will help you in learning while loop also.

import java.util.Scanner;

class Example {
public static void main (String[] args) 

{

Scanner keyboard = new Scanner(System.in);
String character = keyboard.next();
int n = keyboard.nextInt();
int m = keyboard.nextInt();

for (int x = 0;x<m;x++){
    for (int y=0;y<n;y++){
        System.out.print(character);
    }
    System.out.println("");
}
}

}

Upvotes: 0

0xh3xa
0xh3xa

Reputation: 4857

You should use a loop like this start from 0 to row and j from 0 to col for each row, and close the scanner after reading

    public static void main(String[] arg) {
        Scanner keyboard = new Scanner(System.in);
        String character = keyboard.next();
        int col = keyboard.nextInt();
        int row = keyboard.nextInt();

        for (int i = 0; i < row; i++) {
            for (int j = 0; j < col; j++) {
                System.out.print(character);
            }
            System.out.println("");
        }
        keyboard.close();
    }

, output

***
***

Upvotes: 3

Related Questions