I apologize if this question is too basic, but i really am stuck here. I want to print 3 numbers which the user will input , but for some reason i can only take them one at a time. Is there a way the user can input all three numbers at once, without the code asking the same question three times?
using System;
namespace ConsoleApp1
{
public class Program
{
public static void Main(string[] args)
{
Console.WriteLine("Input three values: ");
int[] arr = new int[3]; //this is the array which will store the 3 numbers
for (int i = 0; i < 3; i++) //for loop that iterates three times
{
arr[i] = Convert.ToInt32(Console.ReadLine()); //gets user input and converts it to integer
var value = arr[i]; //input is stored in variable 'value'
Console.WriteLine("Here are your 3 numbers: " + value); //output
}
}
}
}
The output line is inside the for-loop so it will print again every time you put a number. Also, the input is already stored in your array, and the "value" variable holds only a temporary value which will disappear for every loop of your for-loop and when the loop ends up. You should use a for-loop outside the ones that is in your code, which prints every value without a new line
Your code should look like this:
public static void Main()
{
Console.WriteLine("Input three values: ");
int[] arr = new int[3];
for (int i = 0; i < 3; i++)
arr[i] = Convert.ToInt32(Console.ReadLine());
Console.Write("Here are your 3 numbers:");
for(int i = 0; i < arr.Length; i++)
Console.Write(" " + arr[i]);
Console.WriteLine();
}
You can make your code support more than one number and display all of them in a cool way 😎 by treating them as strings.
Something like this:
using System;
public class Program
{
public static void Main()
{
Console.Write("Input your values: ");
string[] list = Console.ReadLine().Split(' ');
Console.Write($"Here are your {list.Length} numbers:");
for(int i = 0; i < list.Length; i++)
Console.Write(" " + list[i]);
Console.WriteLine();
}
}