C
Score calculation
Learn correct count with the score calculation function.
Score calculation
The fourth lesson defines the print_percentage function. This function computes the score as a percentage and prints it. Percentage shows the success rate clearly.
Signature: void print_percentage(int score, int count). Body: int pct = score * 100 / count; printf("Yüzde: %d%%\n", pct);. Here %% prints a single %. The computation does score * 100 first, then divides by count; this order matters because integer division of score / count * 100 may give the wrong result. The previous lesson's solution is in the starting code.
Integer division
In C, integer division discards the fractional part. This makes the order of operations matter when computing percentages. The right order: multiply first, then divide.
Example: 2 * 100 / 2 = 100 (correct). But 2 / 2 * 100 = 100 also works. The issue shows with small values: 1 / 2 * 100 = 0 * 100 = 0 (wrong, should be 50). Whereas 1 * 100 / 2 = 100 / 2 = 50 (correct). So score * 100 / count is the safe order. Integer division needs care; if you need a float, use a (float) cast.
Exercise Write the print_percentage function
Write void print_percentage(int score, int count). In the body compute int pct = score * 100 / count; and print with printf("Yüzde: %d%%\n", pct);. In main, call print_percentage(score, count); (score and count come from previous lessons).
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;
}
void print_percentage(int score, int count) {
int pct = score * 100 / count;
printf("Yüzde: %d%%\n", pct);
}
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);
print_percentage(score, count);
return 0;
}
Test yourself
-
Match percentage parts
- score * 100 / count
- Percentage calc
- %d%%
- Percent format
- printf("Yüzde:")
- Output
- void print_percentage
- Function signature
-
Result of 2 * 100 / 2?
Show answer
100 — 2*100=200, 200/2=100. Integer division gives the right result.
-
Complete the percentage calc
int pct = score ____ / count;
Show answer
int pct = score * 100 / count;
Next lesson: Putting it together