How to Fill an array from user input C#?
string []answer = new string[10];
for(int i = 0;i<answer.length;i++)
{
answer[i]= Console.ReadLine();
}
Getting User Input and Adding it to an array at C#
I would use a while
loop combined with int.TryParse
to check if the user input is a number. Also it doesn't make any sense to put average = marks.Average();
inside a for loop, because LINQ Average
calculates the average of a collection (in your case the marks
array).
static void Main()
{
int[] marks = new int[5];
int a = 0;
Console.WriteLine("Enter 5 elements:");
while (a < 5)
{
if (int.TryParse(Console.ReadLine(), out marks[a]))
a++;
else
Console.WriteLine("You didn't enter a number! Please enter again!");
}
double average = marks.Average();
if (average > 0)
Console.WriteLine("Positive");
else
Console.WriteLine("Negative");
}
DEMO HERE
How to Make User Input into Array and Pass It to a Method in C#?
you can ask user for input of comma delimited numbers. Or, you can repeat input until user enters something like 0. I that case, you can change your program into this:
using System;
using System.Collections.Generic;
using System.Linq;
namespace Averages
{
class Program
{
static void Main(string[] args)
{
//list to hold your numbers, way more flexible than array
List<double> enteredNubers = new List<double>();
//message user
Console.WriteLine("Enter number(s) or 0 to end: ");
//run this block of code indefinitely
while (true)
{
//take user input
string userinput = Console.ReadLine().Trim();
//if user enters 0, exit this loop
if (userinput == "0")
break;
double num;
//try to convert text to number
if (double.TryParse(userinput, out num))
{
//if it is successful, add number to list
enteredNubers.Add(num);
}
else //else message user with error
Console.WriteLine("Wrong input. Please enter number or 0 to end");
}
//when loop is exited (when user entered 0), call method that calculates average
Average(enteredNubers);
Console.ReadKey();
}
static void Average(List<double> numbers)
{
double sum = 0;
//go through list and add each number to sum
foreach (double num in numbers)
{
sum += num;
}
//or, you can sum it using linq like this:
//sum = numbers.Sum();
//or you can even calculate average by calling Average method on list, like numbers. Average();
//show message - all the entered numbers, separated by comma
Console.WriteLine("You have entered: " + string.Join(", ", numbers.ToArray()));
//write average
Console.WriteLine("The average is: " + sum/numbers.Count);
}
}
}
how to add user input to 2d array in C#
If you want to get a vector from user, you can try asking user to provide its components separated by some delimiter(s), e.g.
private static int[] ReadVector(string title) {
while (true) { // keep asking user until valid input is provided
if (!string.IsNullOrEmpty(title))
Console.WriteLine(title);
string[] items = Console
.ReadLine()
.Split(new char[] { ' ', '\t', ';', ',' },
StringSplitOptions.RemoveEmptyEntries);
if (items.Length <= 0) {
Console.WriteLine("You should provide at least one component");
continue;
}
bool failed = false;
int[] result = new int[items.Length];
for (int i = 0; i < items.Length; ++i) {
if (int.TryParse(items[i], out int value))
result[i] = value;
else {
Console.WriteLine($"Syntax error in {i + 1} term");
failed = true;
break;
}
}
if (!failed)
return result;
}
}
Then you can use this routine like this:
// We don't want any 2D matrices here, just 2 vectors to sum
int[] A = ReadVector("Please, enter vector A");
int[] B = ReadVector("Please, enter vector B");
if (A.Length != B.Length)
Console.WriteLine("Vectors A and B have diffrent size");
else {
// A pinch of Linq to compute C = A + B
int[] C = A.Zip(B, (a, b) => a + b).ToArray();
Console.WriteLine($"[{string.Join(", ", A)}] + ");
Console.WriteLine($"[{string.Join(", ", B)}] = ");
Console.WriteLine($"[{string.Join(", ", C)}]");
}
Edit: Sure you can sum vectors with a help of good old for
loop instead of Linq:
int[] C = new int[A.Length];
for (int i = 0; i < A.Length; ++i)
C[i] = A[i] + B[i];
Array which stores information from user input
Apart from a few minor issues, you were nearly there
var friends = new string[2];
for (var i = 0; i < friends.Length; i++)
{
Console.Write($"Enter friend ({i + 1}) : ");
friends[i] = Console.ReadLine();
}
Console.WriteLine();
Console.WriteLine("These are your friends");
foreach (var friend in friends)
Console.WriteLine(friend);
Console.WriteLine("Game Over!");
Output
Enter friend (1) : bob
Enter friend (2) : john
These are your friends
bob
john
Game Over!
It's worth noting, List<T>
are good a match for these types of situations, you don't have to worry about indexes, and can just expand and add to the list with List.Add(something)
Related Topics
Find First Digit of a Number Using Only Integer Operations
How to Automatically Update an Application Without Clickonce
How to Select Last Record in a Linq Groupby Clause
Searching If Value Exists in a List of Objects Using Linq
Save Byte[] into a SQL Server Database from C#
How to Count Number of Visitors for Website in ASP.NET C#
What Regular Expression Would I Use to Remove Everything After the Second Backslash
How to Split Json String in C# and Store in Separate Variables
How to Change Cell Background Color in Wpf Datagrid
Select Multiple Fields from List in Linq
How to Redirect to Login Page If Session Is Not Available in MVC
Removing Elements from Json Based on a Condition in C#
How to Iterate Through the Following Json Using C#
Asp.Net Core Identity Successful Login Redirecting Back to Login Page
How to Calculate Sum (Total) of Datatable Columns Using C#