i made this program and its working just how i want but it should stop when i type x but it doesn't
can any one tell me why?
and if there is any shortcut or smaller way to type this code?
thanks in advance.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int meat[6];
int i;
int total =0;
int avg;
char what[20];
char end;
int days = 0;
char food[20];
char drink[20];
printf("what thing do u want to calculate the average of?(food/drink)\n");
scanf(" %s", &what);
if(strcmp(what, "food")==0)
{
printf("what sort of food did u ate ?\n");
scanf(" %s", food);
}
if(strcmp(what, "drink")==0)
{
printf("what sort of drink did u drank ?\n");
scanf(" %s", drink);
}
for(i=0; i<6; i++)
{
days++;
if(strcmp(what, "food")==0)
{
printf("how many %s did u ate in day %d\n", food, i+1);
}
else if(strcmp(what, "drink")==0)
{
printf("how many liters of %s did u drank in day %d\n", drink, i+1);
}
scanf(" %d", &meat[i]);
total += meat[i];
printf("if u want to continue type y\n");
printf("type x if u want to finish\n");
scanf(" %c", &end);
if((end = 'y')&&(i<5))
{
continue;
}
else if(end = 'x' && strcmp(what, "drink")==0)
{
avg = total / days;
printf("\nyour average amount of liters of %s you had %d\t the total is %d\n", drink, avg, total);
}
else if(end = 'x' && strcmp(what, "food")==0)
{
avg = total / days;
printf("\nyour average amount of %s you had %d\t the total is %d\n", food, avg, total);
}
break;
}
if(strcmp(what, food)==0)
{
printf("\nyour average amount of %s you had is %d\t the total is %d\n", food, avg, total);
}
else if(strcmp(what, drink)==0)
{
printf("\nyour average amount of liters of %s you had is %d\t the total is %d\n", drink, avg, total);
}
return 0;
}
else if(end = 'x' ...
should be:
else if(end == 'x' ...
You use == to test equality in if statements. You've got this in a couple places in your code, which is inadvertently performing an assignment, not what you want to achieve by comparing if user input is equal to a particular character.
Replace the = with == here:
else if(end = 'x' && strcmp(what, "drink")==0)
here:
else if(end = 'x' && strcmp(what, "food")==0)
and here:
if((end = 'y')&&(i<5))
Related
How to make monthly and yearly calculations from a txt file in C language? I'm trying to make a C language read and write program, but I'm confused about how to perform operations from it. I'm confused, please help me
This is an example of a txt file that was written
Jaka 2022 12 10 50000
Juki 2020 10 12 750000
Jaka 12 10 10 4000
And here's the code that I made, it's still limited to calculating all total expenses, I can't calculate monthly and yearly.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
void input();
void count();
void monthly_expenditure();
int main()
{
int choice;
do
{
printf("====================================MENU====================================\n");
printf("1. Input Data\n");
printf("2. count expenditure\n");
printf("3. monthly expenditure\n");
printf("4. exit\n");
printf("choice : ");
scanf("%d", &choice);
switch (choice)
{
case 1:
input();
getchar();
break;
case 2:
count();
getchar();
break;
case 3:
monthly_expenditure();
getchar();
break;
case 4:
printf("thank you\n");
getchar();
break;
default:
printf("error\n");
break;
}
} while (choice != 4);
return 0;
}
void input()
{
FILE *fp;
char name[100], year[100], month[100], date[100], money[100];
fp = fopen("data.txt", "a");
printf("Input name : ");
scanf("%s", name);
printf("Input year : ");
scanf("%s", year);
printf("Input month : ");
scanf("%s", month);
printf("Input date : ");
scanf("%s", date);
printf("Input money : ");
scanf("%s", money);
fprintf(fp, "%s %s %s %s %s\n", name, year, month, date, money);
fclose(fp);
}
void count()
{
FILE *fp;
char name[100], year[100], month[100], date[100], money[100];
int total = 0;
fp = fopen("data.txt", "r");
while (fscanf(fp, "%s %s %s %s %s", name, year, month, date, money) != EOF)
{
total += atoi(money);
}
printf("Total expenditure : %d\n", total);
fclose(fp);
}
void monthly_expenditure(){
}
void year_expenditure(){
}
Create one function that passes in the desired year and month.
Use fgets() to read a line of input, then parse. This has far better error handling.
Do not test against EOF, one of the many return values from *scanf() that you do not want. Test against the return value you want.
Use int for year, month, day.
Use a width with %s to avoid buffer overflow.
Recommend a wider type for money.
Illustrative untested code:
// Filter per year. Use 0 for all years, all months
// Return error code.
int count_filter(int year, int month) {
FILE *fp = fopen("data.txt", "r");
if (fp == NULL) {
return 1;
}
long total = 0;
char buf[200];// Some large buffer
while (fgets(buf, sizeof buf, fp)) {
char name[100];
int y, m, d;
long money;
if (sscanf(buf, "%99s %d %d %d %ld",
name, &y, &m, &d, &money) != 5) {
// Incorrect format
fclose(fp);
return 3;
}
if ((year == 0 || year == y) && (month == 0 || month == m)) {
total += money;
}
}
fclose(fp);
printf("Total expenditure: %ld\n", total);
return 0;
}
Now call as needed:
count_filter(0,0); All expenditures
count_filter(2022,12); Just this month
count_filter(2021,0); Last year
count_filter(0,12); All Decembers
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]);
}
Q) Help out our canteen and develop a program for cash
counter where user selects items out of 5 options with price .
The program keeps on asking until user hit 'q'. After check
out calculate total amount and show user the items purchased.
#include <stdio.h>
int main()
{
char menu[5][15]={"Pizza","Burger","Ice Cream","Pasta","Cold Drink"};
int price[5]={1000,500,300,100,50};
int i,amount=0,total=0,item=0;
printf("\t\t=========ALI FAST FOOD========");
printf("\n\t\tPlease select any option from below\n");
for (i=0;i<5;i++)
{
printf("\nAvailable items are %s press %d",menu[i],item+1);
printf("\tPrice is %d",price[i]);
printf("\n");
item++;
}
int choice;
int start;
printf("Enter number to start buying food");
do {
scanf("\n%d ",&choice);
if (choice==1)
{
static int count=0;
amount = amount+price[0];
printf("\nYou bought %d %s",count+1,menu[0]);
count++;
}
else if (choice==2)
{
static int count=0;
amount = amount+price[1];
printf("\nYou bought %d %s",count+1,menu[1]);
count++;
}
else if (choice==3)
{
static int count=0;
amount = amount+price[2];
printf("\nYou bought %d %s",count+1,menu[2]);
count++;
}
else if (choice==4)
{
static int count=0;
amount = amount+price[3];
printf("\nYou bought %d %s",count+1,menu[3]);
count++;
}
else if (choice==5)
{
int count=0;
amount = amount+price[4];
printf("\nYou bought %d %s",count+1,menu[4]);
count++;
}
else if (choice==0 || choice>=7)
{
printf("\nEnter correct option please\n");
}
}
while (choice!=6);
total = total + amount;
printf("\nTotal amount to be pay is %d",total);
printf("\nThank you for visiting our canteen have a nice day !");
}
In this i need to end the program when user enters "q" instead of "6" . i am unable to do so, please help me fix this issue.
As suggested by "Cid" try handling the input as characters instead of
integers.
Also, as suggested by "JohnBode" use a blank space before "%c" and
not before and after "%c"(i suspect that you tried using a blank
space after the "%c" as well). Let me know if I am mistaken.
Putting it together, you code should look like this....
#include <stdio.h>
int main()
{
char menu[5][15]={"Pizza","Burger","Ice Cream","Pasta","Cold Drink"};
int price[5]={1000,500,300,100,50};
int i,amount=0,total=0,item=0;
printf("\t\t=========ALI FAST FOOD========");
printf("\n\t\tPlease select any option from below\n");
for (i=0;i<5;i++)
{
printf("\nAvailable items are %s press %d",menu[i],item+1);
printf("\tPrice is %d",price[i]);
printf("\n");
item++;
}
char choice;
int start;
printf("Enter number to start buying food\n");
do {
scanf(" %c",&choice);
if (choice=='1')
{
static int count=0;
amount = amount+price[0];
printf("\nYou bought %d %s\n",count+1,menu[0]);
count++;
}
else if (choice=='2')
{
static int count=0;
amount = amount+price[1];
printf("\nYou bought %d %s\n",count+1,menu[1]);
count++;
}
else if (choice=='3')
{
static int count=0;
amount = amount+price[2];
printf("\nYou bought %d %s\n",count+1,menu[2]);
count++;
}
else if (choice=='4')
{
static int count=0;
amount = amount+price[3];
printf("\nYou bought %d %s\n",count+1,menu[3]);
count++;
}
else if (choice=='5')
{
int count=0;
amount = amount+price[4];
printf("\nYou bought %d %s\n",count+1,menu[4]);
count++;
}
//checking for lower and upper case "q"
else if (choice=='0' || choice >= '6' && (choice != 'q' && choice != 'Q'))
{
printf("\nEnter correct option please\n");
}
} while (choice!='q' && choice!='Q');//checking for lower and upper case "q"
total = total + amount;
printf("\nTotal amount to be pay is %d\n",total);
printf("\nThank you for visiting our canteen have a nice day !\n");
}
I am supposed to write a program where the user is asked how many students there are in a class. Then, it asks for the GPA of each of those students. In the end, it is supposed to display number of students with each GPA score. So far this is what i have, but it doesn't seem to count properly.
#include <stdio.h>
int main(void){
int cnt1, cnt2, cnt3, cnt4, student, numofsdts, GPA, GPAFreq[4];
printf("Enter number of students: ");
scanf("%d", &numofsdts);
student = 1;
while(student <= numofsdts){
printf("GPA of student number %d: ", student);
scanf("%d", &GPA);
if(GPA < 1 || GPA > 4){
printf("invalid number \n");
}
else{
student++;
}
if(student == numofsdts + 1)
break;
if(GPAFreq[1])
cnt1++;
else if(GPAFreq[2])
cnt2++;
else if(GPAFreq[3])
cnt3++;
else if(GPAFreq[4])
cnt4++;
}
printf("GPA 1: %d students \n", cnt1);
printf("GPA 2: %d students \n", cnt2);
printf("GPA 3: %d students \n", cnt3);
printf("GPA 4: %d students \n", cnt4);
}
Set int cnt1 = 0, cnt2 = 0 etc. (they are not nullified by default, just have some garbage [like a rented room not cleaned explicitly...]).
Also:
if(GPA < 1 || GPA > 4){
printf("invalid number \n");
continue; // skip the rest of the loop body
}
Or a slightly cleaner approach (in full):
#include <stdio.h>
int main(void){
int cnt1 = 0, cnt2 = 0, cnt3 = 0, cnt4 = 0;
int numofsdts, GPA;
printf("Enter number of students: ");
scanf("%d", &numofsdts);
students = 0;
while(students <= numofsdts){
printf("GPA of student number %d: ", students + 1);
scanf("%d", &GPA);
if(GPA < 1 || GPA > 4){
printf("invalid number \n");
continue;
}
if(GPA == 1)
cnt1++;
else if(GPA == 2)
cnt2++;
else if(GPA == 3)
cnt3++;
else if(GPA == 4)
cnt4++;
students++;
}
printf("GPA 1: %d students \n", cnt1);
printf("GPA 2: %d students \n", cnt2);
printf("GPA 3: %d students \n", cnt3);
printf("GPA 4: %d students \n", cnt4);
}
There are multiple errors here. The first is that cnt1-4 have to be initialized prior to being added to. The second is that C uses zero indexing, so GPAFreq[4] is not accessing the fourth element of your array (which would be GPAFreq[3].
The third is that your if statement isn't doing what you think it is. It is evaluating the values inside of your array as boolean variables, i.e. 0 is false, anything else is true. A better approach is to do this:
GPAFreq[GPA - 1] += 1;
This will be counting the frequencies in each of the indices of the array. Then to print them, you just access GPAFreq and no longer need the cnt variables.
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;
}