Quiz Game in C
A quiz game asks multiple-choice questions, checks each answer and shows a final score. It's simple to play, but building it teaches you how to keep data separate from code: the questions live in an array of structures, and one loop asks all of them, no matter how many there are.
In this project you will build a quiz with four options per question, accept answers in upper or lower case, show the correct answer when the player is wrong, calculate a percentage and grade, and finally load the questions from a text file so anyone can add questions without touching the code.
What You Will Learn
- How to store questions in an array of structures.
- How to loop over all questions and check answers.
- How to accept 'a' and 'A' with
toupper(). - How to compute a score, percentage and grade.
- How to read questions from a text file with
fgets. - How to design data-driven programs.
Quiz Game in C Explained
Exam definition: In a data-driven program, the information (here, questions, options and answers) is stored in data structures or files, and general code processes it. A quiz question is modelled with a structure containing the question text, an array of option strings and the correct answer; an array of these structures holds the whole quiz, and a loop presents each element.
Memory trick: Think of a question paper and an answer key. The structure is one printed question with its options and its line in the answer key. The loop is the invigilator who reads out question 1, 2, 3… The invigilator doesn't change when you add questions; only the paper gets longer.
Syntax: A Question Structure
struct question
{
char text[100];
char option[4][40]; /* A, B, C, D */
char answer; /* 'A' to 'D' */
};
struct question quiz[] = {
{"Who developed C?", {"Dennis Ritchie", "James Gosling", "Bjarne Stroustrup", "Guido van Rossum"}, 'A'},
/* more questions ... */
};
int total = sizeof quiz / sizeof quiz[0]; /* number of questions */
Example 1: Quiz with Score and Grade
#include <stdio.h>
#include <ctype.h>
struct question
{
char text[100];
char option[4][40];
char answer;
};
struct question quiz[] = {
{"Who developed the C language?",
{"Dennis Ritchie", "James Gosling", "Bjarne Stroustrup", "Guido van Rossum"}, 'A'},
{"Which format specifier prints an int?",
{"%f", "%d", "%c", "%s"}, 'B'},
{"What is the size of char in C?",
{"2 bytes", "4 bytes", "1 byte", "8 bytes"}, 'C'},
{"Which loop runs at least once?",
{"for", "while", "if", "do-while"}, 'D'},
{"Which header declares printf?",
{"stdlib.h", "math.h", "stdio.h", "string.h"}, 'C'},
};
char grade(double percent)
{
if (percent >= 80) return 'A';
if (percent >= 60) return 'B';
if (percent >= 40) return 'C';
return 'F';
}
int main(void)
{
int total = sizeof quiz / sizeof quiz[0];
int i, j, score = 0;
char ans;
double percent;
printf("===== C PROGRAMMING QUIZ =====\n");
for (i = 0; i < total; i++)
{
printf("\nQ%d. %s\n", i + 1, quiz[i].text);
for (j = 0; j < 4; j++)
printf(" %c) %s\n", 'A' + j, quiz[i].option[j]);
printf("Your answer: ");
if (scanf(" %c", &ans) != 1)
break;
ans = (char) toupper((unsigned char) ans);
if (ans == quiz[i].answer)
{
printf("Correct!\n");
score++;
}
else
printf("Wrong. Correct answer: %c) %s\n",
quiz[i].answer, quiz[i].option[quiz[i].answer - 'A']);
}
percent = score * 100.0 / total;
printf("\nScore: %d/%d (%.0f%%) Grade: %c\n", score, total, percent, grade(percent));
return 0;
}
Output
===== C PROGRAMMING QUIZ ===== Q1. Who developed the C language? A) Dennis Ritchie B) James Gosling C) Bjarne Stroustrup D) Guido van Rossum Your answer: a Correct! Q2. Which format specifier prints an int? A) %f B) %d C) %c D) %s Your answer: B Correct! Q3. What is the size of char in C? A) 2 bytes B) 4 bytes C) 1 byte D) 8 bytes Your answer: c Correct! Q4. Which loop runs at least once? A) for B) while C) if D) do-while Your answer: D Correct! Q5. Which header declares printf? A) stdlib.h B) math.h C) stdio.h D) string.h Your answer: b Wrong. Correct answer: C) stdio.h Score: 4/5 (80%) Grade: A
Code Explanation
- Each
struct questionholds the text, four options and the correct letter. The array is filled with an initializer list. sizeof quiz / sizeof quiz[0]counts the questions automatically, so adding a question needs no other change.'A' + jprints the letters A, B, C, D because character codes are consecutive.scanf(" %c", &ans)skips the leftover newline;touppermakes 'a' and 'A' the same.quiz[i].answer - 'A'turns the correct letter into an index (C → 2) to print the right option.- The percentage uses
100.0so the division is not integer division;grade()turns it into a letter.
How the Quiz Is Organised
DATA (array of structures) CODE (one loop)
┌──────────────────────────┐ for each question:
│ Q1 text, A..D, answer A │ print text and options
│ Q2 text, A..D, answer B │ ───► read answer, toupper
│ Q3 text, A..D, answer C │ compare with .answer
│ ... │ update score
└──────────────────────────┘ print score, percent, grade
This separation is called data-driven design. The next step is to move the data out of the program into a file.
Example 2: Questions Loaded from a File
The file has 6 lines per question: the question, four options and the answer letter. For a self-contained demo, the program writes a small quiz.txt first and then reads it back.
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define MAXQ 20
struct question
{
char text[100];
char option[4][40];
char answer;
};
void strip_newline(char *s)
{
s[strcspn(s, "\n")] = '\0';
}
int load_quiz(const char *file, struct question q[], int max)
{
FILE *fp = fopen(file, "r");
char line[100];
int n = 0, j;
if (fp == NULL)
return -1;
while (n < max && fgets(q[n].text, sizeof q[n].text, fp) != NULL)
{
strip_newline(q[n].text);
for (j = 0; j < 4; j++)
{
fgets(q[n].option[j], sizeof q[n].option[j], fp);
strip_newline(q[n].option[j]);
}
fgets(line, sizeof line, fp);
q[n].answer = (char) toupper((unsigned char) line[0]);
n++;
}
fclose(fp);
return n;
}
int main(void)
{
struct question q[MAXQ];
FILE *fp = fopen("quiz.txt", "w");
int n, i, j, score = 0;
char ans;
if (fp == NULL)
return 1;
fputs("Capital of India?\nMumbai\nNew Delhi\nKolkata\nChennai\nB\n", fp);
fputs("2 + 2 * 3 = ?\n12\n8\n10\n6\nB\n", fp);
fputs("Which is a prime number?\n7\n9\n15\n21\nA\n", fp);
fclose(fp);
n = load_quiz("quiz.txt", q, MAXQ);
if (n <= 0)
{
printf("Could not load questions\n");
return 1;
}
printf("Loaded %d questions from quiz.txt\n", n);
for (i = 0; i < n; i++)
{
printf("\n%d. %s\n", i + 1, q[i].text);
for (j = 0; j < 4; j++)
printf(" %c) %s\n", 'A' + j, q[i].option[j]);
printf("Answer: ");
if (scanf(" %c", &ans) != 1)
break;
if (toupper((unsigned char) ans) == q[i].answer)
{
score++;
printf("Right!\n");
}
else
printf("Wrong (answer %c)\n", q[i].answer);
}
printf("\nFinal score: %d out of %d\n", score, n);
remove("quiz.txt");
return 0;
}
Output
Loaded 3 questions from quiz.txt 1. Capital of India? A) Mumbai B) New Delhi C) Kolkata D) Chennai Answer: B Right! 2. 2 + 2 * 3 = ? A) 12 B) 8 C) 10 D) 6 Answer: b Right! 3. Which is a prime number? A) 7 B) 9 C) 15 D) 21 Answer: A Right! Final score: 3 out of 3
load_quiz()reads 6 lines per question withfgets, which keeps spaces in the text (unlikescanf("%s")).strcspn(s, "\n")finds the newline that fgets keeps, and we replace it with'\0'.- Now a teacher can edit
quiz.txtin Notepad to add or change questions; the program doesn't need to be recompiled. - The function returns −1 if the file can't be opened, so
maincan show an error.
Important Points to Remember
- Model one question as a structure; the whole quiz as an array of structures.
- Count elements with sizeof array / sizeof array[0].
- Read single-letter answers with " %c" and normalise with toupper().
- Use 100.0 (a double) when computing percentages.
fgetsreads whole lines (with spaces); remove the trailing newline.- Keeping data in files makes programs easy to update without recompiling.
Common Mistakes Beginners Make
| Mistake | What happens | Fix |
|---|---|---|
scanf("%c", &ans) without a space | Reads the newline; every second answer is skipped | Use " %c" |
| Comparing 'a' with 'A' | Correct lower-case answers marked wrong | Apply toupper() |
score * 100 / total with ints | Percentage truncated | Use score * 100.0 / total |
| Hard-coding the question count | Adding a question breaks the loop | Use sizeof or the count returned by the loader |
Not removing '\n' after fgets | Options print with extra blank lines | s[strcspn(s, "\n")] = '\0'; |
Quiz Game Practice Questions
- Why is a structure a good choice for storing a quiz question?
- How does the program find the number of questions automatically?
- What does
toupper()do, and which header declares it? - Why is
fgetsused instead ofscanf("%s")to read questions from a file? - What is a data-driven program?
Show answers
- A question has several related parts of different types (text, options, answer letter) that belong together.
sizeof quiz / sizeof quiz[0]: total size of the array divided by the size of one element.- It converts a lower-case letter to upper case;
<ctype.h>. - fgets reads a whole line including spaces; scanf("%s") stops at the first space.
- A program whose behaviour is controlled by data (in arrays or files) processed by general code, so changing the data changes the program without editing code.
Coding Exercise
Add negative marking: +4 for a correct answer and −1 for a wrong one. Given the correct answers "ABCDA" and a student's answers "ABDDC", calculate and print the result question by question and the total marks.
Show solution
#include <stdio.h>
#include <string.h>
int main(void)
{
const char *key = "ABCDA";
const char *student = "ABDDC";
int i, marks = 0, n = (int) strlen(key);
for (i = 0; i < n; i++)
{
if (student[i] == key[i])
{
marks += 4;
printf("Q%d: %c correct +4\n", i + 1, student[i]);
}
else
{
marks -= 1;
printf("Q%d: %c wrong -1 (answer %c)\n", i + 1, student[i], key[i]);
}
}
printf("Total marks: %d out of %d\n", marks, n * 4);
return 0;
}
Q1: A correct +4 Q2: B correct +4 Q3: D wrong -1 (answer C) Q4: D correct +4 Q5: C wrong -1 (answer A) Total marks: 10 out of 20
Quick Quiz: Quiz Game Project (MCQ)
-
Best way to store many quiz questions:
A) Many separate variables B) Array of structures C) One long string D) A single int
-
toupper('c')returns:A) 'c' B) 'C' C) 67 as a string D) An error
-
'A' + 2is the character:A) 'B' B) 'C' C) '2' D) 'A2'
-
Which function reads a whole line with spaces?
A) scanf("%s") B) getchar C) fgets D) putchar
-
If score = 3 and total = 4,
score * 100 / total(ints) is:A) 75 B) 0 C) 75.0 D) 3
Show answers
- B: an array of structures.
- B: 'C'.
- B: 'C'.
- C: fgets.
- A: 75 (300 / 4 is exact here, but 2 * 100 / 3 would give 66, not 66.67).
Quick Revision for Exams and Interviews
Read this before your exam. The highlighted words are the answer.
Must-remember facts
| One question | struct: text, options[4], answer |
|---|---|
| Whole quiz | Array of structures |
| Count | sizeof a / sizeof a[0] |
| Read a letter | scanf(" %c") |
| Case-insensitive | toupper(), ctype.h |
| Percentage | score * 100.0 / total |
| Questions in a file | fgets + remove '\n' |
Frequently asked questions
- How do you make a quiz game in C?
- Store questions in an array of structures, loop through them, read each answer, compare it with the correct letter and count the score.
- How do you accept both 'a' and 'A' as an answer?
- Convert the input with toupper() before comparing.
- Why load questions from a file?
- So questions can be added or changed without recompiling the program.
Remember
- Quiz = question paper (data) + invigilator (loop).
- Use " %c" and toupper for answers.
Next Topic
Next lesson: Student Record System in C. You will build a file-based student record system with add, display, search, update and delete.