Sum the values of the array with a method - c#

So I'm trying to get 10 inputs from a user via Console, store in them in an array, calculate in a method what the sum is and return it. I'm still in the process, so this isn't mean to be completed code, but I'm confused at this point why my error list says Main should be closed after the while statement?
class Program
{//Start class
//We need to declare the size of our array
const int ARRAYSIZE = 10;
static void Main()
{//Start main
//We need to create a counter for how many entries we currently have
int entries = 0;
int sumScore = 0;
//We need to create the array
int[] myArray = new int[ARRAYSIZE];
//Start a loop to ask for input
do
{//Start loop
Console.Write("Please enter the score of each test: ");
int entry = int.Parse(Console.ReadLine());
myArray[entries] = entry;
entries++;
}
while (entries < ARRAYSIZE);//End loop
static void PrintArray(int[ ] myArray)
{
foreach(int value in myArray)
{
Console.WriteLine(value);
Console.ReadLine();
}
}
}//End main
}//End class

At the position of static void PrintArray(int[ ] myArray), you are declaring a new function. You need the }//End main before you declare a new function:
do
{//Start loop
Console.Write("Please enter the score of each test: ");
int entry = int.Parse(Console.ReadLine());
myArray[entries] = entry;
entries++;
}
while (entries < ARRAYSIZE);//End loop
}//End main
static void PrintArray(int[ ] myArray)
{
foreach(int value in myArray)
{
Console.WriteLine(value);
Console.ReadLine();
}
}

You have misplaced the closing bracket of your Main method. You may also want to call your PrintArray method after while (entries < ARRAYSIZE);//End loopand also compute your sum inside that method. But I guess it is because, as you said, it is a work in progress. Here is what it looks like
class Program
{
const int ARRAYSIZE = 10;
static void Main()
{//Start main
//We need to create a counter for how many entries we currently have
int entries = 0;
int sumScore = 0;
//We need to create the array
int[] myArray = new int[ARRAYSIZE];
//Start a loop to ask for input
do
{//Start loop
Console.Write("Please enter the score of each test: ");
int entry = int.Parse(Console.ReadLine());
myArray[entries] = entry;
entries++;
}
while (entries < ARRAYSIZE);//End loop
PrintArray(myArray);
}//End main
static void PrintArray(int[ ] myArray)
{
int sum = 0;
foreach(int value in myArray)
{
sum += value;
Console.WriteLine(value);
Console.ReadLine();
}
Console.WriteLine(sum);
}
}

This isn't a direct answer to your question, but I thought it might be interesting for you.
If you'd like to do this in a slightly easier way, then try this:
static void Main()
{
var sum =
Enumerable
.Range(0, ARRAYSIZE)
.Select(n =>
{
Console.WriteLine("Please enter the score of each test:");
return int.Parse(Console.ReadLine());
})
.Sum();
Console.WriteLine();
Console.WriteLine("The sum is:");
Console.WriteLine(sum);
}

Related

How to pass a value from one method to another method?

