Total sum/average of random numbers in c# - c#

I am new to programming and i would be delighted if someone could help me with the following question: "Write a program that randomly selects integers whose values range from 0 to 9. The program will calculate the average of the random numbers and print how many of the random numbers are larger than the average. The program's user will specify how many numbers will be randomly generated". How do you get the total sum of random numbers so you can get the average? This is what i got so far:
int ChosenRandom;
Console.Write("Choose a number between 0-10; ");
ChosenRandom = int.Parse(Console.ReadLine());
Random rnd = new Random();
int RandomNumber = rnd.Next(0, 10);
for (int i = 0; i < ChosenRandom; i++)
{
Console.WriteLine("Random numbers: " + rnd.Next(0, 10));
}
int TotalRandom;
TotalRandom = ChosenRandom + (RandomNumber);
Console.WriteLine("Total is:" + TotalRandom);
int avr;
avr = TotalRandom / ChosenRandom;
Console.WriteLine("Average is: " + avr);
if (ChosenRandom > avr)
{
Console.WriteLine("Numbers larger than average" + ChosenRandom);
}
else
{
Console.WriteLine("All numbers under average");
}

simplest way is by using arrays,
store the numbers in an array while generating them
use the array elements to find the total and average
traverse through array comparing each element with that of average

Check if this solution helps for you.
I have used linq to create average and find all numbers above the 'average'.
using System;
using System.Linq;
namespace Test
{
class Program
{
static void Main()
{
int chosenRandom;
Console.WriteLine("Choose a number between 0-10");
chosenRandom = int.Parse(Console.ReadLine());
Random rand = new Random();
double[] randomNumbers = new double[chosenRandom];
for(int i = 0; i < chosenRandom; i++)
{
Console.WriteLine("Random numbers: " + (randomNumbers[i] = rand.Next(0, 10)));
}
double average = randomNumbers.Average(t => t);
var numbersAboveAverage = randomNumbers.Where(t => t > average);
Console.WriteLine("Average of all random numbers - {0}", average);
foreach(var number in numbersAboveAverage)
Console.WriteLine(number);
}
}
}

Your program looks good. But, you understood the question in a wrong way! The question says that the value of random integers should be 0-9. Not the no of random numbers. The number of random numbers can be of any value as given by user.
Please find below the complete implementation.
class Program
{
static void Main(string[] args)
{
//Step 1. Get the no of random numbers (n) to be generated from user.
Console.WriteLine("Enter the no of Random numbers: ");
int n = int.Parse(Console.ReadLine());
//Step 2. Generate 'n' no of random numbers with values rangeing from 0 to 9 and save them in an array.
Random rand = new Random();
int[] randCollection = new int[n];
for (int i = 0; i < n; i++)
{
randCollection[i] = rand.Next(9);
Console.WriteLine("Random No {0} = {1}", i + 1, randCollection[i]);
}
//Step 3. Compute Average
double average = randCollection.Average();
Console.WriteLine("Average = {0}", average);
//Step 4. Find out how many numbers in the array are greated than the average.
int count = 0;
foreach(int i in randCollection){
if (i > average) count++;
}
Console.WriteLine("No of random numbers above their average = {0}", count);
Console.ReadLine();
}
}
Hope this helps. Let me know if you have any questions.

Related

is there a way to make random numbers in a list that i can decide how many numbers that should be there c#

