How to exit program when the choice is not equal to "y" - c

I am trying to make a program that would print 10 integers between 10-50 in an array and when you enter an integer outside 10-50 it would ask you if you want to try again or not. But when I try to enter "n" it would still continue to ask another integer. What am I doing wrong?
#include <stdio.h>
#include <stdlib.h>
#define size 10
int main() {
int i,arr[size],sum=0;
char ch;
do {
for(i = 0; i < size; i++){
printf("Input a number at index %d: ", i);
scanf("%d", &arr[i]);
if(arr[i] <10 ||arr[i] > 50 ){
printf("entered number is not valid\n");
printf ("Do you want to repeat the operation Y/N: ");
scanf (" %c", &ch);
}
}
printf ("Do you want to repeat the operation Y/N: ");
scanf (" %c", &ch);
}
while (ch == 'y' || ch == 'Y');
}

In this if statement you ask whether the user wants to continue or not, but do not handle the situation where the user enters an 'n'. You must enter a comparison followed by a break to exit the loop.
if (arr[i] < 10 || arr[i] > 50){
printf("entered number is not in the range 10..50\n");
printf("Do you want to repeat the operation Y/N: ");
scanf(" %c", &ch);
// ADD THE FOLLOWING TO YOUR CODE
if (ch != 'y' && ch != 'Y')
break;
}

Related

How do i append proper input as integers to an array in C, as long the user wishes to?

int main(){
char answer;
int numbers[100];
int i = 0;
int size;
int max = -9999;
do{
printf("Please enter an number: ");
scanf("%d", &numbers[i]);
printf("Would you like to keep adding numbers:(Y/N)");
scanf("%c", &answer);
scanf("%c");
i++;
}while(answer == 'Y');
size = sizeof(numbers)/sizeof(numbers[0]);
for(int j = 0; j<size; j++){
if(numbers[j]>= max){
max = numbers[j];
}
}
printf("The max number is: %d", max);
return 0;
}
Hello beginner in C, here in my code i am trying to take an arbitrary amount of (the user enters Y if he/she wishes to enter another number.) input as integers and add them to an array and find the maximum of the input using a for loop, however i am not getting the correct output. What could be the error in my code?
Problems include:
Reading a '\n' when a letter is expected
scanf("%c", &answer); reads the character after the prior input of a number (example:9), which is likely the prior entry's '\n' Enter.
Use a space to consume leading white-space like '\n', space, tab, ...
// scanf("%c", &answer);
scanf(" %c", &answer);
Enable all warnings
Invalid/unnecessary code scanf("%c"); will raise a compiler warning with a well enabled compiler.
Best advice in this answer: enable all compiler warnings to save time.
Start at INT_MIN
The maximum input may be less than -9999.
INT_MIN in <limits.h>
// int max = -9999;
int max = INT_MIN;
Iterate to i
Rather than iterate to 100, only need to iterate to i, the count of values entered.
// for(int j = 0; j<size; j++){
for(int j = 0; j<i; j++){
Check return values
scanf() returns a value indicated the number of successful conversions. Use it to validated input successfully happened.
// scanf("%d", &numbers[i]);
if (scanf("%d", &numbers[i]) != 1) {
; // Report error with TBD code.
}
Do not loop too often
// } while(answer == 'Y');
} while(answer == 'Y' && i < 100);
There is no reason to save an array of values
The maximum could be calculated as data is entered.
int max = INT_MIN;
do {
int num;
printf("Please enter an number: ");
if (scanf("%d", number) != 1) {
break;
}
if (num > max) {
max = num;
}
printf("Would you like to keep adding numbers:(Y/N)");
if (scanf(" %c", &answer) != 1) {
break;
}
} while (answer == 'Y' || answer == 'y');
printf("The max number is: %d", max);
Future Improvements
Handle values outside int range. Research intmax_t.
Detect case of no valid input entered. Research fgets()
Detect non-valid Y/N input. Research fgets()
Recover, rather than quit loop with invalid input.

Creates an array that stores character by character in c

