C
Running the quiz
Learn to ask questions in turn with the Run function.
Running the quiz
The third lesson defines the run_quiz function. This function writes each question to the screen, checks whether it was answered correctly, and returns the total score.
Signature: int run_quiz(struct Question *q, int count). Body: an answers array (example {0, 1, 2}) represents the user's answers; a for loop prints each question; if (answers[i] == q[i].correct) checks; score++ counts. Finally return score;. The previous lesson's solution is in the starting code.
Loop and check
The core of run_quiz is a for loop and an if check. The loop writes each question; the check counts correct answers.
Example: for (int i = 0; i < count; i++) { printf("Soru %d: %s\n", i+1, q[i].text); if (answers[i] == q[i].correct) score++; }. i+1 gives a 1-based number; i accesses a 0-based index. The answers array represents the user's answers; in a real app you'd read with scanf. Here we use a fixed array so the output is deterministic.
Exercise Write the run_quiz function
Write int run_quiz(struct Question *q, int count). In the body declare int answers[3] = {0, 1, 2}; and int score = 0;. With a for (int i = 0; i < count; i++) loop, print printf("Soru %d: %s\n", i + 1, q[i].text);; count with if (answers[i] == q[i].correct) score++;. Return return score;. In main, call int score = run_quiz(questions, count); and print with printf("Skor: %d\n", score);.
Show example solution
#include <stdio.h>
#include <string.h>
struct Question {
char text[64];
int correct;
};
void add_question(struct Question *q, int *count, const char *text, int correct) {
strcpy(q[*count].text, text);
q[*count].correct = correct;
(*count)++;
}
int run_quiz(struct Question *q, int count) {
int answers[3] = {0, 1, 2};
int score = 0;
for (int i = 0; i < count; i++) {
printf("Soru %d: %s\n", i + 1, q[i].text);
if (answers[i] == q[i].correct) {
score++;
}
}
return score;
}
int main(void) {
struct Question questions[10];
int count = 0;
add_question(questions, &count, "Başkent?", 0);
add_question(questions, &count, "2+2?", 1);
printf("%d soru eklendi\n", count);
int score = run_quiz(questions, count);
printf("Skor: %d\n", score);
return 0;
}
Test yourself
-
What does run_quiz return?
- The question text
- The correct count
- The answer array
- The question count
Show answer
The correct count — run_quiz returns the number of correct answers.
-
Match run_quiz parts
- for (i=0; i<count; i++)
- Loop
- printf("Soru %d: %s")
- Question print
- if (answers[i] == q[i].correct)
- Check
- return score
- Score return
-
Complete the loop condition
for (int i = 0; i ____; i++)
Show answer
for (int i = 0; i < count; i++)
Next lesson: Score calculation