C# -- Issue with arrays. Not reading user input - c#

So i'm trying to make a console program that takes 10 numbers from the user and adds them then averages the sum. Within the do while loop the program is supposed to keep asking for the next number.
{
Console.WriteLine("Hey there! If you could go ahead and just give me like 10 numbers, that'd be great... And I'll tell you what, if you do, I'll add them up and average them all up for ya.");
// declare an array of strings
int[] aryNumbers;
int intSum = 0;
int intAverage = 0;
// initialize the array
aryNumbers = new int[10];
aryNumbers[0] = int.Parse(Console.ReadLine());
aryNumbers[1] = int.Parse(Console.ReadLine());
aryNumbers[2] = int.Parse(Console.ReadLine());
aryNumbers[3] = int.Parse(Console.ReadLine());
aryNumbers[4] = int.Parse(Console.ReadLine());
aryNumbers[5] = int.Parse(Console.ReadLine());
aryNumbers[6] = int.Parse(Console.ReadLine());
aryNumbers[7] = int.Parse(Console.ReadLine());
aryNumbers[8] = int.Parse(Console.ReadLine());
aryNumbers[9] = int.Parse(Console.ReadLine());
do
{
Console.WriteLine("Okay, give me a number.");
aryNumbers[] = int.Parse(Console.ReadLine());
} while (intSum != 0);
int intNumbers = aryNumbers.Length;
//for loop to average sum of array elements
for (int i = 0; i < intNumbers; i++)
{
intSum += aryNumbers[i];
}
intAverage = intSum / intNumbers;
Console.WriteLine("You're average comes out to... " + intAverage);
Console.ReadKey();
}
}
I really have no clue what to do, i'm very new to this
Thanks

There are many problems with your code. I think you should read a whole chapter on arrays. Here's a tutorial on MSDN.

Here is my code:
using System.Linq;
.....
Console.WriteLine("Hey there! If you could go ahead and just give me like 10 numbers, that'd be great... And I'll tell you what, if you do, I'll add them up and average them all up for ya.");
// declare the array
int[] aryNumbers = new int[10];
for(int i =0; i<aryNumbers.Length;i++)
{
Console.WriteLine("Okay, give me a number.");
aryNumbers[i] = int.Parse(Console.ReadLine());
}
int intAverage = (int)aryNumbers.Average();
Console.WriteLine("You're average comes out to... " + intAverage);
Console.ReadKey();

Related

How to Display an Array in C#?

