C# do while loops - How to remember user input? - c#

I'm new to C#, and i'm writing a do while loop that continues to ask the user to enter "price", until they enter "-1" for price.
Afterwards, I need to add up all the values for price they entered and declare that as the subtotal.
The problem I have is that it only remember the last number entered, which would be -1. What would I have to do to fix this?
using System;
namespace ConsoleApp1
{
class Program
{
static void Main()
{
Console.WriteLine("Your Receipt");
Console.WriteLine("");
Console.WriteLine("");
decimal count;
decimal price;
decimal subtotal;
decimal tax;
decimal total;
count = 1;
do
{
Console.Write("Item {0} Enter Price: ", count);
++count;
price = Convert.ToDecimal(Console.ReadLine());
} while (price != -1);
subtotal = Convert.ToInt32(price);
Console.Write("Subtotal: ${0}", subtotal);
}
}
}

Try this variation to Artem's answer. I think this is a little cleaner.
int count = 0;
decimal input = 0;
decimal price = 0;
while (true)
{
Console.Write("Item {0} Enter Price: ", count++);
input = Convert.ToDecimal(Console.ReadLine());
if (input == -1)
{
break;
}
price += input;
}

In each iteration of the loop, you overwrite the value of price. Separate input and storage price.
decimal input = 0;
do
{
Console.Write("Item {0} Enter Price: ", count);
++count;
input = Convert.ToDecimal(Console.ReadLine());
if (input != -1)
price += input;
} while (input != -1);

Use a list and keep adding the entries to the list.
Or you can keep a running total in another integer.
Something like:
int total = 0; // declare this before your loop / logic other wise it will keep getting reset to 0.
total = total+ input;

Please try to use this
using System;
namespace ConsoleApp1
{
class Program
{
static void Main()
{
Console.WriteLine("Your Receipt");
Console.WriteLine("");
Console.WriteLine("");
decimal count;
decimal price;
decimal subtotal = 0m; //subtotal is needed to be initialized from 0
decimal tax;
decimal total;
count = 1;
do
{
Console.Write("Item {0} Enter Price: ", count);
++count;
price = Convert.ToDecimal(Console.ReadLine());
if (price != -1) //if the console input -1 then we dont want to make addition
subtotal += price;
} while (price != -1);
//subtotal = Convert.ToInt32(price); this line is needed to be deleted. Sorry I didnt see that.
Console.Write("Subtotal: ${0}", subtotal); //now subtotal will print running total
}
}
}

Related

I want to write a program that calculates the sum and average of student grades

Having problem with my work i want to write a program that does the sum and average the student grade in the average function i used a do while loop since i want anyone to enter grade until the user enter -1 the loop end.
The problem is i do not want to run the _cal = Int32.Parse(Console.ReadLine()); in the fucntion instead run it in the main by passing a value to Average() parameter then using the value in main as a console.readlIne because i will use the user input to divide by the sum in order to get average am new to programming.
public static void Main()
{
Console.WriteLine("Please Enter the scores of your student: ");
Console.WriteLine("----------------------------------------");
_studentTotalGrade = Average();
Console.WriteLine("sum " + Sum);
Console.ReadLine();
}
public static double Average()
{
double _cal,_sumTotal = 0;
int i = 0;
do
{
_cal = Int32.Parse(Console.ReadLine());
if (_cal == -1)
{
break;
}
if (_cal > 20)
{
Console.WriteLine("Adjust score\");
continue;
}
_sumTotal +=_cal;
i--;
} while (_cal > i);
return _sumTotal;
}
}

