I am not the best at C yet, but I was creating a code that will allow the user to pick a number from 1 to 10. If the number isn't in range, it will prompt an error . I was using a do-while statements, and somehow I am receiving an error when the number is at range. If successful, the user will receive see number printed at the screen in chronological order example: 7 is in range so it will print 1,2,3,4,5,6,7. The code is shown below:
#include <stdio.h>
int main()
{
int number;
do
{
printf("Enter a number: ");
scanf("%d", &number);
printf("Error: number not in range (1-10). Try again: \n");
}
while(number == 0.0||number<1||number>10);
{printf("you win\n");}
return 0;
}
I would appreciate a tip that I could make it.
You need an if statement inside the loop as well for displaying the message. After picking a number, the printf still gets to go through and that's why you're seeing that message.
For the second part of your question, displaying numbers until the selected number, a simple for loop will suffice. Your condition to stop will depend on the user input.
Use this as you are printing the Error message before checking the condition in while loop
#include <stdio.h>
int main()
{
int number;
do
{
printf("Enter a number: ");
scanf("%d", &number);
if(number<1 ||number >10))
printf("Error: number not in range (1-10). Try again: \n");
}
while(number == 0.0||number<1||number>10);
printf("you win\n");
return 0;
}
Related
I'm new to learning C, and practicing some basic code.
I keep getting either a 0 or a very large random number for the bill multiplication at the end. I think I've narrowed it down to an issue with my "quant" value but I can't figure it out. Here's the first part of the programme (that only calculates for the pizza options so far):
#include <stdio.h>
int main()
{
int num, cho, quant, bill;
printf("Select a number from the menu:\n1. Pizza\n2. Burger\n3. Sandwiches\n4.
Beverages \n");
scanf("%d",&num);
if(num==1)
{
printf("Select a number for the food you want to order, and the quantity. \n");
printf("1. Pepperoni\t\tRs 1000 \n2. Fajita\t\tRs 1000\n3. Hot n spicy\t\tRs 1100\n4.
Chicken Tikka\tRs 1200\n");
scanf("%d,%d",&cho,&quant);
{
if(cho==1)
cho=1000;
else if(cho==2)
cho=1000;
else if(cho==3)
cho=1100;
else if(cho==4)
cho=1200;
}
bill=cho*quant;
printf("Please take your food item(s). Total bill = Rs %d \nThank you.",bill);
}
getchar();
getchar();
getchar(); getchar(); getchar();
return 0;
}
The way you have your scanf for cho and quant right now expects the user to enter two numbers separated by nothing but a comma, i.e. 2,10. If you do that format of input, your code works fine. However, if this format is broken the scanf does not properly read in a number to one or both of your variables, and they are left unitialized with potentially garbage information in them (hence the really large random numbers you're seeing).
You should probably change that line to
scanf("%d%d",&cho,&quant)
This question already has answers here:
Why is scanf() causing infinite loop in this code?
(16 answers)
Closed 4 years ago.
I'm trying to write a C program that computes X^Y (X to the Y power) without using the 'pow' function. The program works fine when I enter numbers, but I'm having an issue with the code not stopping when the user enters a character that isn't a number. It runs through the program once more after giving the message "The character you have entered is not a number.Please try again.The character you have entered is not a number.Please try again. The value is 1." Can someone help? I'm going insane trying to figure this out.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int x, y, i,n=1,val;
printf("Please enter a number: \n");
scanf("%d", &x);
if (x!=1)
printf("The character you have entered is not a number.Please try again.");
else
printf("What power is the number raised to?\n");
scanf("%d", &y);
if (y!=1)
printf("The character you have entered is not a number.Please try again.");
else
for(i=1;i<=y;i++)
{
val=x;
n=n*val;
}
printf("The value is %d.\n", n);
return 0;
}
When your program detects invalid input, it prints a message, but otherwise just continues on ahead as if a valid input had been read. Instead, it needs to do one of these things:
abort when invalid input is detected, or
consume and ignore the invalid input, AND
loop back to provide a chance to enter new input, or
use a default value.
Its message suggests that the program will provide for entering new input, but in fact it does not follow through. Moreover, if it is the input for the first prompt that is invalid, then that input is still waiting to be read when the program prints the second prompt, where it is still invalid, and the program blithely continues on a second time, ultimately printing the initial value of n, 1, without having calculated anything.
You need to check how many items scanf successfully read:
int numItemsRead = 0;
printf("What power is the number raised to?\n");
numItemsRead = scanf("%d", &y);
if (numItemsRead!=1)
printf("The character you have entered is not a number.Please try again.");
} else {
'''
}
int main()
{
int x, y, i,n=1,val;
printf("Please enter a number: \n");
scanf("%d", &x);
if (x!=1)
printf("The character you have entered is not a number.Please try again.");
return 0;
else
printf("What power is the number raised to?\n");
scanf("%d", &y);
Maybe if u do like that even if u entered a invalid character program will be end.
I wrote the following code in C to make a program which calculate the factorial of any number.
I want to add to my program some validation/error handling, such as preventing random characters, floats or negative values from being entered, so I used the isdigit function.
Unfortunately there is a hidden problem which I don't know how to solve. When I enter any input it considers it to be false (i.e. not a digit) even if it's a positive digit.
#include <stdio.h>
#include <ctype.h>
int main()
{
char choice;
unsigned long long int factorial=1;
int counter,number;
for(;;)
{
printf("Please , enter a positive integer number only : ");
scanf("%d",&number);
fflush(stdin);
if(isdigit(number))
{
for(counter=number;counter>1;counter--)
factorial*=counter;
printf("The factorial of number %d is %llu",number,factorial);
}
else
{
printf("\a\aError\n");
continue;
}
printf("\n1-Press c or C if you want to calculate the factorial of a new number\n2-Press any key if you want to exit the program\n ");
scanf("%c",&choice);
if(choice=='c'||choice=='C')
{
factorial=1;
system("cls");
continue;
}
else
return 0;
}
}
You are using isdigit wrong. Read its documentation to find out what it actually does.
You probably meant:
if ( number >= 0 && number <= 9 )
However you also need to check whether scanf succeeded or not. If they type in some words, then scanf("%d" fails and does not update number, so trying to access number in that case accesses an uninitialized variable. To deal with that you could either check the return value of scanf, or do:
int number = -1;
scanf("%d",&number);
because the value will be left unchanged if the input failed.
NB. Don't use fflush(stdin)
isdigit checks a single character if that's a decimal digit character.
But, your input could be say 25, multiple characters. So, I changed a portion:L
char input[30];
for(;;)
{
printf("Please , enter a positive integer number only : ");
scanf("%s",input);
if(isdigit(input[0]))
{
number = atoi(input);
for(counter=number;counter>1;counter--)
Keeping rest of your program snippet same.
Here, isdigit is used to check if the first character in input is a digit and therefore a valid candidate to be converted by atoi into an integer value number.
So I was coding this program and after I was done, I tried to run it but for some reason nothing shows up on the console. I went through the code multiple times and tried multiple ways of performing the same function, which is basically to keep on getting inputs from the user until he/she enters 0, then display the largest and second largest number, and if the user enters 0 and there are no numbers available then continue checking. I think may be there is an infinite loop or some other problem with it. Here is the code:
#include <stdio.h>
#include <math.h>
#include <stdbool.h>
void main()
{
int input,z;
int large,small,counter=0;
bool a=false;
while (1){
if(scanf("%d\n",&input)>0)
{
small=input;
counter++;
if(small>large)
{
z=small;
small=large;
large=z;
}
}
else if(scanf("%d\n",&input)<0)
{
printf("Please enter a positive value\n");
}
else if(scanf("%d\n",&input)==0)
{
if(small>0 && large>0)
{
printf("There are in total %d positive integers entered",counter);
printf("The largest number is %d, while the second largest is %d", large,small);
a=true;
break;
}
else
{
printf("You have to enter atleast two positive integers");
}
}
}
}
Any sort of help would be appreciated, thank you.
The scanf function doesn't return the input, it returns how many numbers it read.
Since your code reads numbers one at a time, scanf will always return 1, causing an infinite loop.
To fix this, hoist the scanf call outside the branching code:
while (1) {
scanf("%d", &input);
if (input > 0) ...
else if (input < 0) ...
else ...
}
There are more bugs in your code (Rohan pointed out one of them) but this should solve the black screen.
Each time you check the value entered, you're doing another scanf() or trying to read a new value instead of checking the value of the number that was entered. And the value you're checking is the return value of scanf(), but the number that's entered is actually stored in your "input" variable. So yes, there are a few things going on here, but you're essentially in an infinite loop because the entered values aren't getting read or evaluated properly.
The C function scanf() doesn't take a newline. Instead use:
scanf("%d", &input);
Also, initialize your "large" variable to 0 when you define it (it's value is not 0 and will give you unpredictable results):
int large = 0, small, counter = 0;
What you want to do is ONLY one scanf() at the top of your while loop to read in a number. After that, your if's should be testing the value of "input":
while (1)
{
scanf("%d", &input);
if (input > 0) /* positive number entered */
{
/* do something */
} else if (input < 0) /* negative number entered */
{
/* print error */
} else /* no need to test value since it must be 0 at this point */
/* do stuff */
}
}
Happy C coding! ;-)
If you walk carefully through the logic of your program, you'll see it doesn't make sense. For example, if a number is entered, you never print anything.
I'm trying to write a simple program where it ask user to enter a bunch of positive integers, and calculate the average of all the number entered. Program will terminate when user enter a non positive number like 0 or -1.
Here is my code. For some reason I get an error right when I try to enter the first input, can someone help?
#include <stdio.h>
int main()
{
int input=0, sum=0,average=0,i=0;
printf("Please enter positive numbers, enter 0 or -1 to end:\n");
scanf("%d",input);
while (input>0)
{
sum+=input;
i++;
scanf("%d",input);
}
average=sum/i;
printf("The average is %d",average);
}
You need to pass the address of the variable to scanf.Try this:
scanf("%d", &input);
^
Also see the C FAQ: Why doesn't the call scanf("%d", i) work?