I'm trying to get a loop to write a to z alphabetically using char, but no matter what I try I get an error. Here's the code I'm working with at the moment:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
int main()
{
int counter = 23;
char a;
int add = 0;
while (counter >= 0){
cout<<a + add<<"\n";
--counter;
++add;
}
I'm sure the error is really obvious. Can someone give me some pointers please! :)
#include<iostream>
usingnamespace std;
int main()
{
int counter = 25; // Should be 25, not 23
char a = 'a'; // You never gave this variable a value. Just calling it a does not work
int add = 0;
while (counter >= 0){
cout << (char)(a + add) << "\n"; // Have to cast it back to a char after the addition, or it will print the number itself (at least it did for me)
--counter;
++add;
}
return 0; // You were missing this and the closing brace of main
} // I'm guessing you have them in your program and just didn't copy them over?
Edit: Just thought I'd add that while your method works, it's not really a great way of doing it. Here's a simpler way:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#include<iostream>
usingnamespace std;
int main()
{
char letter = 'a';
while (letter >= 'a' && letter <= 'z')
{
cout << letter << endl; // If you want to be really cool, put ++ after letter here, and delete the next line
letter++;
}
return 0;
}