Search code examples
c#arraysmethodsreturn

Can I ask some questions about C# ? (Array)(Loop)


I'm studying C# programming. Nevertheless, I don't know how to solve these problems.

Like (Write a MyAvg method that gets 3 different double inputs and calculates the average of them. It should return the average as the output. Use the function in one simple program)

using System;
/*4. Write a MyAvg method that gets 3 different double inputs and calculates the average of them. It should return the average as the output. Use the function in one simple program*/
namespace ConsoleApp36
    {
        class Program
        {
            static void Main(string[] args)
            {
                double a, b, c;
                double avg = 0;

                Console.Write("Input the first value : ");
                a = Convert.ToDouble(Console.ReadLine());
                Console.Write("Input the second value : ");
                b = Convert.ToDouble(Console.ReadLine());
                Console.Write("Input the third value : ");
                c = Convert.ToDouble(Console.ReadLine());

                avg = (a + b + c) / 3;
                Console.WriteLine("Average of 3 different values is : {0}", avg);
            }

        }
    }

and

(Write a MyFact function that gets one integer as an input and calculates the factorial of it. It returns factorial as the result of the function. Use the function in one simple program. Use the function in one simple program.)

using System;
/*4. Write a MyAvg method that gets 3 different double inputs and calculates the average of them. It should return the average as the output. Use the function in one simple program*/
namespace ConsoleApp39
{
    class Program
    {
        static void Main(string[] args)
        {
            int i, f = 1, num;

            Console.Write("Input the number : ");
            num = Convert.ToInt32(Console.ReadLine());
            for (i = 1; i <= num; i++)
                f = f * i;

            Console.Write("The Factorial of {0} is: {1}\n", num, f);
        }
    }
}

Can you guys help me?


Solution

  • You should be more clear with your questions and show us that you actually tried to write some code. Anyways, here MyAvg and MyFact is just abbreviations for "MyAvarage" and "MyFactorial".

    As you should know, average avarage in mathematics is simply summing n numbers, and then dividing the sum with n. So you should implement it in your function MyAvg. Here is how you should take the avarage of three double numbers;

    double average = (a + b + c) / 3;
    

    Also, for the function MyFact, you should be taking an int parameter, and then simply be implying the factorial algorithm. Let's assume you've sent 5 as a parameter to MyFact(), then you should be multiplying the number 5 decreasingly in a for loop, such as 5*4*3*2*1, and it will give you the result. You can return this result, or simply print it directly in function.

    For loop to calculate factorials