Need to get the output only when the loop ends - c

Here, i want to get the output only after the user enters the letter 'Q', which is the last task of my program. However, when i enter 'R' which is another case for my program, it directly prints the output for me.
int main() {
float amountOfTurkishLira = 0;
float amountOfBtc = 0;
float amountOfEth = 0;
char operationCode;
char operationTurkishLira;
// getting the amount of money for the initial money;
scanf(" %c", &operationTurkishLira);
if (operationTurkishLira != 'T') {
printf("Error: Operation could not be completed.");
} else {
scanf(" %f", &amountOfTurkishLira);
scanf(" %c", &operationCode);
while (operationCode != 'Q') {
switch (operationCode) {
case 'R':
if (amountOfBtc == 0 && amountOfEth == 0) {
printf("Our account holds %.2f TRY", amountOfTurkishLira);
} else {
printf("Our account holds %.2f TRY | %.2f BTC | %.2F ETH.", amountOfTurkishLira, amountOfBtc,
amountOfEth);
}
scanf(" %c", &operationCode);
break;
}
}
printf("Bye..");
}
return 0;
}
This happens when i enter the input:
T
1000
R
Our account holds 1000.00 TRY
Bye...
But I want it to be like this:
T
1000
R
Q
after i enter all my input, it should give me
Our account holds 1000.00 TRY
Bye...

Take the printing code out of the loop and do it at the end.
And take scanf(" %c", &operationCode); out of the switch, since it should be done no matter what the previous code was.
int main() {
float amountOfTurkishLira = 0;
float amountOfBtc = 0;
float amountOfEth = 0;
char operationCode;
char operationTurkishLira;
// getting the amount of money for the initial money;
scanf(" %c", &operationTurkishLira);
if (operationTurkishLira != 'T') {
printf("Error: Operation could not be completed.");
} else {
scanf(" %f", &amountOfTurkishLira);
scanf(" %c", &operationCode);
while (operationCode != 'Q') {
switch (operationCode) {
case 'R':
break;
}
scanf(" %c", &operationCode);
}
if (amountOfBtc == 0 && amountOfEth == 0) {
printf("Our account holds %.2f TRY", amountOfTurkishLira);
} else {
printf("Our account holds %.2f TRY | %.2f BTC | %.2F ETH.", amountOfTurkishLira, amountOfBtc,
amountOfEth);
}
printf("Bye..");
}
return 0;
}

Take a look on my version. I have some comments in it. You just have to add your logic for the case you pressing 'R' or an other key (I suppose you will add some more key press listeners).
#include <stdio.h>
int main() {
float amountOfTurkishLira = 0;
float amountOfBtc = 0;
float amountOfEth = 0;
char operationCode;
char operationTurkishLira;
// getting the amount of money for the initial money;
scanf(" %c", &operationTurkishLira);
if (operationTurkishLira != 'T') {
printf("Error: Operation could not be completed.");
}
else {
scanf(" %f", &amountOfTurkishLira);
scanf(" %c", &operationCode);
while (operationCode != 'Q') {
switch (operationCode) {
case 'R':
if (amountOfBtc == 0 && amountOfEth == 0) {
printf("LOGIC FOR amountOfBtc == 0 && amountOfEth == 0\n");
} else {
printf("LOGIC FOR amountOfBtc != 0 || amountOfEth != 0\n");
}
break;
case 'X': // X, Y, or WHATEVER
// LOGIC FOR 'X'
break;
}
scanf(" %c", &operationCode);
}
if (operationCode == 'Q') {
if (amountOfBtc == 0 && amountOfEth == 0) {
printf("Our account holds %.2f TRY\n", amountOfTurkishLira);
}
else {
printf("Our account holds %.2f TRY | %.2f BTC | %.2F ETH.\n", amountOfTurkishLira, amountOfBtc, amountOfEth);
}
printf("Bye..");
}
}
return 0;
}

Related

while loop not breaking even with break C programming

