How to display ASCII characters from ! to ~

Write a program that displays the characters in the ASCII character table from ! to ~.
Display ten characters per line.
The characters are separated by exactly one space.

Not sure what is wrong with my code, anyone know what I am doing wrong?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
using namespace std;

int main()
{
    int loop, counter;
    counter = 0;
    for (loop=32; loop<128; loop++)
    {
    cout<<(char)loop> <<" ";
    counter++;
        if (counter == 9)
        {
        counter = 0;
        cout<<endl;
    }
    }
return(0);
}
  
Why does the loop start at 32? Why does it end at 127?

It would be easier and clearer to use a char for the counter and bounds:
1
2
3
4
for (char loop = '!'; loop <= '~'; ++loop) {
    cout << loop << " ";
    ...
}


One other thing. Right now the code will print a space at the end of each line. Can you change the code to eliminate that?
But I want that. I want it to look like this:

! " # $ % & ' ( ) *
+ , - . / 0 1 2 3 4
5 6 7 8 9 : ; < = >
? @ A B C D E F G H
I J K L M N O P Q R
S T U V W X Y Z [ \
] ^ _ ` a b c d e f
g h i j k l m n o p
q r s t u v w x y z
{ | } ~
I got it. Your for statement did it.

#include <iostream>
using namespace std;

int main()
{
int loop, counter;
counter = 0;
for (char loop = '!'; loop <= '~'; ++loop) {
cout << loop << " ";
counter++;
if (counter == 9)
{
counter = 0;
cout<<endl;
}
}
return(0);
}
Your idea worked, but how would I separate the lines with a space?
What I mean is that each line ends with a space, and then a newline. It should end with just a newline.

Here's a hint, you already have code that prints a newline after every 10th character. Change that logic to:
1
2
3
4
5
if (at end of line) {
    print newline and rest counter
} else {
    print space
}
Topic archived. No new replies allowed.