C If Else Statement
Decision making statements run a block of code only when a condition is true. The if statement is the most basic one.
if statement
#include <stdio.h>
int main(void) {
int age = 20;
if (age >= 18) {
printf("You can vote.\n");
}
return 0;
}
Output:
Output of the above program is
You can vote.
if else statement
Use else to run another block when the condition is false.
#include <stdio.h>
int main(void) {
int number = 7;
if (number % 2 == 0) {
printf("Even number\n");
} else {
printf("Odd number\n");
}
return 0;
}
Output:
Output of the above program is
Odd number
Taking the value from the user
#include <stdio.h>
int main(void) {
int marks;
printf("Enter marks: ");
scanf("%d", &marks);
if (marks >= 40) {
printf("Pass\n");
} else {
printf("Fail\n");
}
return 0;
}
Output:
Output of the above program is
Enter marks: 65
Pass
Important points
- In C any non zero value is true and zero is false.
- Always use braces
{ }, even for one statement. It avoids bugs when you add more lines later. - Do not put a semicolon after the condition, like
if (x > 5);. It makes an empty if.
Note:
Compare with ==, not =. Most beginners make this mistake at least one time.
Next: C Else If Ladder and Nested If.
Congratulations! Chapter Finished. Learn more about the similar topics:
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |