If statement
The if statement is one of the decision making statements in c language.
This is a conditional statement used in C to check condition or to control the flow of execution of statements. This is also called as 'decision making statement or control statement.'
The execution of a whole program is done in one direction only.
Syntax :if(condition)
{
statement;
}
Statement-x;
In above syntax, the condition is checked first. If it is true, then the program control flow goes inside the braces and executes the block of statements associated with it. If it returns false, then program skips the braces. If there are more than 1 (one) statements in if statement then use { } braces else it is not necessary to use.
Note : Both times(whether condition is true or false) Statement-x will execute
Simple example:
#include <conio.h>
void main()
{
int x=5;
int y=2;
clrscr();
if(x>y)
{
printf("x is greater than y");
}
if(x<y)
{
printf("x is less than y");
}
printf("\nBye!");
getch();
}
Output:
Description :
First we have declared and initialize two variables x and y of integer type having value of 5 and 2.
Now in the first if statement is checked since x>y is true, hence the first if statement is executed.
Then the second if statement is checked but the condition is false hence it will not executed.
At last the statement after if statements is executed which print Bye!.
Note:
The statement just after the if() statement will be executed no matter the condition under the
if statementa is true or false.
Example:
#include <conio.h>
void main()
{
int x=5;
int y=2;
clrscr();
if(x==y)
{
printf("x is greater than y");
}
if(x<y)
{
printf("x is less than y");
}
printf("\nBye!");
getch();
}
output :
Bye!
Here the both if statement conditions are false hence none of the if statement is executed. But the printf() statement is executed which will generate Bye! output.
Prev NEXT
0 comments:
Post a Comment