Query regarding calculation of average of some numbers program - c#

I am beginner in C# coding, and I am trying to write some code for the program where my program will show the average of numbers given by users. I have written below code, but I am thinking this would be more better and efficient. Can anyone please help me. Thanks in advance.
static void Main(string[] args)
{
int a=0;
double total = 0;
double result;
Console.Write("For how many numbers you want to do the average calculation: ");
a = int.Parse(Console.ReadLine());
double[] array = new double[a];
for (int j = 0; j < a; j++)
{
Console.Write("Please enter value for {0}: ", j+1);
array[j]= double.Parse(Console.ReadLine());
}
foreach (var item in array)
{
total += item;
}
result = total / a;
Console.WriteLine($"Your Calculated average value is {result}");
Console.ReadKey();
}

You dont need to take extra array for your purpose, you can do this just by adding each input value and then divide that total with total number of input items.
double total = 0;
double result;
Console.Write("For how many numbers you want to do the average calculation: ");
int a = int.Parse(Console.ReadLine());
for (int j = 0; j < a; j++)
{
Console.Write("Please enter value for {0}: ", j + 1);
total += double.Parse(Console.ReadLine());
}
result = total / a;
Console.WriteLine($"Your Calculated average value is {result}");
Console.ReadKey();

Related

Find the sum of user input (only the positive integers) C#

Find the sum of user input (only the positive integers). The code I wrote calculates them in weird way and i got confused. Thanks in advance.
Console.WriteLine("Enter numbers lenght: ");
int lenght = Convert.ToInt32(Console.ReadLine());
int sum = 0;
int input = 0;
for(int i = 0; i < lenght; ++i)
{
Console.WriteLine("Enter a number: ");
input = Convert.ToInt32(Console.ReadLine());
if(input >= 0)
{
sum = input + input;
}
}
Console.WriteLine("The sum of the positive numbers is: " + sum);
sum = input + input; is wrong,
change it to :
sum = sum + input;
or
sum += input;

Need help converting to Do-While loop

using System;
using System.Linq;
namespace PleaseHelpMe
{
public class SumAndAverage
{
public static void Main(string[] args)
{
var data = Enumerable.Range(1, 100);
Console.WriteLine("The sum is "+ data.Sum());
Console.WriteLine("The average is " + data.Average());
Console.ReadKey();
}
}
}
I need to change this to a Do-While loop with an expected output sum of 5050 and an average of 50.
A do/while loop is a bit of a strange choice here, I think. A better choice would be a for loop.
Anyway, you'll need to track the count and the current iteration i:
int i = 1;
int count = 100;
You will also need to store the sum. For big values (sum > 2147483647) you should use long:
int sum = 0;
Now you'll need to increment i until it matches count:
do
{
sum += i; // add current value of i to sum.
}
while (i++ < count);
Note that I've used i++ here because it returns the value of i before it is incremented, in contrast to ++i which returns the value of i after it is incremented. If ++i were used, you would have to compare it with <=.
Finally calculate the average and output the sum:
double average = sum / (double)count;
Console.WriteLine("The sum is " + sum);
Console.WriteLine("The average is " + average);
Console.ReadKey();
Try it online
I think that a for loop is better suited to this (although I understand if it's for an assignment you probably have to jump through the hoops of using do/while):
int sum = 0;
int count = 100;
for (int i = 1; i <= count; ++i)
{
sum += i;
}
double average = sum / (double)count;
Console.WriteLine("The sum is " + sum);
Console.WriteLine("The average is " + average);
Console.ReadKey();
int sum = 0;
decimal avg = 0;
do
{
sum += n;
avg = sum/n;
n++;
} while (n <= 100);
This should works.

School assignments about arrays and looping through them

I was assigned to make the below application
The computer inserts 20 random numbers (with values between 0 and 200)
in an array of 20 elements. After the array has been completely
filled, all elements are shown and the average of the numbers in the
array is determined and shown. Lastly, the difference between the
numbers in the array with the average is shown
I managed to make half of the program but now am at the point where I have to make the app shows the difference between each element of the array and the average and I can't manage to think of a formula to get this done !!!
this is my code so far and it Answers half of the question.
static void Main(string[] args)
{
int sum = 0;
int[] numbers = new int[20];
Random numbergenarator = new Random();
for(int i=0; i<numbers.Length;)
{
numbers[i] = numbergenarator.Next(0, 201);
Console.WriteLine("Element "+i +" is: "+ numbers[i]);
sum += numbers[i];
i++;
}
int average = sum / 20;
Console.WriteLine("The average is: " + average);
Console.ReadKey();
}
thanks in Advance
the resolution to my issues was by adding another (for loop) for generating the difference between each element and the average of elements.
for better comprehension read the code down through :D
static void Main(string[] args)
{
int sum = 0;
int[] numbers = new int[20];
Random numbergenarator = new Random();
for(int i = 0; i<numbers.Length;)
{
numbers[i] = numbergenarator.Next(0, 201);
Console.WriteLine("Element "+i +" is: "+ numbers[i]);
sum += numbers[i];
i++;
}
int average = sum / 20;
Console.WriteLine("The average is: " + average);
for (int i = 0; i < numbers.Length;)
{
Console.WriteLine("the difference between the average and the element " + i +
" is " + (average - numbers[i]));
i++;
}
Console.ReadKey();
}

C# Displaying every other number from a user in a console app

I need to write a console app that asks the user how many number (double) to enter. After accepting that many numbers, display every other number entered. There always seems to be an error when I try to use a double. I also get this error "System.IndexOutOfRangeException was unhandled
HResult=-2146233080
Message=Index was outside the bounds of the array."
after the the for loop has gone through the last loop for this line
myArrai1[i] = int.Parse(Console.ReadLine());
in the first for loop
this all the code I have been able to try to brainstorm with.
class Program
{
static void Main(string[] args)
{
Console.Write("Enter Item Count: ");
int number = int.Parse(Console.ReadLine());
int[] myArrai1 = new int[number];
int i = 0;
for (i = 1; i <= number; i++)
{
Console.WriteLine("Enter Number " + i.ToString() + ": ");
myArrai1[i] = int.Parse(Console.ReadLine());
}
for (i = 0; i < number; i++)
{
Console.WriteLine("Every other number entered: ");
Console.WriteLine(myArrai1[i += 2]);
}
Console.ReadLine();
}
}
}
Not too far off, main changes to fix fix this was loop#1 was set to 0 index to prevent out of range and loop#2 was simplified by intervaling at 2 of ++.
The rest of the changes were aesthetic; I changed the input Console.WriteLine to just Console.Write to keep the input on the same line, and moved the Every Other Line statement to precede the output display loop instead of being written on every iteration.
Console.Write("Enter Item Count: ");
int number = int.Parse(Console.ReadLine());
int[] myArrai1 = new int[number];
for (int i = 0; i < number; i++) {
Console.Write("Enter Number " + (i + 1) + ": ");
myArrai1[i] = int.Parse(Console.ReadLine());
}
Console.WriteLine("Every other number entered: ");
for (int j = 0; j < number; j = j + 2) {
Console.WriteLine(myArrai1[j]);
}

