Hi I am trying to make a program where the user can enter up to 25 numbers and then it tells the user the average, smallest and largest number and the mode of the numbers entered but I am not sure on how to do this.
Any Guidance would be appreciated
here is what I have so far
static void Main(string[] args)
{
Console.WriteLine("enter the amount of numbers you would like to use of: ");
int arraylength = Int32.Parse(Console.ReadLine());
int[] AverageArray = new int[25];
//filling the array with user input
for (int i = 0; i < AverageArray.Length; i++)
{
Console.Write("enter the numbers you wish to find the average for: ");
AverageArray[i] = Int32.Parse(Console.ReadLine());
}
//printing out the array
Console.WriteLine("here is the average: ");
for (int i = 0; i < AverageArray.Length; i++)
{
Console.WriteLine(AverageArray[i]);
}
Console.WriteLine(FindAverage(AverageArray));
}
public static double FindAverage(int[] averageNumbers)
{
int arraySum = 0;
for (int i = 0; i < averageNumbers.Length; i++)
arraySum += averageNumbers[i];
return arraySum / averageNumbers.Length;
}
public static double LargestNumber(int[] Nums, int Count)
{
}
public static double SmallestNumber(int[] Nums, int Count)
{
}
public static double Mode(int[] Nums, int Count)
{
}
}
var smallest = AverageArray.Min();
var largest = AverageArray.Max();
var mode = AverageArray.GroupBy(v => v)
.OrderByDescending(g => g.Count())
.First()
.Key;
If you don't know how to use linq
/*Assign Initial Value*/
int highestNum = numberArray[0];
int lowestNum = numberArray[0];
int sum = 0;
foreach (int item in numberArray)
{
/*Get The Highest Number*/
if (item > highestNum)
{
highestNum = item;
}
/*Get The Lowest Number*/
if (item < highestNum)
{
lowestNum = item;
}
//get the sum
sum = item + sum;
}
//display the Highest Num
Console.WriteLine(highestNum);
//display the Lowest Num
Console.WriteLine(lowestNum);
//Display The Average up to 2 decimal Places
Console.WriteLine((sum/numberArray.Length).ToString("0.00"));
public static double LargestNumber(int[] Nums, int Count)
{
double max = Nums[0];
for (int i = 1; i < Count; i++)
if (Nums[i] > max) max = Nums[i];
return min;
}
public static double SmallestNumber(int[] Nums, int Count)
{
double min = Nums[0];
for (int i = 1; i < Count; i++)
if (Nums[i] < min) min = Nums[i];
return min;
}
public static double Mode(int[] Nums, int Count)
{
double mode = Nums[0];
int maxCount = 1;
for (int i = 0; i < Count; i++)
{
int val = Nums[i];
int count = 1;
for (int j = i+1; j < Count; j++)
{
if (Nums[j] == val)
count++;
}
if (count > maxCount)
{
mode = val;
maxCount = count;
}
}
return mode;
}
Related
static void Main(string[] args)
{
string again;
do
{
Console.Write("Enter size to compute: ");
int size = Convert.ToInt32(Console.ReadLine());
int[] numbers = new int[size];
float[] numberS = new float[size];
Console.Write("Pick one of the operation \"(+) (-) (*) (/)\": ");
string operation = Console.ReadLine();
if (operation == "+")
{
for (int i = 0; i < size; i++)
{
Console.Write("Enter numbers: ");
numbers[i] = Convert.ToInt32(Console.ReadLine());
}
Console.WriteLine("The sum is:" + add(numbers));
}
else if (operation == "-")
{
for (int i = 0; i < size; i++)
{
Console.Write("Enter numbers: ");
numbers[i] = Convert.ToInt32(Console.ReadLine());
}
Console.WriteLine("The subtraction is:" + subtract(numbers));
}
else if (operation == "*")
{
for (int i = 0; i < size; i++)
{
Console.Write("Enter numbers: ");
numbers[i] = Convert.ToInt32(Console.ReadLine());
}
Console.WriteLine("The mulplication is:" + multiply(numbers));
}
else if (operation == "/")
{
for (int i = 0; i < size; i++)
{
Console.Write("Enter numbers: ");
numberS[i] = Convert.ToInt32(Console.ReadLine());
}
Console.WriteLine("The division is:" + division(numberS));
}
else Console.WriteLine("Invalid Input");
Console.Write("Do you want to compute again Y/N: ");
again = Console.ReadLine().ToUpper();
Console.Clear();
} while (again == "Y");
}
static int add(int[] numbers)
{
int total = 0;
for (int i = 0; i < numbers.Length; i++)
{
total += numbers[i];
}
return total;
}
static int subtract(int[] numbers)
{
int total = 0;
for (int i = 0; i < numbers.Length; i++)
{
total += numbers[i] - numbers[i];
}
return total;
}
static int multiply(int[] numbers)
{
int total = 0;
for (int i = 0; i < numbers.Length; i++)
{
total += numbers[i] * numbers[i];
}
return total;
}
static float division(float[] numbers)
{
float total = 0;
for (int i = 0; i < numbers.Length; i++)
{
total += numbers[i] / numbers[i];
}
return total;
}
I was expecting the same results in my phones calculator but no
Your code itself is fine. However your subtract, multiply and division methods are wrong. They are calculating something totally different than intended.
The multiply-method sums the squares of the entered numbers.
The subtract-method always subtracts the current number of itself which equals 0 and always results with a total of 0.
The division method always divides the current number by itself which is 1 and results with a total which equals the number of numbers entered.
Try these methods instead:
static int subtract(int[] numbers)
{
if (numbers.Length == 0)
return 0;
int total = numbers[0];
for (int i = 1; i < numbers.Length; i++)
{
total -= numbers[i];
}
return total;
}
static int multiply(int[] numbers)
{
if (numbers.Length == 0)
return 0;
int total = numbers[0];
for (int i = 1; i < numbers.Length; i++)
{
total *= numbers[i];
}
return total;
}
static float division(float[] numbers)
{
if (numbers.Length == 0)
return 0;
float total = numbers[0];
for (int i = 1; i < numbers.Length; i++)
{
total /= numbers[i];
}
return total;
}
In all of these methods the program first checks if there are any numbers passed. Otherwise it just returns 0.
If there are any numbers you set the first entered number to the total variable because it will be used anyway. The temporary result is always stored in the total variable.
Because the first element is already used the for-loop starts from index 1 instead of 0.
Then the operations are applied to the variable with all remaining numbers.
Edit: What would you have to do if there are two or more functions within in a method. what im having a problem with is that i need to return multiple variable from the maxminavg method and i dont know how to make it so each new variable carries the value from the maxminavg method to the main method.
static void Main(string[] args)
{
double max = 0d;
double sum = 0d;
double min = arr[0];
double avg = sum / arr.Length;
double avgrnd = Math.Round(avg, 2);
int index1 = 0;
int index2 = 0;
int index3 = 0;
string[] txt = File.ReadLines(#"c: \Users\Stark\Moisture_Data.txt").ToArray();
double[] arr = txt.Select(Double.Parse).ToArray();
print(arr);
Console.WriteLine();
maxminavg(arr, sum, max, min, avg);
Console.WriteLine();
Index(arr, max, min, avgrnd, index1, index2, index3);
Console.ReadLine();
}
public static void maximinavg(double[] arr, double sum, double max, double min, double avg)
{
for (int i = 0; i < arr.Length; i++) {
sum += arr.Length;
if (max < arr[i]) {
max = arr[i];
}
if (min > arr[i]) {
min = arr[i];
}
}
avg = sum / arr.Length;
Console.Write("\nMaximum value in array: {0}, Mimimum value {1}, average value {2}", max, min, avg);
}
public static void Index(double[] arr, double max, double min, double avgrnd int index1, int index2, int index3)
{
for (int i = 0; i < arr.Length; i++)
{
if (max == arr[i])
{
index1 = i;
}
if (min == arr[i])
{
index2 = i;
}
if (avgrnd == arr[1])
{
index3 = i;
}
}
Console.Write("\nMax index {0}, Min index {1}, avg index {2}", index1, index2, index3);
}
Why are you not returning the function result to the variable max?
I would recommend not using void functions and returning the function result straight to the variable as below.
static void Main(string[] args)
{
double max = 0d;
double sum = 0d;
int index = 0;
string[] txt = File.ReadLines(#"c: \Users\Stark\Moisture_Data.txt").ToArray();
double[] arr = txt.Select(Double.Parse).ToArray();
print(arr);
Console.WriteLine();
max = maximum(arr, sum, max);
Console.WriteLine();
Index(arr, max, index);
Console.ReadLine();
}
public static double maximum(double[] arr, double sum, double max)
{
for (int i = 0; i < arr.Length; i++) {
sum += arr.Length;
if (max < arr[i]) {
max = arr[i];
}
}
Console.Write("\nMaximim value in array: {0}", max);
return max;
}
public static void Index(double[] arr, double max, int index)
{
for (int i = 0; i < arr.Length; i++)
{
if (max == arr[i])
{
index = i;
}
}
The scope of the variables used within the function is limited to only that function. So you should return value of max as suggested by sjdm.
Another way of doing this is using a ref keyword. e.g
In main method:
max = maximum(arr, sum, ref max);
Signature of maximum method:
public static void maximum(double[] arr, double sum, ref double max)
I wrote a merge sort program, but I have problems calling It from another class. I need help. For some reason after I enter the size and the max number a get a black screen in the output. I believe that the solution is pretty easy, but I can't find the solution by myself
This is the class where It sorts the numbers
class MergeSort
{
public int[] Sort(int[] unsortedSequence)
{
int[] left;
int[] right;
int[] result = new int[unsortedSequence.Length];
if (unsortedSequence.Length <= 1)
return unsortedSequence;
int midPoint = unsortedSequence.Length / 2;
left = new int[midPoint];
if (unsortedSequence.Length % 2 == 0)
right = new int[midPoint];
else
right = new int[midPoint + 1];
for (int i = 0; i < midPoint; i++)
left[i] = unsortedSequence[i];
int x = 0;
for (int i = midPoint; i < unsortedSequence.Length; i++)
{
right[x] = unsortedSequence[i];
x++;
}
left = Sort(left);
right = Sort(right);
result = merge(left, right);
return result;
}
public static int[] merge(int[] left, int[] right)
{
int resultLength = right.Length + left.Length;
int[] result = new int[resultLength];
int indexLeft = 0, indexRight = 0, indexResult = 0;
while (indexLeft < left.Length || indexRight < right.Length)
{
if (indexLeft < left.Length && indexRight < right.Length)
{
if (left[indexLeft] <= right[indexRight])
{
result[indexResult] = left[indexLeft];
indexLeft++;
indexResult++;
}
else
{
result[indexResult] = right[indexRight];
indexRight++;
indexResult++;
}
}
else if (indexLeft < left.Length)
{
result[indexResult] = left[indexLeft];
indexLeft++;
indexResult++;
}
else if (indexRight < right.Length)
{
result[indexResult] = right[indexRight];
indexRight++;
indexResult++;
}
}
return result;
}
}
And this is the class where I'm trying to call the mergesort
class Program
{
static void Main(string[] args)
{
Console.Write("How Many Random Numbers Would you like to Generate : ");
int n = Convert.ToInt32(Console.ReadLine());
Console.Write("What is the Maximum Random Number Would you like to Generate : ");
int max = Convert.ToInt32(Console.ReadLine());
Console.Clear();
int[] unsortedSequence = generateRandomSequence(n, max);
MergeSort mergeSortEngine = new MergeSort();
int[] mergeSortedArray = mergeSortEngine.Sort(unsortedSequence);
Console.Write("Output for Merge Sort: \n\n");
OutputSequence(mergeSortedArray);
Console.WriteLine("\n\nPress Any Key to Continue...");
Console.ReadKey();
Console.Clear();
Because you didn't provide them, I wrote the missing generateRandomSequence() and OutputSequence methods in order to test your code and I can't reproduce your issue. Perhaps you should compare these to your own:
static int[] generateRandomSequence(int count, int max)
{
Random rn = new Random();
int[] seq = new int[count];
for (int i = 0; i < count; ++i)
{
seq[i] = rn.Next(0, max + 1);
}
return seq;
}
static void OutputSequence(int[] array)
{
for (int i = 0; i < array.Length; ++i)
{
if (i > 0)
{
Console.Write(", ");
}
Console.Write(array[i]);
}
Console.WriteLine();
}
Output from your code using the above methods:
It looks like you missing generateRandomSequence(n, max);
It might be like
public static int[] generateRandomSequence(int n, int max)
{
var rnd = new Random();
int[] seq = new int[n];
for (int ctr = 0; ctr < n; ctr++)
{
seq[ctr] = rnd.Next(1, max + 1);
}
return seq;
}
Then, in Program/Test class after Console.Write("Output for Merge Sort: \n\n"); you can iterate with foreach loop to display the sorted array.
foreach (var item in mergeSortedArray)
{
Console.WriteLine("{0}", item);
}
//OutputSequence(mergeSortedArray);
In a program that requires the user to input the number of integers, I cannot find out how to display the minimum of all the values.
static void Main(string[] args)
{
Console.WriteLine("\n Number of values:");
int num = Convert.ToInt32(Console.ReadLine());
int[] number = new int[num];
int i;
for (i = 0; i < number.Length; i++)
{
Console.WriteLine("\n Enter value:");
number[i] = Convert.ToInt32(Console.ReadLine());
}
for (i = 0; i < number.Length; i++)
{
int Min = number[0];
if (number[i + 1] < Min)
{
Min = number[i + 1];
}
}
Console.WriteLine("Smallest is {0}", Min);
}
Declare Min outside for loop
int Min = number[0];
for (i = 1; i < number.Length; i++)
{
if (number[i] < Min)
{
Min = number[i];
}
}
There are methods that do this for you:
int[] number = new int[num];
int min = number.Min();
Use this:
int minNumber = numbers.Min();
You can use the Min method to calculate this.
int min = number.Min();
public static int FindMinimum(int[] values)
{
int result = int.MaxValue;
foreach (int value in values)
result = Math.Min(result, value);
return result;
}
Your current code will overflow the array. You should check index 0 first and then check the rest.
Replace
for (i = 0; i < number.Length; i++)
{
int Min = number[0];
if (number[i + 1] < Min)
{
Min = number[i + 1];
}
}
with
int Min = number[0];
for (i = 1; i < number.Length; i++)
{
if (number[i] < Min)
{
Min = number[i];
}
}
However, you could simply use Enumerable.Min() as int Min = number.Min(x => x)
how about this?!
int[] Numbers = new int[5] { 3, 5, 7, 9, 11, 15 };
var q = (from Num in Numbers
select Num).Min();
Have a look at LINQ samples from MSDN: http://code.msdn.microsoft.com/101-LINQ-Samples-3fb9811b
you can use linq to object.
use Min method
sort your data in descending and take the first one
Declare Min as global static for example - public static int Min
Change the loop condition to for (i = 0; i < number.Length -1 ; i++) you exceed by one index range
Put Console.ReadLine on the end.
Or you don't have to store all numbers
static void Main(string[] args)
{
int min = int.MaxValue;
Console.WriteLine("\n Number of values:");
int num = Convert.ToInt32(Console.ReadLine());
var enteredValue = 0;
for (var i = 0; i < num; i++)
{
Console.WriteLine("\n Enter value:");
enteredValue = Convert.ToInt32(Console.ReadLine());
if (min>enteredValue) min = enteredValue;
}
Console.WriteLine("Smallest is {0}", min);
Console.ReadLine();
}
how can i find the min value in int arry with c#
With LINQ:
int min = theArray.Min();
note that this will error if there aren't any elements; check the .Length first (or alternatively, project to int?, but that adds overhead).
If you don't have LINQ available, then perhaps:
public static int Min(int[] arr) {
switch (arr.Length) {
case 0: throw new InvalidOperationException();
case 1: return arr[0];
case 2: return Math.Min(arr[0], arr[1]);
default:
int min = arr[0];
for (int i = 1; i < arr.Length; i++) {
if (arr[i] < min) min = arr[i];
}
return min;
}
}
I wrote bellow to compare what i said by #Marc Gravell, the way I told is a little faster in my PC, and the linq one is slowest way, Also if you change the position of functions (in code) you will always gain a better performance with a version with if
static void Main(string[] args)
{
Dictionary<string, List<long>> dic = new Dictionary<string, List<long>>();
dic["First"] = new List<long>();
dic["Second"] = new List<long>();
dic["Third"] = new List<long>();
for (int i = 0; i < 500; i++)
{
int[] array = GetRandomArray();
Stopwatch stopWacth = new Stopwatch();
stopWacth.Restart();
int n1 = FindMin(array);
stopWacth.Stop();
long firstTicks = stopWacth.ElapsedTicks;
dic["First"].Add(firstTicks);
stopWacth.Restart();
int n2 = AnotherFindMin(array);
stopWacth.Stop();
long secondTick = stopWacth.ElapsedTicks;
dic["Second"].Add(secondTick);
stopWacth.Restart();
int n3 = array.Min();
stopWacth.Stop();
long thirdTick = stopWacth.ElapsedTicks;
dic["Third"].Add(thirdTick);
Console.WriteLine("first tick : {0}, second tick {1}, third tick {2} ", firstTicks, secondTick, thirdTick);
}
Console.WriteLine("first tick : {0}, second tick {1}, third tick {2} ", dic["First"].Average(), dic["Second"].Average(), dic["Third"].Average());
Console.ReadLine();
}
public static int[] GetRandomArray()
{
int[] retVal = new int[1000000];
Random r = new Random();
for (int i = 0; i < 1000000; i++)
{
retVal[i] = r.Next(1000000000);
}
return retVal;
}
public static int FindMin(int[] arr)
{
switch (arr.Length)
{
case 0: throw new InvalidOperationException();
case 1: return arr[0];
case 2: return Math.Min(arr[0], arr[1]);
default:
int min = arr[0];
for (int i = 1; i < arr.Length; i++)
{
if (arr[i] < min) min = arr[i];
}
return min;
}
}
public static int AnotherFindMin(int[] arr)
{
if (arr.Length > 0)
{
int min = arr[0];
for (int i = 1; i < arr.Length; i++)
{
if (arr[i] < min) min = arr[i];
}
return min;
}
else
{
throw new InvalidOperationException();
}
}
}
// revised test by Marc (see comments discussion)
static class Test {
static void Main(string[] args)
{
Dictionary<string, List<long>> dic = new Dictionary<string, List<long>>();
dic["First"] = new List<long>();
dic["Second"] = new List<long>();
dic["Third"] = new List<long>();
const int OUTER_LOOP = 500, INNER_LOOP = 500000;
for (int arrSize = 1; arrSize <= 3; arrSize++)
{
for (int i = 0; i < OUTER_LOOP; i++)
{
int[] array = GetRandomArray(arrSize);
Stopwatch stopWacth = Stopwatch.StartNew();
for (int j = 0; j < INNER_LOOP; j++)
{
int n1 = FindMin(array);
}
stopWacth.Stop();
long firstTicks = stopWacth.ElapsedTicks;
dic["First"].Add(firstTicks);
stopWacth = Stopwatch.StartNew();
for (int j = 0; j < INNER_LOOP; j++)
{
int n2 = AnotherFindMin(array);
}
stopWacth.Stop();
long secondTick = stopWacth.ElapsedTicks;
dic["Second"].Add(secondTick);
stopWacth = Stopwatch.StartNew();
for (int j = 0; j < INNER_LOOP; j++)
{
int n3 = array.Min();
}
stopWacth.Stop();
long thirdTick = stopWacth.ElapsedTicks;
dic["Third"].Add(thirdTick);
//Console.WriteLine("{3}: switch : {0}, 0-check {1}, Enumerable.Min {2} ", firstTicks, secondTick, thirdTick, arrSize);
}
Console.WriteLine("{3}: switch : {0}, 0-check {1}, Enumerable.Min {2} ", dic["First"].Average(), dic["Second"].Average(), dic["Third"].Average(), arrSize);
}
Console.WriteLine("Done");
Console.ReadLine();
}
public static int[] GetRandomArray(int size)
{
int[] retVal = new int[size];
Random r = new Random();
for (int i = 0; i < retVal.Length; i++)
{
retVal[i] = r.Next(1000000000);
}
return retVal;
}
public static int FindMin(int[] arr)
{
switch (arr.Length)
{
case 0: throw new InvalidOperationException();
case 1: return arr[0];
case 2: return arr[0] < arr[1] ? arr[0] : arr[1];
default:
int min = arr[0];
for (int i = 1; i < arr.Length; i++)
{
if (arr[i] < min) min = arr[i];
}
return min;
}
}
public static int AnotherFindMin(int[] arr)
{
if (arr.Length > 0)
{
int min = arr[0];
for (int i = 1; i < arr.Length; i++)
{
if (arr[i] < min) min = arr[i];
}
return min;
}
else
{
throw new InvalidOperationException();
}
}
}