C# Dice Times each number is rolled - c#

I've created a Dice program which rolls a dice dependant on how many times the user wishes to roll. The problem I'm having is being able to calculate how many times each number appears.
Example. Roll Twice - Number is 5.
Number is 4.
I want to be able to count that a 4 and a 5 has being rolled and display it back to the user.
My Code so far
using System;
namespace Dice
{
class Dice
{
private Random randy;
int total;
public static void Main()
{
Dice myDice = new Dice();
myDice.randy = new Random();
Console.Clear();
myDice.manyThrow();
myDice.throwDice();
Console.ReadKey();
}
//*******************************************************
public void throwDice()
{
double count = 0;
while(count != total)
{
count++;
Console.WriteLine("Throw No " + count + " is " + oneThrow());
}
}
//*******************************************************
public int oneThrow()
{
return randy.Next(6) + 1; // pick a number from 1 to 6 and return this
}
public int manyThrow()
{
Console.Write("How many times do you want to roll\t");
total = Convert.ToInt32(Console.ReadLine());
return total;
}
public void countEm()
{
// This is where I intend to place the code
}
}
}
I've being trying to solve this for hours.

Add an array to count roll results:
using System;
namespace Dice
{
class Dice
{
private Random randy;
int total;
int [] rolls = new int[7];
public static void Main()
{
Dice myDice = new Dice();
myDice.randy = new Random();
Console.Clear();
myDice.manyThrow();
myDice.throwDice();
myDice.countEm();
Console.ReadKey();
}
//*******************************************************
public void throwDice()
{
double count = 0;
while (count != total)
{
count++;
Console.WriteLine("Throw No " + count + " is " + oneThrow());
}
}
//*******************************************************
public int oneThrow()
{
var result = randy.Next(6) + 1; // pick a number from 1 to 6 and return this
this.rolls[result]++;
return result;
}
public int manyThrow()
{
Console.Write("How many times do you want to roll\t");
total = Convert.ToInt32(Console.ReadLine());
return total;
}
public void countEm()
{
for (int i = 1; i<7; i++)
{
Console.WriteLine("{0} rolled {1} times", i, rolls[i]);
}
}
}
}

Try this:
static int[] counts = new int[6];
And in oneThrow():
int result = randy.Next(6);
counts[result]++;
return result + 1;
Then in countEm():
for (int i = 0; i < counts.Length; i++)
{
Console.WriteLine("{0}: {1}", i + 1, counts[i]);
}

