Programming in C

(Barry) #1

6 Making Decisions


6 Making Decisions

INCHAPTER5, “PROGRAMLOOPING,”YOULEARNEDthat one of the fundamental prop-
erties of a computer is its capability to repetitively execute a sequence of instructions.
But another fundamental property lies in its capability to make decisions.You saw how
these decision-making powers were used in the execution of the various looping state-
ments to determine when to terminate the program loop.Without such capabilities, you
would never be able to “get out” of a program loop and would end up executing the
same sequence of statements over and over again, theoretically forever (which is why
such a program loop is called an infiniteloop).
The C programming language also provides several other decision-making constructs,
which are covered in this chapter:


n The ifstatement
n The switchstatement
n The conditional operator

The ifStatement


The C programming language provides a general decision-making capability in the form
of a language construct known as the ifstatement. The general format of this statement
is as follows:


if ( expression)
program statement


Imagine that you could translate a statement such as “If it is not raining, then I will go
swimming” into the C language. Using the preceding format for the ifstatement, this
might be “written” in C as follows:


if ( it is not raining )
I will go swimming

Free download pdf