Handling user input in C is one of the first skills you need as a C programmer. Without it, your programs do the same thing every time they run. In this guide you’ll learn how to read numbers with scanf(), read text safely with fgets(), avoid the most common mistakes, and check what users type before you use it.
The Basics of User Input in C
When you first learn about user input in C, the most common function you will encounter is scanf(). This function reads formatted input from the standard input stream (usually the keyboard).
Here is a basic example of how to use scanf() to capture an integer:
#include <stdio.h>
int main() {
int age;
printf("Please enter your age: ");
scanf("%d", &age);
printf("You are %d years old.\n", age);
return 0;
}
Handling String Input Safely
If you want to capture a full sentence or a string with spaces as user input in C, scanf() often falls short because it stops reading at the first whitespace. Instead, programmers should use fgets().
The fgets() function reads a line of text and stores it into a string buffer. It is much safer because it prevents buffer overflow errors by limiting the number of characters read.
#include <stdio.h>
int main() {
char name[50];
printf("Enter your full name: ");
fgets(name, sizeof(name), stdin);
printf("Hello, %s", name);
return 0;
}
Common Mistakes When Handling User Input in C
When working with user input in C, beginners often run into a few common errors. To ensure your programs run smoothly, keep these tips in mind:
Forgetting the Ampersand (&): When using
scanf()for primitive data types like integers or floats, you must pass the memory address using&. Forgetting this will crash your program.Buffer Overflow: Never use
gets()to capture strings. It does not check the length of the input, which can overwrite memory. Always usefgets().Newline Characters:
fgets()captures the “Enter” key press (newline character) as part of the string. You often need to manually strip this character out of your final string.
How to Remove the Newline from fgets()
Because fgets() keeps the Enter key as \n at the end of the string, printing the name in the middle of a sentence breaks the line in the wrong place. The strcspn() function from <string.h> finds the position of the newline, and you can replace it with the end-of-string character '\0':
#include <stdio.h>
#include <string.h>
int main() {
char name[50];
printf("Enter your full name: ");
if (fgets(name, sizeof(name), stdin) != NULL) {
name[strcspn(name, "\n")] = '\0'; // replace the newline with the end of the string
printf("Hello, %s! Nice to meet you.\n", name);
}
return 0;
}
If the user presses Enter without typing anything, strcspn() returns 0 and the string simply becomes empty, so this line is safe to use every time.
How to Validate User Input in C
A professional program never blindly trusts user input in C. If a user types a letter when your program expects a number, it can cause an infinite loop or a crash.
Always validate your input. You can check the return value of scanf() to ensure it successfully read the expected number of items. If it returns 0, the input was invalid, and you should clear the input buffer before asking the user to try again.
Here is what that looks like in practice. The program keeps asking until the user types a valid number:
#include <stdio.h>
int main() {
int age;
int result;
int c;
printf("Please enter your age: ");
while ((result = scanf("%d", &age)) != 1) {
if (result == EOF) {
return 1; // no more input, so stop
}
while ((c = getchar()) != '\n' && c != EOF) {
// throw away the rest of the bad line
}
printf("That's not a number. Please enter your age: ");
}
printf("You are %d years old.\n", age);
return 0;
}
scanf() returns the number of values it read. When the user types letters, it returns 0 and leaves those letters waiting in the input buffer. The inner loop reads and discards them up to the end of the line, so the next scanf() starts fresh. If the input ends completely (EOF), the program stops instead of looping forever.
For more detail on reading input safely, see the fgets documentation.
New to C? Start with my Introduction to C programming guide to learn about variables and data types.
Let’s put this into practice with a small program that asks for two numbers.
Practice Example: Area of a Rectangle
// calculating the area of a rectangle using user input
#include <stdio.h>
int main() {
int length;
int width;
printf("Enter the length of the rectangle: ");
scanf("%d", &length);
printf("Enter the width of the rectangle: ");
scanf("%d", &width);
int area = length * width;
printf("\n");
printf("The area of the rectangle is %d cm^2\n", area);
return 0;
}
Here is how the program works, line by line. The comment at the top, // calculating the area of a rectangle using user input, tells anyone reading the code what the program does.
#include <stdio.h> loads the standard input/output library, which gives you printf() and scanf().
int main() { ... } is where the program starts running.
int length; and int width; declare two integer variables to hold the whole numbers the user types.
printf shows a prompt asking for the length.
scanf("%d", &length); reads the number the user types and stores it at the memory address of length. That’s why the & is needed.
The same two steps then ask for the width and store it.
int area = length * width; multiplies the two numbers and saves the result in a new variable called area.
printf("\n"); prints an empty line so the result is easier to read.
The last printf prints the area, replacing %d with the value of area and adding “cm^2” as the unit. Here is the output when you enter 5 for the length and 4 for the width:
Try this next: the program happily accepts letters and negative numbers. Add the validation loop from earlier to reject bad input, or switch the variables to double (read them with %lf and print the area with %.2f) so it can handle measurements like 2.5.
Practice Example: Area of a Circle
// calculating the area of a circle
// formula is A = π * r^2
#define _USE_MATH_DEFINES // needed for M_PI with MSVC (cl.exe)
#include <math.h>
#include <stdio.h>
int main() {
int radius;
printf("Enter the radius of the circle: ");
scanf("%d", &radius);
double area = M_PI * radius * radius;
printf("The area of the circle is %.2f cm^2\n", area);
return 0;
}
This program asks for a radius and prints the area of the circle. It uses the same scanf() pattern as the rectangle example, plus one new tool: the math library.
How the Code Works
#define _USE_MATH_DEFINESturns on math constants likeM_PIin Microsoft’s compiler. GCC and Clang usually provide them anyway, so the line is harmless there.#include <math.h>gives youM_PI, which holds π (about 3.14159).int radius;creates a whole-number variable. Thenscanf("%d", &radius);stores the user’s number in it. The&passes the variable’s address, soscanfknows where to write.double area = M_PI * radius * radius;applies the formula A = π × r². The result is adoublebecause π has decimals.%.2fprints the area rounded to two decimal places.
For example, a radius of 5 prints “The area of the circle is 78.54 cm^2”.
Two Things to Watch
First, the radius is an int. If the user types 2.5, scanf reads only the 2 and stops at the dot. As a result, the program quietly prints the area for a radius of 2 (12.57) instead of 19.63.
Second, nothing checks the input. If the user types a letter, scanf reads nothing, so radius keeps a random leftover value. In one test, typing abc printed 82447.96. That’s exactly why validating user input in C matters.
To fix both, read the radius as a double with %lf, and check that scanf returns 1, just like in the validation section above:
double radius;
printf("Enter the radius of the circle: ");
if (scanf("%lf", &radius) != 1 || radius < 0) {
printf("Please enter a positive number.\n");
return 1;
}
Now 2.5 gives the correct area of 19.63, and letters or negative numbers get a clear message.
Practice: the circumference of a circle uses a different formula, C = 2 × π × r. Try adding it to the program so it prints both values.
Making Decisions with User Input: if else in C
Reading input is only half the job. Once your program has the user’s answer, it usually needs to decide what to do next. That’s where if and else come in.
An if statement runs a block of code only when its condition is true. The else block runs when the condition is false. For example, this program reads a number and tells you whether it’s even or odd:
#include <stdio.h>
int main(void) {
int number;
printf("Enter a whole number: ");
if (scanf("%d", &number) != 1) {
printf("That's not a number.\n");
return 1;
}
if (number % 2 == 0) {
printf("%d is even.\n", number);
} else {
printf("%d is odd.\n", number);
}
return 0;
}
Here, number % 2 gives the remainder after dividing by 2. If the remainder is 0, the number is even. Otherwise, the else block reports that it’s odd. Notice that the program checks what scanf() returns first, so typing a letter can’t break it.
Comparison Operators
Conditions usually compare two values. These are the operators you’ll use most:
==equal to, and!=not equal to>greater than, and<less than>=greater than or equal to, and<=less than or equal to&&true when both conditions are true||true when at least one condition is true
Checking Several Conditions with else if
Sometimes there are more than two possible answers. In that case, chain the conditions with else if. C checks them from top to bottom and runs the first block that matches. This grade checker shows how it works:
#include <stdio.h>
int main(void) {
int score;
printf("Enter your score (0-100): ");
if (scanf("%d", &score) != 1 || score < 0 || score > 100) {
printf("Please enter a number from 0 to 100.\n");
return 1;
}
if (score >= 90) {
printf("Grade: A+\n");
} else if (score >= 85) {
printf("Grade: A\n");
} else if (score >= 80) {
printf("Grade: A-\n");
} else if (score >= 77) {
printf("Grade: B+\n");
} else if (score >= 73) {
printf("Grade: B\n");
} else if (score >= 70) {
printf("Grade: B-\n");
} else if (score >= 67) {
printf("Grade: C+\n");
} else if (score >= 63) {
printf("Grade: C\n");
} else if (score >= 60) {
printf("Grade: C-\n");
} else if (score >= 57) {
printf("Grade: D+\n");
} else if (score >= 53) {
printf("Grade: D\n");
} else if (score >= 50) {
printf("Grade: D-\n");
} else {
printf("Grade: F\n");
}
return 0;
}
Because the checks run in order, a score of 82 fails the first two tests. However, it passes score >= 80, so the program prints A-. That’s also why the conditions go from the highest grade down: if score >= 50 came first, every passing score would print D-.
The first if uses || to reject anything outside 0 to 100, so impossible scores never reach the grading logic. The grade bands follow the common Ontario percentage scale (A+ is 90 and up), so change the numbers if your school uses a different one.
A Common Mistake: = Instead of ==
One equals sign assigns a value, while two equals signs compare values. So if (score = 100) doesn’t check the score at all. Instead, it sets the score to 100, and the condition is always true.
if (score = 100) { /* wrong: sets score to 100 */
if (score == 100) { /* right: compares score with 100 */
Luckily, GCC warns you about this when you compile with gcc -Wall. That’s one more reason to always turn warnings on.
Conclusion
Handling user input in C well is what turns a fixed script into a program people can actually use. Use scanf() for simple numbers, fgets() for text, and always check what the user typed before you trust it. Then use if and else to decide what to do with the answer. As a next exercise, add validation to the rectangle program above, and use an if statement to reject lengths that are zero or negative.
Keep learning: Introduction to C programming · Python For Beginners
Voting Age
#include <stdio.h>
int main (void) {
int age;
printf("Please 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;
}
1. Library Inclusion
-
#include <stdio.h>: This includes the Standard Input/Output library, which gives your program the ability to use input and output functions likeprintfandscanf.
2. The Main Function
-
int main (void): This is the entry point of every C program. Execution starts here. Theintmeans it returns an integer value, andvoidindicates that the function takes no arguments.
3. Variable Declaration & Input
int age;: Declares an integer variable namedageto store the user’s input.printf("Please enter your age: ");: Prints the prompt message to the console so the user knows what to type.scanf("%d", &age);: Reads an integer (%d) entered by the user from the keyboard and saves it into the memory location of theagevariable (&age).
4. Conditional Logic (Decision Making)
-
if (age >= 18): Checks if the stored age is greater than or equal to $18$.
If true, it runs printf("You are eligible to vote\n");.
-
else: If the condition is false (the age is less than $18$), it runs the alternative block:printf("You are not eligible to vote\n");.
5. Program Exit
-
return 0;: Tells the operating system that the program has finished executing successfully.
BMI Calculator
int main (void){
float weight;
float height;
printf("Please enter your weight in kg: ");
scanf("%f", &weight);
printf("Please enter your height in cm: ");
scanf("%f", &height);
height = height / 100;
float bmi = weight / (height * height);
printf("Your BMI is %.1f\n", bmi);
if (bmi < 16) {
printf("You are in Severe Thinness class\n");
} else if (bmi < 17) {
printf("You are in Moderate Thinness class\n");
} else if (bmi < 18.5) {
printf("You are in Mild Thinness class\n");
} else if (bmi < 25) {
printf("You are in Normal class\n");
} else if (bmi < 30) {
printf("You are in Overweight class\n");
} else if (bmi < 35) {
printf("You are in Obese class 1\n");
} else if (bmi < 40) {
printf("You are in Obese class 2\n");
} else {
printf("You are in Obese class 3\n");
}
return 0;
}
1. Function Setup & Variables
int main (void): The main entry point of the C program. It takes no arguments (void) and returns an integer (int).float weight;andfloat height;: Declares two variables using thefloatdata type to store decimal numbers for weight and height.
2. Gathering User Input
- Weight Input:
printf("Please enter your weight in kg: "); displays a prompt on the screen.
scanf("%f", &weight);reads the floating-point number (%f) entered by the user and saves it to theweightvariable using its memory address (&weight).Height Input:
printf("Please enter your height in cm: "); asks the user for their height.
-
scanf("%f", &height);captures that height in centimeters.
3. Unit Conversion & Calculation
height = height / 100;: Converts the height from centimeters into meters, because the standard BMI formula requires height to be measured in meters.float bmi = weight / (height * height);: Calculates the BMI using the formula $\text{weight} / \text{height}^2$.printf("Your BMI is %.1f\n", bmi);: Prints out the final calculated BMI, formatting it to display only 1 decimal place (%.1f).
4. Categorization (The if-else Ladder)
The program checks your calculated bmi value against standard clinical thresholds from top to bottom, executing the first block that matches:
bmi < 16: Prints Severe Thinness class.bmi < 17: Prints Moderate Thinness class.bmi < 18.5: Prints Mild Thinness class.bmi < 25: Prints Normal class.bmi < 30: Prints Overweight class.bmi < 35: Prints Obese class 1.bmi < 40: Prints Obese class 2.else: Catches everything else (40 or higher) and prints Obese class 3.
5. Program Completion
-
return 0;: Tells the operating system that the program has run and finished successfully.
Discount Calculator
int main(void) {
float price, discount, discounted_price;
printf("Enter the original price: ");
scanf("%f", &price);
printf("Enter the discount percentage: ");
scanf("%f", &discount);
discounted_price = price - (price * (discount / 100));
if (discounted_price < 0) {
printf("Error: Discounted price cannot be negative.\n");
} else {
printf("The discounted price is: %.2f\n", discounted_price);
}
printf("discounted price is: %.2f\n", discounted_price);
return 0;
}
1. Variable Declarations
-
float price, discount, discounted_price;: Declares three variables using thefloatdata type to handle decimal numbers for the original item price, the discount percentage, and the final calculated price.
2. Getting User Inputs
Original Price:
printf("Enter the original price: ");prompts the user, andscanf("%f", &price);reads the floating-point value into thepricevariable.Discount Percentage:
printf("Enter the discount percentage: ");prompts for the discount, andscanf("%f", &discount);stores it in thediscountvariable.
3. The Calculation
-
discounted_price = price - (price * (discount / 100));:
First, it converts the discount percentage into a decimal by dividing by $100$ (discount / 100).
Next, it multiplies that decimal by the original price to find the discount amount (
price * ...).Finally, it subtracts that amount from the original price to get the final discounted total.
4. Conditional Check (Validation)
-
if (discounted_price < 0): Checks if the resulting price is negative (which would happen if someone entered a discount greater than $100\%$).
If true, it prints an error message: "Error: Discounted price cannot be negative.\n".
- If false (the
elseblock), it prints the successfully calculated price rounded to two decimal places (%.2f).
5. Code Quirk / Redundant Line
-
printf("discounted price is: %.2f\n", discounted_price);: This line sits outside of theif-elsestatement. Because of this, it will run no matter what—meaning if the discount was invalid and triggered the error message, the program will print the error and then still print out the negative discounted price right underneath it.
Quiz Program
// Math Quiz program
#include <stdio.h>
#include <string.h>
int main (){
const char *questions[] = {
"What is 5 + 3?",
"What is 10 - 4?",
"What is 6 * 7?",
"What is 20 / 5?",
"What is 15 -4?",
"What is 8 + 2?",
"What is 12 * 3?",
"what is 100 / 25?",
"What is 9 + 2?",
"What is 20 - 16?",
"What is 5 * 7?",
"What is 18 / 3?"
};
const char *answers[] = {
"8",
"6",
"42",
"4",
"11",
"10",
"36"
"4",
"11",
"4",
"35",
"6"
};
char user_answer[10];
int score = 0;
int total = sizeof(questions) / sizeof(questions[0]);
for (int i = 0; i < total; i++) {
printf("%s ", questions[i]);
scanf("%9s", user_answer);
if (strcmp(user_answer, answers[i]) == 0) {
printf("Correct!\n");
score++;
} else {
printf("Wrong! The answer is %s\n", answers[i]);
}
}
printf("Your score is: %d out of %d (%d%%)\n", score, total, score * 100 / total);
return 0;
}
Written for: beginners reading your blog. I rewrote it in your own voice, in the first person, and turned the real “411” bug you hit into part of the story. Sentences are still short, with plenty of transition words and subheadings. I removed my notes to you from the draft, so it’s ready to paste.
Let’s Build a Math Quiz Game in C
Today I want to show you a little project I had a lot of fun with: a math quiz game in C. It asks you 12 questions, tells you if you got each one right, and gives you a final score with a percentage.
If you’ve already played with scanf and if statements, this is a great next step. It mixes arrays, a loop, and if/else into one small program. Plus, it’s actually fun to play!
Step 1: Bringing in the Tools
First, I add two libraries at the top of the file. stdio.h gives me printf and scanf, so I can show text and read what you type.
Then there’s string.h. I need it for one function, strcmp, which compares your answer with the correct one. You’ll see why it matters in a minute.
Step 2: Writing the Questions
Next, I create a list called questions. In C, a list like this is called an array. It lets me keep lots of values under one name instead of making 12 separate variables.
Each item is a piece of text, which is what const char * means. So questions[0] holds “What is 5 + 3?”. And yes, C starts counting at 0, not 1. That one trips everyone up at first, me included.
Step 3: Writing the Answers
After that, I make a second list called answers. The trick is to keep it in the same order as the questions. That way, answers[0] is “8”, which matches questions[0].
You might wonder why I wrote the answers as text instead of numbers. Honestly, it just makes comparing them simple with strcmp.
A bug that got me: every item in the list needs a comma after it, except the last one. I forgot one while writing this, and my quiz suddenly told me the answer to 20 / 5 was “411”! Here’s why. When two pieces of text sit side by side without a comma, C quietly glues them together. So "4" "11" became "411". Worse, every answer after it moved up one spot, and the quiz marked my right answers as wrong. So check those commas!
Step 4: Keeping Score
Now I set up three variables:
user_answerstores what you type, with room for 10 characters.scorestarts at 0 and goes up each time you get one right.totalholds how many questions there are.
That total line looks a bit scary, so let me explain it. sizeof(questions) gives the size of the whole list, while sizeof(questions[0]) gives the size of one item. Divide one by the other, and you get the number of questions. The best part? You can add new questions later, and the loop updates by itself.
Step 5: Asking Each Question
Here’s where the game really happens. I use a for loop that runs once for every question. The counter i starts at 0, goes up by 1 each round, and stops when it reaches total.
Inside the loop, printf shows the question. Then scanf("%9s", user_answer) reads your answer. That little 9 stops you from typing more than the space can hold, which keeps the program safe.
Step 6: Right or Wrong? Using If and Else
This is my favourite part, because it’s where the program makes a decision. strcmp compares two pieces of text, and when they match, it gives back 0.
So if strcmp returns 0, you got it right. In that case, the program prints “Correct!” and adds a point. By the way, score++ is just a shortcut for score = score + 1.
If not, the else part runs instead. It prints “Wrong!” and shows you the right answer. I like this, because you learn something even when you miss one.
Step 7: Showing Your Final Score
Finally, the program prints your score, the total, and a percentage.
Getting the percentage right took me a moment. In C, dividing two whole numbers throws away the decimal part. For example, 9 ÷ 12 gives 0, not 0.75! To fix that, I multiply the score by 100 first and divide afterwards. That way, 900 ÷ 12 gives 75, which is exactly what we want.
One more small thing: notice the %% in the message. In printf, a single % has a special job. So to print an actual percent sign, I write it twice.
Here’s What It Looks Like
When I got every question right, the end of the game looked like this
Loops in C
A loop repeats the same code many times, so you don’t have to write it again and again.
Without a loop, printing 1 to 5 takes five lines:
printf("1\n");
printf("2\n");
printf("3\n");
printf("4\n");
printf("5\n");
With a loop, it takes one:
for (int i = 1; i <= 5; i++) {
printf("%d\n", i);
}
Both print 1, 2, 3, 4, 5. With the loop, you can count to 1000 by changing a single number.
How the for loop works
for (int i = 1; i <= 5; i++)
The line has three parts:
int i = 1is the start: a counter calledibegins at 1.i <= 5is the condition: keep going whileiis 5 or less.i++is the step: add 1 toiafter each round.
The program runs the code inside { }, adds 1 to i, checks the condition, and repeats. When i becomes 6, the condition is false, so the loop stops.
The three kinds of loops in C
1. for loop: use it when you know how many times to repeat.
for (int i = 1; i <= 10; i++) {
printf("%d\n", i);
}
2. while loop: use it when you don’t know how many times, and you repeat until something happens.
int guess = 0;
while (guess != 7) {
printf("Guess my number: ");
scanf("%d", &guess);
}
printf("You got it!\n");
This keeps asking until the user types 7.
3. do-while loop: this one always runs at least once, then checks the condition.
int choice;
do {
printf("1) Play 2) Exit: ");
scanf("%d", &choice);
} while (choice != 2);
This is good for menus.
You’ve already used one!
Your math quiz has a loop:
for (int i = 0; i < total; i++) {
It runs once for each question. i is 0 for the first question, 1 for the second, and so on, until all 12 questions have been asked.
Watch out for infinite loops. If the condition never becomes false, the loop runs forever. For example, while (1 > 0) never ends. If that happens, press Ctrl + C in the terminal to stop it.
Counting 1 -10 program
// Count from 1 to 10
#include <stdio.h>
int main(void) {
int number = 0;
for (int i = 1; i <= 10; i++) {
number += 1;
printf("%d\n", number);
scanf("%*c"); // Wait for user to press Enter
}
return 0;
}
This program shows the numbers 1 to 10, one at a time. It waits for you to press Enter before it shows the next one. Here it is line by line:
#include <stdio.h>
This loads the library that gives you printf and scanf.
int main(void) {
The program starts running here.
int number = 0;
This makes a variable called number that starts at 0.
for (int i = 1; i <= 10; i++) {
This loop runs 10 times. i starts at 1, goes up by 1 each round, and the loop stops after 10.
number += 1;
This adds 1 to number. number += 1 is a shortcut for number = number + 1. So number becomes 1, then 2, then 3, and so on.
printf("%d\n", number);
This prints the current number on its own line.
scanf("%*c"); // Wait for user to press Enter
This pauses the program until you press a key and then Enter.
%creads one character.The
*means “read it, but throw it away”. You don’t need to store it anywhere, so this line has no&variable.
When you press Enter, scanf reads that Enter key and the program carries on.
return 0;
}
This ends the program successfully.
What you’ll see:
1
(press Enter)
2
(press Enter)
3
...
10
%*c only reads one character at a time. If you type a letter before pressing Enter (for example a), the program reads the a this round and the Enter key the next round, so two numbers appear at once. Just press Enter on its own and it works as expected.
Dice Roller
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void){
int dice1 , dice2;
srand(time(NULL));
printf("Press Enter to roll the dice...");
scanf("%*c");
dice1 = (rand() % 6) + 1;
dice2 = (rand() % 6) + 1;
printf("For dice 1 you rolled a %d and a %d\n", dice1, dice2);
for (int i =0; i < 6; i++){
printf("Rolling the dice...\n");
scanf("%*c");
dice1 = (rand() % 6) + 1;
dice2 = (rand() % 6) + 1;
printf("For dice 2 you rolled a %d and a %d\n", dice1, dice2);
}
return 0;
}
This program simulates rolling two six-sided dice. It rolls once after the user presses Enter, then it rolls six more times in a loop. Each loop roll also waits for Enter.
Headers
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
stdio.hprovidesprintfandscanffor input and output.stdlib.hprovidesrandandsrandfor pseudo-random numbers.time.hprovidestime, which supplies the seed value.
Variable Declaration and Seeding
int dice1, dice2;
srand(time(NULL));
The code declares two integers to hold the dice values. Then srand(time(NULL)) seeds the random number generator with the current time in seconds. Without a seed, rand() would produce the same sequence on every run. You should call srand only once, and the code does that correctly.
First Roll
printf("Press Enter to roll the dice...");
scanf("%*c");
dice1 = (rand() % 6) + 1;
dice2 = (rand() % 6) + 1;
printf("For dice 1 you rolled a %d and a %d\n", dice1, dice2);
scanf("%*c")reads one character and discards it, because the*suppresses assignment. This call pauses the program until the user presses Enter.rand() % 6returns a value from 0 to 5. Adding 1 shifts the range to 1 through 6, which matches a real die.The
printfcall displays both values.
The Loop
for (int i = 0; i < 6; i++){
printf("Rolling the dice...\n");
scanf("%*c");
dice1 = (rand() % 6) + 1;
dice2 = (rand() % 6) + 1;
printf("For dice 2 you rolled a %d and a %d\n", dice1, dice2);
}
The loop runs six times, so the program makes seven rolls in total. Each iteration reuses the same two variables and overwrites the previous values.
Issues and Improvements
Misleading labels. The message says “For dice 1 you rolled a X and a Y”, but both numbers come from two different dice in one roll. The same problem appears with “dice 2” in the loop. A clearer message is
"Roll %d: %d and %d\n".Duplicated logic. The first roll and the loop body repeat the same code. You can remove the first roll and let the loop handle all rolls.
Input handling. If the user types extra characters before pressing Enter,
scanf("%c")consumes only one of them. The leftover characters then trigger later prompts early. Usinggetchar()in a loop that reads until'\n'is more robust.Modulo bias.
rand() % 6has a very slight bias, becauseRAND_MAX + 1is not divisible by 6. This bias does not matter for a simple game.
Improved Version
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define ROLLS 7
static void wait_for_enter(void) {
int c;
while ((c = getchar()) != '\n' && c != EOF) {
/* Discard everything up to the newline. */
}
}
int main(void) {
srand((unsigned int)time(NULL));
for (int i = 1; i <= ROLLS; i++) {
printf("Press Enter to roll the dice...");
wait_for_enter();
int die1 = (rand() % 6) + 1;
int die2 = (rand() % 6) + 1;
printf("Roll %d: you rolled a %d and a %d\n", i, die1, die2);
}
return 0;
}
Originally published on my blog. I post new C, Python and AI-agent guides there regularly.












Top comments (0)