I have run in to a bug in my code I cannot figure out. I am using an array and a switch statement together. a default is set for if user enters invalid selection, then the program loops back to ask for user input. Following the default selection the data entered by the user is not stored. This is only for the loop immediately after the default selection. Following is the main body of my code
//ask user to enter up to 20 numbers, find the average of the numbers and display average to user
main()
{
double number[SIZE] = { 0 };
int i;
int selection = 0, numCount = 0;
double total = 0, average = 0;
while(selection != 4){
for (i = 0; i <= SIZE; i++)
{
printf("\nPress 1 to enter a number, you may enter up to 20\nPress 2 to display your numbers\nPress 3 to see the average of your numbers\nPress 4 to quit\n");
scanf_s("%i", &selection);
switch (selection) {
case 1:
if (numCount < SIZE) {
//prompt user for input and store data
printf("Please enter your number\n");
scanf_s("%lf", &number[i]);
numCount++;
total += number[i];
}
else
printf("\nThe array is full, choose another selection\n");
break;
case 2:
if (numCount != 0)
{
//displays input back to user
for (i = 0; i < numCount; i++)
printf("%.2lf\t", number[i]);
}
else
printf("You must input at least one number first\n");
break;
case 3:
if (numCount != 0)
{
//calculates average of only numbers entered into the array by the user
average = total / numCount;
printf("The average of your numbers is %.2lf\n", average);
break;
}
else
printf("You must input at least one number first\n");
case 4:
{
printf("Thank you\n\n");
return;
}
default:
{
printf("This is not a valid selection, please try again\n\n");
break;
}
}
}
}
}
Related
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 know from my code it's a bit of a mess as I'm a beginner to programming. I just wanted to see if someone could just quickly help me out by letting me know how to get the users input stored into an array and do what my code already does. So, I want the user to input the amount of tickets and then that gets stored in an array then printed like my code already does. Just want to try and cut down my code as it is very messy and need to store it in an array I've been told but I'm stumped at the moment.
#include <stdio.h>
#include<conio.h>
#include<stdbool.h>
#define MAX 10
void showPrices();
void showRoutes();
void orderTickets();
void main()
{
int userChoice;
while(1)
{
// Looping the menu for the user
printf("\n\n**** MENU ****");
printf("\n*NOTE* MAX TICKETS PER CUSTOMER = 10");
printf("\n1. Show Prices\n2. Show Routes\n3. Order Tickets\n4. Exit");
printf("\nEnter your choice: ");
scanf("%d", &userChoice);
//gets to chose between the different options
switch(userChoice)
{
case 1: showPrices();
break;
case 2: showRoutes();
break;
case 3: orderTickets();
break;
case 4: exit(0);
default: printf("\nInvalid, try again!!!");
}
}
}
void showPrices()
{
//for the switch statement, this is what I want to be displayed when they pick this option
printf("\n\n---- Prices - ALL DAY ----");
printf("\n1. Child = £3\n2. Teenager = £5\n3. Standard = £10\n4. Student = £7\n5. Senior = £6");
}
void showRoutes()
{
//for the switch statement, this is what I want to be displayed when they pick this option
printf("\n\n---- Routes - ALL DAY ----");
printf("\n---- Leaving from Nottingham Station ----");
printf("\nDestinations:\nDerby\nLeicester\nSheffield\nBirmingham");
}
void orderTickets()
{
int ticketArray[tickets];
int age;
int userInput = 0;
int tickets;
int ticketSum = 0;
int ticketNumber = 1;
int sum;
int userDesti;
//Main function where the user oders the tickets!
printf("\nWhere do you want to go?");
printf("\n1. Derby\n2. Leicester\n3. Sheffield\n4. Birmingham");
scanf("%d", &userDesti);
//asks the user how many tickets they want
printf ("\nHow many tickets do you need?: ");
scanf ("%d", &tickets);
//loop to keep asking the user to input the information they need to enter for each ticket until it reaches 0
while (tickets > 0)
{
/*only does this if they enter 10 or less and more than 0
if (tickets <= 10 && tickets > 0)
{
printf("\nHow old are you?: ");
scanf("%d", &age);
if(age < 10)
{
printf("\nChild Ticket = £3\n");
ticketSum = ticketSum + 3;
}
else if (age < 16)
{
printf ("\nTeenager Ticket = £5\n");
ticketSum = ticketSum + 5;
}
else if (age >= 16 && age < 60)
{
printf("\nStandard Ticket = £10\n");
ticketSum = ticketSum + 10;
}
else
{
printf("\nSenior Ticket = £6\n");
ticketSum = ticketSum + 6;
}
}
//if they enter an invalid number
else
{
printf("Error, invalid number of tickets!!\n");
break;
}*/
// this allows the student discount to be deducted from the final price
printf("\nAre you a student? Enter 1 for yes or 2 for no: ");
scanf("%i", &userInput);
if(userInput == 1)
{
printf ("\nYou are eligible for the student discount = £3 deducted\n");
//sum to deduct the discount
ticketSum = ticketSum - 3;
}
//if they aren't a student then they will get this message
else if (userInput == 2)
{
printf ("\nYou are not eligible for the student discount, sorry!\n");
}
// gives the user their number for that ticket
printf("\n------------------");
printf("\nTicket Number: %d ", ticketNumber);
printf("\n------------------\n");
ticketNumber++;
// lets the user know how much each ticket adds onto the previous
printf("\n-----------------------");
printf("\nThe summary so far: %d ", ticketSum);
printf("\n-----------------------\n");
// gets out of the main loop when the tickets are less than or equal to 0
if (tickets <= 0 )
{
break;
}
//takes away the value of tickets each time so if they want 2 tickets then it takes away 1 so then it equals 1 left umtil it reaches 0
tickets--;
}
//the receipt of all the tickets added together.
printf("\n-----------------------------------");
printf("\n-----------------------------------");
printf("\nThe receipt for your order: £%d", ticketSum);
printf("\n-----------------------------------");
printf("\n-----------------------------------");
}
This is just a function from my program that is supposed to search for the string or integer the user enters in the struct array. What I'm trying to do is add an error message and the ability to try again when that entered string or integer is not found in the struct array. It searches just fine if you enter the correct string or integer but nothing happens if you don't. I'm trying to change that but can't find the solution.
I've tried for a while now with one of the cases in my switch statement but I need to do it for all three. But so far I've only tried on case 3.
search(struct items aItems[], int *num_items)
{
int choice_of_search, b=0, found_word=0, search_num, i=0, j=0, k=0;
char search_phrase[20]; struct items search[MAX];
printf("Choose what to search for? (1) Item number, (2) Name and (3) Balance. ");
scanf("%d", &choice_of_search);
while(choice_of_search < 1 || choice_of_search > 3)
{
printf("Wrong choice!\n");
printf("Choose what to search for? (1) Item number, (2) Name and (3) Balance. ");
scanf("%d", &choice_of_search);
}
switch(choice_of_search)
{
case 1:
printf("Item number?\n");
scanf("%d", &search_num);
for(i = 0; i < *num_items; i++)
{
if(search_num == aItems[i].itemnumber)
{
printf("Item number found!\n");
search[found_word]=aItems[i];
found_word+=1;
}
}
break;
case 2:
printf("Name?\n");
scanf("%s", search_phrase);
for(i = 0; i < *num_items; i++)
{
if(strstr(aItems[i].name, search_phrase))
{
printf("Name found!\n");
search[found_word]=aItems[i];
found_word+=1;
}
}
break;
case 3:
printf("Balance?\n");
scanf("%d", &search_num);
for(i = 0; i < *num_items; i++)
{
if(search_num == aItems[i].balance)
{
printf("Balance found!\n");
search[found_word]=aItems[i];
found_word+=1;
}
else
{
printf("Balance not found! Try again.\n");
printf("Balance?\n");
scanf("%d", &search_num);
}
}
break;
}
while(b < found_word)
{
printf("Item number: %d Name: %s Balance: %d\n", search[b].itemnumber, search[b].name, search[b].balance);
b++;
}
}
Maybe this can help
int done;
...
...
case 3:
done = 0;
while(1);
{
printf("Balance?\n");
scanf("%d", &search_num);
for(i = 0; i < *num_items; i++)
{
if(search_num == aItems[i].balance)
{
printf("Balance found!\n");
search[found_word]=aItems[i];
found_word+=1;
done = 1;
}
}
if (done) break;
printf("Balance not found! Try again.\n");
}
break;
But notice that the code isn't user friendly as it doesn't allow the user a way to stop the search without a match. So maybe you should consider adding a "Would you like try again" option.
A simple approach could be
printf("Balance not found! Would like to try again?.\n");
scanf(" %c", &some_char);
if (some_char != 'y') break;
my name is Adriel, am new to the site and programming. Anyways I need some help and guidance with my assignment. I am to create a program in C that will allow the user to enter up to 5000 exam scores. Then give the user 5 options that are to get the average grade, show all exams from high to low, curve the exams up by 5 or down by 5 AND the one that I can't do is to display the scores and how many times they were obtained.
this is my code:
main() {
//Declared variables
char choice;
int i, j, a, n;
int examScore = 0, HIGH = 0, LOW = 0, AVG = 0, count = 0, sum = 0, scoreCount = 0;
int highlow[5000], highExam, lowExam;
do{//Begin do while #1
CLS;
FLUSH;
printf("=========================\n");
printf("===== Score program =====\n");
printf("=========================\n");
printf("A. Exam scores\n");
printf("B. Exams average\n");
printf("C. Exam score High - Low\n");
printf("D. Times scores obtained\n");
printf("E. Curved up 5 pts\n");
printf("F. Curved down 5 pts\n");
printf("Q. Exit program\n");
printf("=========================\n");
printf("Enter your choice: ");
scanf(" %c", &choice);
choice = toupper(choice);
switch (choice){//Begin switch
case 'A':
CLS;
printf("Please Enter The Number of exams:\n");
scanf("%d", &n);
printf("Please Enter %d Numbers\n", n);
for (i = 0; i < n; i++){
scanf("%d", &highlow[i]);
}//end for loop
highlow[examScore];
count++;
sum = sum + examScore;
AVG = sum / count;
highExam = examScore + 5;
lowExam = examScore - 5;
CLS;
for (i = 0; i < n; i++)
{
for (j = i + 1; j<n; ++j)
{
if (highlow[i]<highlow[j])
{
a = highlow[i];
highlow[i] = highlow[j];
highlow[j] = a;
}
}
}
PAUSE;
break;
case 'B':
CLS;
printf("Exam average is: %i\n", AVG);
PAUSE;
break;
case 'C':
CLS;
printf("The numbers arranged in descending order are given below\n");
for (i = 0; i < n; ++i)
{
printf("%i\n", highlow[i]);
}
PAUSE;
break;
case 'D':
CLS;
printf("Amount of times scored was obtained: %i-%i\n", examScore, count);
PAUSE;
break;
case 'E':
CLS;
// printf("Exam scores curved up by 5 pts: %i\n", highExam);
PAUSE;
break;
case 'F':
CLS;
// printf("Exam scores curved down by 5 pts: %i\n", lowExam);
PAUSE;
break;
case 'Q':
CLS;
printf("Quitting program. Goodbye.\n");
PAUSE;
break;
default:
printf("- Invalid entry -\n");
PAUSE;
break;
}//End switch
} while (choice != 'Q');//End do while #1
}//End main
As you may see am still far from done, but the other parts are not a big concern to me. Any help and advice would be very appreciate.
Why is it so difficult to count the number of times each score is in your highlow array?
I was thinking of a different approach until I noticed that you had a sorted array of the scores, so any duplicate scores will be adjacent to each other. It should be easy enough to look at the value of highlow[0] and then compare that to highlow[1] to see if highlow[0] is duplicated. You just do that until you find that the next isn't a duplicate, then you start looking for duplicates of the next number.
int a = 1;
printf("Enter the number of items from 1 and 10: \n");
while (a <= 10)
{
scanf("%d", &a);
if (a >= 1 && a <= 10)
{
printf("Thank You!\n");
break;
}
else
{
printf("Wrong input! Try Again.\n");
continue;
}
}
To be more detailed about what I'm asking lets say that the user enters 3 (for 3 items) how would I use the for loop to retrieve that information so I can further finish the code.
You should keep in mind following points:
Get the no.of choice before starting loop
Check the condition in loop with no. of choices.
Only one loop is enough for your task.
I think you need this:
int a = 1;
bool bFlag = true;
int price[10];
printf("Enter the number of items from 1 and 10: \n");
while(bFlag){
scanf("%d", &a);
if (a >= 1 && a <= 10)
{
printf("Thank You!\n");
break;
}
else
{
printf("Wrong input! Try Again.\n");
continue;
}
}
for (int i = 0; i< a; i++)
{
printf("Enter price for item %d = ", i);
scanf("%d",&price[i]);
}