2d array calculator in C# [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I'm having a little trouble making a calculator. I can't seem to be able to enter the item name, only numbers. Also, it only takes the last price and quantity and multiplies them not the entirety. Update: I made the changes to the code about the subtotal and break,but it keeps telling me
Error CS0029
Cannot implicitly convert type 'string' to 'string[,]'
Error CS0019
Operator '==' cannot be applied to operandstype'string[,]' and 'int'
I can't seem to make it work or add a list to the end. Any help would be appreciated.
int[] array;
string[,] name = new string[100, 4];
decimal counter;
decimal price;
decimal subtotal;
decimal tax;
decimal total;
decimal quantity;
subtotal = 0;
counter = 0;
array = new int[5];
while (counter <= 10)
{
Console.Write("Item{0}", counter + 1);
Console.Write(" Enter item name: ");
name = Console.ReadLine();
if (name == 0)
break;
Console.Write(" Enter price: ");
price = Convert.ToDecimal(Console.ReadLine());
counter = counter + 1;
Console.Write(" Enter quantity: ");
quantity= Convert.ToInt32(Console.ReadLine());
subtotal += price * quantity;
}
Console.WriteLine("-------------------");
Console.WriteLine("\nNumber of Items:{0}", counter);
Console.WriteLine("Subtotal is {0}", subtotal);
tax = subtotal * 0.065M;
Console.WriteLine("Tax is {0}", tax);
total = tax + subtotal;
Console.WriteLine("Total is {0}", total);
Console.WriteLine("Thanks for shopping! Please come again.");
Console.Read();
I also know that I need to have for ( int counter = 0; counter < array.Length; counter++ ) in the code too, but it won't work. Thank-you for your time and help in advance.
You're trying to convert name to a number:
name = Convert.ToInt32(Console.ReadLine());
if (name == 0)
break;
Try removing "Convert.ToInt" like this:
name = Console.ReadLine();
Maybe this program will help you in learning C#. But you have to promise to try to understand how and why it works. Also, use the debugger to step in order to see how each statement affects the values stored in the variables.
class Program
{
static void Main(string[] args)
{
const int max_count = 10;
string[] name = new string[max_count];
int[] quantity = new int[max_count];
decimal[] price = new decimal[max_count];
decimal subtotal = 0;
int count = 0;
// Enter Values
for(int i = 0; i<max_count; i++)
{
Console.Write("Item{0}", i+1);
Console.Write("\tEnter Item Name: ");
name[i]=Console.ReadLine();
if(name[i].Length==0)
{
break;
}
Console.Write("\tEnter Price: ");
price[i]=decimal.Parse(Console.ReadLine());
Console.Write("\tEnter Quantity: ");
quantity[i]=int.Parse(Console.ReadLine());
subtotal+=quantity[i]*price[i];
count+=1;
}
// Display Summary
Console.WriteLine("-------------------");
Console.WriteLine("\nNumber of Items:{0}", count);
Console.WriteLine("Subtotal is {0}", subtotal);
decimal tax=subtotal*0.065M;
Console.WriteLine("Tax is {0}", tax);
decimal total=tax+subtotal;
Console.WriteLine("Total is {0}", total);
Console.WriteLine("Thanks for shopping! Please come again.");
Console.Read();
}
}
What you have here is a structure (the Program) of arrays. There are three arrays each storing a different type of value (string, int ,decimal). Later you should learn to make a single array of a structure, each containing multiple values.
public class Item
{
public string name;
public decimal price;
public int quantity;
}
// Usage
var cart = new List<Item>();

How to display highest and lowest of an array

here i ask the user for homework scores which are then averaged after discarding the smallest and largest score. i have stored the user input in an array. in my DisplayResults method im not sure how to display the lowest and highest scores that were discarded. any help is appreciated! Here is what i have so far:
class Scores
{
static void Main(string[] args)
{
double sum = 0;
double average = 0;
int arraySize;
double[] inputValues;
arraySize = HowManyScores();
inputValues = new double[arraySize];
GetScores(inputValues);
sum = CalculateSum(inputValues);
average = CaculateAverage(sum, arraySize);
DisplayResults(inputValues, average);
Console.Read();
}
public static int HowManyScores()
{
string input;
int size;
Console.WriteLine("How many homework scores would you like to enter?");
input = Console.ReadLine();
while (int.TryParse(input, out size) == false)
{
Console.WriteLine("Invalid data. Please enter a numeric value.");
input = Console.ReadLine();
}
return size;
}
public static void GetScores(double[] inputValues)
{
double scoreInput;
Console.Clear();
for (int i = 0; i < inputValues.Length; i++)
{
scoreInput = PromptForScore(i + 1);
inputValues[i] = scoreInput;
}
}
public static double PromptForScore(int j)
{
string input;
double scoreInput;
Console.WriteLine("Enter homework score #{0}:", j);
input = Console.ReadLine();
while (double.TryParse(input, out scoreInput) == false)
{
Console.WriteLine("Invalid Data. Your homework score must be a numerical value.");
input = Console.ReadLine();
}
while (scoreInput < 0)
{
Console.WriteLine("Invalid Data. Your homework score must be between 0 and 10.");
input = Console.ReadLine();
}
while (scoreInput > 10)
{
Console.WriteLine("Invalid Data. Your homework score must be between 0 and 10.");
input = Console.ReadLine();
}
return scoreInput;
}
public static double CalculateSum(double[] inputValues)
{
double sum = 0;
for (int i = 1; i < inputValues.Length - 1; i++)
{
sum += inputValues[i];
}
return sum;
}
public static double CaculateAverage(double sum, int size)
{
double average;
average = sum / ((double)size - 2);
return average;
}
public static void DisplayResults(double[] inputValues, double average)
{
Console.Clear();
Console.WriteLine("Average homework score: {0}", average);
//Console.WriteLine("Lowest score that was discarded: {0}",
//Console.WriteLine("Highest score that was discarded: {0}",
}
}
}
You basically only have to do one thing: Sorting the array after you received your input data. Then, printing the first and last value gives you the minimal and maximal score. Use
Array.Sort(intArray);
in main after calling GetScores and
Console.WriteLine("Lowest score: {0} Highest score: {1}",
inputValues[0], inputValues[inputValues.Length - 1]);
to print the results. Cheers
EDIT: The proposal by Jens from the comments using the Min/Max is probably more what you're looking for if you're not interested in complete ordering of your values.

