Introduction
You can conditionally execute statements using the if or the if...else statement. The control of the program is dependent on the outcome of the Boolean condition that is specified in the if statement.
Program
#include
main()
{
int i,j,big; //variable declaration
scanf("%d%d",&i,&j); big = i;
if(big < j) // statement A
{ // C
big = j; // Part Z, then part
} // D
printf("biggest of two numbers is %d \n",big);
if(i < j) // statement B
{
big = j; // Part X
}
else
{
big = i; // Part Y
}
printf("biggest of two numbers(using else) is %d \n",big);
}
Explanation
1. Statement A indicates the if statement. The general form of the if statement is if(expr)
2. {
3. s1 ;
4. s2 ;
5. ....
6. }
7. expr is a Boolean expression that returns true (nonzero) or false (zero).
8. In C, the value nonzero is true while zero is taken as false.
9. If you want to execute only one statement, opening and closing braces are not required, which is indicated by C and D in the current program.
10. The else part is optional. If the if condition is true then the part that is enclosed after the if is executed (Part X). If the if condition is false then the else part is executed (Part Y).
11. Without the else statement (in the first if statement), if the condition is true then Part Z is executed.
Points to Remember
1. if and if...else are used for conditional execution. After the if statement the control is moved to the next statement.
2. If the if condition is satisfied, then the "then" part is executed; otherwise the else part is executed.
3. You can include any operators such as <, >, <=, >=, = = (for equality). Note that when you want to test two expressions for equality, use = = instead of =.
No comments:
Post a Comment