Answer to Question #191767 in C# for Zahrah

Question #191767

Write a program that reads in 20 numbers and calculates the average of the numbers which are smaller than 10.


1
Expert's answer
2021-05-11T10:00:00-0400
using System;

namespace Test
{
    class NumbersTest
    {
        static int Main()
        {
            const int NUMBERS_COUNT = 20;

            Console.WriteLine("Enter {0} numbers (one line, numbers separated by space):"
                             ,NUMBERS_COUNT);

            string   line = Console.ReadLine();
            string[] nums = line.Split();

            if(nums.Length != NUMBERS_COUNT)
            {
                Console.WriteLine("Bad input");
                return 1;
            }

            int sum   = 0;
            int count = 0;

            for(int i = 0; i < NUMBERS_COUNT; ++i)
            {
                int tmp;

                if(!int.TryParse(nums[i], out tmp))
                {
                    Console.WriteLine("Bad input");
                    return 1;
                }

                if(tmp < 10)
                {
                    sum += tmp;
                    ++count;
                }
            }

            if(count != 0)
            {
                Console.WriteLine("Average is: {0}", (float) sum / count);
            }
            else
            {
                Console.WriteLine("All numbers are bigger than 9");
            }

            return 0;
        }
    }
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
APPROVED BY CLIENTS