Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
C For Dummies 2nd Ed 2004.pdf
Скачиваний:
43
Добавлен:
17.08.2013
Размер:
8.34 Mб
Скачать

Chapter 12: C the Mighty if Command 163

Run the final result and see how much more clairvoyant the computer genie has become. Type 3 and see That number is less than 5! Type 9 and see That number is more than 5! Type 5 and the genie knows: You typed in 5!

The else-if comparison resembles combined else and if statements. The second if comes right after else and a space. Then, it has its own comparison statement, which is judged either true or false.

In GENIE2.C, the else-if comparison is number==5, testing to see whether the value of the number variable is 5. Two equal signs are used for this comparison.

You can do else-if, else-if, else-if all day long, if you want. How­ ever, the C language has a better solution in the select-case structure. I cover this topic in this book’s companion volume, C All-in-One Desk Reference For Dummies (Wiley).

Bonus program! The really, really smart genie

A solution always exists. If you wanted to, you could write a program that would if-compare any value, from zero to infinity and back again, and the “computer genie” would accurately guess it. But, why bother with if at all?

Okay, the if keyword is the subject of this section, along with if-else and else-if and so on. But, the following source code for GENIE3.C doesn’t use if at all. It cheats so that the genie always guesses correctly:

#include <stdio.h>

int main()

{

char num;

printf(“I am your computer genie!\n”);

printf(“Enter a number from 0 to 9:”); num = getchar();

printf(“You typed in %c!\n”,num);

printf(“The genie knows all, sees all!\n”); return(0);

}

164 Part III: Giving Your Programs the Ability to Run Amok

You can create this source code by editing either GENIE1.C or GENIE2.C. Make the necessary modifications and then save the source code to disk as GENIE3.C.

Compile the program. Fix any errors that you (hopefully) don’t get. Run the result:

I am your computer genie!

Enter a number from 0 to 9:8

You typed in 8!

The genie knows all, sees all!

Run the program again and again with different numbers. Hey! That genie knows exactly what you typed! I wonder how that happened? It must be your deftness with the C language. Tame that computer!

The problem with GENIE3.C? It doesn’t make a decision. The genie isn’t smart at all — it’s just repeating what you already know. The purpose behind if, else, and the others is that they allow you to make a deci­ sion in your program.

Refer to Chapter 10 for more information about the getchar() function.