C - SPLessons

Chapter 14

C if

C if

Making a decision in order to execute a group of statements meeting the given conditions or repeat the execution until the conditions are satisfied is called as Decision Making. It can be done by using certain C if statements.

if statements

if

The block of code gets executed only when the condition becomes true otherwise C if block will be skipped.

if(condition)
{
//statements
}


#include<stdio.h> 
void main()
{
	int a=2,b=1; 
	if(a>b) 
	{ 
		printf("a is greater"); 
	} 
}

Output:

a is greater

if…else

The block of code will be executed only when the given if condition is true otherwise compiler executes the statements of else block.

if(condition)
{
//statements;
}
else
{
//statements;
}

#include<stdio.h>
void main( ) 
	{ 
	int x,y; x=1; y=0; if (x > y ) 
	{ 
		printf("x is greater than y"); 
	} 
	else 
	{ 
		printf("y is greater than x"); 
	}
} 

Output:

x is greater than y

Nested-if

Nested-if checks more than one condition. In short,nested if is if in if.When the condition of first if statement is false,then compiler checks for next if block. If if statement is true, compiler executes statements in inner if block, otherwise it executes else block statements.

if(condition1)
{
if(condition2)
{
//statements
}
else
{
//statements
}
}
else
{
//statement
}

#include<stdio.h>
int main() 
{ 
	int a=10,b=20,c=30; 
	if (a>b) 
	{ 
		printf("a is greater than b"); 
	} 
	if(b>c) 
	{ 
		printf("b is greater than c"); 
	} 
	else 
	{ 
		printf("a is less than c"); 
	} 
	} 
} 

Output:

a is less than c

Summary

  • if statements helps in decision making.
  • if block executes only when true.
  • if-else will have true and false options.
  • Nested-if will have multiple if and else blocks.

  • C if statement operate on “condition”, hence do not leave condition part.
  • More than one statement in if are enclosed between “{”  &  “}”.
  • Carefully choose if,if-else, if-else if-else based on the problem.
  • Better to avoid nested-if as it will result in confusion while understanding the code.