Pages

Wednesday, 9 May 2018

C if-else Statement


C if-else Statement
Every coin has two faces and this is also true for our problems. Till now we have learnt about if statement in which we can execute a set of statements by giving some condition or expression.But most of time we need to execute one set of statements if the condition is true, and an entirely different set of statements if the condition is false. This task can be accomplished easily in C language by using if-else statement.


Syntax of if-else statement
if(condition)
{
Statement 1
Statement 2 and so on
}
else
{
Statement 1
Statement 2 and so on
}
C if-else Statement FlowchartFew points about if-else block
The statements inside if keyword is collectively called if block.
The statements inside else keyword is collectively called else block.
The parenthesis inside if-else block can be dropped, if there is only one statement in it. As the default scope of these keywords is only one statement.
No condition is used with else keyword. The statements under else will be executed only if the condition with if statement is turn out false. So it is treated as default choice.
The best way to understand a topic is through a program. Let’s make one program using if-else statement.



Program to check a negative number
#include <stdio.h>

void main()
{
 int num;
 printf("Enter a number to check if it is negative:n");
 scanf("%d",&num);
 if(num<0)
 {
  printf("Number is negative");
 }
 else
 {
  printf("Number is positive");
 }
}