C Code; nested do while loops with inputs - c

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

Related

Program is not printing completely

I'm trying programming 1st time and not getting the output of this program.Though it looks simple but the code doesn't prints after taking the input like name, roll, marks obtained by student.
I have attached the screenshot of compiler.
Thank you!
#include<stdio.h>
int main()
{
int roll,phy,che,ca,total;
float percentage;
char name[20];
printf("enter the name of student: "); //studentname
scanf("%s",&name);
printf("enter the roll number: "); //roll number
scanf("%d",&roll);
printf("enter the marks obtained in phy,che,ca: "); //marks obtained/subject
scanf("%d%d%d ",&phy,&che,&ca);
//doesnt works from here.
total= (phy+che+ca); //calculating total marks
printf("the total marks obtained is %d\n",total);
percentage =total/3.0; //calculating percentage student got.
printf("the total percentage obtained is %d\n",percentage);
if(percentage>=80)
printf("first division\n"); //first division
else if(percentage>=60 && percentage<=80)
printf("second division\n"); //second division
else if(percentage>=60)
printf("third divison\n"); //third division
else if(percentage>=10)
printf("you failed!\n"); //failed
else
printf("invalid input\n"); //invalid input
return 0;
}
screenshot of the compiler
scanf("%d%d%d ",&phy,&che,&ca);
There is an extra blank character in format. So you should input a more character after you input 3 integers.
And you shouldn't use %d to print a float type variable, you should use %f.

Print out isn't working when I enter value to exit program

I am still new to C programming and need to figure out why when I enter the "c" choice the program isn't printing out the grades entered in the program. I am not seeing what I am missing, can someone let me know if they see what I am missing please?
#include <stdio.h>
#include <stdlib.h>
int main()
{
//Add all of the variables and the array for the grades I want to enter.
char choice;
int gradeScore = 0;//percentage
//int gradeArray[100];//percentArrray //Comment Out
int gCount = 0,i;//count
//Allocate dynamic memory point using gradeArray.
int *gradeArray = (int*)malloc(sizeof(int));
/*The for loop is set to enable the user to enter no more than 100 grades. This is because the gradeArray variable
limit is set to 100. This will then loop through until the user has entered up to 100 grades to ensure there
is no buffering issue.*/
for (gCount = 0; gCount < 100;)
{
/*This prompts the user for a choice that enables them to either enter another grade or exit the program and
print the grades. It also reads the choice entered by the user.*/
printf("******************Enter Choice Selection in Parenthesis******************");
printf("\n\n To add grades, enter choice (a)");
printf("\n When finished entering grades, enter choice (c) \n \nEnter Choice: ");
scanf(" %c", &choice); //space is entered to ensure the compiler does not read whitespaces
/* Then I use an if with the condition set to a valid choice of 'a'. Then I prompt the user
to enter a grade, read it and move on to the next if statement.*/
if(choice == 'a')
{
printf("\nEnter grade: ");
scanf(" %d", &gradeScore);
/*If the grade entered does meet the if condition statement below it is added to the gCount
of grades entered. This will allow all of the grades entered to be printed with the exit condition.*/
if(gradeScore <= 100 && gradeScore >= 0)
{
gradeArray = realloc(gradeArray, sizeof(int) * gCount);
}
}
//The last if statement prints out each grade on a new line when the user choice is c.
if(choice == 'c')
{
break;
}
}
printf("Grades are:\n");
for(i = 0; i < gCount ; i++)
{
printf(" %d\%%\n", gradeArray[i]);
}
free(gradeArray);
return 0;
}
Thank you,
Annette
You are using wrong variable inside for loop according to your program. You are re-initialising gCount to 0 in for loop and not incrementing it. Later you are using same gCount to print grades. But since its value is 0 so no grades are printed.
Problem is that you never increased the value of a gCount variable, and for() loop is wrong too, I would recommend using while() here, also you never added gradeScore to gradeArray. You could write something like this:
#include <stdio.h>
#include <stdlib.h>
int main()
{
//Add all of the variables and the array for the grades I want to enter.
char choice;
int gradeScore = 0;//percentage
//int gradeArray[100];//percentArrray //Comment Out
int gCount = 0,i;//count
//Allocate dynamic memory point using gradeArray.
int arr_size = 20;
int *gradeArray = malloc(sizeof(int)*arr_size);
/*The for loop is set to enable the user to enter no more than 100 grades. This is because the gradeArray variable
limit is set to 100. This will then loop through until the user has entered up to 100 grades to ensure there
is no buffering issue.*/
while(gCount < 100)
{
/*This prompts the user for a choice that enables them to either enter another grade or exit the program and
print the grades. It also reads the choice entered by the user.*/
printf("******************Enter Choice Selection in Parenthesis******************");
printf("\n\n To add grades, enter choice (a)");
printf("\n When finished entering grades, enter choice (c) \n \nEnter Choice: ");
scanf(" %c", &choice); //space is entered to ensure the compiler does not read whitespaces
/* Then I use an if with the condition set to a valid choice of 'a'. Then I prompt the user
to enter a grade, read it and move on to the next if statement.*/
if(choice == 'a')
{
printf("\nEnter grade: ");
scanf(" %d", &gradeArray[gCount]);
/*If the grade entered does meet the if condition statement below it is added to the gCount
of grades entered. This will allow all of the grades entered to be printed with the exit condition.*/
if((gCount+1) == arr_size)
{
arr_size += 20;
gradeArray = realloc(gradeArray, sizeof(int) * arr_size);
}
gCount++;
}
//The last if statement prints out each grade on a new line when the user choice is c.
if(choice == 'c')
{
break;
}
}
printf("Grades are:\n");
for(i = 0; i < gCount ; i++)
{
printf(" %d\%%\n", gradeArray[i]);
}
free(gradeArray);
return 0;
}
Also, I want to point out that you shouldn't allocate array with just one element and constantly reallocate it. It is a bad practice, time-consuming, and can lead to some bigger problems later.
I recommend you to check this Do I cast the result of malloc? for malloc casting.

