Anthony J
Anthony J

Reputation: 581

Printing characters (Ascii) in a row/table format with a for loop and if statement?

I've got to print out the Ascii codes in a table format (10 chars per row...)

At the moment I have them printing all in order. However I'd like to print 10 characters then println and print another 10...

I believe I should be able to do this with an if (if there are 10 chars, println...)statement, but I can't seem to figure out the logic of how..

Please help...

My code so far:

public class Ascii {

  public static void main (String[]args) {

   for (int c=32; c<123; c++) {

    System.out.print((char)c);

   // if(

  //System.out.println();

   }
 }

}

Upvotes: 2

Views: 7006

Answers (5)

Jure
Jure

Reputation: 799

You are almost there. Just put your for loop in another for loop which will run 10 times(nested loops).

So your program will be like this:

public static void main(String[] args) 
    {
        for (int c=33; c<123; c+=10) {
            for(int i = 0;i < 10; i++)
            {
                System.out.print((char)(c+i) + " ");
            }
            System.out.println("");
        }
    }   

Upvotes: 0

zb226
zb226

Reputation: 10500

Leverage the modulo operator % to add a newline every 10 characters:

public static void main(String[] args) {
    for (int c = 32; c < 123; c++) {
        System.out.print((char) c);
        if ((c - 31) % 10 == 0) {
            System.out.println();
        }
    }
}

Output:

 !"#$%&'()
*+,-./0123
456789:;<=
>?@ABCDEFG
HIJKLMNOPQ
RSTUVWXYZ[
\]^_`abcde
fghijklmno
pqrstuvwxy
z

Upvotes: 3

Sinic
Sinic

Reputation: 358

You could use the Modulo (%) Operator

if ( (c - 32) % 10 == 0)
  System.out.print("\n");

Upvotes: 1

thegauravmahawar
thegauravmahawar

Reputation: 2823

Just use a counter to keep track of the position. Whenever the counter is divisible by 10 add a new line:

int count = 0;
for (int c = 32; c < 123; c++) {

  System.out.print((char)c);
  count++;
  if(count % 10 == 0)
    System.out.println();

}

Upvotes: 1

Gauthier JACQUES
Gauthier JACQUES

Reputation: 675

Here's a condition that should work.

if((c - 31) % 10 == 0) { System.out.println(); }

Upvotes: 1

Related Questions