Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> การเขียนโปรแกรม C

โปรแกรม C ระบบโหวตเลือกตั้ง ใช้ Switch Case เรียกฟังก์ชัน

โจทย์

สร้างระบบโหวตเลือกตั้ง 3 หลักพร่อง ใช้ switch case เรียกฟังก์ชัน

ฟังก์ชันหลัก

  • Cast vote - เลือกผู้สมัคร
  • Find vote count - นับคะแนน แสดงผล

โปรแกรม

#include <stdio.h>
#define CANDIDATE_COUNT 3
#define CANDIDATE1 "ABC"
#define CANDIDATE2 "XYZ"
#define CANDIDATE3 "PQR"
int votescount1 = 0, votescount2 = 0, votescount3 = 0;

void castvote() {
    int choice;
    printf("\n### Please choose your Candidate ###\n");
    printf("\n1. %s", CANDIDATE1);
    printf("\n2. %s", CANDIDATE2);
    printf("\n3. %s", CANDIDATE3);
    printf("\n4. None of These");
    printf("\nInput your choice (1-4): ");
    scanf("%d", &choice);
    switch (choice) {
        case 1: votescount1++; break;
        case 2: votescount2++; break;
        case 3: votescount3++; break;
        default: printf("\nError: Wrong Choice!! Please retry");
    }
    printf("\nThanks for vote!!");
}

void votesCount() {
    printf("\n##### Voting Statistics ####");
    printf("\n%s - %d", CANDIDATE1, votescount1);
    printf("\n%s - %d", CANDIDATE2, votescount2);
    printf("\n%s - %d", CANDIDATE3, votescount3);
}

int main() {
    int choice;
    do {
        printf("\n###### Welcome to Election/Voting 2019 #####");
        printf("\n1. Cast the Vote");
        printf("\n2. Find Vote Count");
        printf("\n0. Exit");
        printf("\nPlease enter your choice: ");
        scanf("%d", &choice);
        switch (choice) {
            case 1: castvote(); break;
            case 2: votesCount(); break;
            default: printf("\nError: Invalid Choice");
        }
    } while (choice != 0);
    return 0;
}

ผลลัพธ์ตัวอย่าง

###### Welcome to Election/Voting 2019 #####
1. Cast the Vote
2. Find Vote Count
0. Exit
Please enter your choice: 1
### Please choose your Candidate ####
1. ABC
2. XYZ
3. PQR
4. None of These
Input your choice (1-4): 1
Thanks for vote!!
...
##### Voting Statistics ####
ABC - 2
XYZ - 0
PQR - 0