How to limit an integer's input to 2-12 only? - c

I want to strictly limit a user's input on an integer in this program to 2-12 only. How do I do that?
#include <stdio.h>
int main(){
int i;
scanf("%d", &i);
int diceThrown, diceResult;
int sum = 0;
for(diceThrown = 1; diceThrown <= i; diceThrown++){
scanf("%d", &diceResult); //limit this input to 2-12 only, how?
sum += diceResult;
}
if(sum >= 40){
sum = sum % 40;
if(sum == 12){
printf ("28\n");
} else if(sum == 35){
printf ("7\n");
} else{
printf ("%d\n", sum);
}
} else if(sum < 40){
if(sum == 12){
printf ("28\n");
} else if(sum == 35){
printf ("7\n");
} else{
printf ("%d\n", sum);
}
}
return 0;
}
Also just to clarify, that I'm still a beginner in programming (like only 2 months into C.SCi course), so if you could explain it to me like I'm not a expert that would be great.

scanf has no functionality to do what you want. You can just use an if to validate input.
if(scanf("%d", &diceResult) != 1 || diceResult < 2 || diceResult > 12) {
//handle invalid input here
}
If the input is invalid it is up to you what you want to do. You could ignore the input and ask the user to enter a valid number, you can quit the whole program or just ignore the error, or something else entirely.
You can also check the input repeatedly with an while:
while(scanf("%d", &diceResult) != 1 || diceResult < 2 || diceResult > 12) {
//prompt user to enter valid input here
}
As mentioned by chux, part of handling invalid input would be to cosume the invalid input and check for EOF.
The scanf("%d", &diceResult) != 1 will assure, that scanf actually read exactly one number and no parsing errors occurred.

Consider this:
#include <stdio.h>
int main(){
int x;
do
{
printf("give a number between [2-12]\n");
scanf ("%d",&x);
}
while(x<2 || x>12);
return 0;
}
You can use a do-while loop so that you only take the values that are between the 2-12 range. That way you can force the user to give an integer as an input that is in the range that you ask for, in that case from [2,12]. Otherwise the program will turn back and request a valid input again.

Related

C Program - Do - while loops not working

My target output is after users entering a number >2 & <20 (result show) then program continue asking users enter another number. Or if users enters number <=2 or >=20, it will not show result but just re-asking users to enter number.
My Current Output: If I input number <=2 || >=20, it will re-ask. but if I enter number between 2 and 20. It will just stops which suppose to be keep asking for entering new numbers.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define MAX 20
int main(void)
{
unsigned int random_array[MAX][MAX];
unsigned int r, c, x, y;
do {
printf("Number Matrix in array ? ");
scanf("%d", &c);
system("cls");
r = c;
if (c>2 && c<20) {
r = c;
for (x = 0; x <= r - 1; ++x)
{
for (y = 0; y <= c - 1; ++y)
{
random_array[x][y] = -1;
}
}
for (x = 0; x <= r - 1; ++x)
{
for (y = 0; y <= c - 1; ++y)
{
if (x == y)
random_array[x][y] = 0;
else
if (x<y)
random_array[x][y] = 1;
printf("%4d", random_array[x][y]);
}
puts("");
}
system("pause");
}
} while (c<=2 || c >=20);
return 0;
}
Since you want to prompt the user for input regardless of what they last input, you probably need an infinite loop. For this, replace your line with the while condition to this:
} while (1);
This basically tells your program to loop infinitely.
Your codes
do
{
// show something
} while (c<=2 || c >=20);
means that it will stop after showing something if (c > 2 && c < 20), and that is exactly why your program quits after the condition is met.
To achieve your goal, consider using an infinite loop, and do different things using if-else inside the loop.
printf("Number Matrix in array ? ");
scanf("%d", &c);
system("cls");
if (c<=2 || c >=20)
{
continue;
}
else
{
// show something
}
The while condition should be while(c>2&c<20). But if you enter a number <=2 or >=20 the program will end and will not ask you for an input anymore. So the solution would be to use an infinite while loop and use break to end the loop when you want by using a condition.
A do-while loop will run the block of code once, then will repeat until the while conditional evaluates to false.
do{
//Stuff
}while (c > 20 || c < 2);
That would do the //Stuff part once, then it would do it again until c is either greater than 20 or less than 2.
What you want to do is surround the entire thing in an infinite loop, (either for(;;) or while(1)) so that it continues regardless.
But you also want to validate the input, so that's when you could use a do-while loop. When you're getting the scanf, you could do something like:
do{
printf("Enter c: ");
scanf("%d", &c);
}while (c > 20 or whatever);
Then you could make him keep putting in c until it's the desired input!
Hope this helps.
EDIT: Here's an example of putting the do-while inside the while:
while(1){
do{
printf("Enter a positive number: ");
scanf("%d", &aNum);
}while(aNum < 0);
printf("Your positive number is %d.\n", aNum);
}
That would ask a user for input, and if he puts in a negative number it would ask him again. If it's a positive number it would print, then go back to the start and ask him for an input again.

Correct use of scanf() in C, wrong output

