How To get program to repeat when asked y or n - c

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

Related

while loop not breaking even with break C programming

Trying to make a GPA calculator.
Here is my code:
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
int main()
{
float fgpa, grade, n;
char reply;
n = 1;
grade = 1;
printf("--- GPA Calculator ---");
while(fgpa < 1 || fgpa > 4)
{
printf("\n\nEnter your current GPA: ");
scanf("%f", &fgpa);
if(fgpa < 1 || fgpa > 4)
printf("Invalid Input! Please re-enter value.");
}
printf("\nUsing the following table to convert grade to points\n\nA+ = 4.0\nA = 4.0\nB+ = 3.5\nB = 3\nC+ = 2.5\nC = 2.0\nD+ = 1.5\nD = 1\nF = 0\n");
while(grade > 0, n++)
{
printf("\nEnter points for module %.0f, enter \"0\" if there are no more additional modules: ", n);
scanf("%f", &grade);
printf("%f", grade);
fgpa = (fgpa + grade) / n;
}
fgpa = fgpa* n / (n-1);
n--;
printf("\n\nNumber of modules taken: %.0f\nFinal GPA: %.1f", n, fgpa);
return 0;
}
I've tried using if(grade = 0) break; but its still not breaking the loop even when the grade is correctly read 0.
picture of 0 being read correctly but loop still continuing
There are multiple problems in the code:
fgpa is uninitialized so the first test in the loop has undefined behavior.
you should also test the return value of scanf() to detect invalid or missing input.
while (grade > 0, n++) is incorrect too: you should instead always read the next grade and test its value and break from the loop before incrementing n.
Your averaging method seems incorrect too: you do not give the same weight to every module.
It seems more appropriate for your purpose to use for ever loops (for (;;)), unconditionally read input, check for scanf() success and test the input values explicitly before proceeding with the computations.
Here is a modified version:
#include <stdio.h>
// flush the rest of the input line, return EOF at end of file
int flush(void) {
int c;
while ((c = getchar()) != EOF && c != \n')
continue;
return c;
}
int main() {
float fgpa;
float grade;
int n = 1;
char reply;
printf("--- GPA Calculator ---");
for (;;) {
printf("\n\nEnter your current GPA: ");
if (scanf("%f", &fgpa) == 1) {
if (fgpa >= 1 && fgpa <= 4)
break;
}
} else {
if (flush() == EOF) {
fprintf(stderr, "unexpected end of file\n");
return 1;
}
}
printf("Invalid Input! Please re-enter value.\n");
}
printf("\nUsing the following table to convert grade to points\n\n"
"A+ = 4.0\nA = 4.0\nB+ = 3.5\nB = 3\nC+ = 2.5\n"
"C = 2.0\nD+ = 1.5\nD = 1\nF = 0\n");
for (;;) {
printf("\nEnter points for module %d, enter \"0\" if there are no more additional modules: ", n);
if (scanf("%f", &grade) == 1) {
if (grade <= 0)
break;
printf("%f\n", grade);
fgpa = fgpa + grade;
n = n + 1;
} else {
if (flush() == EOF)
break;
printf("Invalid Input! Please re-enter value.\n");
}
}
fgpa = fgpa / n;
printf("\n\nNumber of modules taken: %d\nFinal GPA: %.3f\n", n, fgpa);
return 0;
}

Fixing do-while loop problem and how to add do you want to play again?

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?

How can I modify program to set array range from 0 to 100 in program below

