Program not assigning proper values to variables - c

I am new to programming in general, recently decided to get serious about try to learn C. I am trying to build a light account program using nested loops and arrays.
I'm trying to build the program in CodeBlocks. My program is a little rough,
1) my first issue is that after my program asks how many weeks of work has been done, it then has grabs a value for the next loop, ignoring the value of weeks for at least the first loop.
2) Entering any integer other than "1" causes tax to pull a random value from memory, and even worse, it can overwrite the value for "weeks" despite there not being another scanf function for "weeks", often leading to the for...loop depending on the variable weeks to loop well into the millions.
3) I haven't programmed pathways 5 & 6 for void menu() yet due to the rest of the program not functioning properly
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int pay = 10;
const int overtime;
float taxrate;
int hours; //user input for hours worked
int gross; //calculated integer for gross pay
int tax; //calculated integer for taxes
int net; //calculated integer for net pay
int gross_total = 0; //non printed value for summing gross
int i; //condition to exit loop
void tax_rate();
void menu();
void cust_paid_yn();
void hours_worked();
int menu_input;
int menu_break;
char c;
int unpaid;
int weeks;
int j;
int week_numb_array[];
int gross_array[];
int tax_array[];
int gross_total_array[];
void printfinal();
int main(void)
{
menu();
printf("How many weeks have been worked?\n");
scanf("%d\n", &weeks);
for (int j = 0; j <= weeks; j++)
{
while (menu_input = 1 || 2 || 3 || 4)
{
hours_worked();
while ( hours != 1)
{
//uses hours to calculate gross, taxes, and net
gross = (hours * pay);
//use loop and gross to determine tax
tax_rate();
//uses hours to calculate taxes, net, and gross_total
tax = (gross * taxrate);
net = (gross - tax);
gross_total += (net);
gross_array[j] = gross;
tax_array[j] = tax;
gross_total_array[j] = gross_total;
break;
}
printf("\nexited out of menu_input loop\n");
break;
}
printf("\nexited out of tax loop\n");
printf("\n \n %d\n \n", weeks);
printf("\n \n %d\n \n", j);
}
printf("\nexited out of for...loop\n");
j = 0;
printfinal();
return 0;
}
void printfinal()
{
for (j = 0; j <= weeks; j++)
{
//Prints the title headers: gross pay, taxes and net pay
printf("Week Numb\t gross pay \t taxes \t net pay\n");
//Prints the calculations for gross, taxes, and net
printf("week 1\t\t %ld \t\t %ld \t\t %ld \t\n", gross_array[j],
tax_array[j], gross_total_array[j]);
}
return 0;
}
void tax_rate()
{
//use loop and gross to determine tax
if (gross <= 300)
{
taxrate = .15;
}
else if (gross <= 450)
{
taxrate = .20;
}
else if (gross >= 451)
{
taxrate = .25;
}
return 0;
}
void menu()
{
printf("Please make a selection from the following options\n 1) Set Pay
Rate to 8.75\n 2) Set Pay Rate to 9.33\n 3) Set Pay Rate to 10.00\n 4) Set Pay Rate to 11.20\n 5) Print Out List\n 6) Quit\n");
scanf("%d", &menu_input);
switch (menu_input)
{
case 1:
printf("Pay Rate set to 8.75\n");
menu_break = 0;
pay = 8.75;
break;
case 2:
printf("Pay Rate set to 9.33\n");
menu_break = 0;
pay = 9.33;
break;
case 3:
printf("Pay Rate set to 10.00\n");
menu_break = 0;
pay = 10.00;
break;
case 4:
printf("Pay Rate set to 11.20\n");
menu_break = 0;
pay = 11.20;
break;
case 5:
menu_break = 1;
printf("List Printed\n");
break;
case 6:
printf("QUIT\n");
menu_break = 2;
break;
default:
printf("Unknown\n");
menu_break = 3;
break;
}
return 0;
}
void cust_paid_yn()
{
for (i=0; i<1; 1)
{
//get input for whether cust. was paid
printf("Was customer paid this week? (y/n)\n");
scanf("%c", &c);
//loop to check for y/n response
switch (c)
{
case 'y':
printf("\n");
i=1;
hours = (hours + unpaid);
unpaid = 0;
break;
case 'n':
printf("hours logged\n");
i=1;
unpaid = (unpaid + hours);
hours = 0;
break;
default:
printf("\n");
i=0;
break;
}
break;
}
return 0;
}
void hours_worked()
{
//asks how many hours were worked
printf("How many hours were worked?\n \nIf no work was done enter 0\n");
//gets user input for hours worked
scanf("%ld", &hours);
return 0;
}
I just want to create a program that:
1) gets user input for how many time the program will loop (see weeks var)
2) print out user data using an array
Any help and suggestions are greatly appreciated, I'm at my wits end on why my program pulls random values from memory.

