I've been stumped for the past few days trying to modify my current code to be able to input an undetermined number of students.
#include <stdio.h>
int main(void)
{
char StudentName[100];
float ExamValue, Sum, Avg;
int students, exams;
for (students = 0; students < 5; students++)
{
Sum = 0.0;
printf("Enter Student Name \n");
scanf("%s", StudentName);
for (exams = 0; exams < 3; exams++)
{
printf ("Enter exam grade: \n");
scanf("%f", &ExamValue);
Sum += ExamValue;
}
Avg = Sum / 3.0;
printf("Average for %s is %f\n", StudentName, Avg);
}
return 0;
}
As it is now, I have to manually input the amount of students. Does anyone know how I can modify this code in order to enter an undetermined amount of students? I'm starting to think that it is impossible to do and maintain the integrity of the rest of the code. Any help is greatly appreciated, thanks!
You can do something like while (stillAdding) instead of the for loop, and prompt the user with Enter student name or QUIT to stop, or even Would you like to enter a new student [Y/n]. You'd modify the stillAdding variable accordingly. In short, you leave it up to the user to specify when they want to stop inputting more data.
You can ask for the number of users before the for and then use that number as upper bounds of the for. Something like this:
int students, exams, nr;
printf("Enter Student Number \n");
scanf("%d", &nr);
for (students = 0; students < nr; students++)
{
//your code
}
You can ask the user whether there are more students per loop:
#include <stdio.h>
int main(void)
{
char StudentName[100];
float ExamValue, Sum, Avg;
int students, exams;
char stop;
for (;;)
{
Sum = 0.0;
printf("Enter Student Name \n");
scanf(" %s", StudentName);
for (exams = 0; exams < 3; exams++)
{
printf ("Enter exam grade: \n");
scanf("%f", &ExamValue);
Sum += ExamValue;
}
Avg = Sum / 3.0;
printf("Average for %s is %f\n", StudentName, Avg);
puts("More students?(Y/N)");
scanf("%*[^yYnN]%c%*[^\n]%*c", &stop); // read one of 'y', 'Y', 'n', 'N', then discard that line, including '\n'.
if (stop == 'N' || stop == 'n')
break;
}
return 0;
}
You can prompt the user to supply the number of inputs. Once the user tells you how many inputs will be given, then you can simply use a for loop to read that many inputs
Related
I am required to create a function that uses arrays and a menu system that displays:
the sum of all numbers entered, the average of numbers entered, and all numbers entered. It will allow the user to enter up to 1000 numbers.
I have the majority of the code working, I just need to figure out how to display all of the numbers a user has entered so far. Would anyone be able to help me with this? Thanks!
I've tried displaying the number entered, but this does not fit the assignment requirements.
Here is the code I have so far:
/*
Title: Array Intro
Author: James Henderson
Desc: a program designed to display the sume, average, and all previous numbers entered of user input numbers
Date: 11/06/19
*/
#include <stdio.h>
#include <math.h>
//Create Variables
//used for math
int counter = 0;
float number, sum = 0.0, average;
//user input number
int userInt;
int userInput[1000];
//Void Function
static void sumFunction(userInput)
{
printf("\n\tWelcome!\n");
printf("Enter 1 to begin:\n");
scanf("%i", &userInput);
//switch statement
while (1)
{
switch (userInput)
{
case 1:
printf("\nEnter a number:\n");
while (1)
{
scanf("%i", &userInput);
//determine sum
number = userInput;
sum += number;
counter++;
average = sum / counter;
printf("\n The average of the numbers is %.2f", average);
printf("\n The sum of the numbers is %.2lf", sum);
printf("\n You may enter up to 1000 numbers");
printf("\n You have entered %d numbers\n", counter);
if (counter == 1000)
{
printf("\nThank you for using my program! Have a lovely day :)");
return;
}
}
}
}
}
Your approach was right, just look how i used userInput. Below code works fine:
#include <stdio.h>
#include <math.h>
//Create Variables
//used for math
int counter = 0;
float number, sum = 0.0, average;
//user input number
int userInt;
int userInput[1000];
//Void Function
static void sumFunction()
{
printf("\n\tWelcome!\n");
printf("Enter 1 to begin:\n");
scanf("%i", &userInt);
//switch statement
while (1)
{
switch (userInt)
{
case 1:
printf("\nEnter a number:\n");
while (1)
{
scanf("%i", &userInput[counter]);
//determine sum
number = userInput[counter];
sum += number;
counter++;
average = sum / counter;
printf("\n The average of the numbers is %.2f", average);
printf("\n The sum of the numbers is %.2lf", sum);
printf("\n You may enter up to 1000 numbers");
printf("\n You have entered %d numbers\n", counter);
// number entered so far
printf("\n The list of numbers entered so far : \n");
for(int i=0;i<counter;i++){
printf(" %d ",userInput[i]);
}
printf("\n");
if (counter == 1000)
{
printf("\nThank you for using my program! Have a lovely day :)");
return;
}
}
}
}
}
int main(){
sumFunction();
}
Whenever I run this I got something like ' 196875307' as the total, could
someone tell me whats wrong with it.Here I uploaded the whole code.It says my post is mostly code and to add more details,So forgive me for typing these unnecessory things XD
#include <stdio.h>
int room;
char name[20];
int i;
void main()
{
int answr,fc[6],z=0,tot;
char ans;
char food[8][30]={"Bread","Noodles","Salad","Popcorn","Chocolate ice
cream","Vanilla ice cream","Cold Coffee","Milk Shake"};
int price[8]={180,120,65,55,70,70,110,200};
printf("\n *********");
printf("\n MENU CARD");
printf("\n *********\n\n\n\n");
printf("\n Food Code\t\tprice\t\t Food Name\n");
for(i=0;i<8;i++)
{
printf("\n\t\t%d",i+1);
printf("\t\t%d",price[i]);
printf("\t\t%s",food[i]);
}
printf("\n\n\n\t *PRESS 0 TO GO TO THE MAIN MENU\n\t *PRESS 1 TO ORDER
FOOD");
scanf(" %d",&answr);
switch(answr)
{
case 0:
{
printf("Enter the main menu function here");
break;
}
case 1:do
{
printf("ENTER THE FOOD CODE YOU WANT TO HAVE :: ");
scanf(" %d",&fc[z]);
z++;
tot=tot+fc[z];
printf("total so far is %d",tot);
printf("DO YOU WANT MORE(Y/N) ::");
scanf(" %c",&ans);
}while((ans=='y')||(ans=='Y'));
printf("\nEnter your room number:");
scanf(" %d",&room);
printf("\nEnter your name:");
scanf(" %s",&name);
}
}
The issue lies in your do loop. You need to initialize tot to 0, and use the user-inputted "food code" as an array index into your price array. I don't see any use for the "fc" array you've declared. This code should work for case 1 in your switch statement.
Remember that the main function returns an int in C.
do {
tot = 0;
printf("ENTER THE FOOD CODE YOU WANT TO HAVE :: ");
scanf("%d", &z);
if (z < 1 || z > 8) {
printf("Invalid food code\n");
return -1; // main should return int in a C program
}
tot=tot+price[z-1];
printf("total so far is %d\n",tot);
printf("DO YOU WANT MORE(Y/N) ::");
scanf(" %c",&ans);
} while((ans=='y')||(ans=='Y'));
I think that you should increment your counter z after you do the addition of the total with your freshly added element into the array.
1)Get the value by scanf
2)add it by using vet[z]
3)increment z.
When your code hit the sum it will try to access to a segment of memory that is filled with some other values.
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;
}
So I got some awesome assistance the other day with a C code problem, hoping this one can generate similar responses. First task is to write a code to accept an unknown number of names. Second is to allow input of an unknown number of values (grades) for each name, and each set of values is averaged and printed with the name. There is a similar thread i read and found some inspiration, but it still isn't compiling right.
I am not married to any particular part of this code, but I was trying to keep it simple with nested Do...while loops. I have tried several different approaches, all fall short of elegantly expressing the unknown number of values assigned to an unknown number of people.
My hope is that the user will be prompted to enter a name, then as long as that value isnt nulled out, the user is immediately prompted to enter grade values that are tabulated in a running total. When the value of grade goes null, the loop quits and the sum total is averaged. The name and average are printed together until the name value is null and then the sub quits. Greatly appreciate any input from the community.
#include <stdio.h>
#include <math.h>
int main(){
char b, stu_name;
float grade, sum, avg;
int i,counter;
do{
printf("Enter a student's name? \n");
scanf("%s", &stu_name);
do{
printf("How many grades are to be entered for this student? \n");
scanf("%d", &i);
for (counter = 0; counter < i; counter++) {
printf("Enter %s's grade, hit enter and enter another \n");
scanf("%f", &grade);
sum = sum + grade;
} while (grade != '\0');
avg = sum/i;
printf("GPA for %s is %f\n", stu_name,avg);
printf("Press any key to enter another student");
scanf("%c",b);
}while (b != '\0');
return(0);}
You're missing the ending brace on the for loop, as Helio Santos pointed out.
You're also having various syntax-type problems:
For the "Enter grade" prompt, you need a %c not a %s as you only
defined stu_name as a char not a char[]
The end of the interior Do/While loop should be checking against i, not grade
That check should also be against a value that scanf could return in your setup; the %d will force trying to get a numeric value
Bam! Compilation success. Thanks much, I appreciate the help. Doesn't look like i can test it fully (notice the whacked out GPA down below) because i don't know how use this online compiler to add a grade more than once (in the loop). If anyone knows whats going on with the GPA stdout i am all ears, going to the next step of the assignment with this code.
*edit after some more comments. Currently rockin the below code. It works...but only 3-4 times for some reason.
#include <stdio.h>
#include <math.h>
int main(){
char b;
char stu_name[75];
float grade, sum, avg;
int i,counter;
do{
printf("Enter a student's name? \n");
scanf("%s", stu_name);
b = '\0'
i = 0;
sum = 0;
printf("How many grades are to be entered for this student? \n");
scanf("%d", &i);
for (counter = 0; counter < i; counter++) {
printf("Enter %s's grade, hit enter and input another \n",stu_name);
scanf("%f", &grade);
sum = sum + grade;}
avg = sum/i;
printf("GPA for %s is %f\n", stu_name,avg);
stu_name[0]= '\0';
printf("Type q or Q to quit or enter to input another student \n");
scanf(" %c", &b);
} while (b != 'q' && b!='Q');
return(0);}
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).