How to display index number if variable is outside the main method - c#

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)

Related

Random Array generator in c #

I need to create an array with a specific number of rows and columns based on user input.
So far I have :
Console.WriteLine("Please enter the number of rows: ");
int rows = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Please enter the number of columns: ");
int cols = Convert.ToInt32(Console.ReadLine());
int[,] board = new int[rows, cols];
How do I take this information and then make a random list that goes up based on the entered information?
so it looks like this,
rows=2 colums =3
1 2 3
4 5 6
The program you want has two steps, but can be achieved in one. First create the 2d array, then set the value for each grid index. This can be achieved in one method.
First declare your new grid and counter. Then loop through every column in every row and set the value of each index as the counter + 1. This will count as the loop goes through ever position. For clarity here's an image of what this method would look like, having it take the number of rows and columns as a parameter.
void CreateGrid(int rows, int cols)
{
int[,] Grid = new int[cols, rows];
//create the grid
int counter = 0;
//Intailized the counter
for(int i = 0; i < rows; i++)
{
//loops through every column
Console.WriteLine("");
//Creates a newline to write the columns on.
for (int j = 0; j < cols; j++)
{
//Gos through every column.
Grid[j, i] = counter++;
//Sets the current grid position
//as the current counter number.
Console.Write(" " + Grid[j, i]);
//Writes that grid number in the current line
}
}
}
You need to use two loops for each row and column.
Console.WriteLine("Please enter the number of rows: ");
int rows = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Please enter the number of columns: ");
int cols = Convert.ToInt32(Console.ReadLine());
int[,] board = new int[rows, cols];
var r = new Random();
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
board[i, j] = r.Next(0, 10);
Console.Write(board[i, j]);
}
Console.WriteLine();
}
Then it gives an output like this:
Create a factory class that contains all the methods to generate array structures.
public static class Factory
{
static readonly Random rng = new Random();
public static int[] CreateRandomArray(int size, int minValue, int maxValue)
=> CreateRandomArray(rng, size, minValue, maxValue);
public static int[] CreateRandomArray(this Random rng, int size, int minValue, int maxValue)
{
var array = new int[size];
for (int i = 0; i < array.Length; i++)
{
array[i] = rng.Next(minValue, maxValue);
}
return array;
}
public static int[,] CreateRandomArray2(int rows, int cols, int minValue, int maxValue)
=> CreateRandomArray2(rng, rows, cols, minValue, maxValue);
public static int[,] CreateRandomArray2(this Random rng, int rows, int cols, int minValue, int maxValue)
{
var matrix = new int[rows, cols];
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
matrix[i, j] = rng.Next(minValue, maxValue);
}
}
return matrix;
}
public static double[] CreateRandomVector(int size, double minValue, double maxValue)
=> CreateRandomVector(rng, size, minValue, maxValue);
public static double[] CreateRandomVector(this Random rng, int size, double minValue, double maxValue)
{
var array = new double[size];
for (int i = 0; i < array.Length; i++)
{
array[i] = minValue + (maxValue-minValue) * rng.NextDouble();
}
return array;
}
public static double[,] CreateRandomMatrix(int rows, int cols, double minValue, double maxValue)
=> CreateRandomMatrix(rng, rows, cols, minValue, maxValue);
public static double[,] CreateRandomMatrix(this Random rng, int rows, int cols, double minValue, double maxValue)
{
var matrix = new double[rows, cols];
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
matrix[i, j] = minValue + (maxValue-minValue) * rng.NextDouble();
}
}
return matrix;
}
}
To be used like:
class Program
{
static void Main(string[] args)
{
int[,] A = Factory.CreateRandomArray2(rows: 2, cols: 3, minValue: 0, maxValue: 9);
double[] b = Factory.CreateRandomVector(size: 9, minValue: -1.0, maxValue: 1.0);
}
}
or as an extension method to an existing random number generator Random
class Program
{
static readonly Random random = new Random();
static void Main(string[] args)
{
int[,] A = random.CreateRandomArray2(rows: 2, cols: 3, minValue: 0, maxValue: 9);
double[] b = random.CreateRandomVector(size: 9, minValue: -1.0, maxValue: 1.0);
}
}