Keep an array of the possible outcomes count.
class Dice
{
private Random randy;
private int total;
private static const int NUM_SIDES = 6;
private int[] counts;
public Dice()
{
randy = new Random();
counts = new int[ NUM_SIDES ];
}
public static void Main()
{
Dice myDice = new Dice();
Console.Clear();
int throws = myDice.manyThrow(); // need to save the number of throws
myDice.throwDice( throws );
countEm();
Console.ReadKey();
}
public void throwDice( int throws )
{
double count = 0;
while(count != throws)
{
count++;
int result = oneThrow();
counts[ result - 1 ]++; // NOTE: result-1 because arrays are 0-based.
Console.WriteLine("Throw No " + count + " is " + oneThrow());
}
}
// ...
public void countEm()
{
for( int i = 0; i < counts.Count; ++i )
Console.WriteLine( (i+1) + " thrown " + counts[i] + " times." );
}

If you just want to keep track of the count of each number rolled, then you add to your class an array of integers to store the count of each number rolled. The number of the dice roll could be the index into the array.
If you need to keep track of the order of the numbers rolled. Your class could could use a linked list or other ordered list to keep track of the numbers.
This sort of sounds like a homework assignment, so I'll leave the implementation details to the reader :)

Modify the countEM like this:
public void countEm(int numberOfThrows)
{
List<int> Throws = new List<int>(); //Create list, where value of throws will be stored.
for(int i = 0; i < numberOfThrows) //Loop as many times as are given by parameter.
{
Throws.Add(OneThrow()); //Add return value of throw to the list.
}
//Show values in Throws list.
foreach(var diceValue in Throws)
{
Console.WriteLine(string.Format("Value of throw: {0}", diceValue ));
}
}
coutEM should be called with the number of times you want to throw like:
countEM(5);
Above represents 5 throws. The result for example could be filled with:
1, 4, 6, 3, 4

Related

Compare 7 input numbers with 7 Random Numbers

I'm new in C sharp but I need help about comparing my input value and random numbers, any function, method or class I have to add..
List<int> lista1 = new List<int>();
for (int i = 1; i <= 7; i++)
{
try {
Console.Write("First Number {0}: ", i);
int x = Convert.ToInt16(Console.ReadLine());
lista1.Add(x);
} catch (Exception ex){
Console.WriteLine("The input number is incorret! It has to be whole number");
Console.WriteLine("Error: {0}", ex.Message);
i--;
}
Console.WriteLine("Random Numbers are: ");
InitArray();
Console.WriteLine(item);
}
If you have your inputs in a list, and your random numbers in another list, your can use the following code to know the count of what is common between your lists.
inputs.Intersect(randoms).Count
This is my interpretation.
class Program
{
private static Random rnd = new Random();
static void Main(string[] args)
{
do
{
uint[] myRandoms = GetRandoms();
uint[] userInput = GetUserInput();
List<uint> matches = GetMatches(userInput, myRandoms);
Console.WriteLine("Your Numbers");
PrintEnumerable(userInput);
Console.WriteLine("The Lottery Winners");
PrintEnumerable(myRandoms);
Console.WriteLine("Numbers You Matched");
PrintEnumerable(matches);
int NumOfMatches = matches.Count;
if (matches.Count >= 4)
Console.WriteLine($"You win! You matched {NumOfMatches} numbers.");
else
Console.WriteLine($"Sorry, you only matched {NumOfMatches} numbers.");
Console.WriteLine("Play again? Enter Y for yes and N for no.");
} while (Console.ReadLine().ToUpper() == "Y");
}
private static uint[] GetRandoms()
{
uint[] newRandoms = new uint[7];
int index = 0;
while (index < 7)
{
//.Next(int, int) limits the return to a non-negative random integer
//that is equal to or greater than the first int and less than the second the int.
//Said another way, it is inclusive of the first int and
//exclusive of the second int.
uint r = (uint)rnd.Next(1, 40);
if (!newRandoms.Contains(r)) //prevent duplicates
{
newRandoms[index] = r;
index++;
}
}
return newRandoms.OrderBy(x => x).ToArray();
}
private static uint[] GetUserInput()
{
uint[] inputs = new uint[7];
int i = 0;
while (i < 7)
{
Console.WriteLine("Enter a whole number between 1 and 39 inclusive. No duplicates, please.");
//Note: input <= 39 would cause an error if the first part of the
// if failed and we used & instead of && (And instead of AndAlso in vb.net).
//The second part of the if never executes if the first part fails
//when && is used. //prevents duplicates
if (uint.TryParse(Console.ReadLine(), out uint input) && input <= 39 && input >0 && !inputs.Contains(input))
{
inputs[i] = input;
i++; //Note: i is not incremented unless we have a successful entry
}
else
Console.WriteLine("Try again.");
}
return inputs.OrderBy(x => x).ToArray();
}
//I used a List<T> here because we don't know how many elements we will have.
private static List<uint> GetMatches(uint[] input, uint[] rands)
{
List<uint> matches = new List<uint>();
int i;
for (i=0; i<7; i++)
{
if(rands.Contains(input[i]))
matches.Add(input[i]);
}
//Or skip the for loop and do as Sunny Pelletier answered
//matches = input.Intersect(rands).ToList();
return matches.OrderBy(x=>x).ToList();
}
//You are able to send both List<T> and arrays to this method because they both implement IEnumerable
private static void PrintEnumerable(IEnumerable<uint> ToPrint)
{
foreach (uint item in ToPrint)
Console.WriteLine(item);
}
}
There are many ways to accomplish that, but a simple way is to use a for loop inside of another for loop. i.e
int[] userInputNumbers = {1,2,3,4,5,6,7};
int[] numbersToCompareTo = {1,9,11,12,4,6,16};
int countOfNumbersThatAreTheSame = 0;
for(int i=0; i<userInputNumbers.Length; i++)
{
for(int j=0; j<numbersToCompareTo.Length; j++)
{
if(userInputNumbers[i] == numbersToCompareTo[j])
{
countOfNumbersThatAreTheSame++;
}
}
}
Console.Write(countOfNumbersThatAreTheSame);
Console.Read();
This is how I would Go about approaching it Cleanly using CSharp.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp2
{
class Program
{
public List<List<int>> Players { get; set; } //Your Players
public List<int> RandomNumbers { get; set; } //Your Random numbers enerated my Computer
public List<List<int>> MatchedNumbers { get; set; } //to store Matched Numbers for each player
public int NumbersRequiredCount { get; set; } = 7; //Depends on how many numbers the players must guess, initialize to 7 numbers
Program()
{
//Instantiate your objects
Players = new List<List<int>>(); //List of Players with their list of guessed numbers
RandomNumbers = new List<int>();
MatchedNumbers = new List<List<int>>(); //To hold Matched Values
}
private List<int> GenerateAutoNumbers(int Count, int Min, int Max)
{
var Result = new List<int>(); //Result Container - will be returned
var Random = new Random(); //Create Random Number Object
for(int i = 0; i < Count; i++)
{
//Generate your random number and save
Result.Add(Random.Next(Min, Max));
}
//Return "Count" Numbers of Random Numbers generated
return Result;
}
public List<int> EvaluateMatches(List<int> Inputs, List<int> Bases)
{
var result = new List<int>();
//Inplement a counter to check each value that was inputted
for(int i = 0; i < Inputs.Count; i++)
{
for (int r = 0; r < Bases.Count; r++)
{
//Check if the current input equals the current Random Number at the given index
if(Inputs[i] == Bases[r])
{
//If matched. Add the matched number to the matched list
result.Add(Inputs[i]);
}
}
}
//At this point, all matched numbers are organized in result object
return result; //return result object
}
static void Main(string[] args)
{
Program App = new Program();
//Players must input numbers - Assuming they must guess between 1 - 100
//It can be as many players
//Player 1
App.Players.Add(new List<int> { 5, 47, 33, 47, 36, 89, 33 });
//Player 2
App.Players.Add(new List<int> { 1, 17, 38, 43, 34, 91, 24 });
//Player 3
App.Players.Add(new List<int> { 6, 74, 39, 58, 52, 21, 9 });
//At this point the inputs are all in for the 3 players
//Now generate your RandomNumbers
App.RandomNumbers = App.GenerateAutoNumbers(App.NumbersRequiredCount, 1, 100);
//Now you need to evaluate the guessed numbers
//For each Player
for(int p = 0; p < App.Players.Count; p++)
{
//Create the list for each user to hold the matched numbers
App.MatchedNumbers.Add(App.EvaluateMatches(App.Players[p], App.RandomNumbers));
}
//Now all Players numbers are evaluated, all you need is to print the results
Console.WriteLine("Results has been retrieved");
Console.Write("Generated Numbers are: ");
foreach(int i in App.RandomNumbers)
{
Console.Write(i + " ");
}
Console.WriteLine();
Console.WriteLine();
Console.WriteLine("Following Matches were Found: ");
for(int p = 0; p < App.Players.Count; p++)
{
Console.Write($"Player {p + 1} has {App.MatchedNumbers[p].Count} Matches: ");
foreach(int i in App.MatchedNumbers[p])
{
Console.Write(i + " ");
}
Console.WriteLine();
}
Console.Write("\n");
Console.WriteLine("Press any Key to Exit!");
Console.ReadKey();
}
}
}
It will print the numbers matched on the screen.
Try this tested and working example. If you run this method execRandomNumber();
You will get this output ::
The numbers returned are 18
The numbers matching are 18
The numbers returned are 15
The numbers matching are 15
The numbers returned are 17
The numbers returned are 19
The numbers matching are 19
The numbers returned are 16
The numbers matching are 16
The numbers returned are 14
The numbers returned are 20
Using directives ::
using System.Collections.Generic;
Declarations ::
public static List<int> lista1 = new List<int>();
public static List<int> returnedRandomList = new List<int>();
public static int[] myArrNums = new[] { 12, 25, 15, 16, 18, 19 };
public static int[] myRandArr = new[] { 14, 15, 16, 17, 18, 19, 20 };
Method 1 is for if you need to generate the random numbers ::
private void execRandomNumber()
{
//==============Don't have the numbers but need to generate them?==============
returnedRandomList = Gen(returnedRandomList, null);
returnedRandomList.ForEach(delegate (int num)
{
Console.WriteLine(string.Concat("The numbers returned are ", num));
if (numIsMatch(num) == true)
{
lista1.Add(num);
Console.WriteLine(string.Concat("The numbers matching are ", num));
}
});
//==============Generator will return list of random numbers, then we compared them==============
}
Your number generator ::
//==============Your number generator==============
private List<int> Gen(List<int> randGenerator, Random ranNum)
{
ranNum = new Random();
var rn = 0;
returnedRandomList.Clear();
do
{
if (randGenerator.Count == 7)
break;
rn = ranNum.Next(14, 21);
if (!(randGenerator.Contains(rn)) && randGenerator.Count <= 7)
randGenerator.Add(rn);
}
while (randGenerator.Count <= 7);
return randGenerator;
}
And for method two, assuming you have the numbers already generated and stored in a list or array of numbers, you can do the following ::
private void runArgs()
{
//==============Already have the numbers? Loop through them and compare==============
foreach (int i in myRandArr)
{
if (numIsMatch(i) == true)
{
lista1.Add(i);
}
}
lista1.ForEach(delegate (int num)
{
Console.WriteLine(string.Concat("The numbers that match are ", num));
});
}
And to compare your numbers to see if they are a match, you could do something like this ::
//==============Check is numbers are a match==============
private bool numIsMatch(int inValue)
{
foreach (int ii in myArrNums)
{
if (ii.Equals(inValue))
return true;
else
continue;
}
return false;
}
If you have any questions, I will get back to you tomorrow as it is rather late here now. Hope this helps.

Adding the sum of two randomly generated numbers (using arrays)

class Program
{
const int ROLLS = 51;
static void Main(string[] args)
{
Random r = new Random();
int sum = 0;
int[] dice1 = new int[ROLLS];
int[] dice2 = new int[ROLLS];
for (int roll = 0; roll <= 50; roll++)
{
dice1[roll] = GenerateNum(r);
dice2[roll] = GenerateNum(r);
Console.WriteLine("ROLL{0}: {1} + {2} = sum goes here", roll+1, dice1[roll]+1, dice2[roll]+1);
}
}
static int GenerateNum (Random r)
{
return r.Next(1, 7);
}
}
}
So what I have is two arrays to store two different int values that are randomly generated and what I am trying to achieve is the sum of these two randomly generated int values.
Upon execution it should display:
Roll 1: (random number) + (random number) = (sum of the two random numbers)
Just add the two together and store them in sum. Then present sum in the same manner you have presented the rest of the values in the output of the console:
dice1[roll] = GenerateNum(r);
dice2[roll] = GenerateNum(r);
sum = dice1[roll] + dice2[roll];
Console.WriteLine("ROLL{0}: {1} + {2} = {3}", roll + 1, dice1[roll], dice2[roll], sum);