Trying to make a GPA calculator.
Here is my code:
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
int main()
{
float fgpa, grade, n;
char reply;
n = 1;
grade = 1;
printf("--- GPA Calculator ---");
while(fgpa < 1 || fgpa > 4)
{
printf("\n\nEnter your current GPA: ");
scanf("%f", &fgpa);
if(fgpa < 1 || fgpa > 4)
printf("Invalid Input! Please re-enter value.");
}
printf("\nUsing the following table to convert grade to points\n\nA+ = 4.0\nA = 4.0\nB+ = 3.5\nB = 3\nC+ = 2.5\nC = 2.0\nD+ = 1.5\nD = 1\nF = 0\n");
while(grade > 0, n++)
{
printf("\nEnter points for module %.0f, enter \"0\" if there are no more additional modules: ", n);
scanf("%f", &grade);
printf("%f", grade);
fgpa = (fgpa + grade) / n;
}
fgpa = fgpa* n / (n-1);
n--;
printf("\n\nNumber of modules taken: %.0f\nFinal GPA: %.1f", n, fgpa);
return 0;
}
I've tried using if(grade = 0) break; but its still not breaking the loop even when the grade is correctly read 0.
picture of 0 being read correctly but loop still continuing
There are multiple problems in the code:
fgpa is uninitialized so the first test in the loop has undefined behavior.
you should also test the return value of scanf() to detect invalid or missing input.
while (grade > 0, n++) is incorrect too: you should instead always read the next grade and test its value and break from the loop before incrementing n.
Your averaging method seems incorrect too: you do not give the same weight to every module.
It seems more appropriate for your purpose to use for ever loops (for (;;)), unconditionally read input, check for scanf() success and test the input values explicitly before proceeding with the computations.
Here is a modified version:
#include <stdio.h>
// flush the rest of the input line, return EOF at end of file
int flush(void) {
int c;
while ((c = getchar()) != EOF && c != \n')
continue;
return c;
}
int main() {
float fgpa;
float grade;
int n = 1;
char reply;
printf("--- GPA Calculator ---");
for (;;) {
printf("\n\nEnter your current GPA: ");
if (scanf("%f", &fgpa) == 1) {
if (fgpa >= 1 && fgpa <= 4)
break;
}
} else {
if (flush() == EOF) {
fprintf(stderr, "unexpected end of file\n");
return 1;
}
}
printf("Invalid Input! Please re-enter value.\n");
}
printf("\nUsing the following table to convert grade to points\n\n"
"A+ = 4.0\nA = 4.0\nB+ = 3.5\nB = 3\nC+ = 2.5\n"
"C = 2.0\nD+ = 1.5\nD = 1\nF = 0\n");
for (;;) {
printf("\nEnter points for module %d, enter \"0\" if there are no more additional modules: ", n);
if (scanf("%f", &grade) == 1) {
if (grade <= 0)
break;
printf("%f\n", grade);
fgpa = fgpa + grade;
n = n + 1;
} else {
if (flush() == EOF)
break;
printf("Invalid Input! Please re-enter value.\n");
}
}
fgpa = fgpa / n;
printf("\n\nNumber of modules taken: %d\nFinal GPA: %.3f\n", n, fgpa);
return 0;
}

if condition is not functioning properly

i tried to make a calculator but could the compiler is checking my if conditions properly.
here is my code,
i could not figure out how to solve this
#include <stdio.h>
#include <stdlib.h>
int main()
{
int first;
int sec;
char mode;
printf("enter your forst number : ");
scanf("%d",&first);
printf("enter your second number : ");
scanf("%d",&sec);
printf("to add press \"a\" \n");
printf("to subtract press \"s\" \n");
printf("to multiply press \"m\" \n");
printf("to divide press \"d\" \n");
printf("so, what do you wanna do ");
scanf(" %c",&mode);
printf("%d %d %s \n",first,sec,mode);
if (mode == 'a')
{
printf("%d \n",first + sec);
}
else if (mode == "s")
{
printf("%d \n",first-sec);
}
else if (mode == "m")
{
printf("%d \n",first*sec);
}
else if (mode == "d")
{
printf("%d \n",first/sec);
}
else
{
printf("enter a valid operation code \n");
}
return 0;
}
void def(char name[],int age)
{
printf("het ur a %s and yo age is %i \n",name,age);
}
first attempt tried using a string instead of character (failed )
second attempt tried using a character but failed though!!
For comparing a single character in c, you must use single quotes. Consider an array of characters array[4] = {'c','a','r','\0'};
if(array[0] == 'c'){
//...
}
Comparing with double quotes, make the value inside it a string. For comparing strings you should #include <strings.h> and use the strcmp function.
There are two problems
mode == "s" mode is a char so just use mode == 's' and do the same for others also.
printf("%d %d %s \n",first,sec,mode); should be printf("%d %d %c \n",first,sec,mode);
you are using %s for printing a char
In your code "s" is a string not a caracter,to get a caracter you should write like this: 's'
here is the correction of your code :
int main()
{
int first;
int sec;
char mode;
printf("enter your forst number : ");
scanf("%d",&first);
printf("enter your second number : ");
scanf("%d",&sec);
printf("\nMenu : \n");
printf("\nto add press \"a\" \n");
printf("to subtract press \"s\" \n");
printf("to multiply press \"m\" \n");
printf("to divide press \"d\" \n");
printf("so, what do you wanna do ");
scanf(" %c", &mode);
printf("%d %d %c \n",first,sec,mode);
if(mode == 'a')
{
printf("%d \n",first + sec);
}
else if (mode == 's')
{
printf("%d \n",first-sec);
}
else if (mode == 'm')
{
printf("%d \n",first*sec);
}
else if (mode == 'd')
{
printf("%d \n",first/sec);
}
else
{
printf("enter a valid operation code \n");
}
return 0;
}

