How do I list the ABC's vertically using counter control loop?

#include <iostream>
using namespace std;

int main()
{
char letter;

for(letter = 'A'; letter <= 'Z'; letter++)
cout << letter;

return 0;
}

when it runs it looks like this:

ABCDEFGHIJKLMNOPQRSTUVWXYZ

when I want it to look like this:

A
B
C
...
Y
Z
cout << letter << "\n";
like TheIdeasMan wrote or like this:
 
cout << letter <<endl;
oh sweet! now...how do I make it print like 7 letters per row and then make a new line?
so like this:

ABCDEFG
HIJKLMN
OPQRSTU
VWXYZ
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include <string>
using namespace std;

const string ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

int main()
{
   const int LENGTH = 7;

   int counter = 0;
   for ( char c : ALPHABET )
   {
      cout << c;
      if ( ++counter % LENGTH == 0 ) cout << '\n';
   }
}


You might like a quick look at:
http://www.cplusplus.com/forum/beginner/216132/#msg1002758
Last edited on
So the const makes it where the variables don't change right? why would that be necessary?
Why would that be necessary?

Except in the special case of writing meta-programs, which only operate upon constant expressions, it's not necessary, but rather a good practice.

C++'s name lookup and resolution are very complex, which means that it is quite possible to silently use the wrong name, and potentially to change things that shouldn't be changed; const prevents this. It also distinguishes between things the user should expect to change, and things the user should usually not (rather, usually must not) change. Further, it's much easier to prove correctness of (e.g.) certain compiler optimizations when the compiler can guarantee certain operations don't change things.

The benefits are similar to those gained by static type checking. You should use it when possible.
https://isocpp.org/wiki/faq/const-correctness
Last edited on
an alternative version using the OP for loop:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# include <iostream>

constexpr auto CHARS_PER_LINE = 7;
//should still use 'const' qualifiers as explained by mbozzi

int main()
{
    size_t counter{};

    for (char letter = 'A'; letter <= 'Z'; ++letter)
    //letter is variable local to for loop, can be declared auto as well
    {
        std::cout << letter;

        if (++counter % CHARS_PER_LINE == 0)
	//if (((++counter) % CHARS_PER_LINE) == 0)	
	// alt version to be careful with any op precedence issues 
        {
            std::cout << "\n";
        }
    }
}




Last edited on
Topic archived. No new replies allowed.