When you are writing C program, sometimes you need to make certain checks on variables and based on which you need to take some decisions.. this is called as Decision making statements in C programming Language.
In this post, we will show you how you can use simple conditional statements “if” and “if-else” in your C programs
C programming supports following conditional operators
- x == y means “returns true if x is equals to y” otherwise “return false”
- x != y means “returns true if x is not equals to y” otherwise “return false”
- x < y means “returns true if x is less than y” otherwise “return false”
- x > y means “returns true if x is greater than y” otherwise “return false”
- x <= y means “returns true if x is less than or equals to y” otherwise “return false”
- x >= y means “returns true if x is greater than or equals to y” otherwise “return false”
Now, lets use above conditional operators to show how you can use if and if-else to execute different code based on this conditions.
Using IF
$ vim if.c
#include <stdio.h>
int main (int argc, char **argv) {
int x = 10, y = 22 ;
if (x <= y)
printf ("x is less than or equal to y");
return 0;
}
Notice in above code, how we have written the “if” statement.
- we need to add open and close bracket () in for the condition check
- We can start the next line after “if” at any place
if we execute this C code, now on console.. we can see that it will print the string “x is less than or equal to y” as x is set to 10 and y is set to 22.
$ gcc -o if_bin if.c
$ ./if_bin
x is less than or equal to y
Using IF-ELSE
$ vim ifelse.c
#include <stdio.h>
int main(int argc, char **argv) {
int x = 10, y = 22 ;
if (x <= y)
print ("x is less than or equal to y");
else
print ("x is greater than y");
return 0;
}
As we have checked in “if’ when x = 10 and y = 22 i.e. 10 < 22, the code’s if statement “x <= y” will become true and “x is less than or equal to y” message will get printed.
Now, lets change values of x = 22 and y = 10 as below,
#include <stdio.h>
int main(int argc, char **argv) {
int x = 22, y = 10 ;
if (x <= y)
print ("x is less than or equal to y");
else
print ("x is greater than y");
return 0;
}
and now if we run this code, since 22 > 10 i.e. x > y , the first “if x <= y” returns false, hence code execution will go to “else”
and if will print “x is greater than y”
$ gcc -o ifelse_bin ifelse.c
$ ./ifelse_bin
x is greater than y
1 thought on “Using Decision Making Statements, if and if-else in C program”