I'm trying to create an array that allows me to enter the characters depending on the number that the user has previously entered, if I enter 10 I only want the user to enter 10 characters, A or F. The problem is that it does not work as expected, when entering the number it sends me to the while loop and does not let me exit.
#include <stdio.h>
int main() {
int i, students;
char grade[100];
printf("Welcome, enter the number of students to assign school grade: \n");
scanf("%d", &students);
printf("Enter A (Approved) or F (Failure)\n");
for (i = 0; i < students; i++) {
printf("School grade for student %d: \n", i + 1);
scanf("%c", &grade[i]);
while (grade[i] != 'A' || grade[i] != 'F') {
printf("Please enter a valid school grade: ");
scanf("%c", &grade[i]);
}
}
return 0;
}
After I enter the number 10, the program skips the second scanf and sends me into the while loop.
By changing scanf("%c", &grade[i]) into scanf (" %c", &grade[i]), the problem is that now the while loop is held even when I enter A or F.
Logic error. Your loop condition is always true.
while (grade[i] != 'A' || grade[i] != 'F')
If the value is A then it is not F. And vice versa.
It looks like you want:
while (grade[i] != 'A' && grade[i] != 'F')
This would loop while any value that is not A or F is entered. It's logically equivalent to:
while (!(grade[i] == 'A' || grade[i] == 'F'))
Please read De Morgan's laws for more information.

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;
}

C language: The Array did not return a correct value

