How to create a loop without knowing when the loop will stop? - c

I am trying to create a program which takes a number and we match that number with a variable which has a specific number stored. We need to keep doing that until the user enters the correct number that matches the number we have stored in our variable:
#include <stdio.h>
int main(void) {
int i;
int j;
int num1;
int num2 = 2;
printf("Enter number");
scanf("%d", &num1);
while (num1 == 0) {
printf("Enter number");
scanf("%d", &num1);
}
while (num1 != num2) {
for(j=1;j
printf("This is not the correct number! \n");
printf("Enter number again: ");
scanf("%d", &num1);
}
if (num1 == num2) {
printf("The numbers have matched! \n");
}
}
I am confused with how do we create a loop where we don't know how many times the user will enter an incorrect number. What I want with the loop is to display
is how many times the user enters an incorrect number. Let say if they enter 3 times.
This is not the correct number 1!
This is not the correct number 2!
This is not the correct number 3!
But we don't know how many times the user will enter an incorrect number, so what condition do I put in a loop, so it counts.

You want to create a separate counter variable that keeps track of how many times you've gone through the loop. Set it to 0 before the loop, then increment on each iteration.
int count = 0;
...
while (num1 != num2) {
count++;
printf("This is not the correct number %d! \n", count);
printf("Enter number again: ");
scanf("%d", &num1);
}
Also, I'm presuming this is a typo:
for(j=1;j

Related

Using C to Find Min and Max value using Function

I need to write a program where users can input their numbers as much as many as they defined, then the program will try to find which one is the lowest value and the highest value. The problems I face are:
When the program executed, the second line will wait on user's input (number) before the printf
The error "system" seems unreliable, sometimes works, sometimes doesn't work
The program only checks the last number entry, therefore it only shows the last number in min and max
You may give hints or corrections along the answers. Thank you very much.
#include <stdio.h>
float max(float num1){
float a=0, b;
if(num1 > a){
a=num1;
}
return a;
}
float min(float num2){
float x=100, y;
if(num2 < x ){
x=num2;
}
return num2;
}
int main(){
int times, interval;
float mini, maxi, data_Input;
printf("How many number would you like to type in ? : ");
scanf("%d\n",&times);
printf("Type in the number: ");
scanf("%f", &data_Input);
for(interval=2; interval<=times; interval++){
printf("\nType in the number: ");
scanf("%f",&data_Input);
while(data_Input<0){
printf("Invalid Input! Please re-enter the number:");
scanf("%f",&data_Input);
}
while(data_Input>100){
printf("Invalid Input! Please re-enter the number:");
scanf("%f",&data_Input);
}
}
maxi= max(data_Input);
mini= min(data_Input);
printf("The Lowest Number is %.2f\n", mini);
printf("The Highest Number is %.2f\n", maxi);
return 0;
}
Output:
How many number would you like to type in? : 5
70
Type in the number :
Type in the number : 90.7
Type in the number : 99
Type in the number : 30
Type in the number : 50
The Lowest Number is 50.00
The Highest Number is 50.00
Okay, the thing is that you are not updating the data_input after every successive number is inputted. What you are doing is, comparing the last number to 0 or 100, which is logically incorrect.
How about you take the first number as input, then after every successive input, compare it with the min and max value. Here is the sample code.
#include <stdio.h>
float max(float num1, float num2){
if(num1 > num2){
return num1;
}
return num2;
}
float min(float num1, float num2){
if(num1 < num2){
return num1;
}
return num2;
}
int main(){
int times, interval;
float mini, maxi, data_Input;
printf("How many number would you like to type in ? : ");
scanf("%d\n",&times);
printf("Type in the number: ");
scanf("%f", &data_Input);
// the first number will be minimum and maximum
mini = data_Input;
maxi = data_Input;
for(interval=2; interval<=times; interval++){
printf("\nType in the number: ");
scanf("%f",&data_Input);
// make it a composite if condition
while(data_Input<0 || data_Input>100){
printf("Invalid Input! Please re-enter the number:");
scanf("%f",&data_Input);
}
maxi= max(maxi, data_Input);
mini= min(mini, data_Input);
}
printf("The Lowest Number is %.2f\n", mini);
printf("The Highest Number is %.2f\n", maxi);
return 0;
}
The program checks the last number because you are calling the min and max function out of the for bracelets so instead you can call them inside the for bracelets like:
for(interval=2; interval<=times; interval++){
printf("\nType in the number: ");
scanf("%f",&data_Input);
while(data_Input<0){
printf("Invalid Input! Please re-enter the number:");
scanf("%f",&data_Input);
}
while(data_Input>100){
printf("Invalid Input! Please re-enter the number:");
scanf("%f",&data_Input);
}
maxi= max(data_Input);
mini= min(data_Input);
}
and instead of rewriting the same code you can just ask for the numbers inside the for loop and to initialize your interval to 1 so your main will look like:
int main(){
int times, interval;
float mini, maxi, data_Input;
printf("How many number would you like to type in ? : ");
scanf("%d\n",&times);
for(interval=1; interval<=times; interval++){
printf("\nType in the number: ");
scanf("%f",&data_Input);
while(data_Input<0){
printf("Invalid Input! Please re-enter the number:");
scanf("%f",&data_Input);
}
while(data_Input>100){
printf("Invalid Input! Please re-enter the number:");
scanf("%f",&data_Input);
}
maxi= max(data_Input);
mini= min(data_Input);
}
printf("The Lowest Number is %.2f\n", mini);
printf("The Highest Number is %.2f\n", maxi);
return 0;
}
Solving the printf issue is easy. As stdout is line buffered (at least by default - it can be changed) it is flushed whenever a newline is inserted in the buffer. So, just add a newline after each message print, for example
printf("How many number would you like to type in ? : \n");
and you'll be fine.
Talking about the wrong calculation of min and max, your attempt has basically two big issues:
You are not acquiring times inputs, but only one. In fact, every time you call scanf you overwrite the same variable data_Input without performing any comparison with the previous inputs
You call min() and max() function only once, after the last input. Furthermore you try to compare the argument with a local variable that has local storage and a lifetime limited to the function itself so that at the next call it will be initialized again
In order to have a variable inside a function that it is initialized only the first time you can use static keyword. But it is not I suggest you to solve the issue.
In my opinion you don't need comparison functions: you can just update maxi and mini each time you get a new input (solving both the aforementioned issues at once):
int main(){
int times, interval;
float mini, maxi, data_Input;
printf("How many number would you like to type in ? : \n");
scanf("%d",&times);
printf("Type in the number: ");
scanf("%f", &data_Input);
maxi = data_Input;
mini = data_Input;
for(interval=2; interval<=times; interval++){
printf("\nType in the number: \n");
scanf("%f",&data_Input);
while(data_Input<0){
printf("Invalid Input! Please re-enter the number:\n");
scanf("%f",&data_Input);
}
while(data_Input>100){
printf("Invalid Input! Please re-enter the number:\n");
scanf("%f",&data_Input);
}
/* Check input and, in case, update max and min */
if(data_Input > maxi)
maxi = data_Input;
if(data_Input < mini)
mini = data_Input;
}
printf("The Lowest Number is %.2f\n", mini);
printf("The Highest Number is %.2f\n", maxi);
return 0;
}
The comparison is performed inside the loop, so you don't need to store the inputs into an array.
You have plenty issues in your code.
Functions min & max do not make any sense
You do not check result of the scanf and you do not know if it was successfull
#define MAX(a, b) ((a) > (b) ? (a) : (b))
#define MIN(a, b) ((a) < (b) ? (a) : (b))
int main()
{
int times, interval;
float mini, maxi, data_Input;
do
{
printf("\nHow many number would you like to type in ? : ");
}while(scanf(" %d\n",&times) != 1);
for(interval = 0; interval < times; interval++)
{
do
{
printf("\nType in the number: ");
}while(scanf(" %f",&data_Input) != 1 && (data_Input < 0 || data_Input > 100));
printf("%f\n", data_Input);
maxi = interval == 0 ? data_Input : MAX(maxi, data_Input);
mini = interval == 0 ? data_Input : MIN(mini, data_Input);
}
printf("The Lowest Number is %.2f\n", mini);
printf("The Highest Number is %.2f\n", maxi);
return 0;
}
When the program executed, the second line will wait on user's input (number) before the printf
Drop "\n" from "%d\n". It blocks until non-white space detected after the number and is not needed.
printf("How many number would you like to type in ? : ");
// scanf("%d\n",&times);
scanf("%d",&times);
printf("Type in the number: ");
If output still not seen when expected, flush it. Typically printing a '\n' will flush stdout, but not certainly.
printf("How many number would you like to type in ? : ");
fflush(stdout); // add
The error "system" seems unreliable, sometimes works, sometimes doesn't work
At least this issue: sequential check vs. checking both conditions together input validity.
Rather than
while(data_Input<0){
...
}
while(data_Input>100){
...
}
Test together.
while(data_Input<0 || data_Input>100){
...
}
The program only checks the last number entry, therefore it only shows the last number in min and max
True as code only compares values once with one call to max(). That function only compares the number to 0 rather than prior values. Likewise for min().
Consider an algorithm change
// Pseudo code for max
prompt How many number would you like to type in ? : "
get times
max_value = -INF // set to minimum possible float
for each value 1 to times
prompt "Type in the number: "
get data_Input
if data_Input > max_value
max_value = data_Input
print max_value

Why does my count becomes 0 when my random number is greater than the number I write?

I have written C code for a game where a random number is generated and the user has to guess the correct number. So, whenever the I write a number and it is greater than the random number, my code is executing as it should. However when I write a number which is less than the random number,the count variable becomes zero, instead of decreasing the count value by 1. I cannot figure out what am I doing wrong?
I have attached the image of my output where the problem can be seen.
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
main()
{
time_t t;
int a,count=5;
srand((unsigned)time(&t));
int randomnumber=rand()%21;
printf("This is a guessing game, Only 5 tries are left\n");
printf("enter the number: ");
scanf("%d",&a);
printf(" \n");
if (a>=20){
printf("ERROR!! Enter number only between 0-20\n");
}
printf("You only have %d tries left\n",count);
printf("enter number only between 0-20: ");
scanf("%d",&a);
printf(" \n");
if (a==randomnumber){
printf("You guessed it correctly, YOU WIN!!\n");
}
else{
for(count=4;count>=1;count--)
{
if (a>randomnumber){
printf("My number is smaller than that\n");
printf("You only have %d tries left\n",(count));
printf("enter number again: ");
scanf("%d",&a);
printf(" \n");
}
}
if (a<randomnumber){
printf("My number is greater than that\n");
printf("You only have %d tries left\n",(count));
printf("enter number again: ");
scanf("%d",&a);
printf(" \n");
}
if (a==randomnumber){
printf("You guessed it correctly, YOU WIN!!\n");
}
}
if (a!=randomnumber)
{
printf("You LOOSE!!, the Number was %d",randomnumber);
}
return 0;
}
Your tests for a < randomnumber and a == randomnumber are not inside the for loop. So you only check them after you've counted all the way down to 0.
You need to put all the tests inside the loop. You should also use else if so that you don't check the new number that they've entered on the same iteration (since you haven't decremented count yet).
And you need to break out of the loop when they guess the number.
The simplest way to organize this is to take all the code that prompts for the next number out of the if blocks, since it's the same for less than and greater than. The if blocks just print which way the error was, and break out when they win.
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
main()
{
time_t t;
int a,count=5;
srand((unsigned)time(&t));
int randomnumber=rand()%21;
printf("This is a guessing game, Only 5 tries are left\n");
printf("enter the number: ");
scanf("%d",&a);
printf(" \n");
if (a>=20){
printf("ERROR!! Enter number only between 0-20\n");
}
printf("You only have %d tries left\n",count);
printf("enter number only between 0-20: ");
scanf("%d",&a);
printf(" \n");
if (a==randomnumber){
printf("You guessed it correctly, YOU WIN!!\n");
}
else{
for(count=4;count>=1;count--)
{
if (a>randomnumber) {
printf("My number is smaller than that\n");
} else if (a<randomnumber) {
printf("My number is greater than that\n");
} else {
printf("You guessed it correctly, YOU WIN!!\n");
break;
}
printf("You only have %d tries left\n",(count));
printf("enter number again: ");
scanf("%d",&a);
printf(" \n");
}
}
if (a!=randomnumber)
{
printf("You LOOSE!!, the Number was %d",randomnumber);
}
return 0;
}

Prompt user to re-enter number

I'm doing a practice 'do while' program where I want the user to enter three numbers and the program will print the sum on screen. After receiving the answer, the program will ask the user if he wants to enter another three numbers to get another answer, and so on. I'm fine with this.
If user enters anything other than an integer ("A,!,%") etc, I want the program to prompt the user to re-enter a number. See comments in program.
#include <stdio.h>
/*
Do - While
This program shall ask the user to enter
three numbers and print out the sum. Entering letters
or special characters will ask the user to re-enter that
number.
example:
Enter Number 1: 2
Enter Number 2: 5
Enter Number 3: 9
Answer is 16
...
Enter Number 1: 2
Enter Number 2: yum here user incorrectly enters letters
Enter Number 2: 8 re-prompted to enter number to continue
Enter Number 3: 9
Answer is 19
*/
int main(void) {
int a,b,c,ans,n;
do{
do{
printf("Enter Number 1: ");
scanf("%d", &a);
printf("\n");
}
while((a>0) || (a<0)|| (a==0));
do{
printf("Enter Number 2: ");
scanf("%d", &b);
printf("\n");
}
while((b>0) || (b<0)|| (b==0));
do{
printf("Enter Number 3: ");
scanf("%d", &c);
printf("\n");
}
while ((c>0) || (c<0)|| (c==0));
ans = a+b+c;
printf("Answer is %d\n\n", ans);
printf("Press 1 to start over, or 0 to quit...");
scanf("%d",&n);
printf("\n");
}while (n!=0);
return 0;
}
Your program contains multiple repeated sections. Since you are gathering three numbers, you should use a for loop which runs three times.
for (int i = 0; i < 3; i++) {
/* ... */
}
Inside the for loop, you're gathering the i+1-th number each time. If the user doesn't enter a valid number, you keep trying to gather it. So the do-while loop containing the printf and scanf will go inside the for loop.
for (int i = 0; i < 3; i++) {
do {
printf("Enter Number %d: ", i+1);
scanf( /* ... */ );
} while ( /* ... */ );
}
scanf returns the number of input items successfully read as an int. So the do-while loop should repeat as long as the return value of scanf is zero. We could store the return value in a variable and check the variable in the while (...);, but we can just move the scanf itself into the while (...);. We also need an array to store the three input numbers.
int n[3];
for (int i = 0; i < 3; i++) {
do {
printf("Enter Number %d: ", i+1);
} while (scanf("%d", n+i) == 0);
}
The rest of the program would loop over the array and store the sum of the elements. You would then output the sum. This approach is robust and maintainable as changing the amount of input numbers is easy and repeated or similar code sections are eliminated.
You can use fgets to get the input and use strtol() to cast the string the user input into an int. If strtol returns 0 when the user input does not start with a number or have a number in it. From there you can check if the user input is 0 and then reprompt the user until a is not 0.
*instead of scanf()*
char num1[5];
char *end;
fgets(num1, 5, stdin);
a = strtol(num1, &end, 10);
while( a = 0){
fgets....
}

c language if wrong number is entered ask the user again

I am trying to get the user to re enter the the number again if they enter a value of less than ten
i am certain the problem lies with the while statement.
this what i have
printf_s("Enter the player first name: ");
scanf_s("%s", names[i], 25); //enters name and creates a newline <enter key>//
printf_s("Minimum number to stop in a turn: ");
scanf_s("%d", &min_number, sizeof(int));
do {
printf_s("please enter a number greater or egual to 10");
} while (min_number <= 10);
scanf_s("%d ", &min_number);
printf_s("please enter a number greater or equal to 10\n\n");
is a do while loop the best option or should i look at using another type of loop
enter image description here
As I was corrected, thoughfully scanf returns the number of receiving arguments successfully assigned.
Here is a fixed version:
void main(){
int num = 0;
while(num <=10){
scanf("%d ", &num);
printf_s("please enter a number greater or equal to 10\n\n");
}
}
After the authour edited the code in his question and upon his request:
do {
printf_s("please enter a number greater or egual to 10\n\n");
scanf_s("%d", &min_number);
} while (min_number < 10);
When doing the do/while loop the body of the loop is in the
do{body goes here}while(some condition);.
After another edit, on author request:
printf_s("Minimum number to stop in a turn: ");
scanf_s("%d", &min_number, sizeof(int));
while(min_number < 10){
printf_s("please enter a number greater or egual to 10\n\n");
scanf_s("%d", &min_number);
}
This will do the following it will ask for "Minimum number to stop in a turn: " if it is greater or equal to 10 it will continue after the loop. If it is not it will give clarification "please enter a number greater or egual to 10" and will receive another input. It will loop until it receive greater or egual to 10.

C program gives incorrect output?

I am writing a C program which calculates average grade and tells if you pass or fail. The user can choose as many attempts as they want and they will be given a final average of all attempts. Here is my code:
#include <stdio.h>
int main(void)
{
int num1;
double num2, num3, average, average_1;
printf("Enter number of attempts: ");
scanf("%d", &num1);
while (num1 > 0) {
printf("Enter your mark for subject one: ");
scanf("%lf", &num2);
printf("Enter your mark for subject two: ");
scanf("%lf", &num3);
if (num2 < 50 || num3 < 50) {
printf("You have failed \n");
} else {
printf("You have passed \n");
}
num1--;
}
average = num1 * num2 * num3;
average_1 = average / 100;
printf("Average for all %d attempts is %.2f \n", num1, average_1);
}
The problem with this code is that the final output, which is the last printf line, gives me 0 for attempts and 0 for average. Here is the exact output:
Enter number of attempts: 2
Enter your mark for subject one: 49
Enter your mark for subject two: 96
You have failed
Enter your mark for subject one: 22
Enter your mark for subject two: 100
You have failed
Average for all 0 attempts is 0.00
You are dicrementing the variable num1. So, when you finish your loop you will have num1 = 0.
I suggest you do a 'for' instead of a 'while'. Like this:
#include <stdio.h>
int main(void) {
int num1, i;
double num2,num3,average,average_1;
printf("Enter number of attempts: ");
scanf("%d", &num1);
for(i = num1; i > 0; i--) {
printf("Enter your mark for subject one: ");
scanf("%lf", &num2);
printf("Enter your mark for subject two: ");
scanf("%lf", &num3);
if (num2 < 50 || num3 < 50) {
printf("You have failed \n");
}
else {
printf("You have passed \n");
}
}
average = num1*num2*num3;
average_1 = average / 100;
printf("Average for all %d attempts is %.2f \n", num1, average_1);
}
You have put the average calculation part in wrong place. Once you're out of the while loop, num1 will have a value 0, hence all the related calculations will return 0.
You are reducing num1 until it becomes 0
while (num1 > 0) {
// other code
num1--;
}
Then naturally
average = num1*num2*num3;
becomes
average = 0*num2*num3;
and that is 0
First, because you deduct num1 by one till 0.
You should use for loop:
for(int counter = num1; num1 > 0; num--)
{ Your code here }
Your loop will iterate until num1 is greater than 0 . As it decrement and become 0 program come out of loop but num1 has value 0 . Thus ,in these expressions num1 is 0-
average = num1*num2*num3; // 0*num2*num3 therefore , 0
average_1 = average / 100; // as average is 0 , thus result is 0
Also formula for calculating average_1 is wrong . It should be -
average_1=average/3; // you calculate average of 3 numbers
To get correct output create a temporary variable -
int i=num1;
while(i>0){
// your code
i--;
}
In this way num1 remain unchanged.
after the while loop, your num1 will be 0.

Resources