I'm a new to C#, please give me some advice on my program. How to pass a value from a method to another method? I am trying to do a calculation by using the value n from part_number in another method.
class Program
{
static void Main(string[] args)
{
int n;
part_number(out n);
Athlete myobj = new Athlete();
int n1 = 0;
for (n1 = 0; n1 < n; ++n1)
{
Write("Enter your participant name >> ");
myobj.participant_Name = ReadLine();
WriteLine("Event codes are:");
WriteLine("T Tennis");
WriteLine("B Badminton");
WriteLine("S Swimming");
WriteLine("R Running");
WriteLine("O Other");
Write("Enter event code>> ");
myobj.event_Code0 = ReadLine();
}
double totalCost;
const double cost = 30.00;
totalCost = cost * n1;
WriteLine("The total cost is {0}", totalCost);
static void part_number(out int n)
{
n = 0;
WriteLine("Enter the number the participant this year>> ");
n = System.Convert.ToInt32(ReadLine());
while (n >= 40)
{
WriteLine("Please enter number between 0 to 40");
n = System.Convert.ToInt32(ReadLine());
}
}
}
How to pass the value of n from part_number method and another method? I need to the use that value to do a calculation in another method. Should I build a class for it?
Thank you!
You would simply add an argument to the method such as:
void MyOtherMethod(int number)
{
// do something with number
}
If you wanted, you could pass multiple things by commad delimiting them:
void MyOtherMethod(int number, string name)
{
}
You can also have a method returning a value:
int MyReturningMethod(int number)
{
return number + 2;
}
The possibilities are endless.
You will have to call your other method and pass it in.
public static Main(string[] args)
{
PartNumer(out var partNumber);
OtherMethod(partNumber);
}
static void PartNumber(out int pn)
{
pn =1;
}
static void OtherMehtod(int partNumber)
{
Console.WriteLine($"Your part number is {partNumber}");
}

c# input only using slot 0

I'm trying to get a user to input 1 value into the array, and then exit to main menu, then the next person to enter a value gets his put into the next bracket, not replace slot 0, currently it just loops the first array bracket and replaces the number. Help would be much appreciated
static void Main(string[] args)
{
int[] myArray = new int[10];
while (true)
{
int enteredNumber;
Startmenu();
enteredNumber = Convert.ToInt32(Console.ReadLine());
if (enteredNumber == 1)
{
for (int i = 0; i < myArray.Length; i++)
{
Console.WriteLine("Insert Number:");
myArray[i] = Convert.ToInt32(Console.ReadLine());
}
Console.Clear();
Console.WriteLine("blabla");
Thread.Sleep(2000);
Console.Clear();
}
if (enteredNumber == 9)
{
if (Login(1234, 3) == true)
{
foreach (int number in myArray)
{
Console.WriteLine(number);
}
}
}
}
}
One problem I think you have in that code is that you're trying to do too much in one method. You might want to break out discreet operations into separate methods, which will both enable code reuse and also serve to make your code more readable.
First, you need a method that will get an int from the user. Let's write a helper method that does that, which takes in a string that will be displayed as a prompt to the user, and which will continue to prompt them until they enter a valid int. We can use int.TryParse to determine if they enter a valie int. It takes a string argument to parse, and an out int that will contain the parsed value if it succeeds. The method itself returns true if it was successful:
private static int GetIntFromUser(string prompt)
{
int result;
do
{
Console.Write(prompt);
} while (!int.TryParse(Console.ReadLine(), out result));
return result;
}
You don't show the code for ShowMenu, but it probably gives the user some menu choices, and I've added the functionality where it returns the menu choice entered by the user:
private static int ShowMenu()
{
int menuChoice;
do
{
Console.Clear();
Console.WriteLine("Main Menu:");
Console.WriteLine("1. Input an array item");
Console.WriteLine("9. Print the numbers\n");
menuChoice = GetIntFromUser("Enter your choice (1 or 9): ");
} while (menuChoice != 1 && menuChoice != 9);
return menuChoice;
}
Now, another thing you seem to be missing that might help here, is to add a "pause" to the program after printing out the array items, so the user has a chance to see them. I think this is probably the main problem. Currently you write them all out to the screen, then the while loop runs again and you don't get a chance to see it. Here's a helper method that asks the user to press a key when they're ready, and then waits for the user to press a key:
private static void WaitForUserInput()
{
Console.Write("\nPress any key to continue...");
Console.ReadKey();
}
We can also put the code to populate the array in a separate method. Since you want to enable the user to populate only one item at a time, we will need to keep track of which item is the next one to populate, so we'll set a class-level variable for that, and make use of it in the method. We'll populate that item, then increment the variable. Of course we have to first make sure the next item is not greater than the number of items available:
private static int NextIndexToPopulate = 0;
private static void PopulateNextArrayItem(int[] array)
{
if (array == null) return;
if (NextIndexToPopulate >= array.Length)
{
Console.WriteLine("The array is full; no items left to enter.");
WaitForUserInput();
}
else
{
array[NextIndexToPopulate] = GetIntFromUser("Enter number to insert: ");
NextIndexToPopulate++;
}
}
And another method can be used to print out the array:
private static void PrintArray(int[] array)
{
if (array == null)
{
Console.WriteLine("The array is null - nothing to print.");
}
else
{
Console.WriteLine("Here are the array items entered:");
for (int i = 0; i < NextIndexToPopulate; i++)
{
Console.WriteLine(array[i]);
}
}
}
You also didn't show the Login code, so here's a dummy method I'll use that always returns true:
private static bool Login(int first, int second)
{
return true;
}
Now, with all that extra stuff encapsulated in methods, our main code becomes a little more readable, there's less chance for errors, and when there are errors, it's more clear what they are:
private static void Main()
{
int[] myArray = new int[10];
while (true)
{
int enteredNumber = ShowMenu();
if (enteredNumber == 1)
{
PopulateNextArrayItem(myArray);
}
else if (enteredNumber == 9)
{
if (Login(1234, 3))
{
PrintArray(myArray);
WaitForUserInput();
}
}
}
}

How to loop through array to find all occurrences of an element C#

I'm pretty new to programming,
I have two arrays that correspond with eachother.
The First displays student names the other displays the students grade.
My goal is to loop through the arrays and print out all of the students who have the grade
87 for example.
As of right now I am able to print the first person with that grade, however the loop ends once it finds the first grade.
I'm having trouble figuring out how to find ALL of the people with that grade. Any help would be appreciated. Thanks
public static void OptionTwo()
{
LoadArray();
Console.WriteLine("Enter a student grade to see all students with that grade");
int userInput = Convert.ToInt32(Console.ReadLine());
int subscript;
subscript = Search(studentGrade, userInput, ref counter);
ShowResults(userInput, subscript, counter);
}
public static int Search(int[] studentGrade, int userInput, ref int counter)
{
counter = 0;
for (int s = 0; s < studentGrade.Length; s++)
{
counter++;
if (studentGrade[s] == userInput)
return s;
}
return -1;
}
public static void ShowResults(int userInput, int subscript, int counter)
{
//LOOP THROUGH ARRAY
Console.WriteLine();
Console.WriteLine("The following students have that grade: ");
Console.WriteLine();
if (subscript == -1)
Console.WriteLine("{0} is NOT in array, # of comparisons is {1}",
userInput, counter);
else
Console.WriteLine("{0} {1}", studentName[subscript].PadRight(20), studentGrade[subscript].ToString().PadRight(5));
}
Good programming is the art of reducing cognitive load. In your architecture, you - the programmer - know that both arrays are related to each other. If you create a Student class as such:
public class Student
{
public string Name;
public int Grade;
}
Now you can create a
var students = new List<Student>();
At this point, the compiler knows to associate student names and their grades, and you don't have to remember which arrays are correlated.
You can now return your filtered list using System.Linq as such:
return students.Where(x => x.Grade == 87);
You have reduced cognitive load. This may seem trivial for your example, but it becomes central to good programming in a large organization where you will spend most of your time maintaining someone else's code.
First, let's state the problem. We have two arrays:
string[] studentName = new string[] {
"Amy", "Bob", "Charly", "Dimitry", "Eva",
};
int[] studentGrade = new int[] {
80, 70, 80, 95, 68,
};
And you want to get all the students with the given grade. E.g. "Amy" and "Charly" for 80.
If it's your case you have to scan both arrays:
private static List<string> Search(string[] studentName, int[] studentGrade, int grade) {
List<string> result = new List<string>();
// Let's use good old for loop instead of Linq
for (int i = 0; i < studentGrade.Length; ++i)
if (studentGrade[i] == grade)
result.Add(studentName[i]);
return result;
}
public static void ShowResults(int userInput) {
Console.WriteLine();
Console.WriteLine("The following students have that grade: ");
Console.WriteLine();
List<string> list = Search(studentGrade, studentName, userInput);
if (list.Count <= 0)
Console.WriteLine("{0} is NOT in array", userInput);
else
Console.WriteLine("{0} {1}", string.Join(", ", list), userInput);
}
Linq is perfect for it:
var choosenGrades = studentGrade.Where(x=>x == userInput).ToList();
Remember to add import System.Linq
The reason your loop is ending after one is because you are returning the first instance of the subscript and the function ends there.
you should create a list of subscripts to return.
so you search function should be changed to something like this
public static List<int> Search(int[] studentGrade, int userInput, ref int counter)
{
var listOfSubscripts = new List<int>();
counter = 0;
for (int s = 0; s < studentGrade.Length; s++)
{
counter++;
if (studentGrade[s] == userInput)
listOfSubscripts.Add(s);
}
return listOfSubscripts;
}
And then your show results function should be like
public static void ShowResults(int userInput, List<int> subscripts, int counter)
{
//LOOP THROUGH ARRAY
Console.WriteLine();
Console.WriteLine("The following students have that grade: ");
Console.WriteLine();
if (subscript == -1)
Console.WriteLine("{0} is NOT in array, # of comparisons is {1}",
userInput, counter);
else
{
foreach(var subscript in subscripts)
{
Console.WriteLine("{0} {1}", studentName[subscript].PadRight(20), studentGrade[subscript].ToString().PadRight(5));
}
}
}

How do I split an array into two different arrays?

I can't seem to figure out how to fix my code so that it works. I need the user to be able to input their first name then space then the what they scored. Then I need to split the array into two different arrays and pass them to the four different methods to display to the user what they scored, etc. Can anyone help me figure this problem out?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace proj09LEA
{
class Program
{
static void Main(string[] args)
{
// declare and array of integers
int[] array = new int[10];
Console.WriteLine("\nSaturday Coder's Bowling Team");
Console.WriteLine("Enter in a name and score for each person on the team.");
Console.WriteLine("For example, Mary 143. Just hit Enter when you are done.\n");
// fill an array with user input
for (int i = 0; i < array.Length; i++)
{
Console.WriteLine("Enter in a name and score: ");
string userInput;
string[] parsedInput;
parsedInput = userInput.Split();
string name = parsedInput[0];
int score = int.Parse(parsedInput[1]);
}
Console.WriteLine("------------ Input Complete ------------\n");
Console.WriteLine("Here are the scores for this game:");
DisplayScore(array);
HighScore(array);
LowScore(array);
AverageScore(array);
Console.WriteLine("Press Enter to continue. . .");
Console.ReadLine();
}
static void DisplayScore(int[] array)
{
foreach (int n in array)
{
Console.WriteLine("{0}'s score was {0}.\n", array);
}
}
static void HighScore(int[] array)
{
int max = array.Max();
Console.WriteLine("Congratulations {0}, your score of {0} was the highest.", max);
}
static void LowScore(int[] array)
{
int min = array.Min();
Console.WriteLine("{0}, your score of {0} was the lowest. Better get some practice.", min);
}
static void AverageScore(int[] array)
{
int sum = array.Sum();
int average = sum / array.Length;
Console.WriteLine("The average score for this game was {0:d}.", average);
}
}
}
If you absolutely have to use simple primitive arrays, you would need two distinct arrays of the same size, to hold the names as strings and scores as ints:
class Program
{
const int MaxScores = 10; // .. Use a constant to ensure the sizes remain in sync
static void Main(string[] args)
{ ///
string[] names = new int[MaxScores];
int[] scores = new int[MaxScores];
// ... parse names into names[] and scores into scores[]
DisplayScore(names, scores);
You would then need to pass both arrays to the various methods:
static void DisplayScore(string[] names, int[] scores)
{
for(int i=0; i < MaxScores; i++)
{
Console.WriteLine("{0}'s score was {1}.\n", names[i], scores[i]);
}
}
// etc
However, there are better ways to do this, e.g. by defining a custom class for the tuple of Name, Score:
class PersonScore
{
public string Name {get; set;}
public int Score {get; set;}
}
You can then declare and pass the single array of PersonScore[] around.
PersonScore[] personScores = new PersonScore[MaxScores];
for (... prompting the user for data)
{
... parsing user input
personScores[i] = new PersonScore{Name = name, Score = score};
}
DisplayScore(personScores); // Pass around the single array
static void DisplayScore(IEnumerable personScores)
{
foreach(var personScore in personScores)
{
Console.WriteLine("{0}'s score was {1}.\n", personScore.Name, personScores.Score);
}
}
// etc - other methods
As others have mentioned, other collections are also possible alternatives to an array, most commonly List.
You can do like this. Just use Console.ReadLine() to get user input. This is what you do in your code. There are better ways to do this but following will solve your problem.Also you need to perform validation as well.
for (int i = 0; i < array.Length; i++)
{
Console.WriteLine("Enter in a name and score: ");
string userInput = Console.ReadLine();
string[] parsedInput;
parsedInput = userInput.Split(' ');
string name = parsedInput[0];
int score = int.Parse(parsedInput[1]);
array[i] = score;
}
Why you need to split array in to two arrays on containing names and other containing score. Its better to create a structure having String field for name and integer field for score and write Comparator for sorting the Array containing elements of this Data structure type and sort them.
It will solve all your problems and that too efficiently.
Not many data integrity checks in the methods you are using, but here are the extensions I use to split arrays or any type of enumerable. I have not tested these all that much, so I cannot guarantee that they will work. I have removed all my input validation, but I suggest you add those back your own way.
public static List<List<T>> Split<T>(this IEnumerable<T> collection, Int32 groupSize)
{
var collectionList = collection.ToList();
if (groupSize > collectionList.Count)
groupSize = collectionList.Count;
var chunks = new List<List<T>>();
while (collectionList.Any())
{
var chunk = collectionList.Take(groupSize);
chunks.Add(chunk.ToList());
collectionList = collectionList.Skip(groupSize).ToList();
}
return chunks;
}
public static List<List<T>> Split<T>(this IEnumerable<T> collection, Func<T, Boolean> splitFunction)
{
var collectionList = collection.ToList();
if (collectionList.IsNullOrEmpty())
return new List<List<T>>();
var indices = collectionList.FindIndices(splitFunction); // Custom method that searches for the indices that satisfy the predicate and returns the index of each matching item in the list.
if (indices.IsNullOrEmpty()) // equivalent to indices == null || !indices.Any()
return new List<List<T>> { collectionList };
var chunks = new List<List<T>>();
var lastIndex = 0;
if (indices[0] > 0)
{
chunks.Add(collectionList.Take(indices[0]).ToList());
lastIndex = indices[0];
}
for (var i = 1; i < indices.Count; i++)
{
var chunkSize = indices[i] - lastIndex;
var chunk = collectionList.Skip(lastIndex).Take(chunkSize).ToList();
if (chunk.IsNullOrEmpty())
{
break;
}
chunks.Add(chunk);
lastIndex = indices[i];
}
if (collectionList.Count - lastIndex > 0)
{
var lastChunk = collectionList.Skip(lastIndex).ToList();
chunks.Add(lastChunk);
}
return chunks;
}

random number gen, loop and store

How can I implement this so it is always ten numbers in length and how would I store n and r, loop 10 times, and store each loop aswell?
loop the random generator 10x to create 2x10 multiple 10 digit numbers.
namespace ConsoleApplication1
{
class Program
{
static void Main()
{
F();
F();
}
static Random _r = new Random();
static void F()
{
int n = _r.Next();
int r = _r.Next();
Console.WriteLine(n);
Console.WriteLine(r);
Console.ReadLine();
}
}
Something like this may be what you're looking for?
Though I'm not keen on the naming conventions, I'm not sure what these apply to, so can't exactly name them relevantly myself...
static int[] randomNumberArray0 = new int[10];
static int[] randomNumberArray1 = new int[10];
static Random random = new Random();
static void PopulateRandomNumberArrays()
{
for (int i = 0; i < 10; i++)
{
randomNumberArray0[i] = random.Next();
randomNumberArray1[i] = random.Next();
}
}
Update:
To execute this method then further output the values at a later time, try this:
static void PrintRandomNumberArrayValues(int[] array)
{
for (int i = 0; i < array.Length; i++)
{
Console.WriteLine("{0}", array[i]);
}
Console.WriteLine();
}
static void Main()
{
PopulateRandomNumberArrays();
PrintRandomNumberArrayValues(randomNumberArray0);
PrintRandomNumberArrayValues(randomNumberArray1);
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
}
Output would look something like this:
2044334973
153458690
1271210885
734397658
746062572
162210281
1091625245
123317926
410432738
989880682
866647035
481104609
834599031
1153970253
94252627
1041485031
1934449666
414036889
1886559958
2083967380
Further update:
For the generated values to be constrained to 10 digits in length, it means the minimum generated value must be larger than 999999999 and, since an int has a max value of 2,147,483,647, smaller or equal to that, so:
for (int i = 0; i < 10; i++)
{
randomNumberArray0[i] = random.Next(1000000000, int.MaxValue);
randomNumberArray1[i] = random.Next(1000000000, int.MaxValue);
}
I have a feeling this still may not satisfy your needs though, as what I see coming next is that the numbers should be able to be represented as 0000000001, for instance - let's see.
Yet another update:
As I thought, the value of numbers should not be constrained to our specified range, but rather only the output formatted appropriately; thus generation reverts to my original suggestion and printing is altered as so:
Console.WriteLine("{0:D10}", array[i]);
I guess you could use a list of tuples to store and return your results:
static List<Tuple<int,int>> F()
{
var results = new List<Tuple<int,int>> ();
for (int i = 0; i < 10; i++)
{
results.Add(new Tuple<int, int>(_r.Next(), _r.Next()));
}
return results;
}

Categories

Resources