Hi There
I have question, while I was going trough one of the exercises assigned by my tutor I came across problem and solution (thank you google).
Majority of the code is self explanatory but there are few parts that I don't understand.
Exercise was to create an array that will hold in char alphabet.
parts that is unclear for me are:
1. I understand that string need to be finished with \0 but why assign this character at the start?
char letter = '\0';
2. in first loop, there are two items. a) int val is set to 1 in for loop parameters and following line where char letter is asinged with val-1
for ( val = 1; val < 26; val++)
{
letter = alphabet[val-1];
I have tried to use in what I tough would correct but this does not provide correct output.
for ( val = 0; val < 27; val++)
{
letter = alphabet[val];
with such changes I am getting characters that are not correct (not sure even what are they as i can't find most of on ascii code table.
if you could walk me trough the first for loop it would be fab :)
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 27 28 29 30 31 32 33 34 35 36
|
/*
Exercise 1.
Write a program that prints out in the console the whole alphabet 'abcdefghijklmnopqrstuvwxyz'.
All of the characters from the alphabet should be stored in a 27 element array of chars and
printing out of each of those elements should be done with the use of the for loop&
eg.
Output:
abcdefghijklmnopqrstuvwxyz
*/
#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
char alphabet[27];
char letter = '\0';
int val=0;
alphabet[0]='a';
for ( val = 1; val < 26; val++)
{
letter = alphabet[val-1];
letter++;
alphabet[val] = letter;
}
for (val = 0; val < 26; val++)
{
cout << alphabet[val];
}
return 0;
}
|