In this post, we’ll walk through a simple C program that checks whether a person is eligible to vote based on their age.
Example Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | #include <stdio.h> int main(void) { int age; printf("Enter your age: "); scanf("%d", &age); if (age >= 18) { printf("You are eligible to vote.\n"); } else { printf("You are not eligible to vote.\n"); } return 0; } |
How the Program Works
Let’s break down the steps of this program to understand how it works:
Including the Header File
The program begins by including the stdio.h
library, which gives access to essential functions like printf
(for output) and scanf
(for input).
1 2 3 | #include <stdio.h> |
Declaring the Main Function
The main()
function is the starting point of every C program. Here, it’s where the program logic will unfold.
1 2 3 | int main(void) { |
Reading the User’s Age
Inside the main
function, we declare an integer variable named age
to store the user’s input. We then prompt the user to enter their age using printf
, and read the input with scanf
.
1 2 3 4 5 | int age; printf("Enter your age: "); scanf("%d", &age); |
1 2 3 4 5 | int age; printf("Enter your age: "); scanf("%d", &age); |
Checking Voting Eligibility
Next, the program uses an if-else
statement to check whether the user is eligible to vote. If their age is 18 or older, it prints a message saying they are eligible to vote. Otherwise, it tells them they are not eligible.
1 2 3 4 5 6 7 | if (age >= 18) { printf("You are eligible to vote.\n"); } else { printf("You are not eligible to vote.\n"); } |
Returning from the Program
At the end of the program, return 0;
is used to indicate that the program has finished executing successfully.
1 2 3 | return 0; |
How the Output Works
When you run this program, it will ask you to input your age. Depending on the number you enter, it will tell you whether you’re eligible to vote or not.
Example Outputs
If you enter 20 as your age, the output will be:
1 2 3 4 | Enter your age: 20 You are eligible to vote. |
If you enter 15, the output will be:
1 2 3 | mathematicaKodu kopyala |
1 2 3 4 | Enter your age: 15 You are not eligible to vote. |
Key Notes
- Voting Age: This program assumes the voting age is 18, which is the case in many countries, but keep in mind that the voting age varies by country. Some countries may have different age requirements.
- How the Program Works: The program’s logic is straightforward: it checks the inputted age and compares it to 18. Depending on the result, it outputs one of two possible messages: either you’re eligible to vote, or you’re not.
Conclusion
This simple C program helps determine whether someone is eligible to vote based on their age. It’s a great example for beginners to understand how to use conditional statements (if-else
) and how to handle user input and output in C.