so I'm new to coding and I've decided to learn C# with the whole Covid-19 going on, and I've run into a small problem if anybody can assist me.
I'm just writing a basic C# program to allow the user to input 5 numbers into an array and then display the array, but for some reason, I only display the number 5, not the whole array.
Please find my code: ( if anyone can make it easier for me please help me lol (: )
int[] numbers = new int[5];
int num = 0;
int i = 0;
Console.WriteLine("This porgram allows the user to input 5 numbers into an array");
Console.Write("--------------------------------------------------------------");
Console.WriteLine("\n");
for ( i = 0; i < numbers.Length; i ++)
{
Console.WriteLine("Please input number");
num = Convert.ToInt32(Console.ReadLine());
}
for (i = 0; i < numbers.Length; i++)
{
Console.ReadLine();
Console.WriteLine("Your array is: " , numbers );
}
Console.WriteLine();
// any help will be appreciated!
Two problems:
1) You haven't put the number coming in. After
num = Convert.ToInt32(Console.ReadLine());
put
numbers[i] = num;
Though in fact num is superfluous, so you could just have
numbers[i]= Convert.ToInt32(Console.ReadLine());
2) In the second loop you need to display the specific array element:
Console.WriteLine("Your array item is: " , numbers[i] );
Also, not sure what the ReadLine() in the second loop is for - just means the users has to hit return to see each number.
It's worth mentioning a few other issues in the code:
Variables should be declared as close as possible to where they are used. this i should be declared separately for each for loop - for(int i = 0; ... and num should be declared inside the loop (though as mentioned, it's redundant).
Be clear on the difference between Console.Write() and Console.WriteLine(). WriteLine() simply adds a \n to whatever is displayed. Thus it would be clearer (for the same output to have:
Console.WriteLine("--------------------------------------------------------------");
Console.WriteLine();
here is code:
it is the basic syntax of displaying an array.
public class Work
{
public static void Main()
{
int[] arr = new int[5];
int i;
Console.Write("\nRead & Print elements of an array:\n");
Console.Write("-----------------------------------------\n");
Console.Write("Input 5 elements in the array :\n");
for(i=0; i<5; i++)
{
Console.Write("element - {0} : ",i);
arr[i] = Convert.ToInt32(Console.ReadLine());
}
Console.Write("\nElements in array are: ");
for(i=0; i<5; i++)
{
Console.Write("{0} ", arr[i]);
}
Console.Write("\n");
}
}

C#: Is there a way to stop a random from generating again after it has been displayed

i need a way to store the random numbers generated in the parenthesis for a true/false or if statement but can't because it keeps regenerating new numbers after i input an answer. also if it generated a random of 44 and i answered 48 how do i call the random to display whether if it is correct or not?
Just a simple exercise to help myself with C# coding. Thank you for any answers given.
//There wasn't any problem with the coding at all. The problem was the Online compiler i was using, it kept refreshing every time i enter an input for answer so i thought it was giving me a new random set of numbers after it was already done with printing the entire set in the for loops. i apologize for the confusion! I don't have a visual studio so i was using an online compiler.
public static void Main()
{
Random rand = new Random();
int count, a, b, x, y;
Console.Write("Sequence: ");
count = int.Parse(Console.ReadLine());
Console.Write("Minima: ");
x = int.Parse(Console.ReadLine());
Console.Write("Maxima: ");
y = int.Parse(Console.ReadLine());
int[] roll = new int[count];
for(a = 0; a < count; a++){
roll[a] = rand.Next(x, y);
}
Console.Write("( ");
foreach(var nr in roll){
Console.Write(nr + " ");
}
Console.WriteLine(")");
Console.WriteLine("");
int[] answer = new int[count];
for(b = 0; b < count; b++){
Console.Write("{0}. Answer: ",b+1);
answer[b] =int.Parse(Console.ReadLine());
}
Console.ReadLine();
}
}
The solution is this
for(int i = 0; i < count; i++)
{
if(roll[i] == answer[i])
{
Console.WriteLine("Question " + i + " is correct");
}
}

Get sequence of random n numbers that add up to something but only from a specific set of numbers

What I need is:
e.g:
Sum should be equal to:
120 (user input)
Number of numbers/items:
80 (user input)
Range of numbers to be used in set(from):
0 (user input)
Range of numbers to be used in set(to):
4 (user input)
Output:
1,1,3,2,1,1,0,0,1,1,2,1,0,2,3,3,1,2,0,0,0,1,3,2,3,1,0,0,2,3,2,3,2,2,1,1,0,0,2,0,1,0,1,1,3,3,1,3,1,0,0,3,2,1,0,0,2,1,2,3,0,3,1,1,3,3,2,2,1,1,3,1,3,3,3,3,3,1,2,0
These are all numbers that are between 0 and 4, their sum is 120 and are 80 in total.
What i've done is:
static void Main(string[] args)
{
bool loopOn = true;
Program p = new Program();
Console.WriteLine("____________________________________________________________________________");
Console.WriteLine("");
Console.WriteLine("Sum should be equal to:");
int sum = int.Parse(Console.ReadLine());
Console.WriteLine("Number of items:");
int items = int.Parse(Console.ReadLine());
Console.WriteLine("Range(from):");
int from = int.Parse(Console.ReadLine());
Console.WriteLine("Range(to):");
int to = int.Parse(Console.ReadLine());
while (loopOn == true)
{
List<int> number_list = p.createNumberSet(items, from, to);
if (number_list.Sum() == sum)
{
loopOn = false;
Console.WriteLine("____________________________________________________________________________");
Console.WriteLine("Start");
number_list.ForEach(Console.WriteLine);
Console.WriteLine("Stop");
Console.WriteLine("____________________________________________________________________________");
}
}
Console.WriteLine("Press any key to exit....");
Console.ReadLine();
}
public List<int> createNumberSet(int itemNumber, int range_from, int range_to)
{
List<int> number_set = new List<int>();
Random r = new Random();
for (int i = 0; itemNumber > i; i++)
{
number_set.Add(r.Next(range_from, range_to));
}
return number_set;
}
But this seems extremely in-efficent and doesn't seem to work with a lot of other examples. Does anyone have a better way of doing this?
Well, I am a bit lazy right now, so this is just an idea
Keep the first part:
bool loopOn = true;
Program p = new Program();
Console.WriteLine("____________________________________________________________________________");
Console.WriteLine("");
Console.WriteLine("Sum should be equal to:");
int sum = int.Parse(Console.ReadLine());
Console.WriteLine("Number of items:");
int items = int.Parse(Console.ReadLine());
Console.WriteLine("Range(from):");
int from = int.Parse(Console.ReadLine());
Console.WriteLine("Range(to):");
int to = int.Parse(Console.ReadLine());
Now, first of all, check is a solution exists:
if (from * items > sum) {
// There is no solution, handle accordingly
}
Let's focus on the interesting part now:
First create the list of necessary items
int[] number_set = new int[items];
for(int i = 0; i < items; i++) {
number_set[i] = from;
}
Find the difference between the wanted sum and the current sum of the list
int left_to_add = sum - from * items;
int idx = 0;
Random r = new Random();
while(left_to_add > 0) {
int toAdd = 0;
if (left_to_add < range_to - range_from) {
toAdd = r.Next(1, left_to_add);
} else {
toAdd = r.Next(1, range_to - range_from);
}
left_to_add -= toAdd;
number_set[idx] += toAdd;
idx++;
}
What's left to do is, convert the array to a list and shuffle it.
(I forgot that you actually can access list items by index, so there is no need to use an array as I did here)
At the algorithm level, this is what I would try:
Determine the number of each element, n[0], n[1], n[2], n[3] in your example (i.e. number of 0, number of 1 ...) and then generate a simple sequence by concatenating n[0] "0", n[1] "1", n[2] "2" and n[3] "3". Finally, a random sequence is obtained by performing a random permutation on this simple sequence.
The problem is therefore to determine the n[i].
The first step is to determine the average values of these n[i]. It your example, it is simple, as we can take average n_av[i]=20 for all index i.
In a more general case, we have to insure that
sum_i n_av[i]*i = sum_target (120 here) (1)
knowing that
sum_i (n[i]) = n = 80 here. (2)
In the general case, there is no necessary one unique good solution. I will try to propose an example of solution here if you provide an example of a difficult scenario.
The second step consists in selecting some random n[i] values around these average values. One possibility is to generate rounded Gaussian variables: we already know the averages, we just need to determine the variances. One possibility is to consider the variance that we will get if we were generating directly the random values, i.e. by considering the variance of the corresponding binomial variable :
var = n p(1-p). Here p[i] = n_av[i]/n
The last step consists in adjusting the values of the n[i] such that the sum of the n[i] is equal to the target. This is simply obtained by slightly increasing or decreasing some n[i] values.

Read array of integers from user which is separated by space in C#

I was asked to solve a problem in C# to get the sum of 'n' user inputs from console, which is separated by space, in a single line.
int n = Convert.ToInt32(Console.ReadLine());
int[] arr = new int[n];
int sum = 0;
for(int i = 0; i < n; i++) {
arr[i] = Convert.ToInt32(Console.ReadLine());
sum += arr[i];
}
Console.WriteLine("{0}",sum);
How can I modify this code to get the expected output from the space separated input?
Also the values need to be stored in array.
Input:
5
1 2 3 4 5
Output:
15
int result = Console.ReadLine().Split().Select(int.Parse).Sum();
You'll of course have to handle any bad user input as needed.
Per your added requirements:
int[] items = Console.ReadLine().Split().Select(int.Parse).ToArray();
int sum = items.Sum();
You could do something like this:
int result = input.Split(' ').Take(n).Select(int.Parse).Sum();
But it seems to me that you could avoid asking the user for the count, and just add together all the lines that they typed in:
string input = Console.ReadLine();
int result = input.Split(' ').Select(int.Parse).Sum();
Console.WriteLine(result);
(Note that this code does no error checking.)
EDIT: It seems that you want to have an array of ints. In that case, you can do it like this (again, with no error checking):
using System;
using System.Linq;
namespace Demo
{
internal class Program
{
private static void Main()
{
int n = int.Parse(Console.ReadLine());
int[] arr = Console.ReadLine().Split(' ').Take(n).Select(int.Parse).ToArray();
int sum = arr.Sum();
Console.WriteLine("{0}", sum);
}
}
}
You need to use the split function in C#. When you read the line, you get the whole line. This means you're attempting to say "sum = 0 plus Convert.ToInt32('5 1 2 3 4 5')" which doesn't work.
You need an array of integers equal to
Console.ReadLine().Split(" ");
String.Split function:
https://msdn.microsoft.com/en-us/library/b873y76a.aspx
using arr[i] = Convert.ToInt32(Console.ReadLine()) inside the loop will cause the program to expect an input on a different line and not on a single line.
What you can do is to take the input as a string and then split based on space, which produces an array of the inputed values. You can then sum them
Considering the fact that Naveen seems a student, I think some more code can explain better and let him learn some more from this exercise:
I've made a sample that gets some numbers separated by space or an enter and when the user enters a T calculates the sum in a traditional way using a loop and using Linq. I'm sure there are plenty of better ways to do the same, but maybe something a little bit more structured can be better to begin understanding C#.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SumTheNumbers
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Insert the numbers separated by a space or [Enter]> key, when finished write T and press [Enter] and you will have the result");
List<int> values = new List<int>();
while (true)
{
string inputData = Console.ReadLine();
if (inputData.ToUpper().StartsWith("T")) break;
string[] svals = inputData.Split(' ');
for (int i = 0; i < svals.Length; i++)
{
int x = 0;
int.TryParse(svals[i], out x);
if (x != 0) values.Add(x);
}
}
//Traditional mode
int total = 0;
for (int i = 0; i < values.Count; i++)
{
total = total + values[i];
}
//Linq mode
int totalLinq = values.Sum();
Console.WriteLine("The sum is");
Console.Write("Total: ");
Console.WriteLine(total.ToString());
Console.Write("Total linq: ");
Console.WriteLine(totalLinq.ToString());
Console.WriteLine("Press a key to end...");
Console.ReadKey();
}
}
}

