for loop overwriting itself for an array.

I have to write a program that prints out the reversed alphabet without vowels. Then it has to read an input number, and print the letter it corresponds to.
This is what I've written so far, the alphabet works fine but I can't seem to do anything with the array, even if i write something like "cout << alpha[6];" it prints the last value it stored, so "b".

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <string>
using namespace std;

int main()
{
	char alpha[22];
	for (char l = 'z'; l >= 'a'; l--)
	{

          if (l == 'a' || l == 'e' || l == 'i' || l == 'o' || l == 'u') {
		 continue;
	  }
          for (int n = 0; n < 22; n++) {
		 alpha[n] = l;
          }

	cout << l << endl;
        }

}
Consider:

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>
#include <string>
using namespace std;

int main()
{
	char alpha[22] {};

	int indx {};

	for (char l = 'z'; l >= 'a'; l--)
		if (l != 'a' && l != 'e' && l != 'i' && l != 'o' && l != 'u')
			alpha[indx++] = l;

	cout << alpha << '\n';

	int no {};

	cout << "Enter a number (1 - 21) :";
	cin >> no;

	if (no >= 1 && no <= 21)
		cout << "Letter is: " << alpha[no - 1] << '\n';
	else
		cout << "Invalid letter number\n";
}


Also:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <string>
using namespace std;

int main()
{
	const char alpha[22] {"zyxwvtsrqpnmlkjhgfdcb"};

	cout << alpha << '\n';

	int no {};

	cout << "Enter a number (1 - 21) :";
	cin >> no;

	if (no >= 1 && no <= 21)
		cout << "Letter is: " << alpha[no - 1] << '\n';
	else
		cout << "Invalid letter number\n";
}


As you know what the reversed alphabet is without the vowels.
Last edited on
1
2
3
          for (int n = 0; n < 22; n++) {
		 alpha[n] = l;
          }

The logical problem with that is that you overwrite all elements of 'alpha' with same value.
We know that the last time this loop executes is when l == 'b'
That is why all elements of alpha are 'b'.

What seeplus does is to keep track (with indx) of how many characters does 'alpha' already have and use that to store new character to next unused element:
1
2
3
4
5
6
7
8
9
10
11
12
char alpha[22];
int indx {}; // does initialize indx = 0
for (char l = 'z'; l >= 'a'; l--)
{
  if (l == 'a' || l == 'e' || l == 'i' || l == 'o' || l == 'u') {
    continue;
  }
  alpha[indx] = l;
  ++indx;
  cout << l << endl;
}
cout << "alpha has " << indx << " characters\n";
this is so much clearer now! thank you so much.
Topic archived. No new replies allowed.