C# Arrays in a Bowling Program. Wont use Lowest Score

I am trying to create a bowling program that when you enter in your name followed by your score, it will take the average, lowest, and highest scores of the players and print them. However for some reason I cannot get the lowest score to print, as when I hit enter twice, it will use the blank value instead of the lowest entered value and name. How can I fix this so that it will display the lowest score?
{
class Program
{
static void Main(string[] args)
{
const int SIZE = 10;
int i;
// create an array with 10 elements
string[] scoreInfo = new string[SIZE];
string[] names = new string[SIZE];
int[] scores = new int[SIZE];
for (i = 0; i < SIZE; i++)
{
// Prompt the user
Console.Write("Enter your first name and score on one line");
Console.WriteLine(" separated by a space.");
// Read one line of data from the file and save it in inputStr
string inputStr = Console.ReadLine( );
// if statement to break when the user enters a zero
if (inputStr == String.Empty)
{
break;
}
// The Split method creates an array of two strings
scoreInfo = inputStr.Split();
// Parse each element of the array into the correct data type
names[i] = scoreInfo[0];
scores[i] = int.Parse(scoreInfo[1]);
}
Console.WriteLine("The avarage score is {0}", AverageScore(scores, i));
Console.WriteLine("{0} scored the lowest at {1}", names[LowScore(scores, i--)], scores[LowScore(scores, i--)]);
Console.WriteLine("{0} scored the highest at {1}", names[HighScore(scores)], scores[HighScore(scores)]);
Console.ReadLine();
Console.ReadLine();
}
static int LowScore(int[] scores, int j)
{
int min = scores.Min();
return Array.IndexOf(scores, min);
}
static int HighScore(int[] scores)
{
int max = scores.Max();
return Array.IndexOf(scores, max);
}
static double AverageScore(int[] numbers, int j)
{
double average = 0;
for (int i = 0; i < j--; i++)
{
int product = 1;
product = numbers[i] * product;
average = product / j;
}
return average;
}
}
}
Use a different data structure and make less work for yourself.
Start with a dictionary that maps names to scores so that you don't have to mess around with indexes.
Then, LINQ is your friend, as you've already noticed. You don't need to create functions for things that already exist (like min/max/average).
eg.
Dictionary<string, int> ranking = new Dictionary<string, int>();
ranking.Add("adam", 20);
ranking.Add("bill", 10);
ranking.Add("carl", 30);
double avg = ranking.Average(kvp => (double)kvp.Value);
var sorted = ranking.OrderBy(kvp => kvp.Value);
var min = sorted.First();
var max = sorted.Last();
Console.WriteLine("Average: {0}", avg);
Console.WriteLine("Lowest: {0} with {1}", min.Key, min.Value);
Console.WriteLine("Highest: {0} with {1}", max.Key, max.Value);
Modify your Average function like this:-
static double AverageScore(int[] numbers, int j)
{
double sum = 0;
for (int i = 0; i < j; i++)
{
sum += numbers[i];
}
return (double)sum / j;
}
I am not sure why you were taking product of items for finding average of scores.
And Your Min function like this:-
static int LowScore(int[] scores, int j)
{
int min = scores.Where((v, i) => i < j).Min();
return Array.IndexOf(scores, min);
}
Here, you are passing the complete array of integer, so if only 3 players entered values, rest of the values will be initialized to default, i.e. 0 for int, Thus you were getting 0 as Min value.
Also, You need to change the method invocation like this:-
Console.WriteLine("{0} scored the lowest at {1}", names[LowScore(scores, i)], scores[LowScore(scores, i)]);

