matt
matt

Reputation: 33

not printing out all alphabet just one letter but it needs to print out every letter after the one that was entered

so far it just prints out z after a but after a is b so i want it to print b c d e f g....z

#include <iostream>

using namespace std;

int main() 
{
   char a = 'a';
   while (a < 'z')
   a++; 
  cout << a; 
}

im just looking for some help on how to do that then after that i need to enter 2 letters and do that with 2 letters but that is just for me i know this is not a code writing service just looking for some help on how to do that. thanks any help is good

Upvotes: 0

Views: 126

Answers (3)

Bathsheba
Bathsheba

Reputation: 234785

In the loop, you need to enclose multiple statements in braces:

int main() 
{
    char a = 'a';
    while (a < 'z'){
        a++; 
        cout << a; 
    }
    cout << '\n'; // let's have a line break at the end
}

Otherwise the cout statement is only ran once the loop finishes.

Sadly though this code is not portable since the C++ standard mandates few requirements as to how the alpha characters are encoded. And their being contiguous and consecutive is not a requirement. The portable solution is based on the obvious if ostensibly puerile

int main()
{
    std::cout << "abcdefghijklmnopqrstuvwxyz\n";
}

; if you want to print all letters from a certain value, then use something on the lines of

int main() {
    const char* s = "abcdefghijklmnopqrstuvwxyz";   
    char a = 'k'; // print from k onwards, for example
    for ( ; *s /*to prevent overrun*/ && *s != a; ++s);     
    std::cout << s; 
}

Upvotes: 3

Haruki
Haruki

Reputation: 109

Only thing executed in while is a++; because there are no brackets surrounding statements that belongs to while. to do multiple statements surround them in brackets. Or like in this case its possible to make them into one statement.

#include <iostream>

int main() 
{
    char a = 'a';
    while (a < 'z')
        std::cout << ++a;
}

Upvotes: 1

Steve
Steve

Reputation: 1757

Need to put the cout inside the loop:

#include <iostream>

int main() 
{
   char a = 'a';
   while (a < 'z')
   {
      a++; 
      std::cout << a << " "; 
   }
}

Also added a space to distinguish the different letters. And removed the using namespace std; as it's not recommended.

Upvotes: 2

Related Questions