# Making A square by loop

Page 1 of 1

## 4 Replies - 20684 Views - Last Post: 15 March 2010 - 06:21 PMRate Topic: //<![CDATA[ rating = new ipb.rating( 'topic_rate_', { url: 'http://www.dreamincode.net/forums/index.php?app=forums&module=ajax&section=topics&do=rateTopic&t=162104&amp;s=cc5e2b118a124c650ae0941773ed4111&md5check=' + ipb.vars['secure_hash'], cur_rating: 0, rated: 0, allow_rate: 0, multi_rate: 1, show_rate_text: true } ); //]]>

### #1 ice_skate3

Reputation: -6
• Posts: 78
• Joined: 13-March 09

# Making A square by loop

Posted 15 March 2010 - 12:21 PM

```import java.util.Scanner;
public class KML
{
public static void main(String[]args){

Scanner scankeyboard = new Scanner(System.in);
System.out.print("Enter a number: ");
String sUserInput=scankeyboard.nextLine();

int R = Integer.parseInt(sUserInput);

int Z;
for (Z=R-1; Z>0; Z--)
{       System.out.print("*");
}
for (Z=R-1; Z>0; Z--)
{       System.out.println("*");
}
for (Z=R-1; Z>0; Z--){
System.out.print("*");}
}
}
```

output should be

output:

Enter A number: 4

****
****
****
****

Or
Enter A number: 3

***
***
***

need some help...

Is This A Good Question/Topic? 0

## Replies To: Making A square by loop

### #2 erik.price

• D.I.C Lover

Reputation: 486
• Posts: 2,690
• Joined: 18-December 08

## Re: Making A square by loop

Posted 15 March 2010 - 12:32 PM

You could do this with nested for loops:

```for(int row = 0; row < R; row++){ //for every row..
for(int col = 0; col < R; col++) { //for every column in the row...
System.out.print("*"); //print * R times (on the same row)
}
System.out.println(); //print a new line (new row)
}
```

### #3 ice_skate3

Reputation: -6
• Posts: 78
• Joined: 13-March 09

## Re: Making A square by loop

Posted 15 March 2010 - 12:38 PM

erik.price, on 15 March 2010 - 11:32 AM, said:

You could do this with nested for loops:

```for(int row = 0; row < R; row++){ //for every row..
for(int col = 0; col < R; col++) { //for every column in the row...
System.out.print("*"); //print * R times (on the same row)
}
System.out.println(); //print a new line (new row)
}
```

Thank you so much

### #4 redv

Reputation: 0
• Posts: 2
• Joined: 25-February 10

## Re: Making A square by loop

Posted 15 March 2010 - 06:19 PM

Hey!
Remember the fastest loop always goes nested!
This is how I do it:

```import java.util.Scanner;

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

int i, n, j;

Scanner key = new Scanner(System.in);
System.out.print("Enter the size of the box (n x n): ");
n = key.nextInt();

for (i = 0 ; i < n ; i++) {
System.out.print("\n");
for (j = 0 ; j < n ; j++) {
System.out.print("*");
}
}
}
}
```

### #5 erik.price

• D.I.C Lover

Reputation: 486
• Posts: 2,690
• Joined: 18-December 08

## Re: Making A square by loop

Posted 15 March 2010 - 06:21 PM

@redv that's exactly what I had, except you went to a newline at the beginning of each loop, not the end