I'm trying to get a list with random numbers with my decision
when I start the application I get to decide which number I want it to insert/count but insert doesn't do anything, I know that am missing something coding with the number generator but I just can't find out what it is.
So basically i want it to show this if i typed 5
Random Number
Random Number
Random Number
Random Number
Random Number
then if i typed 3 i want it to show me how many three's are there.
for now I made this code:
Console.Write("insert number to decide: ");
int numbers = Convert.ToInt32(Console.ReadLine());
Console.Write("Number to count: ");
int yoy = Convert.ToInt32(Console.ReadLine());
Random random = new Random();
numbers = random.Next(0, 10);
var number = numbers;
var count = 0;
var digit = yoy;
var n = number;
while (n > 0)
{
if (n % 10 == digit)
count++;
n = n / 10;
}
Console.WriteLine($"Number: {number}");
Console.WriteLine(
$"Digit {digit} appears {count} times.");
Console.ReadKey();
Let me try to explain your code
Console.Write("insert number to decide: ");
int numbers = Convert.ToInt32(Console.ReadLine());
Console.Write("Number to count: ");
int yoy = Convert.ToInt32(Console.ReadLine());
Random random = new Random();
numbers = random.Next(0, 10); // You are overwriting user input here from line 2.
var number = numbers; // Redundant duplicate variable.
var count = 0;
var digit = yoy;
var n = number;
while (n > 0)
{
if (n % 10 == digit)
count++;
n = n / 10;
}
Console.WriteLine($"Number: {number}");
Console.WriteLine(
$"Digit {digit} appears {count} times.");
Console.ReadKey();
What are you trying to achieve?
If you want to count the occurrence of a digit in a random number between 0 and the users input, then I would write this on line 6:
numbers = random.Next(0, numbers + 1);
Remove '+ 1' if users input should not be included.
UPDATE:
for your updated explanation i would write:
Console.Write("insert number to decide: ");
string userNumber = Console.ReadLine();
Console.Write("Number to count: ");
string userYoy = Console.ReadLine();
int number = 0;
int yoy = 0;
int count = 0;
bool numbersSuccess = int.TryParse(userNumber, out number);
bool yoySuccess = int.TryParse(userYoy, out yoy);
if(numberSuccess && yoySuccess)
{
Random random = new Random();
List<int> numbers = new List<int>();
for(int i = 0; 0 < number; i++)
{
int randomNumber = random.Next(0,10);
if(randomNumber == yoy)
{
count++;
}
Console.WriteLine($"Number: {randomNumber}");
}
Console.WriteLine(
$"Digit {yoy} appears {count} times.");
}
else
{
Console.WriteLine("Something went wrong, only type hole numbers!");
}
Console.ReadKey();
UPDATE #2
For an N digit long random number, you could write something like this:
Console.Write("insert number to decide: ");
string userNumber = Console.ReadLine();
Console.Write("Number to count: ");
string userYoy = Console.ReadLine();
int numberOfDigits = 0;
int yoy = 0;
int count = 0;
bool numbersSuccess = int.TryParse(userNumber, out numberOfDigits );
bool yoySuccess = int.TryParse(userYoy, out yoy);
if(numberSuccess && yoySuccess)
{
int randomMax = (int)Math.Pow(10,numberOfDigits);
Random random = new Random();
int number = random.Next(0,randomMax);
var n = number;
while (n > 0)
{
if (n % 10 == digit)
count++;
n = n / 10;
}
Console.WriteLine($"Number: {number}");
Console.WriteLine($"Digit {digit} appears {count} times.");
}
else
{
Console.WriteLine("Something went wrong, only type hole numbers!");
}
Console.ReadKey();

C# How to print/show the ''difference'' between all numbers in an Array and the average

I am new to c# and trying to learn the concept of arrays. In my program, I want to show the difference between all the numbers in the array and the average. I only managed to print 1 element(number) in the array with the difference.
If you try to run my program it is divided into 3 parts. the last part is where I am stuck. it only prints the last(19th) element/difference of the array instead of all the Elements.
Any tips are welcome :)
(FYI, I did not yet learn the concept of methods/functions.)
static void Main(string[] args)
{
int[] Elements = new int[20]; // this creates/declares an integer array with 20 Elements
double avg = 0, sum = 0, diff = 0; // declare average variable
for (int i = 0; i < Elements.Length; i++) // this is a loop to show the random numbers of elements
{
int Element = i; // declare the Element variable
Random rn = new Random();
int numbers = rn.Next(0, 200); // creates a number between 0 and 200
Console.WriteLine("Element {0} is {1}", Element, numbers); // print values
sum += numbers; // calculate the sum of numbers
avg = sum / Elements.Length; // calculate average of the sum
if (avg > numbers) // calculate diffrence
{
diff = avg - numbers;
}
else
{
diff = numbers - avg;
}
if (Element == 19)
{
Console.WriteLine("\n");
Console.WriteLine("The average is: {0}", avg);
Console.WriteLine("\n");
for (int z = 0; z < Elements.Length; z++)
{
Console.WriteLine("Diffrence between Element {0} and average is: {1}", Element, Math.Abs(diff));
}
}
}
Console.ReadKey();
}
I made sure the number was added to the array.
The creation of the Random instance should be outside the array otherwise the generated numbers won't be random.
Adjusted the last loop.
int[] Elements = new int[20]; // this creates/declares an integer array with 20 Elements
double avg = 0, sum = 0, diff = 0; // declare average variable
Random rn = new Random();
for (int i = 0; i < Elements.Length; i++) // this is a loop to show the random numbers of elements
{
int Element = i; // declare the Element variable
int numbers = rn.Next(0, 200); // creates a number between 0 and 200
Console.WriteLine("Element {0} is {1}", Element, numbers); // print values
Elements[Element] = numbers;
sum += numbers; // calculate the sum of numbers
avg = sum / Elements.Length; // calculate average of the sum
}
Console.WriteLine("\n");
Console.WriteLine("The average is: {0}", avg);
Console.WriteLine("\n");
for (int z = 0; z < Elements.Length; z++)
{
diff = Elements[z] - avg;
Console.WriteLine("Diffrence between Element {0} and average is: {1}", z, Math.Abs(diff));
}
Console.ReadKey();

C# Random number generator, to display in MessageBox