C# - displaying the max, min, and average

I am new to C#. I have been working on this program and researching but am not getting anywhere. The goal is to have the user enter numbers (how many is up to the user). when they enter a 0, it will stop the program and display the minimum number entered, the maximum number entered, and the average of all numbers entered. I am not getting any errors and I am getting. If someone can please point me in the right direction.
The WriteLines are returning:
Lowest number is 0
Highest number is 0
Average is: 0
Count: 5
Here is my code:
int LOWEST =0;
int HIGHEST=0;
const int STOP = 0;
double average = 0;
int input;
int count = 0;
Console.WriteLine("Enter a number. You can end the program at anytime by entering 0");
input = Convert.ToInt32(Console.ReadLine());
while (input != STOP)
{
for (int i=0; input != STOP; i++)
{
Console.WriteLine("Enter a number. You can end the program at anytime by entering 0");
input = Convert.ToInt32(Console.ReadLine());
count++;
var Out = new int[] { input };
LOWEST = Out.Min();
HIGHEST = Out.Max();
average = Out.Average();
if ((input > LOWEST) || (input < HIGHEST))
{
LOWEST = Out.Min();
}
if (input > HIGHEST)
{
HIGHEST = Out.Max();
}
}
}
Console.WriteLine("Lowest number is {0}", LOWEST);
Console.WriteLine("Highest number is {0}", HIGHEST);
Console.WriteLine("Average is {0}", average);
Console.WriteLine("Count: {0}", count);
Console.ReadLine();
On each run you are constructing a new array of integers:
var Out = new int[] { input };
After this line, Out contains one item: the last input. Calling Min, Max and Average on it will return the last value. Which is zero if you ended the program.
instead of creating a new array each time, you want to create a List<int> at the beginning of your program and then add each input to it. You can then use the whole list of values to calculate Min, Max and Average.
Eventually you can change your code into something like this:
const int STOP = 0;
int input = -1;
List<int> Out = new List<int>();
while (input != STOP)
{
Console.WriteLine("Enter a number. You can end the program at anytime by entering 0");
input = Convert.ToInt32(Console.ReadLine());
if (input == STOP) break;
Out.Add(input);
}
Console.WriteLine("Lowest number is {0}", Out.Min());
Console.WriteLine("Highest number is {0}", Out.Max());
Console.WriteLine("Average is {0}", Out.Average());
Console.WriteLine("Count: {0}", Out.Count);
Console.ReadLine();
List<int> numbers = new List<int>();
numbers.Add(10);
numbers.Add(30);
numbers.Add(20);
numbers.Add(0);
numbers.Max();
numbers.Min();
numbers.Average();
returns 30, 0 and 15.
Before your loop, you should probably make Out an extensible data structure analogous to an array, the List.
List<int> Out = new List<int>();
then each loop, you can
Out.Add(input);
Since this sounds like an exercise for the reader, you can then traverse your list and compute the average from all data values.
Alternately, before the loop, you could declare
int n = 0;
int total = 0;
and each loop, do
n += 1;
total += input;
From these, you should be easily able to compute the average.

Categories