need help on creating a counter with a total, number enter, and average

The requirement are:
create an application that will allow the user to enter numbers and
provide the average of the numbers entered. The user will be allowed to enter as many numbers as they choose. After each entry we will display the current average.
Keep repeating until the user decides to quit.
I want to user to keep entering number until they type "q" to quit. Please help.
string input = "";
int numbersEntered = 0;
int average = 0;
int total = 0;
do
{
Console.Clear();
Console.WriteLine("Enter a number or Q to quit", input);
input = Console.ReadLine();
total += Convert.ToInt32(input);
average = (total / numbersEntered);
Console.WriteLine("Total: {0}\t Numbers Entered: {1}\t Average: {2}\t", total, numbersEntered++, average);
}
while (input.ToUpper() == "Q");
{
Console.WriteLine("Press any key to continue");
Console.ReadKey();
}
Console.ReadKey();
Put the Console.ReadLine inside the loop -- and put the writing of the total/average after calculating those numbers.
Also, you might want to validate the input, instead of assuming it is a number -- use int.TryParse.
do
{
Console.WriteLine("Enter a number of Q to quit", input);
input = Console.ReadLine();
int val;
if (int.TryParse(input, out val))
{
total += val;
average = (total / numbersEntered);
Console.WriteLine("Total: {0}\t Numbers Entered: {1}\t Average: {2}\t", total, numbersEntered++, average);
}
}
while (input.ToUpper() != "Q");
There are three points needs to be corrected.
numbersEntered is 0 in the first calculation. You should pre-increment it while dividing by it.
also in the condation of while loop, it should be input.ToUpper() != "Q" instead of input.ToUpper() == "Q".
After correcting above two things your current code is calculating the average but it clearing the console after printing it. So, you should want after printing it by Console.Read();
Following is the code corrected:
string input = "";
int numbersEntered = 0;
int average = 0;
int total = 0;
do
{
Console.Clear();
Console.WriteLine("Enter a number or Q to quit", input);
input = Console.ReadLine();
int valueEntered;
if (int.TryParse(input, out valueEntered))
{
total += valueEntered;
average = (total / ++numbersEntered);
Console.WriteLine("Total: {0}\t Numbers Entered: {1}\t Average: {2}\t", total, numbersEntered, average);
Console.ReadKey();
}
}
while (input.ToUpper() != "Q");
Console.WriteLine("Press any key to continue");
Console.ReadKey();
Simply a typo(?) Your while needs to be:
...
while (input.ToUpper() != "Q");
That is != instead of ==.
Minimalistic solution:
int nTotal = 0;
double avg = 0;
string input;
while ((input = Console.ReadLine()).ToUpper() != "Q")
{
int number = int.Parse(input);
avg += (number-avg) / ++nTotal;
Console.WriteLine("Total numbers entered: {0}. Average: {1}", nTotal, avg);
}

Enter a number or Q to quit