I'm trying to create a random number generator, ranging from 1 to 1000 for 100 times to achieve the following results on both Console App and popup Windows Message Box (MessageBox.Show) in this format:
100 random numbers in order from smallest to largest
Amount of even numbers generated
Smallest number generated
Largest number generated
The range of numbers
I'm confused at creating the array to store the value and getting the amount of even numbers generated with what I have here, say for example my array name would be "array" and to store the numbers with "n"
string [] array = {item};
string output = string.Join("\n", array);
MessageBox.Show(output)
This is my code, how do I add this in?
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
namespace NumberGenerator
{
class Program
{
static void Main(string[] args)
{
Random number = new Random();
int min = int.MaxValue,
max = int.MinValue;
for (int counter = 0; counter < 100; counter++)
{
int n = number.Next(0, 999);
Console.WriteLine(n);
if (n < min)
min = n;
if (n > max)
max = n;
}
int range = min - max + 1;
string[] array = { "Minimum number is (min)" };
string output = string.Join("\n", array);
Console.WriteLine("Minimum number = {0}, Maximum number = {1}, Range = {2}", min, max, range);
MessageBox.Show(output);
}
}
}
Here is one way to do it.
Code should be self expanatory
static void Main(string[] args)
{
Random number = new Random();
int rangeFrom = 0;
int rangeTo = 999;
List<int> generatedNumbers = new List<int>();
for (int counter = 0; counter < 100; counter++)
{
generatedNumbers.Add(number.Next(rangeFrom, rangeTo));
}
generatedNumbers.Sort();
string output = "generated numbers: {0} \r\n\rmin: {1}\r\n\r\nmax: {2}\r\n\r\nrange: {3}-{4}";
output = string.Format(output,
string.Join(", ", generatedNumbers.ToArray()),
generatedNumbers.Min(),
generatedNumbers.Max(),
rangeFrom,
rangeTo);
MessageBox.Show(output);
}
to summarize:
I have used List for easier manipulation of data and used Linq (make sure you have using System.Linq; in your app).

get max odd number

class Program
{
static void Main(string[] args)
{
Random rnd = new Random();
int[] mass = new int[10];
for (int i = 0; i < mass.Length; i++)
{
mass[i] = rnd.Next(0, 10);
}
Console.WriteLine("display random Massive: \n");
foreach (var i in mass)
{
Console.Write("{0} ", i);
}
Console.WriteLine("\n");
int max = mass.Max();
Console.WriteLine("max value in Massive = {0}", max);
Console.ReadLine();
}
}
my code gives me max value in massive, I need get max odd value. How to get max odd value?
You can use Linq to do this easily
mass.Where (x => x % 2 != 0).Max ();
You can do this easier using linq:
static void Main(string[] args)
{
Random rnd = new Random();
int[] mass = Enumerable.Range(0, 10).Select(i => rnd.Next(0, 10)).ToArray();
Console.WriteLine("display random Massive: ");
Console.WriteLine(string.Join(" ", mass));
Console.WriteLine();
int max = mass.Where(i => (i & 1) == 1).Max();
Console.WriteLine("max value in Massive = {0}", max);
Console.ReadLine();
}
Explanations:
I initialize the array by generating 10 random numbers, converting them to an array
I output them using string.Join
using Where with testing that the last bit is set filters for odd numbers
calling Max on only these odd numbers.
Note that you don't need to use \n as Console.WriteLine adds a new line at the end.
just change
int max = mass.Max();
to
int max = mass.Where(x=>(x%2)==1).Max();
I am asuming you're a beginner like me and don't understand linq yet
Declare a list for holding odd values
List<int> oddList = new List<int>();
Then in your foreach method
foreach (var i in mass)
{
if (i % 2 != 0) //check that number is odd
{
oddList.Add(i); //add odd randoms to list
{
}
Console. WriteLine(oddList.Max().ToString());

Adding Array Elements

i'm attempting to learn C# and I have this code. I want it to display a random list of integers and then add them all together within the array and then display the average of all the numbers. Where have I gone wrong, can anyone help? Thanks.
using System;
class grades
{
public static void Main(string[] args)
{
int sumValue = 0;
int[] grades = new int [ 30 ];
Random rnd = new Random();
for (int i = 0; i < 30; i++)
grades[i] = rnd.Next(1,101);
foreach (int i in grades)
{
Console.WriteLine("{0}", i);
sumValue = sumValue + i;
}
double average = sumValue/30;
Console.WriteLine("{0}", average);
}
}
Yeah, the random integers are displayed but the adding and the average isn't calculated.
Yes, it is; you can make it more obvious:
double average = sumValue / 30.0;
Console.WriteLine("The average is: {0:##0.0}", average);
Note also the .0 which ensures we aren't doing integer arithmetic (different fraction / rounding rules).

Categories

Resources