Find sum of elements of an array

What calculations do I need to find the total?
else if (a =2) {
TotalCredit = new int[15];
Console.WriteLine("please enter the credits");
int i = 0;
for (i = 0; i < 15; i++) {
int Credit = Convert.ToInt32(Console.ReadLine());
Total + Credit;
}
Console.WriteLine(Total);
}
You need to declare the variable Total ahead it use and it should be before loop to keep its scope available after loop. More than that your sum operation should be corrected using += operator
Correct it as follows:
int Total=0;
for (i = 0; i < 15; i++)
{
int Credit = Convert.ToInt32(Console.ReadLine());
Total += Credit;
}
Console.WriteLine(Total);
Try this.
else if (a ==2)
{
int[] TotalCredit = new int[15];
Console.WriteLine("please enter the credits");
int i = 0;
int Total = 0;
for (i = 0; i < 15; i++)
{
int Credit = Convert.ToInt32(Console.ReadLine());
Total += Credit;
}
Console.WriteLine(Total);
}
I've added this line int Total = 0; to declare a variable Total with the value 0, to store the total there.
Then I've changed a line in the for to be Total += Credit; which is the same as Total = Total + Credit; so every new value will be added and store into the variable Total.
This is a C# I guess, as convention https://msdn.microsoft.com/en-us/library/ff926074.aspx you'd better declare the variables to be lowercase.
As you have declared an array of ints I'm going to assume you want to keep the actual values the user has entered and not just the total. Make sure you add System.Linq in your using clauses.
else if (a==2)
{
var totalCredit = new int[15];
Console.WriteLine("please enter the credits");
for (int i = 0; i < 15; i++)
totalCredit[i] = Convert.ToInt32(Console.ReadLine());
var total = totalCredit.Sum();
Console.WriteLine (total);
}
A good idea would be to validate input gracefully, and minimize duplication of the magic constant 15—even better would be to assign it a meaningful name (the same goes for the a variable). Also, if you intend to store each input into the array for later usage outside of the else if block, you'll need to declare it outside of said block. However, if you do not need the individual credit values, the array is unnecessary.
const int numberOfCredits = 15;
int[] credits = new int[numberOfCredits];
...
else if (a == 2)
{
int total = 0;
int count = 0;
while (count < numberOfCredits)
{
Console.WriteLine("Enter credit #" + (count + 1).ToString() + ":");
int input;
if (int.TryParse(Console.ReadLine(), out input))
{
credits[count] = input;
total += input;
count += 1;
}
}
Console.WriteLine(total);
}

Categories