if statement

Control flow allow you to change order of execution. It is important feature of C where you can instruct compiler to evaluate line of code according to you.

C provides two types of flow control

  1.   Branching
  2.   looping

Branching is deciding what action to take and looping is deciding how many times to take a certain action. Next we will see both types of C flow control in this tutorial.

2.1 if statement

if statement is used when a unit of code to be executed by a condition true or false.

The syntax is:-

if  ( expression)
{

statement 1;

}
else
{

statement 2;

}

Here else part is optional. The expression inside if() is evaluated, if it is true (that is, if expression has non zero value) then statment 1 is executed . if it is false(that, expression is zero) an else part , statment 2 is executed.

Lets see some examples then things will be more cleared. Suppose you want to write a C programm to check in  exam a student is pass or not based on given marks,

#include<stdio.h>
int main()
{

int   marks;

printf(“Enter the marks\n”);
scanf(“%d”,&marks);

if (marks >= 30)
{

printf(” Student is pass\n”);

}
return 0;

}

Case 1:  Suppose you enter 50 means if condition is true,  the output will be:-
$  ./a.out
$   Enter the marks
$   Student is pass

Case 2 :  Suppose you enter 20 means if condition is false  then program wont print anything, the output will be:-
$  ./a.out
$   Enter the marks

Now  you want to check a student is pass or fail based on given marks. lets try this C program.

#include<stdio.h>
int main()
{

int   marks;

printf(“Enter the marks\n”);
scanf(“%d”,&marks);

if (marks >= 30)
{

printf(” Student is pass\n”);

}

printf(” Student is fail\n”);
return 0;

}

Case 1:  Suppose you enter 20 means if condition is false, then this program execute lines after if statement, the output will be:-
$  ./a.out
$   Enter the marks
$   Student is fail

Case 2 :  Suppose you enter 50 means if condition is true, then compiler execute both printf() and the output will be:-
$  ./a.out
$   Enter the marks
$   Student is pass
$   Student is fails

We can clearly see in above C program. when a student secure more than 30 marks  the output of program is unexpected. Our intension was to print either pass or fail. In this case we need to use if – else statement. Now we check  example C program of  chapter 2.2

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.