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".
#include <iostream>
#include <string>
usingnamespace 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;
}
}
#include <iostream>
#include <string>
usingnamespace 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";
}
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";