Loop to display ASCII characters

I would like to the output to look like:
54321A
4321B
321C
21D
1E

but
my loop keep printing A only
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


#include <iostream>

using namespace std;

int main()
{
int i, j, k;
for(i=5;i>=1;i--)
{
    for(j=i;j>=1;j--)
    {
        cout<<j;
    }
   for(k='A'; k<='Z'; k++)
   {
		cout<<(char)k<<endl;
        break;
    }
    
}

return 0;
}
The initialization statement in a for loop runs every time, including the for loop on line 16.

Side note, C++ allows you to declare variables throughout your function instead of just at the top, just in case you didn't know.

-Albatross
Last edited on
you are doing a ton more work and logic than necessary making it harder to debug etc.

1
2
3
4
5
6
7
8
9
10

string d ="54321";
string a = "ABCDE";
char * lazy = &(d[0]);
for(int i = 0; i < 5; i++)
{
   cout << lazy << a[i]<<endl;
   lazy++;
}


granted, some patterns you do need to generate, and knowing how is useful. You need both: the ability to loop and generate when you need to and the ability to NOT do all that when the pattern is simplistic.

your way, fixed:
1
2
3
4
5
6
7
8
9
10
11
12

int i, j, k;
char magic_letter = 'A';
for(i=5;i>=1;i--)
{
    for(j=i;j>=1;j--)
    {
        cout<<j;
    }
	cout<<magic_letter++<<endl;         
}
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>

int main()
{
   char hex_char = 'A';

   for (unsigned num_loops = 5; num_loops >= 1; num_loops--)
   {
      for (unsigned digits = num_loops; digits >= 1; digits--)
      {
         std::cout << digits;

         if (digits == 1)
         {
            std::cout << hex_char << '\n';
            hex_char++;
         }
      }
   }
}
54321A
4321B
321C
21D
1E

Meaningful names for your variables makes source code easier to read and debug if there are problems.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include <string>
using namespace std;

void pattern( string S )
{
   cout << S << '\n';
   int n = S.length() - 1;
   if ( n > 1 ) pattern( S.substr( 1, n-1 ) + ++S[n] );
}
    
int main()
{
   string S = "54321A";
   pattern( S );
}
Topic archived. No new replies allowed.