C - SPLessons
boy2 Chapter 14

C if

C - SPLessons

C if

shape Description

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.

shape Conceptual
figure

if statements

if

shape Description

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

shape Syntax

if(condition)
{
//statements
}


shape Example

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

Output:

a is greater

if…else

shape Description

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

shape Syntax

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

shape Example

#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

shape Description

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.

shape Syntax

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

shape Example

#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

shape Key Points

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

shape Programming
Tips

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