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();
}
Related
I`m quite new to the whole programming world.
And i started studying C#
i got the following exersice to do:
Write a program that upon the input of 2 numbers (a and b), u receive
an output of the sum of squares in between.
I.e. - The program receives a and b where b > a and calculates a^2
+ (a+1)^2 + (a+2)^2 + ... + (b-1)^2 + b^2.
E.g. - If a = 3 and b = 6, the output would be 86, since 3^2 +
4^2 + 5^2 + 6^2 = 9 + 16 + 25 + 36 = 86
But i don't have any idea where do i even begin.
I`m guessing i need some sort of loop within a loop maybe?
You need to use for loop for this. Please see below, if that helps-
int i, j, k;
int value=0;
Console.WriteLine("Enter the fist number ");
i = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter the second number ");
j = Convert.ToInt32(Console.ReadLine());
if (i > j)
{
Console.WriteLine("Second number should be greater then First");
Console.ReadLine();
Environment.Exit(0);
}
for (k = i; k <= j; k++)
{
value += k * k;
}
Console.WriteLine(value);
Console.ReadLine();
Perhaps a method that takes in two integers and returns a double is a good place to start (returning a double allows you to specify a wider range of numbers without getting inaccurate results):
public static double GetSumOfSquaresBetween(int first, int second)
{
}
Then you could implement the body by creating a loop that goes from the lowest number to the highest number, adding the square of the current number to a result, and then returning that result at the end.
Here's a Linq example that would most likely not be acceptable for this assignment but gives you the idea:
public static double GetSumOfSquaresBetween(int first, int second)
{
return Enumerable
.Range(Math.Min(first, second), Math.Abs(first - second) + 1)
.Select(number => Math.Pow(number, 2))
.Sum();
}
Try this
int a, b, sum = 0;
Console.WriteLine("Enter the fist number ");
a = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter the second number ");
b = Convert.ToInt32(Console.ReadLine());
if (a<b){
for (int x = a+1; x < b; x++)
{
sum += x * x;
}
Console.WriteLine(sum);
}
else{
Console.WriteLine("Wrong input!");
}
Console.ReadLine();
}
}
A for loop should do it.
double nTotal = 0;
for (int a = 3; a <= 6; a++)
{
nTotal += Math.Pow(a, 2);
}
I am trying to work out how to count how many numbers in an array fall between the values of, 1.5 - 35. I am struggling to work out which method I should use to achieve this. I was thinking maybe a for-each embedded loop but then the more I think about it the more I question that method. Any help would be appreciated on how I may achieve this, I will post my current code below as I have already worked out how to calculate the average and minimum price for the equation.
class Program
{
static void Main(string[] args)
{
read_stock_price();
}
static void read_stock_price()
{
Console.Write("Enter how many stocks to enter price for: ");
int numStocks = Convert.ToInt32(Console.ReadLine());
double[] arrayinput = new double[numStocks];
for (int i = 0; i < numStocks; ++i)
{
Console.Write("Enter price for stock number: ");
arrayinput[i] = Convert.ToDouble(Console.ReadLine());
}
double sum = arrayinput.Sum();
double average = sum / numStocks;
Console.WriteLine("Average price: {0} out of {1} stocks", average, numStocks);
Console.WriteLine("Minimum price: {0}", arrayinput.Min());
}
}
You can use LINQ instead of a for-each. First filter the array then count the elements.
var count = arrayinput
.Where(x => 1.5 <= x && x <= 35.0)
.Count();
Shortest way is Enumerable.Count
var count = arrayinput.Count(x => 1.5 < x && x < 35.0);
if we assumed arrayinput is your filled array you can use this:
double[] arrayinput = new double[numStocks];
double[] filteredArray = arrayinput.Where(p => p > 1.5 && p < 3.5).ToArray();
int count = filteredArray.Count();
this code filter your array with value between 1.5 & 3.5.
I have to write a simple program where you have to input student names and their average grade and then print out the highest average grade and who it belongs to. There are several topics here on how to find if value appears in array. The thing i'm struggling with is what to do if there are more than 1 students with the max average grade.
Here's what I have so far:
Console.WriteLine("Enter the overall count of students.");
int stuCount = Convert.ToInt32(Console.ReadLine());
string[] name = new string[stuCount];
double[] avg = new double[stuCount];
for (int i = 0; i < stuCount; i++)
{
Console.WriteLine("Enter the name of student # {0}.", i + 1);
name[i] = Console.ReadLine();
Console.WriteLine("Enter the average grade of {0}.", name[i]);
avg[i] = Convert.ToDouble(Console.ReadLine());
}
// Finding the max average
double maxAvg = avg[0];
for (int i = 1; i < stuCount; i++)
{
if (avg[i] > maxAvg)
{
maxAvg = avg[i];
}
}
// Displaying the max average
Console.WriteLine("The highest average grade is {0}.", maxAvg);
So, can I use Array.IndexOf() method to find multiple indices?
Thank you.
Consider using a class to represent the grades as so;
class Grade {
public String Name {get;set;}
public double Average {get;set;}
}
Then your code can be more like;
Console.WriteLine("Enter the overall count of students.");
int stuCount = Convert.ToInt32(Console.ReadLine());
List<Grade> allGrades = new List<Grade>();
for (int i = 0; i < stuCount; i++)
{
Console.WriteLine("Enter the name of student # {0}.", i + 1);
var name = Console.ReadLine();
Console.WriteLine("Enter the average grade of {0}.", name[i]);
var avg = Convert.ToDouble(Console.ReadLine());
Grade current = new Grade(){
Name = name,
Average = avg
};
allGrades.Add(current);
}
// Finding the max average
double maxAvg = allGrades.Max(g => g.Average);
var highestGrades = allGrades.Where(g => g.Average == maxAvg);
Console.WriteLine("The following Student(s) have the highest average grade:");
foreach(var grade in highestGrades){
// Displaying the max average
Console.WriteLine("Student: {0}. Grade: {1}.", grade.Name, grade.Average);
}
}
Another way is creating a class containing two properties (name and average grade), then generate a List and fill it in a for cycle. The next step is order by descending the list through average grade and select the first N element equals. After that you can simply print the result using a ForEach
After you've found the highest average just loop again through the averages array to see which ones are the max ones and print the stud using the index.
Console.WriteLine("The highest average grade is {0}.", maxAvg);
Console.WriteLine("The students with this average grade are");
for (int i = 0; i < stuCount; i++)
{
if (avg[i] == maxAvg)
{
Console.WriteLine(name[i]);
}
}
Here's the problem:
Write a program named TipsList that accepts seven double values
representing tips earned by a waiter each day during the week. Display
each of the values along with a message that indicates how far it is
from the average.
This is what I have figured out so far.
static void Main(string[] args)
{
double[] tips;
tips = new double[7];
double one = tips[0];
double two = tips[1];
double three = tips[2];
double four = tips[3];
double five = tips[4];
double six = tips[5];
double seven = tips[6];
double average = (one + two + three + four + five + six + seven) / 7;
//Now I am trying to take the tip 1,2,3,4,5,6, and 7 that the user has entered
//And display the diffrence of tip 1,2,3,4,5,6, and 7 from the average
//So one-average = tip 1 console.Write tip1 ??????
for (int i = 0; i <= 6; i++)
{
Console.Write("Please enter the amount of tips earned by waiter #" + i + ".");
tips[i] = Console.Read();
Console.Write("tips 1????????????HELP");
}
}
}
I have an understanding of how I would try and do it and think I should do
one-average = tip 1 console.Write tip1 ?????
but C# doesn't like it. I just don't get it still does C# only let me do it in 1 determined way.
I just realised this is for a class so I'd stay away from Linq, it would be too obvious for any teacher.
Simply just write out the value of each taken away from the average
foreach(double tip in tips)
{
Console.WriteLine(Average - tip);
}
Edit Just realised the problem is getting the input.
Your better off to use TryParse as this will handle invalid input
while(!double.TryParse(Console.ReadLine(), out tips[i]))
{
Console.WriteLine("Thats not a valid number");
}
Use somthing like this:
double[] tips = new double[7];
for (int i = 0; i < tips.Length; i++)
{
Console.Write("Please enter the amount of tips earned by waiter #" + i + ": ");
tips[i] = double.Parse(Console.ReadLine());
}
double average = tips.Average();
//without linq
/*
double sum = 0;
for (int i = 0; i < tips.Length; i++)
{
sum = sum + tips[i];
}
double average = sum / tips.Length;
*/
for (int i = 0; i < tips.Length; i++)
{
Console.WriteLine("Tip #" + i + " is: " + tips[i] + " - The difference between the average is: " + Math.Abs(tips[i] - average));
}
Console.ReadLine()
I was doing this program myself, and i realized that it is actually asking for a 2D array hence the 7 inputs for the 7 days of the week. you can accomplish that by usingdouble[,] tips = new double[7, 7];Then you would use 2 loops to access each index element
for (int i = 0; i < 7; i++)
{
for (int j = 0; j < 7; j++)
{
tips[i, j] = int.Parse(Console.ReadLine());
}
}`
Then you would first get an average(i.e add the sum of all indexes per day(7) or for the week(49) depending on how accurate you would want your data to be, then divide)
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