This is a follow up from my previous post: Program that converts a number to a letter of the alphabet
This is meant to teach my little brother (who only knows how to make games in Geometry Dash) about C, and computers. This is an example I've written meant to be shown and explained to him.
#include <stdio.h>
#include <stdbool.h>
int main() {
//A string is an array of characters
const char * alphabet = "ABCDEFGHIJKLMNOPQRSTUVWSYZ";
int temp, letter = 0;
while( (1 <= letter && letter <= 26) == false){
/*
* if scanf fails, valadate input to avoid infinite loop
* (the below while statement).
* Uncomment the below printf and comment out the below
* while statement to see what happens if you type
* something like "asdef4grvgrthd" instead of a number.
*/
if(scanf("%d", &letter) != 1){
while((temp=getchar()) != EOF && temp != '\n');
//printf("Fun loop :) ");
}
}
printf("The number %i corresponds to the letter '%c'\n",
letter, alphabet[letter-1]);
}
This is intended to help beginners understand C by being a slightly harder "Hello World" program.
sizeof(alphabet) == 27
, there's a trailing null character in there.strlen(alphabet) == 26
. \$\endgroup\$