Finding minimum value of a table

I need to find the value and position of the lowest entry in the table. Problem is, I don't know how to specify it. I can't put any numeric in the int value for minimum because the user can always specify a higher value. It works for the highest value but it doesn't for the smallest.
Console.WriteLine("Podaj wymiar tablicy.");
int dlugosc = Convert.ToInt32(Console.ReadLine());
int[] tablica = new int[dlugosc];
int max = 0;
int min = tablica[0];
for (int i = 0; i < tablica.Length; i++)
{
Console.WriteLine("Podaj wartosc {0} elementu.", i + 1);
tablica[i] = Convert.ToInt32(Console.ReadLine());
}
for (int i = 0; i < tablica.Length; i++)
{
while (tablica[i] > max)
{
max = tablica[i];
}
}
for (int x = 0; x < tablica.Length; x++)
{
while (tablica[x] < min)
{
min = tablica[x];
}
}
int najmniejsze_miejsce = Array.IndexOf(tablica, min);
int najwieksze_miejsce = Array.IndexOf(tablica, max);
Console.WriteLine("Najwyzsza wartosc tablicy to {0}.", max);
Console.WriteLine("Najwieksza wartosc wystepuje na miejscu {0}.", najwieksze_miejsce);
Console.WriteLine("Najniższa wartość tablicy to {0}.", min);
Console.WriteLine("Najnizsza wartosc wystepuje na miejscu {0}", najmniejsze_miejsce);
Console.ReadKey();
you can just use:
Console.WriteLine(tablica.Min());
since your using an integer array
The current code is below:
int min = tablica[0];
for (int i = 0; i < tablica.Length; i++)
{
Console.WriteLine("Podaj wartosc {0} elementu.", i + 1);
tablica[i] = Convert.ToInt32(Console.ReadLine());
}
The min value being declared before the array is initialized means it will simply be zero. No value from your array can ever be less unless it's a negative number.
To fix, the min should be declared after the array is initialized:
for (int i = 0; i < tablica.Length; i++)
{
Console.WriteLine("Podaj wartosc {0} elementu.", i + 1);
tablica[i] = Convert.ToInt32(Console.ReadLine());
}
int min = tablica[0];`
You can find the first occurence of the min value in your table
int minIndex = Array.IndexOf(tablica, tablica.Min());
or simple:
Console.WriteLine(Convert.ToString(Array.IndexOf(tablica, tablica.Min())));
When you do need to do a scan you typically set the min value to Int.MaxValue and the max value to Int.MinValue before the loop and then you are guaranteed to set it on the first element and any element that improves either value.
You can then do it all in one loop (and you don't need to use while when you mean if). You can also track the index as you go:
int max = Int.MinValue;
int min = Int.MaxValue;
int maxindex = -1;
int minindex = -1;
for (int i = 0; i < tablica.Length; i++)
{
if (tablica[i] > max) { max = tablica[i]; maxindex = i; }
if (tablica[i] < min) { min = tablica[i]; minindex = i; }
}

Find the average. largest, smallest number and mode of a int array

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;
}

Finding minimum of several integers

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 to find the highest and the lowest number C#

I get three values from three variables. How can i check who is the highest number and who is the lowest number?
The numbers are represented like this:
private int _score1;
private int _score2;
private int _score2;
Code:
Public int Highest
{
return the highest number here;
}
public int Lowest
{
return the lowest number here;
}
Can i calculate the highest and the lowest number in my constructor?
The obligatory Linq answer:
Public int Highest(params int[] inputs)
{
return inputs.Max();
}
public int Lowest(params int[] inputs)
{
return inputs.Min();
}
The beauty of this one is that it can take any number of integer inputs. To make it fail-safe you should check for a null/empty inputs array (meaning nothing was passed into the method).
To do this without Linq, you basically just have to mimic the logic performed by the extension method:
Public int Lowest(params int[] inputs)
{
int lowest = inputs[0];
foreach(var input in inputs)
if(input < lowest) lowest = input;
return lowest;
}
Again, to make it foolproof you should check for an empty or null inputs array, because calling Lowest() will throw an ArrayIndexOutOfBoundsException.
This is one way to do it:
public int Highest
{
get { return Math.Max(_score1, Math.Max(_score2, _score3)); }
}
public int Lowest
{
get { return Math.Min(_score1, Math.Min(_score2, _score3)); }
}
int[] numbers = new[] { _score1, _score2, _score3 };
int min = numbers.Min();
int max = numbers.Max();
Highest
return (x > y) ? (x > z ? x : z) : (y > z ? y : z)
Lowest
return (x < y) ? (x < z ? x : z) : (y < z ? y : z)
Here's something you could do:
public class Numbers
{
private int _number1;
private int _number2;
private int _number3;
public readonly int Highest;
public readonly int Lowest;
public Numbers(int num1, int num2, int num3)
{
int high;
int low;
_number1 = num1;
_number2 = num2;
_number3 = num3;
high = num1 > num2 ? num1 : num2;
high = high > num3 ? high : num3;
low = num1 < num2 ? num1 : num2;
low = low < num3 ? low : num3;
Highest = high;
Lowest = low;
}
}
If you want to simply check which is the highest you can do this
private int _highest = _score1;
if (_score2 > _highest)
_highest = _score2
if (_score3 > _highest)
_highest = _score3
Similarly, you can find the lowest like so
private int _lowest = _score1;
if (_score2 < _lowest)
_lowest = _score2
if (_score3 < _lowest)
_lowest = _score3
Using LINQ-to-Objects, you could do something like this.
var numbers = new [] {_score1, _score2, _score3};
numbers.Sort();
var lowest = numbers.First();
var highest = numbers.Last();
For a reference: in some cases you'll be having more than three variables (possibly not knowing how many). If they are stored in an array, here's the way to do it:
int Highest(int[] numbers)
{
int highest = Int32.MinValue();
for (int i = 0; i < numbers.Length; i++)
{
if (numbers[i] > highest)
highest = numbers[i];
}
return highest;
}
int Lowest(int[] numbers)
{
int lowest = Int32.MaxValue();
for (int i = 0; i < numbers.Length; i++)
{
if (numbers[i] < lowest)
lowest = numbers[i];
}
return lowest;
}
This will work for any length of int array.
Find the Largest and smallest number
using System;
namespace LargeSmall;
{
class Program
{
public static void Main()
{
float large, small;
int[] a = new int[50];
Console.WriteLine("Enter the size of Array");
int max = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter the array elements");
for (int i = 0; i < max; i++)
{
string s1 = Console.ReadLine();
a[i] = Int32.Parse(s1);
}
Console.Write("");
large = a[0];
small = a[0];
for (int i = 1; i < max; i++)
{
if (a[i] > large)
large = a[i];
else if (a[i] < small)
small = a[i];
}
Console.WriteLine("Largest element in the array is {0}", large);
Console.WriteLine("Smallest element in the array is {0}", small);
}
}
Here is simple logic for finding Smallest Number
Input : 11, 0 , 3, 33 Output : "0"
namespace PurushLogics
{
class Purush_SmallestNumber
{
static void Main()
{
int count = 0;
Console.WriteLine("Enter Total Number of Integers\n");
count = int.Parse(Console.ReadLine());
int[] numbers = new int[count];
Console.WriteLine("Enter the numbers"); // Input 44, 55, 111, 2 Output = "2"
for (int temp = 0; temp < count; temp++)
{
numbers[temp] = int.Parse(Console.ReadLine());
}
int smallest = numbers[0];
for (int small = 1; small < numbers.Length; small++)
{
if (smallest > numbers[small])
{
smallest = numbers[small];
}
}
Console.WriteLine("Smallest Number is : \"{0}\"",smallest);
Console.ReadKey();
}
}
}

Categories