Related

Confused with breaks and looping in my program

Use for loops to process the data for 5 employees.
One loop to load the data
One loop to print the output.
In for loops, if any of the entered fields are –1, break out of the loop immediately after getting -1
Update the output as shown in the sample data.
Use arrays to store the user input.
I have a problem with breaking out of the loop. I think the system is reading it as an integer, not a character.
I also have a problem with looping the output. It is not looping the number of times the user has entered the info.
#include <stdio.h>
int main()
{
char name[5][10];
float hourswork[10];
float hourspay[10];
float grosspay[10];
float taxes[10];
float netpay[10];
int i = 0;
for (i = 0; i < 5; i++)
{
printf("Hello, enter your name: \n");
scanf("%s", &name[i][10]);
printf("Enter your hourly wage: \n");
scanf("%f", &hourspay[i]);
printf("Enter the hours you have worked \n");
scanf("%f", &hourswork[i]);
if (hourswork[i] <= 40)
{
grosspay[i] = hourspay[i] * hourswork[i];
}
else if (hourswork[i] > 40)
{
grosspay[i] = (40 * hourspay[i]) + (((hourswork[i] - 40) * 1.5) * hourspay[i]);
}
taxes[i] = grosspay[i] * 0.2;
if (name[i][10] == -1||hourspay[i] == -1||hourswork[i] == -1)
{
break;
}
}
for (i = 0; i < 5; i++)
{
printf("\n%c's Pay:\n", name[i][10]);
printf("Hourly Rate: %.2f\n", hourspay[i]);
printf("Hours Worked: %.2f\n", hourswork[i]);
printf("Gross Pay: %.2f\n", grosspay[i]);
printf("Taxes: %.2f\n", taxes[i]);
netpay[i] = grosspay[i] - taxes[i];
printf("Net Pay: %.2f\n\n", netpay[i]);
}

How to store the users input into an array?

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

for/while loop memory clearing in C

In my program I'm messing around with, it simply asks for how many tests one has written and then returns an average. However I've modified it a bit so that it asks if the marks entered are correct.
Problem 1: It doesn't let you input your marks for all your tests
Problem 2: If the marks are wrong it starts over but keep the previous inputs in it's memory? How do I fix the?
Here's the code:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
//int variables for grade
unsigned int counter; //number of grades to be entered next
int grade;
int total;
float average;
// user input
int userInput; // amount of tests
int yesNo;
//amount of test passed
unsigned int pass = 0;
unsigned int fail = 0;
int doCount = 1;
//unsigned int test;
//---------------------------------------------------------------------------------------------------//
//standards for program to abide to
total = 0; //Total amount of test to be set to zero, until while statement
counter = 1; //Loop counter to start from one
//---------------------------------------------------------------------------------------------------//
printf ("Please enter amount of test you've written so far: ");
scanf ("%d", &userInput);
//printf ("%d", userInput);
//---------------------------------------------------------------------------------------------------//
do {
//Body of calculations of program
for(counter = 0; counter <= userInput; ++counter) { //for loop that correlates to userInput for amount of passes and test marks
printf ("Please enter percentage mark: "); //prompt for test mark
scanf("%d", &grade);
total = total + grade;
counter = counter + 1;
if (grade >= 40) { //if statement for pass or fail
pass = pass + 1;
} else {
fail = fail + 1;
}
}//end of for loop
printf ("Are the grades entered correct? (1 = yes, 2 = no): "); // user input for yesNo - are inputs correct
scanf ("%d", &yesNo);
if (yesNo == 2) {
} else {
average = ((float)total / userInput); //Getting average for tests so far
//if statement to clarify if you're passing
if (average < 40) {
printf ("\nYou are below sub minimum!\n");
printf ("Your overall average is: %.2f %\n", average);
printf ("Passed: %d\n", pass);
printf ("Failed: %d", fail);
} else if (average >= 75){
printf ("\nYou have a distinction agregate!\n");
printf ("Your overall average is: %.2f %\n", average);
printf ("Passed: %d\n", pass);
printf ("Failed: %d", fail);
} else {
printf ("\nYour overall average is: %.2f %\n", average);
printf ("Passed: %d\n", pass);
printf ("Failed: %d", fail);
}
doCount = 2;
}
} while (doCount == 1);
average = ((float)total / userInput); //Getting average for tests so far
//---------------------------------------------------------------------------------------------------//
getch ();
return 0;
}
In your do while loop, when you come around for your second pass you need to reset your variables. Specifically the total variable should be reset to zero. You do it for the first time outside the do while loop but once it's in the loop for the second pass it doesn't get reset to 0.
As for not reading all test inputs, if it asks for 9 but you need 10 then it likely is a problem with the for loop. I typically use counter++ and not ++counter as it increments the counter after the operation and not before the operation. That may or may not be the reason as I did not run your code, but it is worth looking at.
I've edited your code and commented the changes:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
//int variables for grade
unsigned int counter; //number of grades to be entered next
int grade;
int total;
float average;
// user input
int userInput; // amount of tests
int yesNo;
//amount of test passed
unsigned int pass = 0;
unsigned int fail = 0;
int doCount = 1;
//unsigned int test;
//---------------------------------------------------------------------------------------------------//
//standards for program to abide to
total = 0; //Total amount of test to be set to zero, until while statement
counter = 0; //Loop counter to start from zero, It's always better to start from zero
//---------------------------------------------------------------------------------------------------//
printf("Please enter amount of test you've written so far: ");
scanf("%d", &userInput);
//printf ("%d", userInput);
//---------------------------------------------------------------------------------------------------//
do {
//Body of calculations of program
total = 0; //You need to reset total pass and fail
pass = 0;
fail = 0;
for (counter = 0; counter < userInput; ++counter) { //for loop that correlates to userInput for amount of passes and test marks
printf("Please enter percentage mark: "); //prompt for test mark
scanf("%d", &grade);
total = total + grade;
//counter = counter + 1; You DON't need that
if (grade >= 40) { //if statement for pass or fail
pass = pass + 1;
}
else {
fail = fail + 1;
}
}//end of for loop
printf("Are the grades entered correct? (1 = yes, 2 = no): "); // user input for yesNo - are inputs correct
scanf("%d", &yesNo);
if (yesNo == 2) {
}
else {
average = ((float)total / userInput); //Getting average for tests so far
//if statement to clarify if you're passing
if (average < 40) {
printf("\nYou are below sub minimum!\n");
printf("Your overall average is: %.2f %\n", average);
printf("Passed: %d\n", pass);
printf("Failed: %d", fail);
}
else if (average >= 75) {
printf("\nYou have a distinction agregate!\n");
printf("Your overall average is: %.2f %\n", average);
printf("Passed: %d\n", pass);
printf("Failed: %d", fail);
}
else {
printf("\nYour overall average is: %.2f %\n", average);
printf("Passed: %d\n", pass);
printf("Failed: %d", fail);
}
doCount = 2;
}
} while (doCount == 1);
average = ((float)total / userInput); //Getting average for tests so far
//---------------------------------------------------------------------------------------------------//
getch();
return 0;
}

Showing the scores and number of times each score was obtained

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.

Loop with rolling total in c

I am trying to get a c program to ask me how many items i am buying than to ask the price for each item while keeping a rolling total and than ask again in a loop. I have the loop working fine but am having problems getting it to give me proper output.
here is the output i am getting when i run it.
http://i119.photobucket.com/albums/o134/halodude808/assignment2_zpsd46e84b8.jpg
#include <stdio.h>
#include <math.h>
int main(void)
{
//variables used
float penny = .01;
float nickel = .05;
float dime = .1;
float quarter = .25;
int items = 0;
float paid= 0.0;
float total = 0.0;
float price =0.0;
int counter =0.0;
for (;;)
{
printf("Please enter the number of grocery items:");
scanf("%d", &items);
for (counter = 1; counter <= items; counter++)
{
printf("Please enter the price for item #%d:", counter);
scanf("%f", &price);
total += price;
}
printf("items = %d total = %f \n", &items, &total);
getchar();
getchar();
}
}
Change
printf("items = %f total = %f \n", &items, &total);
to
printf("items = %i total = %f \n", items, total);
Also, you might want to consider checking for invalid values (zeroes, negative, characters, etc).

Resources