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).
Related
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();
I'm very new to coding and I just can't wrap my head around Loops/Arrays/Randoms. I understand the concept but when it comes to applying it, I'm just lost.
Here I'm trying to generate 100 random numbers between 1-1000 and it has to output the maximum value. Here's my code so far:
Random rnd = new Random();
int nums = rnd.Next(0, 1001);
for (int i = 1; i <= 100; i++)
{
}
Console.WriteLine(nums);
Console.ReadLine();
It's only giving me one number. :(
I'd greatly appreciate any help!
Thanks!
You can accumulate your random generated number to the array and then by using Max function of the array you can find the maximum value
class Program
{
public static void Main(string[] args)
{
Random rnd = new Random();
int[] intArr = new int[100];
for (int i = 0; i < intArr.Length; i++)
{
int num = rnd.Next(1, 1000);
intArr[i] = num;
Console.WriteLine(num);
}
Console.WriteLine();
int maxNum = intArr.Max();
Console.WriteLine("The max num is:" + maxNum);
Console.ReadLine();
}
}
Click to watch online demo
You need to call rnd.Next() inside loop.
Random rnd = new Random();
for (int i = 1; i <= 100; i++)
{
int nums = rnd.Next(0, 1001);
Console.WriteLine(nums);
}
Console.ReadLine();
A good approach would be initializing a variable that stores your max. Then generate a random number within your iterative block and if it is greater than your max, set it as the new max.
Random r = new Random();
int max = 0; //declare our max variable
for(int i = 0; i < 100; i++)
{
int rand = r.Next(0, 1001);
if(rand > max) //if the new random value is greater than our max, set max = rand
max = rand;
}
Console.WriteLine(max); //Output the maximum value
Console.ReadLine();
If you want to output every random value and then output the max out of all the values generated, simply modify the code above by outputting rand within your loop as well.
Hope this helps!
I am not sure, are you asking like this?
Random random = new Random();
int[] nums = new int[100];
// when for loop ends, nums are full of 100 numbers
for (int i = 0; i < nums.Length; i++)
{
int newNum = random.Next(1, 1000);
// show every number
Console.WriteLine(newNum);
nums[i] = newNum;
}
// get the max number
var maxNum = nums.Max();
Console.WriteLine(maxNum);
If you want to see the code for Loops/Arrays/Randoms all working together you can use the below with the comments walking through what each line is doing (Working .NET Fiddle Example)
public static void Main()
{
// Pass in what range we want our randomly generated numbers to be in
// In your case, between 1 - 1000 and we want to create 100 of them.
//(See GenerateRandomNumbers())
var random = GenerateRandomNumbers(1, 1000, 100);
//Take our newly returned randomly created numbers and
//pass them to our GetMaxNumber method so it can find the Max number
//See (GetMaxNumber())
var result = GetMaxNumber(random);
//We now have our max number; print it to the Console.
Console.WriteLine("Max: " + result);
}
public static int GetMaxNumber(params int[] inputs)
{
//Create a variable that will store the largest number we find in our array
int max = inputs[0];
//Iterate (loop) through all of the 100 values in our array that we passed in
//Here we define "input" which will hold the value for each value in inputs as we check
//if the value of input is greater than our current value of max. If it is greater than our
//current value of max, then we need to update max to now be equal to the value of our input.
//Note: it will do this comparison 100 times beginning with the first value in the inputs array
foreach (var input in inputs)
{
if (input > max)
{
//input's value is greater than the current value of max; update max so that it is equal to the current value of input.
max = input;
}
//no more code; return to top of foreach loop and set input to the next value in inputs
}
//When we get here, it means our foreach loop has completed going through and comparing all 100 values of inputs to see which value is the largest.
//now return this value to Main()
return max;
}
public static int[] GenerateRandomNumbers(int beginRange, int endRange, int maxNumbers)
{
// Instantiate random number generator
Random rnd = new Random();
//Generate and display
int[] intArr = new int[maxNumbers];
//Generate 100 numbers with numbers between 1 and 1000
for (int i = 0; i < intArr.Length; i++)
{
int num = rnd.Next(beginRange, endRange);
intArr[i] = num;
}
return intArr;
}
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).
class Program
{
const int ROLLS = 51;
static void Main(string[] args)
{
Random r = new Random();
int sum = 0;
int[] dice1 = new int[ROLLS];
int[] dice2 = new int[ROLLS];
for (int roll = 0; roll <= 50; roll++)
{
dice1[roll] = GenerateNum(r);
dice2[roll] = GenerateNum(r);
Console.WriteLine("ROLL{0}: {1} + {2} = sum goes here", roll+1, dice1[roll]+1, dice2[roll]+1);
}
}
static int GenerateNum (Random r)
{
return r.Next(1, 7);
}
}
}
So what I have is two arrays to store two different int values that are randomly generated and what I am trying to achieve is the sum of these two randomly generated int values.
Upon execution it should display:
Roll 1: (random number) + (random number) = (sum of the two random numbers)
Just add the two together and store them in sum. Then present sum in the same manner you have presented the rest of the values in the output of the console:
dice1[roll] = GenerateNum(r);
dice2[roll] = GenerateNum(r);
sum = dice1[roll] + dice2[roll];
Console.WriteLine("ROLL{0}: {1} + {2} = {3}", roll + 1, dice1[roll], dice2[roll], sum);
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.