Finding Items in Struct and edit them

i have a problem in my code (Case 2), I try to get the position of the item what I get from the scanf() but when I try to get the position it give me a complete random number like 537890.
I can't figure out why my code do that, because the max size of my struct ist 200.
I'm not sure if its because I tried to do &find==wh[a]->artikel
int main() {
struct managementtool {
char artikel[200];
int anzahl;
};
//wh = warehouse
struct managementtool **wh = malloc(200 * sizeof(struct managementtool *));
for (int i = 0; i < 200; i++) {
wh[i] = malloc(sizeof(struct managementtool));
}
printf("Welcome to Warehouse Management 97\n\n\nWhat do you want to do ?\n");
int x,v,f,i,exit,all,end,a,b;
char ques,find, nu1;
do {
i=0;
printf("\n(1)Add article\n(2)Edit article.\n(3)Search entry.\n(4)Show stock.\n(5)Exit\n");
scanf("%x",&x);
switch (x) {
case 1://add
do {
printf("\nEnter the product name: ");
scanf("%s", wh[f]->artikel);
printf("\nAmount of products: ");
scanf("%i", &wh[f]->anzahl);
printf("\n\nAdd another product ? (Y/N)");
// add a space before % to skip leading whitespace
scanf(" %c", &ques);
f++;
switch (ques) {
case 'Y':
v++;
break;
case 'N':
end = 1;
v = 0;
break;
default:
printf("Wrong entry\n");
break;
}
} while (end != 1);
if (v >= 2) {
printf("Product added successfully\n\n");
}else {
printf("Products have been successfully added\n\n");
}
break;
case 2://edit
printf("Which article do you want to edit?");
fflush(stdin);
scanf("%s", &find);
for (a=0;a<f;a++) {
if (&find==wh[a]->artikel) {
b=a;
}
}
if (b==0) {
printf("Article not found");
}
printf("f: %i, b:%i",f,b);
puts(wh[b]->artikel);
printf("Amount: %d\n", wh[b]->anzahl);
break;
case 3://search
break;
case 4://Spam-it
while (i<f) {
printf("\nProduct number %i\n", i+1);
printf("Name: ");
puts(wh[i]->artikel);
printf("Amount: %d\n", wh[i]->anzahl);
i++;
}
printf("\nTotal amount of Items: %i", all);
break;
case 5://go away
printf("Goodbye :)");
exit=1;
break;
default://well
printf("Wrong Input\n");
break;
}
all=0;
while (i<f) {
all += wh[i]->anzahl;
i++;
}
} while (exit==0);
}
In C you need to use strcmp instead of using == to compare strings. You should also use fgets instead of scanf it will make your life easier, you don't have to worry about trying to flush. Example : fgets( my_string_buffer, number_of_char_maximum_to_read , stdin ) . Example for strcmp : if(! strcmp( string1 , string2) , strcmp returns 0 if they are identical.

Repeat the Program Prompt

