C if. .else Statement.
C if Statement
The syntax of the if statement in C programming is:
Syntax :
if (test expression) {
// statements to be executed if the test expression is true
}
How if statement works?
1: The if statement evaluates the test expression inside the parenthesis ().
2: If the test expression is evaluated to true, statements inside the body of if are executed.
3: If the test expression is evaluated to false, statements inside the body of if are not executed.
Example 1: if statement
#include <stdio.h>
void main()
{
int x,y;
printf("Enter the Value of x: ");
scanf("%d",&x);
printf("Enter the Value of y: ");
scanf("%d",&y);
if (x<y) {
printf("\n%d is less than %d",x,y);
}
}
C if...else Statement
// 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?
1: If the test expression is evaluated to true,
statements inside the body of if are executed.
statements inside the body of else are skipped from execution.
2: If the test expression is evaluated to false,
statements inside the body of else are executed
statements inside the body of if are skipped from execution.
Example 2: if..else statement
#include <stdio.h>
void main () {
int a;
printf("Enter the Value of a: ");
scanf("%d",&a);
/* check the boolean condition */
if( a < 20 ) {
/* if condition is true then print the following */
printf("%d is less than 20\n",a);
}
else {
/* if condition is false then print the following */
printf("%d is not less than 20\n",a);
}
}
C if...else Ladder
Syntax of if...else Ladder:
if (test expression1) {
// statement(s)
}
else if(test expression2) {
// statement(s)
}
else if (test expression3) {
// statement(s)
} . .
else {
// statement(s)
}
Example 3: C if...else Ladder
#include<stdio.h>
void main(){
int n;
printf("Enter the Value of n: ");
scanf("%d",&n);
if(n<18){
printf("\nYou are not able for driving");
}
else if(n>18){
printf("\nYou are able for driving");
}
else{
printf("\nInvalid choice");
}
}
Enter the Value of n: 25
You are able for driving
Output 2:
Enter the Value of n: 10
You are not able for driving
Comments
Post a Comment