2

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

3 Answers 3

2

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).

Sign up to request clarification or add additional context in comments.

11 Comments

I did it but then i cannot use the '/' I get an errors saying that i cannot use that operand when working with int[]. Any suggestions?
Yes - you cannot divide a whole array of numbers by something, that doesn't make sense! Instead, you need to get down to a single value from that array, which I presume in your example is the sum of the numbers in the array. So create a new function that takes in an array of integers and returns a single integer which is the sum, and then use the results of that new function to then divide by the number of values in the array.
Here's a hint: for a function to take in an array, you need to put something like int[] scoreArray between the parentheses after the function name. Then you can refer to that array inside the function using the name scoreArray. For instance, you can (and will need to) do scoreArray.Length.
Thanks, I assume i should create this new function inside a method other than GetValues() ? or can it be within it? I'm thinking it will make more sense to create the sum function inside FindAverage(). Am I on the right track?
FYI, "function" and "method" mean the same thing. You could just calculate the total inside the FindAverage() method, yes. Or you could have a separate function/method to calculate it (better programming practise, and reusable too!).
|
1

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

5 Comments

+1 for making helpful recommendations. Your solution should work, and is probably the easiest solution in this case, but it is much harder to reuse than if you have the functions take in the array as a parameter. There are too many dependencies - e.g. FindAverage() relies on there being a member array called score that has already been correctly initialised. Thoughts?
@Icarus Thanks man, this is very helpful specially for people like me who are learning. This let's me see what I was doing wrong.
@Icarus Would you mind explaining to me why did you move int[] score out of GetValues() and what was wrong with it being inside of it?
@Oskar nothing wrong in general, but since all your methods are static and you needed to access score from other functions, it needed to be moved outside the GetValues method and be made static. Read about instance & static methods.
@GregL My intention was to explain some very basic principles. Yes, there are many things that can be refactored from my code to make it more generic but it requires a longer post and explaining far more things that I am willing to write about :)
0

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.

7 Comments

Thanks but I need to do this with only 3 methods (excluding main). and without pointer since i haven't gotten that far yet. Any ideas?
Ok how about making GetValues() return an array. Passing Show() the array, make a loop that displays them and adds them at the same time, and then work out the average and display that too.
Why only 3 methods? The best way of programming almost anything is to break it down into lots of little functions that just do one thing, and avoid repetition. Forcing you to use 3 functions is not helping you to be a better programmer.
If you really are confined to 3 methods, though, then I would suggest putting the logic to print the results into the Main() function, and then have the following 3 functions: GetValues(), GetTotal() and GetAverage(). Hint: GetTotal() will only be called in GetAverage(), if you don't need to print out the total.
Well, those are the requirements i was given. if it was for me i would've done everything inside Main haha. I think the firs thing i must do is change the code so GetValues returns the array, no doubts about it. But then i'd need to figure out a way to get that array sum done somewhere else. I know this may sound silly for someone experienced but I've been working for 3 days on this code. With the code i posed i had 2 out of 3 things working. By changing it now i will be down to where i started.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.