The current problem is with the Evaluate another interval (Y/N)? prompt. Let's say I run the program 4 times; in order to end it, it requires me to type N 4 times.
int main() {
int trap, test;
double low, hi;
char repeat, c;
//Gather End Points
do {
printf("Enter endpoints of interval to be integrated (low hi): ");
test = scanf("%lf %lf", &low, &hi);
if (test != 2) {
printf("Error: Improperly formatted input\n");
while((c = getchar()) != '\n' && c != EOF); //Discard extra characters
} else
if (low > hi)
printf("Error: low must be < hi\n");
} while ((test != 2 || low > hi));
//Gather amount of triangles
do {
printf("Enter number of trapezoids to be used: ");
test = scanf("%d", &trap);
if (test != 1) {
printf("Error: Improperly formated input\n");
while((c = getchar()) != '\n' && c != EOF); //Discard extra characters
} else
if (trap < 1)
printf("Error: numT must be >= 1\n");
} while ((trap < 1 || test != 1));
//Output integrate
printf("Using %d trapezoids, integral between %lf and %lf is %lf",
trap, low, hi, integrate(low, hi, trap));
//Prompt user for another time
while (1) {
printf("\nEvaluate another interval (Y/N)? ");
scanf(" %c", &repeat);
switch (repeat) {
case 'Y':
main();
case 'y':
main();
case 'N':
return 0;
case 'n':
return 0;
default:
printf("Error: must enter Y or N");
}
}
return 0;
}
I expect it so that no matter what run of the program I'm on it will close when I type one N.
There are many ways to achieve what you want but calling main recursively is not a good idea.
A pretty simple way to change your program is to add an additional while(1) level. Something like:
int main(void)
{
char repeat;
while(1){ // Outer while to keep the program running
printf("running program\n");
// Put your program here
printf("program done\n");
repeat = '?';
while(repeat != 'y' && repeat != 'Y'){ // Repeat until input is 'Y' or 'y'
printf("\nEvaluate another interval (Y/N)? ");
scanf(" %c", &repeat);
switch (repeat){
case 'Y':
case 'y':
break;
case 'N':
case 'n':
return 0; // Stop if input is 'n' or 'N'
default:
printf("Error: must enter Y or N");
}
}
}
return 0; // This will never be reached
}
Another way (a simpler way, IMO) is to put the code where you ask the user into a function that you call from main. Like:
int continueProg()
{
char repeat = '?';
while(1){
printf("\nEvaluate another interval (Y/N)? ");
scanf(" %c", &repeat);
switch (repeat){
case 'Y':
case 'y':
return 1;;
case 'N':
case 'n':
return 0;
default:
printf("Error: must enter Y or N");
}
}
}
int main(void)
{
do {
printf("running program\n");
// Put your program here
printf("program done\n");
} while(continueProg());
return 0;
}
BTW: Take a look at getchar instead of using scanf
There are multiple problems in your program:
You test the return value of scanf() when reading the user's answer to the prompts, and you clear the pending input correctly, but you do not handle the potential end of file, leading to endless loops.
c must be defined as int to accommodate for all values returned by getchar(): 256 values of type unsigned char and the special value EOF.
You can main() recursively to repeat the program's action requiring multiple N answers. You should instead add an outer loop and exit from it upon a N answer or an end of file condition.
Here is a modified version:
#include <stdio.h>
double integrate(double low, double hi, int trap) {
...
}
int flush_line(void) {
// Consume the pending input and return `'\n`` or `EOF`
int c;
while ((c = getchar()) != EOF && c != '\n')
continue;
return c;
}
int main() {
// Main program loop
for (;;) {
int trap, test;
double low, hi;
char repeat;
//Gather End Points
for (;;) {
printf("Enter endpoints of interval to be integrated (low hi): ");
test = scanf("%lf %lf", &low, &hi);
if (test == EOF)
return 1;
if (test != 2) {
printf("Error: Improperly formatted input\n");
if (flush_line() == EOF)
return 1;
continue; // ask again
}
if (low > hi) {
printf("Error: low must be < hi\n");
continue;
}
break; // input is valid
}
//Gather amount of triangles
for (;;) {
printf("Enter number of trapezoids to be used: ");
test = scanf("%d", &trap);
if (test == EOF)
return 1;
if (test != 1) {
printf("Error: Improperly formated input\n");
if (flush_line() == EOF)
return 1;
continue;
}
if (trap < 1) {
printf("Error: numT must be >= 1\n");
continue;
}
break;
}
//Output integrate
printf("Using %d trapezoids, integral between %lf and %lf is %lf\n",
trap, low, hi, integrate(low, hi, trap));
//Prompt user for another time
for (;;) {
printf("\nEvaluate another interval (Y/N)? ");
if (scanf(" %c", &repeat) != 1)
return 1; // unexpected end of file
switch (repeat) {
case 'Y':
case 'y':
break;
case 'N':
case 'n':
return 0;
default:
printf("Error: must enter Y or N\n");
if (flush_line() == EOF)
return 1;
continue;
}
break;
}
}
}

