Download 1.1 Programming in C Language
Transcript
Introduction to C Language
1
1.4 Control Statements
1.4.2 Branching Processing Depending on Condition (branch processing)
Control statements used to write branch processing include "if-else", "else-if", and "switch-case"
statements.
This section explains how to write these control statements and shows some examples of usage.
if-else statement
This statement executes the next block if the given condition is true or the "else" block if the
condition is false. Specification of an "else" block can be omitted.
• If the else statement is omitted
Is condition
expression
true?
False
if (condition
expression)
{
Execution statement A
True
Execution
statement A
}
False
if (condition
expression)
Execution
statement A
{
Execution statement A
True
else{
Execution
statement B
Is condition
expression
true?
}
Execution statement B
}
Figure 1.4.1 Example for if-else statement
Example 1.4.1 Count Up (if-else statement)
In this example, the program counts up a seconds counter "second" and a minutes counter
"minute". When this program module is called up every 1 second, it functions as a clock.
void count_up(void) ;
Declares "count_up" function. (Refer to Section 1.5,
"Functions".)
unsigned int second = 0 ;
unsigned int minute = 0 ;
Declares variables for "second" (seconds counter)
and "minute" (m inutes counter).
void count_up(void)
{
if(second >= 59 ){
second = 0 ;
minute ++ ;
}
else{
second ++ ;
}
}
Defines "count_up" function.
If greater than 59 seconds,
the module resets "second" and
counts up "minute".
If less than 59 seconds,
the module counts up "second".
Example 1.4.1 Count up (if-else statement)
28