loop to write a to z alphabetically using char

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! :)
What error?

Andy
It says "Run-Time Check Failure #3 - The variable 'a' is being used without being initialized."
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include<iostream>
using namespace 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>
using namespace 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;
}
Last edited on
Perfect! Thank you for your help!
Or even?

1
2
3
4
5
6
7
8
9
10
11
12
#include<iostream>
using namespace std;

int main()
{
    for (char letter = 'a'; letter <= 'z'; ++letter)
    {
        cout << letter << endl;
    }

    return 0;
}


Andy

PS @freddy92 As you are incrementing from 'a', there is no need to test the lower bound in the while() loop condition.
Last edited on
Topic archived. No new replies allowed.