I am trying to design a program that calculates the average of any desired number of floats, until EOF. The program should also check if the input was correct and return "Wrong Input" when e.g. entering a string. The code I wrote works, but it gives wrong ouputs for the average. Can anyone tell me why?
#include <stdio.h>
int main(void) {
int times = 0;
float sum = 0;
float scan;
float avrg;
int scanvalue = 1;
while (scanvalue == 1) {
scanvalue = scanf("%f", &scan);
sum = sum + scan;
times++;
}
if (scanvalue == EOF) {
avrg = sum / times;
printf("The average is %f\n", avrg);
} else {
printf("Wrong input");
}
return 0;
}
Best regards.
You don't check scanvalue after scanf() and still use the value at scan which is messing up the average. Note that when scanf() returns EOF it will not modify scan, and thus it will still have its last value so you are adding the last value twice.
But if you enter invalid input at the beginning then the behavior is undefined, change it to
while ((result = scanf("%f", &value)) == 1) {
}
Also, I deliberately changed the names of your variables to illustrate a better way of naming them.
You need to check scanvalue after the scanf, otherwise times will be incremented even if you enter EOF and sum will get a wrong input, thus resulting the average being wrong/messed.
So you should change
while (scanvalue == 1) {
scanvalue = scanf("%f", &scan);
sum = sum + scan;
times++;
}
To
while (scanvalue == 1) {
scanvalue = scanf("%f", &scan);
if (scanvalue != 1)
break;
sum = sum + scan;
times++;
}

how to stop scanning when input is null (scan an unknown number of ints)

I'm currently working on a program that scans each int and finds out if it is perfect or not. The problem is, I do not know how many ints there are in the input, so I want to find out how to stop scanning when the input ends.
Code:
#include <stdio.h>
int main() {
int input[500], count;
for (count = 0; count < 500; count++) {
scanf("%d", &input[count]);
if (input[count] == 0)
break;
}
for (count = 0; count < 500; count++) {
if (findFactors(input[count]) % input[count] == 0)
printf("%d perfect\n", input[count]);
else if (findFactors(input[count]) % input[count] <= 2 ||
findFactors(input[count]) % input[count] >= input[count] - 2)
printf("%d almost perfect\n", input[count]);
else
printf("%d not perfect\n", input[count]);
}
}
In this case, I need to enter 500 numbers for the code to run. I need it to run when the input is null. I know there is '/0' or something but I don't know how to use it in this code.
When you use a function read the doc
In return value
These functions return the number of input items successfully matched
and assigned, which can be fewer than provided for, or even zero in
the event of an early matching failure.
So you need to check the return value of scanf:
if (scanf("%d", &input[count]) != 1)
break;

Number guessing what the user has in mind C

I'm trying to create a program where the program guesses what kind of number the user has in mind. First it will ask the user for a minimum and maximum number, for example 1 and 10(the number I have in mind should be between 1 and 10 then).
Lets say I have the number 4 in mind and the program will output a number. I can type in L for low, H for high or G for good.
If I type in L, the program should generate a number lower than the guessed number, for H it should guess an higher number. If I input G, the program should stop and print out how many times it guessed.
I have added my code below, what am I missing?
#include <stdio.h>
#include <stdlib.h>
int main() {
int minNumber;
int maxNumber;
int counter;
printf("Give min and max: ");
scanf("%d %d", &minNumber, &maxNumber);
//printf("%d %d", minNumber, maxNumber);
int num_between_x_and_y = (rand() % (maxNumber - minNumber)) + minNumber;
char input[100];
do {
printf("is it %d? ", num_between_x_and_y);
scanf("%s", input);
if (input == 'L') {
counter++;
}
if (input == 'H') {
counter++;
}
} while (input != 'G');
printf("I guessed it in %d times!", counter);
return 0;
}
I do not see any "counter" variable initialization
int counter = 1;
I do not see the new random number regeneration in the cycle, it should be something like:
do {
printf("is it %d? ", num_between_x_and_y);
scanf("%s", input);
if (input[0] == 'L') {
counter++;
maxNumber = num_between_x_and_y;
}
if (input[0] == 'H') {
counter++;
minNumber = num_between_x_and_y;
}
num_between_x_and_y = (rand() % (maxNumber - minNumber)) + minNumber;
} while (input[0] != 'G');
You can't use == to compare strings (which are multiple bytes).
Either do if (input[0] == 'L') to just compare the first letter the user entered to a literal value, or if (strcmp(input,"L") == 0) to compare everything the user entered to the 1 character string literal (to use strcmp you will need to add #include <string.h>
Also your code is missing other things, like counter should be set to presumably set to zero before you use it. I assume you haven't finished your code yet because you can't get the user input part to work.

Error check if user enters a letter or number

I'm error checking for letters. If a letter is entered then its suppose to print out error and exit. If its a number then it's suppose to run the statement (which I didn't put in the code since its irrelevant at the moment) under the if. When I enter a number it should run the if statement but when I enter a letter or a number it goes to the else statement.
#include <stdio.h>
#include <ctype.h>
int main()
{
int x;
printf("Enter up to 10 positive integer ending with EOF:\n");
while((scanf("%d",&x)) != EOF && x < 100){
if( isdigit(x) ){
//statement
}
else{
printf("error, wrong input\n");
return 0;
}
}
if(x >= 100)
printf("error, wrong input\n");
return 0;
}
You want isdigit to check a char , please change scanf to :
while((scanf("%c",&x)) != EOF && x < 100){ // yes x is an int, but here you want a char

Resources