- if Statement :
- If the test expression is evaluated to true, statements inside the body of if are executed.
- If the test expression is evaluated to false, statements inside the body of if are not executed.
- if...else Statement :
- statements inside the body of if are executed.
- statements inside the body of else are skipped from execution.
- statements inside the body of else are executed
- statements inside the body of if are skipped from execution.
- if...else Ladder:
The syntax of the if statement in C programming is:
if (test expression)
{
// statements to be executed if the test expression is true
}
How if statement works?
Example :
#include <stdio.h>
void main()
{
int number;
printf("Enter an integer: ");
scanf("%d", &number);
// true if number is greater than 0
if (number > 0)
{
printf("You entered %d.\n", number);
}
printf("Sign of Good Learner",);
}
First run:
Enter an integer: 20
You entered 20
Sign of Good Learner
Second run:
Enter an integer: -10
Sign of Good Learner
The syntax of the if...else statement in C programming is:
if (test expression)
{
// statements to be executed if the test expression is true
}
else
{
// statements to be executed if the test expression is false
}
How if...else statement works?
If the test expression is evaluated to true,
If the test expression is evaluated to false,
#include <stdio.h>
void main()
{
int number;
printf("Enter an integer: ");
scanf("%d", &number);
if (number > 0)
{
printf("You entered Positive Number");
}
else
{
printf("You entered Negative Number");
}
}
First run:
Enter an integer: 20
You entered Positive Number.
Second run:
Enter an integer: -10
You entered Negative Number
The if...else statement executes two different codes depending upon whether the test expression is true or false. Sometimes, a choice has to be made from more than 2 possibilities.
The if...else ladder allows you to check between multiple test expressions and execute different statements.
if (test expression)
{
// statements to be executed if the test expression is true
}
else if(test expression)
{
// statements to be executed if the test expression is true in else if
}
else
{
// statements to be executed if the test expression is false
}
Example :
#include <stdio.h>
void main()
{
int number;
printf("Enter an integer: ");
scanf("%d", &number);
if (number > 0)
{
printf("You entered Positive Number");
}
else if (number < 0)
{
printf("You entered Negative Number");
}
else
{
printf("You entered Zero");
}
}
First run:
Enter an integer: 20
You entered Positive Number.
Second run:
Enter an integer: -10
You entered Negative Number
Third run:
Enter an integer: 0
You entered Zero
Post a Comment
If you have any doubts, Please let me know
Thanks!