College of Engineering
Computer Engineering Department
Computer Fundamentals and Programming
Experiment No. 2
CONDITIONAL if STATEMENT
I. OBJECTIVES
a. To implement the different conditional if statements in C++ programs. b. To be able to identify the application and limitations of the different conditional if statements.
II. DISCUSSION A program is usually not limited to a linear sequence of instructions. During its process it may bifurcate, repeat code or take decisions. For that purpose, C++ provides control structures that serve to specify what has to be done to perform our program. With the introduction of control sequences we are going to have to introduce a new concept: the block of instructions. A block of instructions is a group of instructions separated by semicolons (;) but grouped in a block delimited by curly bracket signs: { and}.
Different conditional structure: a. if and else statement The general decision making capability in C++ is provided by the if statement. The format of this statement is | if (expression) program statement |
You will see what sort of `expression' you need to use in the following section. The program statement may be a single statement or may be a block of statements enclosed within braces `{}'. If it is a single statement the format is
| if (expression) single statement; |
but if more statements are to be executed as a compound statement or program block the format becomes
| if (expression) { statement1; statement2; //..... and so on as long as you wantstatement_last;} |
A program block, or compound statement, is a series of statements places inside curly braces {}. When the if statement is true, then all the statements inside the {} are run. When the if statement is false, then none of them are run and the program jumps to the next statement after the closing brace `}' The condition to be tested appears in parenthesis