The if Statement :-
C uses the keyword ' if ' to implement the decision control instruction. The general form of ' if ' statement looks like this:if ( this condition is true )
{
execute the statement
The keyword ' if ' tells the compiler that what follows is a decision control instruction. The condition following the keyword ' if ' is always enclosed within a pair of parentheses. If the condition, whatever it is, is TRUE, then the statement is executed. If the condition is FALSE, then the statement is not executed.
// Program to display a number if user enters negative number
#include <stdio.h>
int main()
{
int number;
printf("Enter an integer: ");
scanf("%d", &number);
// Test expression is true if number is less than 0
if (number < 0)
{
printf("You entered %d.\n", number);
}
printf("The if statement is easy.");
return 0;
}
Output 2
Enter an integer: 5 The if statement is easy.
The else Statement :-
Otherwise , if we want to add another statement by using else keyword if the condition is FALSE so that statement executed and we easily understand that the given condition is FALSE.
#include <stdio.h> int main() { int age; printf("Enter your age:"); scanf("%d",&age); if(age >=18) { /* This statement will only execute if the * above condition (age>=18) returns true */ printf("You are eligible for voting"); } else { /* This statement will only execute if the * condition specified in the "if" returns false. */ printf("You are not eligible for voting"); } return 0; }
Output:
Enter your age:14
You are not eligible for voting
No comments:
Post a Comment