Situatie
Algoritmul codului prezentat mai jos, poate fi folosit in diverse aplicatii utile si practice (ex. setarea unei alarme in casa, deschiderea unei usi folosind o anumita combinatie de numere sau cifre, securizarea seifului, programarea in timp a aplicatiilor, control temperatura si multe altele).
Alte informatii cu privire la functionarea programului sunt prezentate in imaginile aditionale.
Solutie
#include <iostream.h>
#include <ctype.h>
#include <stdlib.h>
typedef int Bool;
const Bool TRUE = 1;
const Bool FALSE = 0;
void readLetter(char&);
int computeCorrespondingDigit(char);
Bool doOneLetter(); //returns flag saying whether you should quit
void main () {
Bool flag = FALSE;
while (!flag) {
flag = doOneLetter();
}
}
int exitLetter (char c) {
return ((c == ‘Q’) || (c == ‘Z’));
}
Bool doOneLetter() {
char l;
int i;
readLetter(l); // returns upper case letter
if (exitLetter(l)) {
cout << “Quit.” << endl;
return(TRUE);
}
else {
i = computeCorrespondingDigit(l);
cout << “The letter ” << l << ” corresponds to ” << i
<< ” on the telephone” << endl;
return(FALSE);
}
}
int computeCorrespondingDigit (char l) {
switch (l) {
case ‘A’ :
case ‘B’ :
case ‘C’ :
return(2);
case ‘D’ :
case ‘E’ :
case ‘F’ :
return(3);
case ‘G’ :
case ‘H’ :
case ‘I’ :
return(4);
case ‘J’ :
case ‘K’ :
case ‘L’ :
return(5);
case ‘M’ :
case ‘N’ :
case ‘O’ :
return(6);
case ‘P’ :
case ‘R’ :
case ‘S’ :
return(7);
case ‘T’ :
case ‘U’ :
case ‘V’ :
return(8);
case ‘W’ :
case ‘X’ :
case ‘Y’ :
return(9);
}
}
void readLetter(char& c) {
cout << “Enter a letter: “;
cin >> c;
while (cin && !isalpha(c)) {
cout << “You have not entered a letter. Try again: “;
cin >> c;
}
if (!cin) {
cout << “Unrecoverable error… Exiting” << endl;
exit(-1);
}
c = toupper(c);
}
Leave A Comment?