|
Lesson 4Decision Making: making programs intelligentHave you heard of computers that beat chess champions or mimic experts? The decision making statement responsible for making a program an intelligent entity is known as the " if " statement. However, not using the proper decision-making can cause a program to fail or possibly become dumb. This is known as a computer error. An example of a program error is to print or display a paycheck for an employee who worked regular hours with a negative amount of money. MAKING THE DECISIONIf given an employee's salary, how would you determine the tax rate? If given the number of hours an employee worked, how would you determine the overtime hours? If you were asked whether you want to continue, or stop what you are doing, what would you answer? If you were asked to enter your password and you typed either the right or the wrong password, what would you expect to happen? If given a menu with a list of items, how would you make a selection? These are a few examples of decision-making. They are used in a similar fashion in programming. HOW DO YOU MAKE A DECISION IN C/C++?In C/C++, decision making is done by using an if or a switch statement. The if statement uses the form shown in Figure 4.1.
The expression after the if must evaluate to
either true or false. If the expression evaluates to true, the “body of the
if”, which is the statement next to parentheses, will be executed. If the
expression evaluates to false, the “body of the else” will be executed. If
the body of if or the body of else contain more than one
statement, then braces { } should be used. It is good practice to always
use braces. |
This
information was powered by
Prof A, Ebrahimi