Random Number Array [duplicate]

This question already has answers here:
Most efficient way to randomly "sort" (Shuffle) a list of integers in C#
(13 answers)
Closed 8 years ago.
I'm trying to create a console application for basic banking functions. I understand how the random number generator works, but I need to set up an array so that the random numbers don't repeat, considering that the random number that is generated represents the users personalized PIN number. How would I implement this into my current code?
class BankAccount
{
private string firstName;
private string lastName;
private int accountNumber;
private decimal balance;
static public int customers = 0;
private int pinNumber;
public decimal Balance
{
get
{
return balance;
}
set
{
if (value >= 0)
balance = value;
else
{
Console.WriteLine("There will be an overdraft fee of $10.00.");
balance = value - 10;
}
}
}
public string FirstName
{
get
{
return firstName;
}
}
public string LastName
{
get
{
return lastName;
}
}
public int AccountNumber
{
get
{
return accountNumber;
}
}
public int PinNumber
{
get
{
return pinNumber;
}
}
public BankAccount(string firstNameValue, string lastNameValue)
{
firstName = firstNameValue;
lastName = lastNameValue;
accountNumber = customers + 1;
Random pin = new Random();
pinNumber = pin.Next(1111, 9999);
Balance = 0;
customers++;
}
public BankAccount()
{
Balance = 0;
customers++;
}
public void Credit(decimal amount)
{
Balance = Balance + amount;
}
public void Debit(decimal amount)
{
if (amount > Balance)
Console.WriteLine("Debit amount exceeded account balance.");
Balance = Balance - amount;
}
public static decimal AverageBalance(BankAccount[] accounts)
{
int count = 0;
decimal total = 0;
for (int i = 0; i < accounts.Length; i++)
{
if (accounts[i] != null)
{
total += accounts[i].Balance;
count++;
}
}
return total / count;
}
}
When you do new Random(), .Net uses the current time as seed. If you do this more than once in a short span of time, you'll generate the same string of random numbers. You might want to just make a static Random variable in BankAccount.
static Random random = new Random();
// later, in the constructor
pinNumber = random.Next(0, 10000); // 0 <= pinNumber < 10000
I changed the range on Next so that it will generate in the full range.
This method initializes an array with distinct random numbers. I didn't test it but it should work.
Create an array, initialize it using the code below and then pass it to your method.
public void SetValues(int[] array)
{
Random randomNumber = new Random();
for (int i = 0; i < array.Length; i++)
{
bool distinctNumber = true;
int number = randomNumber.Next(1, 100);
for (int j = 0; j < i; j++)
{
if (number == array[j])
{
distinctNumber = false;
break;
}
}
if ( distinctNumber )
array[i] = number;
else
--i;
}
}
While I do not understand the concern about repeating digits in a PIN number, the solution should be pretty straight forward. Your array will only contain very few (four) digits, so there is no problem in checking if a number is repeated. The simplest way would be to use the Contains method and only append if the number is unique. Contains will however look at all numbers in the array, so you should either initialize it to something you do not allow (negative values), or build it using a list.
Random rnd = new Random();
var pin = new[] {-1, -1, -1, -1};
for(var i = 0; i < pin.length; i++)
int nextDigit = rnd.Next(0, 10);
while (pin.contains(nextDigit)){ nextDigit + rnd.Next(0, 10); }
pin[i] = nextDigit;
}
By borrowing an extension method from this excellent answer based on the Fisher-Yates shuffle this can be accomplished relatively cleanly.
First define an extension method to shuffle a given List<T>:
public static void Shuffle<T>(this IList<T> list)
{
Random rng = new Random();
int n = list.Count;
while (n > 1) {
n--;
int k = rng.Next(n + 1);
T value = list[k];
list[k] = list[n];
list[n] = value;
}
}
Then define the function to generate a PIN consisting of distinct digits:
public IEnumerable GeneratePIN() {
var pinDigits = new List<int>(Enumerable.Range(0,10));
pinDigits.Shuffle();
return pinDigits.Take(4);
}
Or, as an even better option, you can also use a more generalized pin generation function to generate pins of arbitrary lengths from arbitrary types.
public static IEnumerable<T> GeneratePIN<T>(IEnumerable<T> valueRange, int length)
{
var pinValues = new List<T>(valueRange);
pinValues.Shuffle();
return pinValues.Take(length);
}
That said, it's worth mentioning that restricting the PINs to distinct values reduces to number of possible PINs from 10000 to 5040, making it significantly less secure.

