C Programming - SPLessons
SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

C if

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

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

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

[c]#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"); } } [/c] Output: [c]x is greater than y[/c]

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

[c] #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"); } } } [/c] Output: [c]a is less than c[/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.