Simple IF Statement in C with Examples
After learning all these operators, we have to learn condition statements in C like IF statement. Here we should learn IF statement to understand remaining operators in C.
IF statement is the most popular and powerful decision making statement in all programming language also in C. IF statement is approximately same as normal usage of ‘if’ in English language.
if(he is a programmer)
He can create software;
|
That is, after the keyword ‘if’, write condition inside a normal bracket ( ), then write the statement that if the condition become true.
In C:
if(you are a bird)
you can fly;
|
These are not original implementation in C, just for learning. Here we saw, if condition is true (correct) then remaining part will work. If condition is false, then remaining part will not work. That is, in above example (if you are a bird, you can fly), if you are not a bird, then you can’t fly. That means, you can fly if and only if you are a bird, else you can’t.
Syntax of IF statement in C:
if(condition)
statement; |
- At the end of IF condition, there is no semicolon( ; ). If you put a semicolon at the end, then condition line will work, but statement after condition will not work.
- There should be a semicolon at the end of statements. Otherwise error will appear.
A curled bracket is necessary if you are write more than one statements after the condition.
In C
if(he is a driver) {
He can drive car;
He can drive bus;
}
|
If you write some other codes after closing curled bracket, then that code will work even test condition is false.
In C mode:
If(she is a teacher)
{
She can teach in college;
Can teach in school;
}
She can teach to her children; |
Here the statement ‘She can teach to her children;’ will work even the condition is false (that is, even she is not a teacher).
Flow chart of Simple Statement is given below:
Continue to Operators in C (Relational operators). It contains many examples of IF statement.
Go to Next Lesson (else… if statement) if you are already completed the lessons of Operators in C.
Be First to Comment