So what you are missing now is only the braces:
int main()
{
char letter = 'a';
for (int i = 97; i < 123; i = i + 1)
{
cout << letter << '\t' << i << '\n';
letter = letter + 1;
}
}
All of these control structures expect a block of statements after it (e.g. if
, else
, for
, while
). A block of statements is enclosed in braces. However all of these controls also accept a single statement instead of a block of statements. So if there is no opening brace following the for(...)
then only the next statement will be considered part of the loop iteration. But in your case you want both following statements to be executed in each loop iteration, so the braces are needed. It is good practice to always use the braces, even if only one statement is part of the loop body.
From your earlier version it seemed that you want to include both the i
, as well as the letter
as loop variables in your for
loop. This is partially possible, but the individual statements must be in the matching section between the ;
, e.g.:
int main()
{
char letter = 'a';
for (int i = 97; i < 123; i = i + 1, letter = letter + 1)
{
cout << letter << '\t' << i << '\n';
}
}
or
int main()
{
char letter;
int i;
for (i = 97, letter='a'; i < 123; i = i + 1, letter = letter + 1)
{
cout << letter << '\t' << i << '\n';
}
}
However you cannot declare two variables of different type in one for
statement.
Also besides the problem of the for
loop: I don't have a reference for the exercise at hand, but is it really required to iterate both i
and letter
? It seems that you hold the ASCII integer representation of letter
in i
, so you can just iterate either i
or letter
, remove the other one, and cast appropriately in your output:
int main()
{
for (int i = 97; i < 123; i = i + 1)
{
cout << static_cast<char>(i) << '\t' << i << '\n';
}
}
(Although it should be noted that this makes the assumption that the character set encoding is (a super-set of) ASCII, but I think in practice this is almost always true)