Can someone explain me whats wrong with finding total part in this code

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.

How do I get multiple lines to print after ending this logical loop

Me again. The C rookie. I am working on an assignment to write a program that prompts a user to enter info after which the program should list back out the data that was entered. My code only prints the last record info that is entered.
For example, I enter the following info for employee #1 "Rookie Coder" as the first employee name and enter 25 and 40 for hourly wage and hours worked, respectively. Then, I enter the following info for employee #2 "Slow Learner" as the 2nd employee name and enter 20 and 45 for hourly wage and hours worked, respectively. The program only prints the info related to "Slow Learner". But I want to print out the info for both records entered.
Can someone please offer guidance on what I'm missing to get both records to print? Thank you from the C Rookie
// C Libraries Used
#include <stdio.h>
#include <math.h>
#include <string.h>
// Constant declerations
const float OTPAYFACTOR = 1.5;
FILE *userinputfile; //disk file (for input)
// Variable declerations
char deptname [21];
char firstname [10];
char lastname [10];
char fullname [21];
float hrsworked;
float hrwage;
int count;
char again;
// Function Prototypes
// M A I N F U N C T I O N
int main (void){
printf("Mountain Pacific Corporation\nDepartment Salary Program\n\n");
printf("Please enter the name of the department: ");
scanf("%s", &deptname);
count = 0; // Initialize this "counting" variable to zero to start
printf("\n");
count = 0; // Initialize this "counting" variable to zero to start
printf("\n");
do {
count++; // Increment the counting variable
printf("Enter employee #%d: ", count);
scanf("%s %s", &firstname, &lastname);
strcpy(fullname, firstname);
strcat(fullname, " ");
strcat(fullname, lastname);
printf("Enter the hourly wage of %s: ", fullname);
scanf("%f", &hrwage);
printf("Enter total number of hours: ");
scanf("%f", &hrsworked);
printf("\nThank you. Process another employee? ");
scanf ("%s", &again);
printf("\n");
} while (again != 'N' && again != 'n');
printf("End of processing.");
printf("%s, $%0.2f, %0.2f: \n", fullname, hrwage, hrsworked);
return 0;
}
You only have one set of variables that you use on each iteration of the loop. Anything stored the first time through the loop is overwritten the second time through the loop. So you'll only ever store the most recently entered set of values.
You want to declare each of the variables that are taking data as an array, that way you can save multiple values.
char deptname [5][21];
char firstname [5][10];
char lastname [5][10];
char fullname [5][21];
float hrsworked[5];
float hrwage[5];
...
do {
printf("Enter employee #%d: ", count+1);
scanf("%s %s", &firstname[count], &lastname[count]);
strcpy(fullname[count], firstname[count]);
strcat(fullname[count], " ");
strcat(fullname[count], lastname[count]);
printf("Enter the hourly wage of %s: ", fullname[count]);
scanf("%f", &hrwage[count]);
printf("Enter total number of hours: ");
scanf("%f", &hrsworked[count]);
printf("\nThank you. Process another employee? ");
scanf ("%s", &again);
printf("\n");
count++; // Increment the counting variable
} while (again != 'N' && again != 'n');
Then you need to loop through the array to print each element:
int i;
for (i=0; i<count; i++) {
printf("%s, $%0.2f, %0.2f: \n", fullname[i], hrwage[i], hrsworked[i]);
}
:) naive from your side but don't worry. You are storing only the last data into the fullname, hrwage, hrsworked, so only the last output is saved there. You need a better data structure to store the data as they are inserted by user.
1) If you know how many inputs there will be you can use a predefined array of strings for strings for the name and floats for the hours and wage.
2) if you don't know then you will need an scaling data structure like for example a list in order to put/add/append elements to it ;)
for C Arrays check this and for Lists in C check this
Then last but not least after you fill them with the input you just need to loop with a for / while loop in order to print the array or list.
Hope this will help!
remove the & symbol from below statement because deptname itself is string
scanf("%s", &deptname);
do same from below statements also
scanf("%s %s", &firstname, &lastname);
you want to print all records but at last there is only one printf so obviously it prints only last employee records
printf("%s, $%0.2f, %0.2f: \n", fullname, hrwage, hrsworked);
if you wants to prints all employee data after giving 'N' option, you should store information before that, my suggestion is put all entries inside structure and then take array of structure and store every time.

C loop with undetermined number

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

Resources