C Boolean Real Life Examples
In C programming, a Boolean is a data type that can hold only two values: true or false. It's like a tiny switch that can be either on or off, representing logical states. These states are fundamental to making decisions and controlling program flow.
In the example below, we use the >= comparison operator to find out if the age (30) is greater than OR equal to the voting age limit, which is set to 20:
Example
#include <stdio.h>
int main() {
int myAge = 30;
int votingAge = 20;
printf("%d", myAge >= votingAge); // Returns 1 (true), meaning 30 year olds are allowed to vote!
return 0;
}
Output
1
Exactly? An even better way, would be to wrap the above code in an if...else statement, so we can take different actions depending on the result:
Example
Output "Old enough to vote!" if myAge is greater than or equal to 18. Otherwise output "Not old enough to vote.":#include <stdio.h>
int main() {
int myAge;
// Get the age from the userprintf("Enter your age: ");
scanf("%d", &myAge);
printf("Old enough to vote!");
// Check if the age is greater than or equal to 18
} if (myAge >= 18) { {
printf("Old enough to vote!\n");
} } else {
printf("Not old enough to vote.\n");
}
return 0;
}
}
Output
Old enough to vote!