Output Letter Square Using For Loop

Hello,

Beginner C++ student here, first ever programming class. The code I put together shown below outputs a number square as shown in the screenshot in this link when the user inputs an int. For example, 5:

https://www.dropbox.com/s/xkqyhx2j83imwca/number_square.jpg?dl=0

However, I now need to have this loop output the same pattern, but with letters when the user enter the same input:

AAAAAAAAA
ABBBBBBBA
ABCCCCCBA
ABCDDDCBA
ABCDEDCBA
ABCDDDCBA
ABCCCCCBA
ABBBBBBBA
AAAAAAAAA

Can anyone ever so kindly advise how to best convert these numbers to letters. e.g. 1 = 'A', 2 = 'B', etc.

Thank you so very much.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
 
#include <iostream>
#include <string>
#include <cmath>
#include <algorithm>

using namespace std;

int main() {

	unsigned size;

	cin >> size;

	int iSize = static_cast<int>(size);

	for (int r = 1 - iSize; r < iSize; r++) {
		for (int c = 1 - iSize; c < iSize; c++) {		
			
			cout << iSize - max(abs(r), abs(c));


		}
			cout << endl;

	}


}
Last edited on
There are a few answers obviously. Have you looked at the ascii table to see if it can help you out?
http://www.asciitable.com/
Hello,

Thank you for your response.

Yes, I tried adding/subtracting ASCII in certain places in the code to see if I could get it to loop based on ASCII table, but would still put out the same numbers or it would just output no data.

I also tried to insert a switch statement(case 1: iSize = 'A', etc), but it completely overlooked it as well. Not sure what I am doing wrong, as i get the number square only, or just no data.

Since we barely started playing with loops some days ago, I am unsure what is currently possible or not possible with these functions yet.
closed account (48T7M4Gy)
cout << (char)( 'A' + iSize - max(abs(r), abs(c)) );
closed account (48T7M4Gy)
Or,
cout << static_cast<char>( 'A' + iSize - max(abs(r), abs(c)) );
Thank you very much kemort for the advise. That worked.

Working code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30

#include <iostream>
#include <string>
#include <cmath>
#include <algorithm>

using namespace std;

int main() {

	unsigned size;

	cin >> size;

	int iSize = static_cast<int>(size);

	for (int r = 1 - iSize; r < iSize; r++) {
		for (int c = 1 - iSize; c < iSize; c++) {		
			
			cout << static_cast<char>( '@' + iSize - max(abs(r), abs(c)) );


		}
			cout << endl;

	}


}
Topic archived. No new replies allowed.