Deposit gives negative number?

Good morning, guys! I'm currently a newly started programming learner. Down here is my code for a mini app store. However, there is a problem going on, yet I couldnt locate the problem.
The problem happen when I tried buying an app for $89.99 and I chose to redeem $10 9 times so I would have enough money to purchase the app (I didnt choose the $100 option because it would work just fine). However, the remained amount became $-79.99 instead of $0.01. Like I said, if I chose to deposit $100, the remained balance would be $10.01, which is normal. I don't get where I did wrong. Here is my code!
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <ctype.h>
int Compare(double deposit, double choiceCost);
void DisplayApps(char *selectionPtr);
void SetCost(char selection, double *costPtr);
void PaymentOptions(double *depositPtr,double cost);
void DoItAgain(char *quitPtr);
//void Pay(double *depositPtr, double choiceCost);
void GetChange(double *depositPtr, double choiceCost);
void DoItAgain(char *quitPtr);
int main()
{
char selectionPtr;
char selection;
char quitPtr;
double costPtr;
double deposit = 0.0;
double choiceCost;
double depositPtr = 0.0;
double cost = 0.0;
printf("Welcome to the App Store\n");
printf("***************************\n\n");
printf("Your deposit is: %.2f\n", deposit);
printf("\n");
while (1)
{
do {
DisplayApps(&selectionPtr);
selection = selectionPtr;
SetCost(selection, &costPtr);
choiceCost = costPtr;
Compare(deposit, choiceCost);
while (Compare(deposit, choiceCost) == 0)
{
printf("Your balance isn't enough.\n");
printf("In order to purchase this item, you have to redeem more money.\n");
PaymentOptions(&depositPtr, cost);
deposit += depositPtr;
printf("You have redeemed $%.2f\n", depositPtr);
printf("Your balance now is: $%.2f\n", deposit);
printf("\n");
}
deposit = depositPtr;
GetChange(&depositPtr, choiceCost);
DoItAgain(&quitPtr);
} while (quitPtr == 'Y' || quitPtr == 'y');
return 1;
}
return 0;
}
void DisplayApps(char *selectionPtr)
{
printf("-------------------------\n");
printf("HERE ARE THE SLECTIONS\n");
printf("C -- Clown Punching $299.99\n");
printf("V -- Virtual Snow Globe $349.99\n");
printf("R -- Remote PC $999.99\n");
printf("G -- Grocery List Helper $2.99\n");
printf("M -- Mobile Cam Viewer $89.99\n");
printf("\n");
printf("Please enter a selection: ");
scanf(" %c", &*selectionPtr);
printf("\n");
}
void SetCost(char selection, double *costPtr)
{
if (selection == 'C' || selection == 'c')
{
*costPtr = 299.99;
}
else if (selection == 'V' || selection == 'v')
{
*costPtr = 349.99;
}
else if (selection == 'R' || selection == 'r')
{
*costPtr = 999.99;
}
else if (selection == 'G' || selection == 'g')
{
*costPtr = 2.99;
}
else if (selection == 'M' || selection == 'm')
{
*costPtr = 89.99;
}
}
int Compare(double deposit, double choiceCost)
{
if (deposit < choiceCost)
{
return 0;
}
else
{
return 1;
}
}
void PaymentOptions(double *depositPtr, double cost)
{
printf("You have (4) options to choose:\n");
printf("1 - $1000.00\n");
printf("2 - $500.00\n");
printf("3 - $100.00\n");
printf("4 - $10.00\n");
printf("How much do you want to redeem?");
printf(">>>>> ");
scanf("%lf", &cost);
printf("\n");
printf("-------------------------------------\n");
if (cost == 1)
{
*depositPtr = 1000.00;
}
else if (cost == 2)
{
*depositPtr = 500.00;
}
else if (cost == 3)
{
*depositPtr = 100.00;
}
else if (cost == 4)
{
*depositPtr = 10.00;
}
}
void GetChange(double *depositPtr, double choiceCost)
{
*depositPtr = *depositPtr - choiceCost;
printf("You have purchased this item successfully.\n");
printf("You still have $%.2f remained in you balance.\n", *depositPtr);
}
void DoItAgain(char *quitPtr)
{
printf("Do you want to continue purchase another item? [Y/N]\n");
scanf(" %c", &*quitPtr);
}
In this code : GetChange(&depositPtr, choiceCost);
You shold pass deposit (total deposit) and not &depositPtr (last deposit, only 10)

Resources