I have an assignment in C language that requires to ask users to enter values to arrays. My idea is createing two different arrays which one contains integer values and the other holds character values. This is my code so far:
#include <stdio.h>
int main()
{
char continued;
int i = 0;
char instrType[10];
int time[10];
printf("\nL-lock a resource");
printf("\nU-unlock a resource");
printf("\nC-compute");
printf("\nPlease Enter The Instruction Type");
printf(" and Time Input:");
scanf("%c", &instrType[0]);
scanf("%d", &time[0]);
printf("\nContinue? (Y/N) ");
scanf("%s", &continued);
i = i + 1;
while (continued == 'Y' || continued == 'y')
{
printf("\nL-lock a resource");
printf("\nU-unlock a resource");
printf("\nC-compute");
printf("\nPlease Enter The Instruction Type ");
printf("Time Input:");
scanf("%c", &instrType[i]);
scanf("%d", &time[i]);
printf("\nContinue? (Y/N) ");
scanf("%s", &continued);
i = i + 1;
}
return 0;
}
The expected value should be: L1 L2 C3 U1
My Screenshot
The loop just stopped when I tried to enter new values and the condition did not check the value even I entered 'Y' meaning 'yes to continue' please help :(
You are comparing a string with a character that is instead of using scanf("%s",&continued) try using "%c"
The main problem is scanf("%c", &char) because scanf() after had read the input print a \n to pass at the next line, this cause that the next scanf() instead of reading your input, go to read \n, causing the failure in the reading of the input.
To avoid this problem put a space before %c ==> scanf(" %c", &char)
#include <stdio.h>
int main()
{
char continued;
int i = 0;
char instrType[10];
int time[10];
do
{
printf("L-lock a resource\n");
printf("U-unlock a resource\n");
printf("C-compute\n");
printf("Please Enter The Instruction Type and Time Input: ");
scanf(" %c%d", &instrType[i], &time[i]);
printf("Continue? (Y/N) ");
scanf(" %c", &continued);
i++;
} while (continued == 'Y' || continued == 'y');
return 0;
}
Other things:
Instead of i = i + 1 you can use i++
Instead of using a while() is better using a do{...}while() for saving some line of code.
You can concatenate more inputs in a single line ==> scanf(" %c%d", &instrType[i], &time[i])

How to loop a whole codeblock in C?

So basically after the calculation the program prompts the user if they want to quit the program and the user inputs a character ('y' or 'n') and if the user puts a number or letter that is not 'y' or 'n' then the program will keep prompting the user until they input one of the characters.
The issue I'm running into is that the program will keep looping and prompting the user even if 'y' or 'n' is inputted. When I try fflush(stdin) it still doesn't work
I want to know how to loop the statement again if the user does not input one of the options and when they do input it properly, how to get the code inside the "do while" loop to repeat. Preferably without having to copy and paste the whole bloc again.
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <math.h>
int main()
{
float x, t, term = 1 , sum = 1;
int i;
char d;
printf("This program will compute the value of cos x, where x is user input\n\n");
do {
printf("Please input the value of x: ");
while (scanf("%f", &x) != 1)
{
fflush(stdin);
printf("Please input the value of x: ");
scanf("%f", &x);
}
fflush(stdin);
printf("\nPlease input the number of terms: ");
while (scanf("%f", &t) != 1)
{
fflush(stdin);
printf("\nPlease input the number of terms: ");
scanf("%f", &t);
}
fflush(stdin);
for (i=1; i<t+1; i++)
{
term = -term *((x*x)/((2*i)*(2*i-1)));
sum = sum+term;
}
printf("\nThe value of the series is %f", sum);
printf("\n****************************************");
printf("\nDo you wish to quit? (y/n): ");
scanf("%c", &d);
while (d != 'y' || d != 'n')
{
printf("\n****************************************");
printf("\nDo you wish to quit? (y/n): ");
scanf("%c", &d);
}
} while (d == 'n');
if (d == 'y')
{
printf("terminating program");
exit(0);
}
return (0);
}
scanf() will not throw away the newline character '\n' in the input buffer unless your format string is set to discard it. In your code, after entering input for your floats and pressing Enter, the newline is still in the buffer. So for the code that prompts Y\N, use this format string to ignore the newline
scanf(" %c",&d);
You can remove the fflush() calls if you do that. In your case, it looks like your loop conditionals are wrong though.
This line
while (d != 'y' || d != 'n')
is wrong.
Think of it like this:
The loop runs if d is NOT 'y' OR d is NOT 'n'
Now imagine you put in 'y'
d is 'y'. The loop runs if d is NOT 'y' OR d is NOT 'n'. Is d != 'y'? No. Is d != 'n'? Yes. Therefore the loop must run.
You need to use &&
while (d != 'y' && d != 'n')
Also, scanf doesn't throw away the newline so add a space for all your scanfs.
scanf("%c", &d); //change to scanf(" %c", &d);
Look in this part-
while (d != 'y' || d != 'n')
{
printf("\n****************************************");
printf("\nDo you wish to quit? (y/n): ");
scanf("%c", &d);
}
} while (d == 'n');
you are using whiletwice, i think you will wish to have a single while condition over here.. also if you are terminating while, then be sure there is a doinvolved.
Here is code which I think is right since you have many problems so i just have changed a lot :
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <math.h>
int main()
{
float x, t, term = 1 , sum = 1;
int i;
char d;
printf("This program will compute the value of cos x, where x is user input\n\n");
do {
printf("Please input the value of x: ");
while (scanf("%f", &x) != 1)
{
fflush(stdin);
printf("Please input the value of x: ");//delete the repeat scanf
}
fflush(stdin);
printf("\nPlease input the number of terms: ");
while (scanf("%f", &t) != 1)
{
fflush(stdin);
printf("\nPlease input the number of terms: ");
}
fflush(stdin);
sum=0;//no initalization
for (i=1; i<t+1; i++)
{
term = -term *((x*x)/((2*i)*(2*i-1)));
sum = sum+term;
}
printf("\nThe value of the series is %f", sum);
printf("\n****************************************");
printf("\nDo you wish to quit? (y/n): ");
scanf("%c", &d);
while ((d != 'y' )&& (d != 'n'))//this logical expression is the right way
{
scanf("%c", &d);
fflush(stdin);
printf("\n****************************************");//I change the pos of print to avoid double printing
printf("\nDo you wish to quit? (y/n): ");
}
} while (d == 'n');
if (d == 'y')
{
printf("terminating program");
exit(0);
}
return (0);
}
ps:for your calculate part of cos I'm not sure about the correctness while runing:)

Resources