My assignment is to use two different kinds of loops (For, While, do While). The task is to ask the user to enter a number between 1 and 10 and then the program will count from 0 to the users number. Also, the program must be able to display an error message and ask the user to enter a number again if the user enters a number outside of 1 through 10. The part of the code with the error message and the prompt to enter a number again is working just fine. However, when I enter a number within the range, it either does nothing or counts from 0 to their number an infinite amount of times and won't stop looping the count. Please help!
#include <stdio.h>
int main(void)
{
//Variables
int num;
int zero;
//Explains to the user what the program will do
printf("This program will count from 0 to a number you pick.\n\n");
//Asks the user to input a value
printf("Please enter a number (between 1 and 10): \n");
scanf("%d", &num);
//If the correct range was selected by the user
while ( num >= 1 && num <= 10 )
{
for ( zero = 0; zero <= num; zero++ )
{
printf("%d...", zero);
}
}
//If a value outside of the accepted range is entered
while ( num < 1 || num > 10)
{
printf("I'm sorry, that is incorrect.\n");
printf("Please enter a number (between 1 and 10): \n");
scanf("%d", &num);
}
printf("\n\n\n");
return 0;
}
while ( num >= 1 && num <= 10 )
{
for ( zero = 0; zero <= num; zero++ )
{
printf("%d...", zero);
}
}
will run forever if num is between 1 and 10, since num is not changed inside the loop - once you're in, you're in for good.
If you enter a "bad" value then you'll skip this and go into your second while loop. However once you get out of that while loop by entering a "good" value, all that's left to execute is
printf("\n\n\n");
return 0;
You need to get rid of the first while loop and move the second one above the for loop:
#include <stdio.h>
int main(void)
{
//Variables
int num;
int zero;
//Explains to the user what the program will do
printf("This program will count from 0 to a number you pick.\n\n");
//Asks the user to input a value
printf("Please enter a number (between 1 and 10): \n");
scanf("%d", &num);
//If a value outside of the accepted range is entered
while ( num < 1 || num > 10)
{
printf("I'm sorry, that is incorrect.\n");
printf("Please enter a number (between 1 and 10): \n");
scanf("%d", &num);
}
for ( zero = 0; zero <= num; zero++ )
{
printf("%d...", zero);
}
printf("\n\n\n");
return 0;
}
Change two of your while loops to if guards,
num=1;
while(num>0)
{
//Asks the user to input a value
printf("Please enter a number (between 1 and 10): \n");
scanf("%d", &num);
//If the correct range was selected by the user
if ( num >= 1 && num <= 10 )
{
for ( zero = 0; zero <= num; zero++ )
{
printf("%d...", zero);
}
}
//If a value outside of the accepted range is entered
if ( num < 1 || num > 10)
{
printf("I'm sorry, that is incorrect.\n");
printf("Please enter a number (between 1 and 10): \n");
//scanf("%d", &num);
}
while(0); while(0); while(0); while(0); //gratuitous loops
do ; while(0); for(;0;);
}
Really Simple!
You may use a break inside the while loop:
#include <stdio.h>
int main(void)
{
//Variables
int num;
int zero;
//Explains to the user what the program will do
printf("This program will count from 0 to a number you pick.\n\n");
//Asks the user to input a value
printf("Please enter a number (between 1 and 10): \n");
scanf("%d", &num);
//If the correct range was selected by the user
while ( num >= 1 && num <= 10 )
{
for ( zero = 0; zero <= num; zero++ )
{
printf("%d...", zero);
}
break; // !!! Here !!!
}
//If a value outside of the accepted range is entered
while ( num < 1 || num > 10)
{
printf("I'm sorry, that is incorrect.\n");
printf("Please enter a number (between 1 and 10): \n");
scanf("%d", &num);
}
printf("\n\n\n");
return 0;
}
Related
I started C courses today and teacher assigned to do:
Guess the number and if the number is higher say it is higher but if it is lower say it is lower and count every time you guess AND if you guess it ten times already then say do you want to try again?
I don't know why my code is stop when I just play it only 1 time and how to do the "do you want to play again?"
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
int x;
char name[20], result;
int count = 0;
int number;
srand(time(NULL));
x = rand() % 100 + 1;
printf("What's your name :");
scanf("%s", &name);
printf("Hello!! %s\n", name);
printf("Guess the number : ");
scanf(" %d", &number);
do {
count++;
if (x > number) {
printf("This is your count : %d\n",count);
printf("The number is higher\n");
} else
if (x < number) {
printf("This is your count : %d\n",count);
printf("The number is lower\n");
} else
if (x == number) {
printf("\nYou're right!!, the number is %d",x);
}
} while (count == 10);
}
The code allows only 1 try because the test while (count == 10) is false at the end of the first iteration. You should have while (count < 10).
You should move the input call scanf(" %d", &number); inside the loop.
Also note that you should break from the loop if the number was found.
For the Do you want to play again? part, you could wrap this code in another loop.
Here is a modified version:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
char name[20] = "", ch;
srand(time(NULL));
printf("What's your name: ");
scanf("%19s", &name);
printf("Hello!! %s\n", name);
for (;;) {
int x = rand() % 100 + 1;
int number;
for (int count = 1; count <= 10; count++) {
printf("Enter your guess: ");
if (scanf(" %d", &number) != 1)
break;
if (x > number) {
printf("This is your count: %d\n",count);
printf("The number is higher\n");
} else
if (x < number) {
printf("This is your count: %d\n",count);
printf("The number is lower\n");
} else
if (x == number) {
printf("You're right!!, the number is %d\n",x);
break;
}
}
printf("Do you want to play again? ");
if (scanf(" %c", &ch) != 1)
break;
if (ch != 'y' && ch != 'Y')
break;
}
return 0;
}
The loop condition in the line
} while (count == 10);
is wrong, because it will be false after the first loop iteration. It would be more meaningful to write
} while (count < 10);
Also, you probably want to put the lines
printf("Guess the number : ");
scanf(" %d", &number);
inside the loop, so that they get executed more than once. Otherwise, you will be processing the same user guess 10 times, which is not what you want.
Another issue is that you don't want the loop to always run 10 times. You only want it to run 10 times if the user hasn't guessed the number. If the user has guessed the number, you want to break out of the loop immediately, without waiting for count to reach 10. For this, you can use the break statement.
I'm a VB guy mostly but can you use while count <= 10?
Perhaps Do Until?
I am a beginner in C programming and I am stuck in my little program .
I just wanna make a list from which I ask users to select a number from that list. Then the program should do what it should be done.
My list is:
Create a table
Max & Min Number Checking
Negative & Positive Number Checking
Ascending Order
Descending order
Exit
I couldn't start correctly! When I first press 1 to create the table, the program keeps looping again and again!!
I want my program to ask me for some values then take my value and draw me a table and then store these values temporary in memory, so that I can execute the rest of commands from my list.
Here's my code:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int t[100],n,a,f,s=0,i,max,min,m,l;
{
printf("Welcome to My simple Math Program in C language \n");
printf("1:Create a table\n 2:Max&Min Number Checking\n 3:Negative&Positive Number Checking\n 4:Ascending Order\n 5:Descending ordert\n 6:Exit\n ");
printf("Please Choose a number from the list" );
scanf("%d",&a);
while(a!=6){
switch(a){
case 1:printf("Please Enter The Length Of Your Table ");
scanf("%d",&n);
printf("Please Enter Your Table Elements ");
for(int i=0;i<n;i++){
scanf("%d",&t[i]);
}
for(int i=0;i<n;i++){
printf("%d ",t[i]);
}
break;
case 3:
if(t[i]<0){
printf("This Number is Negative %d",t[i]);
}
else if(t[i]==0){
printf("This Number is nulle %d",t[i]);
}
else
{
printf("This Number is Positive %d",t[i]);
}
;break;
case 6:
break;
}
}
return 0;
}
}
Your scanf() statement is outside your while loop so it is only executed once. You need something like this:
do
{
scanf("%d",&a);
...rest of code
} while (a!=6)
You should print the message and read the option inside the main loop:
#include <stdio.h>
#include <stdlib.h>
int main() {
int t[100], n, a, f, s = 0, i, max, min, m, l;
printf("Welcome to My simple Math Program in C language\n");
for (;;) {
printf("1: Create a table\n"
"2: Max&Min Number Checking\n"
"3: Negative&Positive Number Checking\n"
"4: Ascending Order\n"
"5: Descending ordert\n"
"6: Exit\n");
printf("Please Choose a number from the list: ");
if (scanf("%d", &a) != 1) /* invalid input */
break;
if (a == 6)
break;
switch (a) {
case 1:
printf("Please Enter The Length Of Your Table ");
if (scanf("%d", &n) != 1)
break;
if (n > 100)
n = 100;
printf("Please Enter Your Table Elements: ");
for (i = 0; i < n; i++) {
scanf("%d", &t[i]);
}
for (i = 0; i < n; i++) {
printf("%d ",t[i]);
}
break;
case 3:
i = 0;
if (t[i] < 0) {
printf("This Number is Negative %d\n", t[i]);
} else
if (t[i] == 0) {
printf("This Number is null %d\n", t[i]);
} else {
printf("This Number is Positive %d",t[i]);
}
break;
}
}
return 0;
}
i am trying to get this program to repeat when prompted Y or N and i cant seem to get it to work right for some reason and this is the last thing i have left and im pretty sure the rest of the code is right i think all i need is it to repeat the whole program if the user enters a "Y" or just exits if the user enters "N"
int main(void)
{
// Constant and Variable Declarations
const int MPH_SPEED_MIN = 1;
const int MPH_SPEED_MAX = 100;
const int HOURS_TRAVLED_MIN = 1;
int mphSpeed = 1;
int hoursEntered = 0;
int distanceTraveled = 0;
int counterNum = 0;
int distanceNum = 0;
char ch = 'y';
// *** Input ***
do {
printf("What is the speed of the vehicle in MPH? ");
scanf("%d", &mphSpeed);
while ((mphSpeed < MPH_SPEED_MIN) || (mphSpeed > MPH_SPEED_MAX)) {
printf("\tThe speed entered must be between %d and %d inclusive
\n",MPH_SPEED_MIN, MPH_SPEED_MAX);
printf("\tPlease re-enter the speed of the vehicle in MPH: ");
scanf("%d", &mphSpeed);
}
printf("How many hours has it traveled? ");
scanf("%d", &hoursEntered);
while (hoursEntered < HOURS_TRAVLED_MIN) {
printf("\tThe hours traveled must be a positive number.\n");
printf("\tPlease re-enter the number of hours traveled: ");
scanf("%d", &hoursEntered);
}
printf("\n");
printf("Hour\tDistance Traveled\n");
distanceTraveled = hoursEntered * mphSpeed;
for (counterNum = 1; counterNum <= hoursEntered; counterNum++) {
distanceNum = distanceTraveled * counterNum;
printf("%d\t%d miles\n", counterNum, distanceNum);
}
printf("\n");
printf("Run the program again (Y/N)? ");
scanf("%c", &ch);
printf("\n");
} while (ch == 'Y' || ch == 'y');
; return 0;
When reading in with scanf(%c..., the statement very likely reads in a new line character left in the buffer from previous inputs. Read in a string instead, because %s ignores any leading white spaces (including such a new line character left in the buffer).
Try ...
char exitYN[2];
if (scanf("%1s",exitYN) != 1) {
exitYN[0]='N';
}
char ch = exitYN[0];
} while (ch == 'Y' || ch == 'y');
The one small yet, the most effective change that can be made here is adding a <space> before the %c while accepting the Y or N, i.e, scanf(" %c, &ch");
And I don't know if the following are errors while typing the code in StackOverflow, or are they originally errors in your code, but definitely are worth making changes:
Header file missing: #include<stdio.h>,
Unwanted and extra semicolon (;) before the return statement at the end,
missing closing bracket (}) at the end, after the return.
Here is the working code:
#include<stdio.h>
int main(void)
{
// Constant and Variable Declarations
const int MPH_SPEED_MIN = 1;
const int MPH_SPEED_MAX = 100;
const int HOURS_TRAVLED_MIN = 1;
int mphSpeed = 1;
int hoursEntered = 0;
int distanceTraveled = 0;
int counterNum = 0;
int distanceNum = 0;
char ch = 'y';
// *** Input ***
do {
printf("What is the speed of the vehicle in MPH? ");
scanf("%d", &mphSpeed);
while ((mphSpeed < MPH_SPEED_MIN) || (mphSpeed > MPH_SPEED_MAX)) {
printf("\tThe speed entered must be between %d and %d inclusive\n",MPH_SPEED_MIN, MPH_SPEED_MAX);
printf("\tPlease re-enter the speed of the vehicle in MPH: ");
scanf("%d", &mphSpeed);
}
printf("How many hours has it traveled? ");
scanf("%d", &hoursEntered);
while (hoursEntered < HOURS_TRAVLED_MIN) {
printf("\tThe hours traveled must be a positive number.\n");
printf("\tPlease re-enter the number of hours traveled: ");
scanf("%d", &hoursEntered);
}
printf("\n");
printf("Hour\tDistance Traveled\n");
distanceTraveled = hoursEntered * mphSpeed;
for (counterNum = 1; counterNum <= hoursEntered; counterNum++) {
distanceNum = distanceTraveled * counterNum;
printf("%d\t%d miles\n", counterNum, distanceNum);
}
printf("\n");
printf("Run the program again (Y/N)? ");
scanf(" %c", &ch);
printf("\n");
} while (ch == 'Y' || ch == 'y');
return 0;
}
I have also attached the output just in case you need to verify.
OUTPUT:
What is the speed of the vehicle in MPH? 12
How many hours has it traveled? 1
Hour Distance Traveled
1 12 miles
Run the program again (Y/N)? y
What is the speed of the vehicle in MPH? 6
How many hours has it traveled? 6
Hour Distance Traveled
1 36 miles
2 72 miles
3 108 miles
4 144 miles
5 180 miles
6 216 miles
Run the program again (Y/N)? n
I have a function exits the loop when INCORRECT value is entered.
I want the function to ask the user to enter the correct value BEFORE it exits the loop.
I am passing the value of hours entered by the user into the function wrongHours
if the user is to enter hours below 0 or above 23, the function should ask the user to enter something again, but it just goes to the next line? am I missing a flag or something?
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <conio.h>
// function prototypes
int wrongHours(int n);
int main(void)
{
int hours;
int minutes;
printf("Enter the first hour value (0 - 23): ");
scanf("%d", &hours);
while (wrongHours(hours)) {
printf("Enter the first hour value (0 - 23): ");
scanf("%d", &hours);
}
printf("\nEnter the first minute value (0 - 59): ");
scanf("%d", &minutes);
_getch();
return 0;
} // end main
// function validates that hours are between 0 - 23
int wrongHours(int n) {
int i;
if (n < 0 || n > 23) {
printf("Invalid data entered, try again!");
return 0;
}
return 1;
}
I dont know why you want to use for loop , below is some formatted code , please check if it satisfy your need
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <conio.h>
// function prototypes
int wrongHours(int n);
int main(void)
{
int hours;
int minutes;
printf("Enter the first hour value (0 - 23): ");
scanf("%d", &hours);
while( wrongHours(hours)) {
printf("Enter the first hour value (0 - 23): ");
scanf("%d", &hours);
}
printf("\nEnter the first minute value (0 - 59): ");
scanf("%d", &minutes);
_getch();
return 0;
} // end main
// function validates that hours are between 0 - 23
int wrongHours(int n)
{
if (n < 0 || n > 23) {
printf("Invalid data entered, try again!");
return 1;
}
return 0;
}
I'm having a problem and I tried several times to solve this problem maybe you could help.
I need to modify the program below so that it asks the user to enter any number other than the number equal to the number of times they've been asked to enter a number. (i.e on the first iteration "Please enter any number other than 0" and on the second iteration "Please enter any number other than 1"m etc. etc. The program must behave accordingly exiting when the user enters the number they were asked not to.) Now the code that I have below reacts a bit differently and here's what's happening when I run it:
Enter a number: 4
Please enter a number other than 4
5
Enter a number other than 5
5
wrong
6
Enter a number other than 6
7
Enter a number other than 6
and this is my code below:
#include <stdio.h>
int main()
{
int number, x=0, counter = 0;
printf("Enter a number: ");
scanf("%d", &number);
printf("Please enter a number other than %d\n", number);
while (number!=x)
{
scanf("%d", &x);
while (x!=counter)
{
printf("Enter a number other than %d\n", x);
scanf("%d", &counter);
if (counter==x)
{
printf("wrong\n");
break;
}
}
if (number==x)
{
printf("wrong\n");
break;
}
}
return 0;
}
I really hope I explained the question correctly please let me know.
If I understood it well, you want a program that behaves like this, isn't it?
Please enter a number other than 0
4
Please enter a number other than 1
7
Please enter a number other than 2
8
Please enter a number other than 3
2
Please enter a number other than 4
4
** END OF PROGRAM **
Then, it's much more simpler than you thought...
#include <stdio.h>
int main()
{
int number, counter = 0;
do
{
printf("Please enter a number other than %d\n", counter);
scanf("%d", &number);
}
while (number != counter++);
return 0;
}
UPDATE:
#include <stdio.h>
int main()
{
int number = 0, previous;
do
{
previous = number;
printf("Please enter a number other than %d\n", previous);
scanf("%d", &number);
}
while (number != previous);
return 0;
}
Try:
#include <stdio.h>
int main()
{
int number, x=0, counter = 0;
int flag = 0;
printf("Enter a number: ");
scanf("%d", &number);
printf("Please enter a number other than %d\n", number);
while (number!=x)
{
scanf("%d", &x);
while (x!=counter)
{
printf("Enter a number other than %d\n", x);
scanf("%d", &counter);
if (counter==x)
{
printf("wrong\n");
flag = 1;
break;
}
}
if (number==x || flag=1)
{
printf("wrong\n");
break;
}
}
return 0;
}