I am trying to enter a loop to stop the number of areas being below 0 or above 5, I've tried entering a do while loop, but it still executes the next block of code even when incorrect input has been entered. I've commented the section with the loop. Help would be much appreciated, thank you.
const int MaxItems = 5; // max size of array needed
double[] itemCosts = new double[MaxItems];
int jobType; // valid values are 1=normal, 2=waterproofing, 3=skim
int nAreas;
int i;
string customer;
double totalCost = 0.0;
double averageCost;
const double discountPrice = 800; // price at which discount available
const double discountRate = 0.1; // discount rate
const double setupCostPerArea = 30.00;
// cost of moving furniture, carpets etc.
double discount, discountedTotal; // discount amount and discounted total
double width, height; // width and height of plaster area
double[] basePrices = { 0, 35.0, 30.0, 20.0 }; // added 0 as index placeholder, so 35 can be selected using 1, and so forth.
// prices per square metre for standard, plasterboard and skim, and skim only
Console.Write("enter name of customer: ");
customer = Console.ReadLine();
Console.Write("enter number of plaster areas to quote for: ");
nAreas = Convert.ToInt32(Console.ReadLine());
do
{
Console.WriteLine("Please Enter numbers of rooms between 1 and 5 only!!!!");
} while (nAreas < 1 && nAreas > 5); // loop
for (i = 0; i < nAreas; i++)
{
Console.WriteLine("Data entry for area {0}", i + 1);
Console.Write("enter 1 (standard), 2 (plasterboard and skim) or 3 (skim only): ");
jobType = Convert.ToInt32(Console.ReadLine());
Console.Write("enter width of area {0} in metres: ", i + 1);
width = Convert.ToDouble(Console.ReadLine());
Console.Write("enter height of area {0} in metres: ", i + 1);
height = Convert.ToDouble(Console.ReadLine());
// add base area cost to price based on area and type of plaster
itemCosts[i] = setupCostPerArea + (basePrices[jobType] * (width * height));
totalCost += itemCosts[i];
}
averageCost = totalCost / nAreas;
// main report heading
Console.WriteLine("\n");
Console.WriteLine("Plasterers R US Job Costing Report");
Console.WriteLine("===================================");
Console.WriteLine("\nName of customer: {0}\n", customer);
Console.WriteLine("No. of plaster areas: {0}", nAreas);
Console.WriteLine("Average Cost per area £{0:0.00}", averageCost);
// output subheadings
Console.WriteLine("Area\tCost\tDifference From Average");
for (i = 0; i < nAreas; i++)
{
Console.Write("{0}\t", i + 1);
Console.Write("£{0:0.00}\t", itemCosts[i]);
Console.WriteLine("£{0:0.00}", itemCosts[i] - averageCost);
}
Console.WriteLine("Total Cost £{0:0.00}", totalCost);
if (totalCost > discountPrice)
{
discount = totalCost * discountRate;
discountedTotal = totalCost - discount;
Console.WriteLine(" - Discount of £{0:0.00}", discount);
Console.WriteLine(" Discounted Total £{0:0.00}", discountedTotal);
}
Console.WriteLine("press enter to continue");
Console.ReadLine();
do
{
Console.Write("enter number of plaster areas to quote for: ");
nAreas = Convert.ToInt32(Console.ReadLine());
if(nAreas < 1 || nAreas > 5)
Console.WriteLine("Please Enter numbers of rooms between 1 and 5 only!!!!");
} while (nAreas < 1 || nAreas > 5); // loop
Two problems:
you are not asking for new input within your loop
you have the wrong exit condition for your loop - an illegal are number would be less than 1 or larger than 5.
Adjusting for both:
do
{
Console.Write("enter number of plaster areas to quote for: ");
nAreas = Convert.ToInt32(Console.ReadLine());
if(nAreas < 1 || nAreas > 5)
Console.WriteLine("Please Enter numbers of rooms between 1 and 5 only!!!!");
} while (nAreas < 1 || nAreas > 5); // loop
Related
I'm new to learning C# and I was wondering how to keep adding numbers I type to a total number. Right now instead of adding up all the numbers I typed in before typing 0, it just takes the last typed in number... The number count does go up however, which is why I'm pretty confused.
For example:
Enter number: 2
Enter number: 6
Enter number: 4
Enter number: 7
Enter number: 0
There are 4 positive numbers (Works like I intended)
The total amount is 7 (Is supposed to be 2+6+4+7 = 21)
Console.Write("Enter number: ");
string numberInput = Console.ReadLine();
double number = double.Parse(numberInput);
int count = 0;
double begin = 0;
double total = 0;
while (number != 0)
{
if (number >= 0)
{
count++;
total = begin + number;
}
Console.Write("Enter number: ");
number = double.Parse(Console.ReadLine());
}
double average = total / count;
Console.WriteLine("There are {0} positive numbers", count);
Console.WriteLine("The total amount is {0}", total);
Console.WriteLine("Your average is: {0}", average);
Console.ReadKey();
I figured it out already, had to change this:
total = begin + number;
to
total = total + number;
You don't need to use begin variable as you can sum input values like below:
total += number; // This is the same with 'total = total + number;'
As a suggestion, you can improve your code using do while loop like below:
int count = 0;
double total = 0;
double number;
do
{
Console.Write("Enter number: ");
number = double.Parse(Console.ReadLine());
if (number > 0)
{
count++;
total += number;
}
} while (number != 0);
double average = total / count;
Console.WriteLine("There are {0} positive numbers", count);
Console.WriteLine("The total amount is {0}", total);
Console.WriteLine("Your average is: {0}", average);
Console.ReadKey();
I need some help with the for-loop. I'm trying to sum up every fifth number that I type in, instead it sums them all up. What do I have to change?
int count = 0;
double total = 0;
Console.Write("Enter your number: ");
int input = int.Parse(Console.ReadLine());
while (input != 0)
{
count++;
for (count = 0; count <= 0; count += 5)
{
total = total + input;
}
Console.Write("Enter your number: ");
input = int.Parse(Console.ReadLine());
}
Console.WriteLine("The sum of every +5 numbers is: {0}", total);
Console.ReadKey();
Assuming that you enter a list of numbers, and the 1st number and every five afterwards is added (so 1st, 6th, 11th, etc.):
int count = 0;
double total = 0;
Console.Write("Enter your number: ");
int input = int.Parse(Console.ReadLine());
while (input != 0)
{
count++;
if (count % 5 == 1)
total = total + input;
Console.Write("Enter your number: ");
input = int.Parse(Console.ReadLine());
}
Console.WriteLine("The sum of every +5 numbers is: {0}", total);
Console.ReadKey();
This works by using the modulo operator (%). The modulo operator returns the remainder of a division operation involving the number you specify.
In the code if (count % 5 == 1), the question is:
Is the remainder of count divided by 5 equal to 1?
If so, it adds the number. If not, it is skipped
The reason the remainder is one is because we want results 1, 6, 11, etc:
1 / 5 = remainder 1
6 / 5 = remainder 1
11 / 5 = remainder 1
If you change the modulo value to 0 it will return the results at position 5, 10, 15, etc.
You could just store the numbers in a list and calculate it at the end:
var numbers = new List<int>();
Console.Write("Enter your number: ");
var input = int.Parse(Console.ReadLine());
while (input != 0)
{
numbers.Add(input);
input = int.Parse(Console.ReadLine());
}
var total = numbers.Where((x, i) => (i + 1) % 5 == 0).Sum(); // i + 1 since indexes are 0-based.
Console.WriteLine("The sum of every +5 numbers is: {0}", total);
You can try this:
double total = 0;
int passover = 4;
int input = 0;
do
{
passover++;
Console.Write("Enter your number: ");
int.TryParse(Console.ReadLine(), out input);
if ( passover != 5 ) continue;
passover = 1;
total = total + input;
}
while ( input != 0 );
Console.WriteLine("The sum of every fifth numbers is: {0}", total);
Console.ReadKey();
I think the best way is to recover all the values before making the sum, this code works:
double total = 0;
int input = -1;
List<int> allInput = new List<int>();
while (input != 0)
{
Console.Write("Enter your number: ");
input = int.Parse(Console.ReadLine());
allInput.Add(input);
}
for (int i = 0; i < allInput.Count()-1; i += 5)
{
total = total + allInput[i];
}
Console.WriteLine("The sum of every +5 numbers is: {0}", total);
Console.ReadKey();
Your sample would go forever, because there is no break point in your loop. You should always put a break point in your loop, otherwise it'll loop indefinitely.
Here is what you need :
int total = 0;
int count = 0;
Console.Write("Enter your number: ");
while (true)
{
int input = 0;
bool isNumber = int.TryParse(Console.ReadLine(), out input);
if (isNumber)
{
count++;
if (count % 5 == 0)
total += input;
}
else
{
break;
}
Console.Write("Add another number or press enter to get the sum : ");
}
Console.WriteLine("The sum of every +5 numbers is: {0}", total);
Console.ReadKey();
So, you'll need first to put the user input inside a loop, and keep asking the user for adding another number until hits the condition where you close this loop. In the example, I decided to break the loop if the user typed anything not a number. but I told the user to press enter to get the some, to end the loop. For you, you'll need to translate that to your application breakpoint, how would you want the user to get the sum ?. Then, change the condition to your logic, so it breaks the loop and gets the sum.
another point is that int.TryParse. When you want to convert strings to numbers (int, long, decimal ..etc). You should always use `TryParse, this will verify the number, if the conversion failed, it'll return false. This way you can maintain the conversion and do something about it.
I'm trying to create a 5,4 array in C# where each cell is made up of user data. The code I have below works sometimes, but not consistently. I can input data into cell [4,5] or [3,4] for example. However, sometimes when I run the code It does not accept the data and displays an empty cell. and Any tips?
decimal[,] departments = new decimal[4, 5];
//int count = 0;
Console.WriteLine("If you would like to run the program, type enter");
string exit = Console.ReadLine();
while (exit != "yes")
{
Console.WriteLine("What is the department number that you would like to enter sales for? Enter 9 to exit");
int departmentNo = int.Parse(Console.ReadLine());
Console.WriteLine("What day would you like to enter sales for?");
int input = int.Parse(Console.ReadLine());
Console.WriteLine("Enter sales");
departments[departmentNo, input] = decimal.Parse(Console.ReadLine());
Console.WriteLine("If you are finished, enter yes");
exit = Console.ReadLine();
}
Example output
0 0 0 0
0 0 0 0
0 0 500 0
500 0 0 0
You can use .GetUpperBound(dimension) to obtain the maximum bound (in the example below, it will return 1 for each dimension) for a specific dimension. Once you've got that, you just need to go through each position (I'm assuming you just need to fill data at each position).
Here's a sample:
int[,] items = new int[2, 2];
int width = items.GetUpperBound(0) + 1;
int height = items.GetUpperBound(1) + 1;
for (int x = 0; x < width; ++x)
{
for (int y = 0; y < height; ++y)
{
string input;
int inputValue;
do
{
Console.WriteLine($"Please input value for ({x},{y}): ");
}
while (!int.TryParse(input = Console.ReadLine(), out inputValue));
items[x, y] = inputValue;
}
}
Or if you do need the user to be able to specify where the sales value goes, you can update your code to add some validation checks:
while (exit != "yes")
{
Console.WriteLine("What is the department number that you would like to enter sales for? Enter 9 to exit");
int departmentNo = int.Parse(Console.ReadLine());
if (departmentNo > departments.GetUpperBound(0) || departmentNo < 0)
{
Console.WriteLine("Please enter a valid department number.");
continue;
}
Console.WriteLine("What day would you like to enter sales for?");
int input = int.Parse(Console.ReadLine());
if (input > departments.GetUpperBound(1) || input < 0)
{
Console.WriteLine("Please enter a valid input.");
continue;
}
Console.WriteLine("Enter sales");
if (!decimal.TryParse(Console.ReadLine(), out decimal value))
{
Console.WriteLine("Please enter a valid sales figure.");
continue;
}
departments[departmentNo, input] = value;
Console.WriteLine("If you are finished, enter yes");
exit = Console.ReadLine();
}
You probably want to change it to be similar to my example above so that you don't have to restart the entire loop again if the input is bad.
Because the departments has a fixed length of [4,5], it means the departmentNo can only be in range 0-3 and the input can only be in range 0-4. In addition, decimal keyword indicates a 128-bit data type, it's mean the value for a cell is in range ±1.0 x 10^28 to ±7.9228 x 10^28, which means 28-29 significant digits approximately. You should make some if conditions to make sure input values are in available range.
I wrote a code to find the sum of the digits and the reverse of a number-
static void Main(string[] args)
{
int number, sum = 0;
Console.WriteLine("Enter a number:");
number = int.Parse(Console.ReadLine());
while (number!= 0)
{
int m = number % 10;
number = number / 10;
sum = sum + m;
}
Console.WriteLine("Sum of digits of the number:" + sum);
Console.ReadLine();
int reverse = 0;
while (number!= 0)
{
reverse = reverse * 10;
reverse = reverse + number % 10;
number = number / 10;
}
Console.WriteLine("Reversed Number is:" + reverse);
Console.ReadLine();
}
but, the output for reversed number comes as 0. I checked my code, and I am not sure what is wrong with it.
You modify number as you sum the digits so when you try to go through the second loop, number is already at 0. Save off the input and reset number before the second loop:
Console.WriteLine("Enter a number:");
int input = int.Parse(Console.ReadLine());
number = input;
while (number!= 0)
{
// ...
}
Console.WriteLine("Sum of digits of the number:" + sum);
number = input; // reset number back to original input
// ...
There's also a possible solution to the problem using LINQ:
int number = 1234567890;
int sumOfDigits = number.ToString().Select(c => int.Parse(c.ToString())).Sum();
int reversedNumber = int.Parse(new string(number.ToString().Reverse().ToArray()));
Console.WriteLine($"sum of digits: {sumOfDigits}");
Console.WriteLine($"reversed number: {reversedNumber}");
I'm absolutely stuck so I would appreciate some guidance into how I can do this.
First off, here is my code so far:
int i;
int x = 0;
int b = 0;
Console.Write("\nHow many stocks to enter price for:\t"); // enter size of array
int size = int.Parse(Console.ReadLine());
double[] arr = new double[size]; // size of array
// Accepting value from user
for (i = 0; i < size; i++)
{
Console.Write("\nEnter price for stock #{0}: \t", ++x);
//Storing value in an array
arr[i] = Convert.ToDouble(Console.ReadLine());
}
Console.WriteLine("\n\n");
//Printing the value on console
for (i = 0; i < size; i++)
{
Console.WriteLine("Average Price: " + arr.Average() + " out of {0} stocks", x);
Console.WriteLine("Minimum Price: " + arr.Min());
Console.WriteLine("Number of stocks priced between 1.5-35: " + b);
}
Console.ReadLine();
Sorry, I'm not very sure on how to add the colors.
Anyway, I am stuck on displaying the number of stocks priced between 1.5 and 35. Shown in this line here: Console.WriteLine("Number of stocks priced between 1.5-35: "+ b);
Basically, it asks for the number of stocks to enter the price for. This will determine the size of the array. Then the user will enter the prices for the stocks x many times as they set it in the beginning. Thus calculating the Average price of a stock, the minimum price then (what i'm stuck on) the number of stocks priced between 1.5 and 35.
Also, i'm sure I could figure this out myself, but for some reason it is displaying the results 2 times each. Not too sure about that as well.
Any help would be appreciated as I've been stuck on this for too damn long.
Hello #nullcat as suggested by #Rob you have to fix your last loop. Also the variable b is never assigned and therefore you don't have the number of stocks that are priced between 1.5 and 35. I added a for sentence to check that
for (i = 0; i < size; i++)
{
//Check if the stock on index i is between 1.5 and 35 and add 1 to the variable b
if(arr[i] >=1.5 && arr[i] <=35.0){
b++
}
}
//Printing the value on console
Console.WriteLine("Average Price: "+ arr.Average() + " out of {0} stocks", x);
Console.WriteLine("Minimum Price: "+ arr.Min());
Console.WriteLine("Number of stocks priced between 1.5-35: "+ b);
Console.ReadLine();
Please check it out and let me know your comments
To provide a slightly shorter alternative solution:
static void Main()
{
int x = 0;
Console.Write("\nHow many stocks to enter price for:\t");
int size = int.Parse(Console.ReadLine());
double[] arr = new double[size];
for (int i = 0; i < size; i++)
{
Console.Write($"\nEnter price for stock #{++x}: \t");
arr[i] = Convert.ToDouble(Console.ReadLine()); //Storing value in an array
}
Console.WriteLine($"\r\nAverage Price: {arr.Average()} out of {arr.Count()} stocks");
Console.WriteLine($"Minimum Price: {arr.Min()}");
Console.WriteLine($"Number of stocks priced between 1.5-35: " +
$"{arr.Where(v => v >= 1.5 && v < 35).Count()}");
Console.ReadLine();
}