Press "Enter" to skip to content

Simple IF Statement in C with Examples

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.

Simple IF Statement:

            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.

Example: If he is a programmer, then he can create software
How can we write this as matter of C 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.

Example 2: if you are a bird, you can fly

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;

Note:
  • 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.

Example: If he is driver, he can drive car, he can drive bus.

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.

Example: if she is a teacher, then she can teach in college, can teach in school

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:

Flow chart of simple if statement in C
          – Here ‘Block of statementwill wok if and only if the condition is true. And ‘Statement 2‘ will work even the condition is true or false

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

Leave a Reply