I need the code below to recognize if the grades entered is below 1 or greater than 100. If it is not within the parameters, I want to let the user know and allow them to enter another grade without exiting the program or losing grades they have already entered. I don't want the program to quit until the user enters q and I want to ensure all of the valid grades entered print at that time. I have tried numerous methods and am not getting the right results. I think I probably need some other else if statement, but I haven't been able to find the right one to work. Any information you can share to get me on the right track would be greatly appreciated.
#include <stdio.h>
#include <stdlib.h>
int main()
{
char choice;
int gradeArray[100];
int grades;
int gCount=0,i;
for(gCount=0; gCount<100; gCount++)
{
//for loop to read the grades till array size
printf("******Enter Choice Selection in Parenthesis******\n Add grades(a)\n Quit(q) \n");
scanf("%c",&choice);
if(choice == 'a' || 'A')
{
//if user choice is a, then read the grade
printf( "Enter grade: ");
scanf("%d", &grades);
getchar();
gradeArray[gCount] = grades; //add the grade to array
}
if(choice == 'q') //if the user choice is q, then exit the loop
{
break;
}
}
printf("Grades are:\n");
for(i=0; i<gCount; i++)
{
printf(" %d%%\n", gradeArray[i]); //print grades
}
return 0;
}
You can do a while loop to verify the user input. With a while you'll be able to force the user to enter the right grade.
if(choice == 'A' || choice == 'a'){
printf("Enter grade:");
scanf("%d", &grades);
getchar();
while(grade < 1 || grade > 100){
printf("You entered a wrong number\n");
printf("Enter a grade between 1 and 100: ");
scanf("%d", &grades);
getchar();
}
gradeArray[gCount] = grades;
}
your solution is almost aligned with what you had in mind. Here is how you can do it differently.
#include <stdio.h>
int main()
{
char choice;
int arraySize = 100; //change this to any number you wish
int gradeScore = 0;
int gradeArray[arraySize];
int gCount = 0;
int showCount = 0;
while(choice != 'q')
{
//to ask for user's input every time
printf("What do you want to do? Enter\n");
printf("'a' to add grades\n");
printf("'q' to quit\n");
scanf(" %c", &choice); //space is entered to ensure the compiler does not read whitespaces
//your implementation should check for user input before proceeding
if(choice != 'a')
{
//in this condition, 'q' is technically an incorrect input but your design states that 'q' is for quitting
//thus, do not alert the user here if 'q' is entered
if(choice != 'q')
{
//a condition to warn the user for incorrect input
printf("Incorrect input. Please enter only 'a' or 'q'\n");
}
}
else if(choice == 'a')
{
printf("Enter grade: \n");
scanf(" %d", &gradeScore);
//to check for user input if the grades entered are less than 1 or more than 100
if(gradeScore < 1 || gradeScore >100)
{
//print a warning message
printf("The grade you entered is invalid. Please enter a grade from 1 - 100\n");
}
//for all correct inputs, store them in an array
else
{
printf("Grade entered\n");
gradeArray[gCount] = gradeScore;
gCount++;
}
}
}
//prints grade when 'q' is entered
if(choice == 'q')
{
printf("Grades are: \n");
for(showCount = 0; showCount < gCount ; showCount++)
{
printf("%d\n", gradeArray[showCount]);
}
}
}
To sum up the important parts, be sure to check for the user grade input to be in range of 1 - 100. Store the grade in the array if it is within range and be sure to increase the array counter, otherwise it will always store it in gradeArray[0] for the subsequent grades. Hope this helps
Use a do-while loop to keep the program looping back to get another choice unless a valid choice has been entered. Use fgetc to read a single character - fewer problems. Only print grades if at least one grade has been entered.
#include <stdio.h>
#include <stdlib.h>
int main()
{
char choice;
int gradeArray[100];
int grades;
int gCount=0,i;
for(gCount=0; gCount<100; gCount++)
{
//for loop to read the grades till array size
printf("******Enter Choice Selection******\n Add grades(a)\n Quit(q) \n");
do
{
choice = fgetc(stdin);
if(choice == 'a' || choice == 'A')
{
//if user choice is a, then read the grade
printf( "Enter grade: ");
scanf("%d", &grades);
getchar();
gradeArray[gCount] = grades; //add the grade to array
}
else if(choice != 'q')
printf("Invalid choice - try again\n");
} while (choice != 'a' && choice != 'A' && choice != 'q');
if(choice == 'q') //if the user choice is q, then exit the loop
break;
}
if(gCount > 0)
{
printf("Grades are:\n");
for(i=0; i<gCount; i++)
printf(" %d%%\n", gradeArray[i]); //print grades
}
return 0;
}

For loop cumulative calculation problem. C programming

