CHAPTER 2 C Programing
CHAPTER 2 C Programing
LOOPS
The C language provides three typ es of decision-making c onstructs: if-else, the conditional
expression ?: , and the switch statement. It also provides three looping constructs: while, do-
while,
and for. And it has the infamous goto, which is capable of both non-conditional branching and
looping.
I- I f-Else
The basic if statement tests a conditional expression and, if it is non-zero (i.e.,
TRUE), executes
the subsequent statement. For example, in this code segment
if (a < b)
b = a;
the assignment b = a will only occur if a is less-than b. The else statement deals
with the alternative
case where the conditional expression is 0 (i.e., FALSE).
if (a < b)
b = a;
else
b += 7;
The if-else statement can also command multiple statements by wrapping them in
braces. Statements so grouped are called a compound statement, or block, and they
are syntactically equivalent
to a single statement.
if (a < b) {
b = a;
a *= 2;
}
else {
b += 7;
--a;
}
It is possible to chain if-else statements if the following form
if (expression)
statement;
else if (expression)
statement;
else if (expression)
statement;
else
statement;
It is worth mentioning here that all the c ontrol structures—if-else, ?: , while, do-while, and
for—can be nested, which means that they can exist within other control statements. The
switchstatement is no exception, and the statements following a case label may include a
switch or other
control structure. For example, the following code-structure is legitimate.
if (expression)
while (expression)
switch(integer expression) {
case A1:
switch(integer expression) {
case B1: statements
case B2: statements
case B3: statements
}
case A2: statements