Hi all I have been having some problems with a task I have been set
The first part of the task was to output a price table with the following rules:
The price for up to 50 is £5 each. For between 51 and 80, the price is £4 each, while for between 81 and 100 the price is a rock bottom £2.50 each.
Using loop structures and selection statements (if.. etc) your program should output a widget price chart for widgets in multiples of 10 up to 100.
I have done this however the second part of the task has me stumped
after the table has been output to input a number of widgets. You should then calculate the cost and output the value. If the user enters ‘q’ or ‘Q’, the program should terminate.
Here is the full code
using System;
namespace w5Task3
{
class Program
{ public static void Main ( string[] args )
{
double PriceEach1 = 5;
double PriceEach2 = 4;
double PriceEach3 = 2.50;
double Quantity = 10;
int UserOrder=0;
Console.WriteLine("\n\nBelow is the price chart:\n\n");
Console.WriteLine("WidgetQuantity\t\t\tPrice\n");
while (Quantity <=100)
{
double Price1 = PriceEach1*Quantity;
double Price2 = PriceEach2*Quantity;
double Price3 = PriceEach3*Quantity;
if (Quantity <=50)
{
Console.WriteLine("\t{0}\t\t\t{1:C}", Quantity, Price1);
}
if(Quantity >=51 && Quantity <=80)
{
Console.WriteLine("\t{0}\t\t\t{1:C}", Quantity, Price2);
}
if (Quantity >80 && Quantity <=100)
{
Console.WriteLine ("\t{0}\t\t\t{1:C}",Quantity, Price3);
}
Quantity +=10;
}
while (UserOrder >=0)
{
try
{
Console.WriteLine("Enter the amount of widgets you would like to purchase or press q to quit");
string temp = Console.ReadLine();
if (temp =="q") break;
if (temp =="Q") break;
int.TryParse(temp, out UserOrder);
double UserPrice;
if (UserOrder <=50)
{
UserPrice = UserOrder*5;
Console.WriteLine("The price is {0:C}",UserPrice);
}
if (UserOrder >=51 && UserOrder <=80)
{
UserPrice = UserOrder*4;
Console.WriteLine("The price is {0:C}",UserPrice");
}
if (UserOrder >80)
{
UserPrice = UserOrder*2.5;
Console.WriteLine("The price is {0:C}",UserPrice");
}
}
catch(Exception)
{
Console.WriteLine("You have entered an incorrect value. Please enter a number or press q to quit");
}
}
}
}
The part I am having issues with is:
while (UserOrder >=0)
{
try
{
Console.WriteLine("Enter the amount of widgets you would like to purchase or press q to quit");
string temp = Console.ReadLine();
if (temp =="q") break;
if (temp =="Q") break;
int.TryParse(temp, out UserOrder);
double UserPrice;
if (UserOrder <=50)
{
UserPrice = UserOrder*5;
Console.WriteLine("The price is {0:C}",UserPrice);
}
if (UserOrder >=51 && UserOrder <=80)
{
UserPrice = UserOrder*4;
Console.WriteLine("The price is {0:C}",UserPrice");
}
if (UserOrder >80)
{
UserPrice = UserOrder*2.5;
Console.WriteLine("The price is {0:C}",UserPrice");
}
}
catch(Exception)
{
Console.WriteLine("You have entered an incorrect value. Please enter a number or press q to quit");
}
}
}
I can get the program to quit or do one UserPrice but it is when I need to make it change the price dependent on the amount ordered.
Any help or suggestions are much appreciated!
You have newlines in your constant expressions at lines 67 and 73!
Fix those, and it all runs fine.
I think your problem is the quote after UserPrice on rows 64 and 70..
Console.WriteLine("The price is {0:C}",UserPrice");
remove it
The easiest way to do it is to adjust UserOrder after you calculate the price for that portion of the order. You can go in either direction, but it basically looks like:
if (HasThisQuantityRange)
{
Total += ThisAmount * (Lower of: ThisQuantity or UserOrder);
UserOrder -= (Lower of: ThisQuantity or UserOrder);
}
if (UserOrder > 0 && HasAdjustedQuantityRange)
{
Total += ThisAmount * (Lower of: ThisQuantity or UserOrder);
UserOrder -= (Lower of: ThisQuantity or UserOrder);
}
and so on.
Obviously, this is all pseudocode, and you'll need to implement it yourself, but this will hopefully get you pointed in the right direction.
I'm having trouble understanding what exactly the problem you're having is. Are you struggling to get the right calculation for the order or is the Quit behavior not acting in the way that you're expecting.
In general I think its bad form to use a transient variable like that for your while loop condition. When I want a console app to repeat I typically set up a variable specifically used for the loop condition like this:
bool isRunning = true;
while (isRunning)
{
....
Then when you check for your input
if (temp.ToUpper() == "Q")
{
isRunning = false;
break;
}

Categories