HOME C C++ PYTHON JAVA HTML CSS JAVASCRIPT BOOTSTRAP JQUERY REACT PHP SQL AJAX JSON DATA SCIENCE AI

C if-else : Real-Life Examples


An if-else statement in C programming is a decision-making construct that allows you to control the flow of your code based on certain conditions.

This example shows how you can use if..else to "open the door" if the user enters the correct code:

Example

#include <stdio.h>

int main() {

int doorCode = 1337;

if (doorCode == 1337) {

printf("Correct code.\nThe door is now open.");

} else {

printf("Wrong code.\nThe door remains closed.");

}

return 0;

}


Output

Correct code.

The door is now open.


This example shows how you can use if..else to find out whether a number is positive or negative:


Example

#include <stdio.h>

int main() {

int myNum = 10;

if (myNum > 0) {

printf("The value is a positive number.");

} else if (myNum < 0) {

printf("The value is a negative number.");

} else {

printf("The value is 0.");

}

return 0;

}


Output

The value is a positive number.


Find out if a person is old enough to vote:

Example

#include <stdio.h>

int main() {

int myAge = 25

int votingAge = 18;

if (myAge >= votingAge) {

printf("Old enough to vote!");

} else {

printf("Not old enough to vote.");

}

return 0;

}


Output

Old enough to vote!


Find out if a number is even or odd:

Example

#include <stdio.h>

int main() {

int myNum = 5;

if (myNum % 2 == 0) {

printf("%d is even.\n", myNum);

} else {

printf("%d is odd.\n", myNum);

}

return 0;

}


Output

5 is odd.