Displaying Array within Method

This relates to another code I posted earlier but since this is a different question I decided to make a new post. I'm currently stuck with this code, I'm a c# beginner so this look complicated to me. I've been working on this code that is supposed to get an array from the user, calculate its average then display the results inside show(). I got this working to show the average of the array but now I need to actually display the array each value individually i.e. The 1st value you entered was : 12
The 2nd value you enteres was : 32
Thank guys!
private static int Array()
{
string inValue;
int[] score = new int[10];
int total = 0;
for (int i = 0; i < score.Length; i++)
{
Console.Write("Enter Value {0}: ", i + 1);
inValue = Console.ReadLine();
score[i] = Convert.ToInt32(inValue);
}
for (int i = 0; i < score.Length; i++)
{
total += score[i];
}
return total;
}
Change your GetValues() function to actually return the array of integers, then use the return value in your other functions.
i.e. change GetValues() to:
private static int[] GetValues()
{
string inValue;
int[] score = new int[5];
int total = 0;
for (int i = 0; i < score.Length; i++)
{
Console.Write("Enter Value {0}: ", i + 1);
inValue = Console.ReadLine();
score[i] = Convert.ToInt32(inValue);
}
return score;
}
EDIT: Here is how to use the GetValues() function above in a function to print out all the values. You should be able to work out the rest from here:
private static void PrintArray(int[] scoreArray)
{
for (int i = 0; i < scoreArray.Length; i++)
{
Console.WriteLine("Value #{0}: {1}", i + 1, scoreArray[i]);
}
}
Note how the scoreArray is passed in, as well as how each value is accessed, using scoreArray[i] (where i is a number from 0 to 4 inclusive).
Move int[] score out of GetValues and declare it at the class level making it static:
static int[] score = new int[5];
My next recommendation is that you don't do inside your functions more than what they claim to do from their name; for example, GetValues() should only get the values from user; not calculate totals (as you are doing) because it's misleading; it forces you to look at the implementation to know exactly what it does. Similarly for Show(); if the purpose is to show values entered by user, then call it ShowValues(); If the purpose is to show values entered by user as well as calculate the average, then name it something along the lines of ShowValuesAndAverage()
Here's a complete implementation of your program with my recommendations:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace testscores
{
class Program
{
static int[] score = new int[5];
//Get Values
private static void GetValues()
{
string inValue;
for (int i = 0; i < score.Length; i++)
{
Console.Write("Enter Value {0}: ", i + 1);
inValue = Console.ReadLine();
score[i] = Convert.ToInt32(inValue);
}
}
//FIND AVERAGE
private static double FindAverage()
{
double total = 0.0;
for (int i = 0; i < score.Length; i++)
{
total += score[i];
}
double average = total / 5.0;
return average;
}
//Show
static void ShowValuesAndAverage()
{
Console.WriteLine("The values are:");
for (int i = 0; i < score.Length; i++)
{
Console.WriteLine(string.Format("The {0} value you entered was {1}", i + 1, score[i]));
}
Console.WriteLine("The average is: {0}", FindAverage());
}
//Main
static void Main()
{
GetValues();
ShowValuesAndAverage();
Console.ReadKey();
}
}
}
Make one function for GetValues() and return the array. Then pass the array into a AddValues() function, and into Show().
Either that or read up on how to use pointers, but that might be overcomplicating things a little.

Categories

Resources