Here I have created a compounding interest calculator. The user inputs principal, interest% and duration (in quarters). I have used a for loop for the initial calculation. But, I don't know how to get the total to rollover to the next quarter's principal.
Say the user inputs 1000, 5% and 2 quarters. The output should look like, Q1 Principal=$1000, Interest=0.05, Total=$1012.50, Q2 =$1012.50 =0.05 =$1025.16
Also my last Do while is giving me some issues. The ouput is spitting out a couple extra lines before letting the user start over.
Any advice would be greatly appreciated.
Thank you
#include <stdio.h>
int main (void)
{
int a = 0, b=0;
double interest, prin, total=0;
char check = ' ';
do{
do{
do{
printf (" Please enter principal:\n");
scanf ("%lf", &prin);
}while(prin <=0);
do{
printf ("Please enter desired interest greater
than 0 less than 20 :\n");
scanf ("%lf", &interest);
}while(interest <=0 || interest >20);
interest = interest/100;
do{
printf ("For how many quarters would you like
to deposit: (more than 0, less than 40) \n");
scanf ("%d", &b);
}while(b <=0 || b >40);
printf ("Is this information correct? Press X
to continue" );
scanf ("\n%c", &check);
}while(check != 'x' && check != 'X');
total = prin * (1+(interest *.25));
printf ("Quarter Principal Interest
Total\n");
for(a=1; ;++a){
printf ("%2d $%.2f %.2lf
$%.2lf\n", a, prin, interest, total);
if(a == b)
break;
}
printf ("Do you want to start over (Y/N)?");
scanf ("%c\n", &check);
}while(check != 'y' || check != 'Y');
return 0;
}
The are some problem with indentation and logic in your code. You need to updade principle in for loop statement. Then print it out .Here is my solution
#include <stdio.h>
int main(void)
{
int a = 0, b = 0;
double interest, prin, total = 0;
char check = ' ';
do {
do {
do {
printf(" Please enter principal:\n");
scanf("%lf", &prin);
} while (prin <= 0);
do {
printf("Please enter desired interest greater than 0 less than 20 :\n");
scanf("%lf", &interest);
} while (interest <= 0 || interest > 20);
interest = interest / 100;
do {
printf("For how many quarters would you like to deposit : (more than 0, less than 40) \n");
scanf("%d", &b);
} while (b <= 0 || b > 40);
printf("Is this information correct? Press X to continue" );
scanf("\n%c", &check);
} while (check != 'x' && check != 'X');
printf("Quarter Principal Interest Total\n");
for (a = 1; a<=b; ++a) {
total = prin * (1 + (interest *.25));
printf("%2d $%.2f %.2lf $%.2lf\n", a, prin, interest, total);
prin = total;
}
printf("Do you want to start over (Y/N)?");
scanf("%c\n", &check);
} while (check != 'y' || check != 'Y');
return 0;
}

Program that asks the user for a number n and gives him the possibility to choose between computing the sum and computing the factorial of n

The code is supposed to ask the user whether to find the sum of numbers from 1 to x or finding the factorial of x. After taking the user's input for the value of x, the program directly ends without running the if and else if statement. This is my code.
#include <stdio.h>
int sum(int num);
int fact(int num);
int main(void)
{
int x = 0;
char choice;
printf("Enter a number : \n");
scanf("%d", &x);
printf("Enter f for factorial, s for sum \n");
choice = getchar();
//These lines are ignored by C
if (choice == 'f' || choice == 'F')
{
printf("The factorial of %i is %i \n",x, fact(x));
}
else if (choice == 's' || choice == 'S')
{
printf("The sum from 1 to %i is %i \n",x, sum(x));
}
}
int sum (int num)
{
int sum =0;
for (int i =1; i <=num; i++ )
sum = sum+i;
return sum;
}
int fact (int num)
{
int fact =1;
for (int i =1; i <=num; i++ )
fact = fact*i;
return fact;
}
Can anyone please explain to me what is wrong with my code and how can I fix it? Thank you.
I think buffer problem. So, use
scanf(" %d", &x);
^^^
white-space
instead of
scanf("%d", &x);
and also, use
scanf(" %c", &choice);
instead of
choice = getchar();
The problem in this code is in getchar() function.
In first scanning : scanf("%d", &x); when user press enter key, it remain in the input buffer and the integer val is stored in variable x.
In second scanning: choice = getchar();, it reads the enter key in variable choice.
And you have written only two conditions:
if (choice == 'f' || choice == 'F')
else if (choice == 's' || choice == 'S')
That's why it is directly ending the code; as there is no code written for choice = other than 'f' and 's'
if you write 'else' part like this:
else printf("%d", choice);
It will print: 10 which is the ascii value of Enter / New line feed.
To avoid this, try to make following changes in your code:
int x = 0;
char choice;
printf("Enter a number : \n");
scanf("%d", &x); //here the integer is scanned in variable 'x'
choice = getchar(); //here the enter key is scanned in variable 'choice' so now input buffer is free
printf("Entr f for factorial, s for sum \n");
scanf("%c", &choice); //here the character entered by use will be stored in variable 'choice' so it is overwritten.

Resources