I am trying to get input from user 5 times and add those values to marks array;
Then, it will calculate the average and print positive or negative accordingly. However, I can not take input from the user it just prints "Enter 5 elements". After getting input from user how can I add them to marks array? Any tips would be helpful.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
class Program
{
static void Main()
{
double average =0;
int [] marks = new int[] { };
for (int a = 0; a < 5; a++){
Console.WriteLine("Enter 5 elements:");
string line = Console.ReadLine();
Console.WriteLine(line);
}
for (int i = 0; i < marks.Length; i++){
average = marks.Average();
}
if(average>0){
Console.WriteLine("Positive");
}else{
Console.WriteLine("Negative");
}
}
}
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
Edited my answer to illustrate solving your problem without a for loop.
class Program
{
const int numberOfMarks = 5;
static void Main()
{
List<int> marks = new List<int>();
Enumerable.Range(1, numberOfMarks)
.ForEach((i) => {
Console.Write($"Enter element {i}:");
marks.Add(int.TryParse(Console.ReadLine(), out var valueRead) ? valueRead : 0);
Console.WriteLine($" {valueRead}");
});
Console.WriteLine(marks.Average() >= 0 ? "Positive" : "Negative");
}
}
This will help you, just copy and paste it.
There are some explanation with comments.
class Program
{
static void Main()
{
const int numberOfMarks = 5;
int[] marks = new int[numberOfMarks];
Console.WriteLine("Enter 5 elements:");
for (int a = 0; a < numberOfMarks; a++)
{
// If entered character not a number, give a chance to try again till number not entered
while(!int.TryParse(Console.ReadLine(), out marks[a]))
{
Console.WriteLine("Entered not a character");
}
Console.WriteLine("You entered : " + marks[a]);
}
// Have to call Average only once.
var avg = marks.Average();
Console.WriteLine(avg > 0 ? "Positive average" : "Negative average");
Console.ReadLine();
}
}
Follow Stackoverflow Answer
since integer array is being used, and as input from the console is a string value, you need to convert it using Parse() Method. For e.g.
string words = "83";
int number = int.Parse(words);
Edit: using string variable in parsing.
Related
so we can give any number of parameters to a method, like this:
static int sumPrices(params int[] prices) {
int sum = 0;
for (int i = 0; i < prices.Length; i++) {
sum += prices[i];
}
return sum;
}
static void Main(string[] args)
{
int total = sumPrices(100, 50, 200, 350);
Console.WriteLine(total);
Console.ReadKey();
}
but ... what if we wanted to get the "100, 50, 200, 350" from the USER?
in above example it's the coder giving the sumPrices method its arguments/parameters.
i mean, it would be one solution to just pass the method an array.
static int sumPrices(int[] prices) {
int sum = 0;
for (int i = 0; i < prices.Length; i++) {
sum += prices[i];
}
return sum;
}
static void Main(string[] args)
{
//get up to 9999 inputs and sum them using a method
bool whileLoop = true;
int[] inputs = new int[9999];
int index = 0;
while (whileLoop == true)
{
Console.WriteLine("entering price #" + index + ", type 'stop' to sum prices");
string check = Console.ReadLine();
if (check == "stop") {
whileLoop = false;
break;
}
inputs[index] = int.Parse(check);
index++;
}
int[] prices = new int[index];
for (int i = 0; i < index; i++)
{
prices[i] = inputs[i];
}
Console.WriteLine("-----------------");
Console.WriteLine(sumPrices(prices));
Console.ReadKey();
}
BUT... longer code... and has limits.
our professor basically wanted the first code, however, i don't see how and where it's
supposed be used if we didn't know the user's inputs and if params arguments were coming from the coder (unless of course, coder using the same function multiple times for convenience)
i have tried to think of a solution and i'm not exactly sure how it could be done.
but it basically goes like this.
we could get inputs from the user separated by commas:
100,200,50
and the program would translate it into params arguments:
sumPrices("100,200,50");
but as you can see... it's a string. i wonder if there's a JSON.parse() thing like in js.
The code in the OP has some unnecessary code as well as some limitations such as 9999.
Let's examine the following code:
bool whileLoop = true;
while (whileLoop == true)
{
}
This could be re-written as:
while (true == true)
{
}
or
while (true)
{
}
Next, let's examine the following code:
if (check == "stop") {
whileLoop = false;
break;
}
You've set whileLoop = false; which is unnecessary because once break is executed, excution has moved to after the loop.
Since the input array has a hard-code size of 9999, you've limited yourself to 9999 values. You may consider using a List instead or resize the array.
Try the following:
using System;
using System.Collections.Generic;
using System.Linq;
namespace UserInputTest
{
internal class Program
{
static void Main(string[] args)
{
decimal price = 0;
List<decimal> _values = new List<decimal>();
if (args.Length == 0)
{
//prompts for user input
Console.WriteLine("The following program will sum the prices that are entered. To exit, type 'q'");
do
{
Console.Write("Please enter a price: ");
string userInput = Console.ReadLine();
if (userInput.ToLower() == "q")
break; //exit loop
else if (Decimal.TryParse(userInput, out price))
_values.Add(price); //if the user input can be converted to a decimal, add it to the list
else
Console.WriteLine($"Error: Invalid price ('{userInput}'). Please try again.");
} while (true);
}
else
{
//reads input from command-line arguments instead of prompting for user input
foreach (string arg in args)
{
if (Decimal.TryParse(arg, out price))
{
//if the user input can be converted to a decimal, add it to the list
_values.Add(price); //add
}
else
{
Console.WriteLine($"Error: Invalid price ('{arg}'). Exiting.");
Environment.Exit(-1);
}
}
}
Console.WriteLine($"\nThe sum is: {SumPrices(_values)}");
}
static decimal SumPrices(List<decimal> prices)
{
return prices.Sum(x => x);
}
static decimal SumPricesF(List<decimal> prices)
{
decimal sum = 0;
foreach (decimal price in prices)
sum += price;
return sum;
}
}
}
Usage 1:
UserInputTest.exe
Usage 2:
UserInputTest.exe 1 2 3 4 5
Resources:
Built-in types (C# reference)
Floating-point numeric types (C# reference)
Decimal.TryParse
Iteration statements - for, foreach, do, and while
String interpolation using $
List Class
Enumerable.Sum Method
Default values of C# types (C# reference)
Environment.Exit
The trick is input from the user always starts out as strings. You must parse those strings into integers. We can do it in very little code like this:
static int sumPrices(IEnumerable<int> prices)
{
return prices.Sum();
}
static void Main(string[] args)
{
int total = sumPrices(args.Select(int.Parse));
Console.WriteLine(total);
Console.ReadKey();
}
See it here (with adjustments for the sandbox environment):
https://dotnetfiddle.net/Pv6B6e
Note this assumes a perfect typist. There is no error checking if a provided value will not parse.
But I doubt using linq operations are expected in an early school project, so we can expand this a little bit to only use techniques that are more familiar:
static int sumPrices(int[] prices)
{
int total = 0;
foreach(int price in prices)
{
total += price;
}
return total;
}
static void Main(string[] args)
{
int[] prices = new int[args.Length];
for(int i = 0; i<args.Length; i++)
{
prices[i] = int.Parse(args[i]);
}
int total = sumPrices(prices);
Console.WriteLine(total);
Console.ReadKey();
}
If you're also not allowed to use int.Parse() (which is nuts, but sometimes homework has odd constraints) you would keep everything else the same, but replace int.Parse() with your own ParseInt() method:
static int ParseInt(string input)
{
int exponent = 0;
int result = 0;
for(int i = input.Length -1; i>=0; i--)
{
result += ((int)(input[i]-'0') * (int)Math.Pow(10, exponent));
exponent++;
}
return result;
}
Again: there's no error checking here for things like out-of-bounds or non-numeric inputs, and this particular implementation only works for positive integers.
This question already has answers here:
Check if a value is in an array (C#)
(10 answers)
Closed 4 years ago.
I'm working on a problem and i've tried it every way I can think of with a for loop but i can't figure out how to make it work as I only started on c# and programming as a whole a few weeks ago.
Write an app that inputs five numbers. As each number is read search the array if the number doesn’t exist in the array output the word “new” and insert the number into the array. If the number does exist in the array output “exists”. Once all five numbers have been entered output the content of the array.
This is what I have so far. Thanks for any help
using System;
public class Program
{
// Main method begins execution of C# application
public static void Main(string[] args)
{
int[] array = new int[5];
for (int i = 0; i < array.Length; i++)
{
Console.WriteLine("Enter a number:");
array[i] = Convert.ToInt32(Console.ReadLine());
for (int a = 0; a < 5; a++)
{
if (array[i] != array[a])
{
array[i] = int.Parse(Console.ReadLine());
Console.WriteLine("new\n");
}
}
array[i] = int.Parse(Console.ReadLine());
Console.WriteLine("exists\n");
}
Console.WriteLine(array);
Console.ReadKey();
}
} // end class
First of all try thinking about a solution before you actually start writing some code, couple of hints
You expect some user input, we will use a variable to save the user input
You need to validate that the values does not exist in you array or structure, this can be done using the Contains method.
If it exists we continue to the next user input and print the required message.
If the value does not exists we add the value and print the new message
We will do this until the Count of the structure is equal to 5.
for reference use this While loop, Hashset.Contains and Hashset
try this:
var numbers = new HashSet<int>();
while(numbers.Count < 5)
{
Console.WriteLine("Enter a number:"); //1.
var number = Convert.ToInt32(Console.ReadLine());
if (numbers.Contains(number)) // 2.
{
Console.WriteLine("exists\n"); //3.
continue;
}
Console.WriteLine("new\n"); //4.
numbers.Add(number);
}
foreach (var n in numbers)
{
Console.WriteLine(n);
}
Use .Any() in System.Linq. Also, you don't need to continuously grab user input in your loop:
using System;
using System.Linq;
public class Program
{
// Main method begins execution of C# application
public static void Main(string[] args)
{
int[] array = new int[5];
for (int i = 0; i < array.Length; i++)
{
Console.WriteLine("Enter a number:");
// Get user input and convert to integer:
int input = Convert.ToInt32(Console.ReadLine());
// Check if given input is already in the array:
if (! array.Any(number => number == input))
{
array[i] = input;
Console.WriteLine("new\n");
}
else
{
Console.WriteLine("exists\n");
}
}
// Print the contents of array separated by ','
Console.WriteLine(string.Join(", ", array));
Console.ReadKey();
}
}
Edit: Another variant if you want the user to fill the array completely:
using System;
using System.Linq;
public class Program
{
public static void Main(string[] args)
{
// Btw, if this is not an array of nullables,
// we will not be able to insert a zero later, as
// we will treat them as duplicates.
int?[] array = new int?[5];
for (int i = 0; i < array.Length; i++)
{
Console.WriteLine("Enter a number:");
int input = 0;
bool duplicateAttempt = false;
do {
// Get and convert the input.
input = Convert.ToInt32(Console.ReadLine());
// See if this number is already in.
duplicateAttempt = array.Contains(input);
// Report if we attempt to insert a duplicate.
if (duplicateAttempt) Console.WriteLine("exists");
}
while (duplicateAttempt); // Keep asking while we don't get a unique number.
array[i] = input; // Store the number
Console.WriteLine("new");
}
// Print the contents of array separated by ','
Console.WriteLine(string.Join(", ", array));
Console.ReadKey();
}
}
A couple of issues with your code. You should only increment the array index if successful - otherwise the missing values will be zero. It's also a good idea to validate the input in case the user entered an invalid value. You can use linq to check if the value already exists in the array:
Here's an example:
static void Main(string[] args)
{
int[] array = new int[5];
var index = 0;
while (index < array.Length)
{
Console.WriteLine("Enter a number:");
var input = Console.ReadLine();
var value = 0;
if (!int.TryParse(input, out value))
{
Console.WriteLine("Error - value entered was not a number");
}
else
{
var match = array.Where(a => a == value);
if (match.Any())
{
Console.WriteLine("exists\n");
}
else
{
array[index] = value;
Console.WriteLine("new\n");
index++;
}
}
}
foreach (var item in array)
{
Console.WriteLine(item);
}
Console.ReadKey();
}
This appears to be a homework question, so I think it's more helpful to explain what you've done wrong and tell you what you should do...
It won't help you learn to copy and paste other people's answers.
using System;
public class Program
{
// Main method begins execution of C# application
public static void Main(string[] args)
{
int[] array = new int[5];
for (int i = 0; i < array.Length; i++)
{
Console.WriteLine("Enter a number:");
// you are putting the value into your array here. so it will always 'exist' below
array[i] = Convert.ToInt32(Console.ReadLine());
// you need to do this check before you insert the number into the array
// put the ReadLine into a variable, not directly into the array.
// then check if it's in the array already
for (int a = 0; a < 5; a++)
{
if (array[i] != array[a])
{
// here you are trying to read another value from the user.
// Console.ReadLine() will always wait for user input
// use the variable from above. but only after you have looped through all the items.
// and verified that it is not present
array[i] = int.Parse(Console.ReadLine());
Console.WriteLine("new\n");
}
}
// this is the third time you have assigned the number to the array
// and the third time you've asked for user input per loop
array[i] = int.Parse(Console.ReadLine());
Console.WriteLine("exists\n");
}
Console.WriteLine(array);
Console.ReadKey();
}
} // end class
To summarize:
you need a for loop that runs 5 times.
The for loop will do the following:
assign the user input to a variable
loop through your array (second loop) and see if it contains this variable
if the number is found, set a boolean to true. (found)
if after the loop is over, found = false, then print false
also add the number to the array (at the index of the outer loop is fine)
I'm very sorry this is such an easy question, I'm just starting out. I've created code that allows a user to enter a number of random dice rolls, and outputs the sum of those rolls. I've now been asked to create a loop that repeats these steps, including the prompt, until the user types 'quit'. My issue is that my code converts the string to an integer, so typing anything kills the code. Any tips of how to insert the loop and break? My code is:
static void Main(string[] args)
{
Random random = new Random();
Console.WriteLine("Enter a number of dice to roll:");
string numberDiceString = Console.ReadLine();
int numberDice = Convert.ToInt32(numberDiceString);
int total = 0;
for (int index = 0; index < numberDice; index++)
{
int DieRoll = random.Next(6) + 1;
total += DieRoll;
}
Console.WriteLine(total);
Console.ReadKey();
}
I wouldn't use a "while(true)" statement. As someone pointed out in the comments i would prefer using the right condition in there.
That being said i would do it this way:
static void Main(string[] args)
{
Random random = new Random();
string numberDiceString;
int numberDice;
Console.WriteLine("Enter a number of dice to roll:");
while ((numberDiceString = Console.ReadLine()) != "quit")
{
bool parsed = int.TryParse(numberDiceString, out numberDice);
if (!parsed)
{
//Handle the error. The user input was not a number or "quit" word
break;
}
int total = 0;
for (int index = 0; index < numberDice; index++)
{
int DieRoll = random.Next(6) + 1;
total += DieRoll;
}
Console.WriteLine(total);
Console.WriteLine("Enter a number of dice to roll:");
}
}
I have to say that i prefer this way because you can easily see when the loop will stop. Also i added an error handling that you should be doing (What happen if the user enters any words that are not numbers?).
Hope this helps.
This change should be fairly simple. What you need to do is to create a while loop, and then a check before you actually parse for an int. The psuedocode for this would be something like.
while(true) {
//Ask for input
//Check if it equals "quit"
//If so -> break;
//If not convert to int
//For Loop for dice rolls
//Print Total
}
I'm sure it could be a little more elegant than this, and you would want to put some more checks to make sure that invalid input doesn't crash the program, but it should get the job done.
This is a very simple solution that shows how to parse the user input.
using System;
namespace Simpleton
{
class Program
{
static public int GetChoice()
{
int choice = 0;
while (true)
{
Console.Write("Enter number of rolls or \"quit\" to finish: ");
var answer = Console.ReadLine();
if (String.Compare(answer, "quit", true) == 0)
{
return 0; // Done
}
if (Int32.TryParse(answer, out choice))
{
return choice;
}
}
}
static void Main(string[] args)
{
var choice = 0;
while ((choice = GetChoice()) > 0)
{
Console.WriteLine($"You'll be looping {choice} times.");
for (int tries = 0; tries < choice; tries++)
{
// Looping
}
}
}
}
}
Try this code:
static void Main(string[] args)
{
Random random = new Random();
while(true)
{
String numberDiceString = "";
int numberDice = 0;
Console.WriteLine("Enter a number of dice to roll:");
numberDiceString = Console.ReadLine();
if (numberDiceString == "quit") { return; }
int total = 0;
if (Int32.TryParse(numberDiceString, out numberDice))
{
total = 0;
for (int index = 0; index < numberDice; index++)
{
int DieRoll = random.Next(6) + 1;
total += DieRoll;
}
}
Console.WriteLine(total);
}
}
I'm not a C# programmer, but you can test for "quit" explicitly and use a goto
BeginLoop:
Console.WriteLine("Enter a number of dice to roll:");
string numberDiceString = Console.ReadLine();
if (numberDiceString == "quit")
{
goto EndLoop;
}
int numberDice = Convert.ToInt32(numberDiceString);
/* Rest of code you want to do per iteration */
goto BeginLoop;
EndLoop:
I am trying to make a program that calculates some specific data from numbers given by a user.
In this example, my program counts amount of numbers in range (10,103) that are divisible by 2, and amount of numbers that are in range (15,50) divisible by 3 within numbers given by user.
On this stage, my program gives the results, when 10 numbers are given (as I specified it in the loop). How can I make my program stop reading numbers and give the results when user imputs an empty line no matter if he, entered 5 or 100 numbers before?
Here is my code, as it looks for now:
using System;
namespace Program1
{
class MainClass
{
public static void Main (string[] args)
{
int input10_103_div_2 = 0;
int input15_50_div_3 = 0;
for (int i = 0; i < 10; i++)
{
string input = Console.ReadLine ();
double xinput = double.Parse (input);
if (xinput > 10 && xinput <= 103 && (xinput % 2) == 0)
{
input10_103_div_2++;
}
if (xinput > 15 && xinput < 50 && (xinput % 3) == 0)
{
input15_50_div_3++;
}
}
Console.WriteLine ("Amount of numbers in range (10,103) divisible by 2: " + input10_103_div_2);
Console.WriteLine ("Amount of numbers in range (15,50) divisible by 3: " + input15_50_div_3);
}
}
}
instead of for, do:
string input = Console.ReadLine();
while(input != String.Empty)
{
//do things
input = Console.ReadLine();
}
if you're trying to allow any number of inputs. Or
if(input == "")
break;
if you want the for loop
Change your loop to go forever and break out of the loop when the string is empty:
for (;;)
{
string input = Console.ReadLine ();
if (String.IsNullOrEmpty(input))
{
break;
}
// rest of code inside loop goes here
}
If you want to restructure the loop, you can use a do while loop:
string input;
do{
input = Console.ReadLine();
//stuff
} while(!string.IsNullOrEmpty(input));
If you just want to be able to break early:
string input = Console.ReadLine ();
if(string.IsNullOrEmpty(str))
break;
double xinput = double.Parse (input);
Below is a program that I wrote to practice some C# basics and principles.
This program asks the user for how large they want an int array to be, then to fill the array and finally return the average of the individual elements of the array.
I know that I can do this using LINQ but since I'm learning I need to learn the nuts and bolts way.
As it stands, the method I wrote doesn't return anything to the console, can someone give me a clue as to what's wrong with it?
There's also a comment near one of the for loops that I need some help understanding why it's behaving that way.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace _9_21_Test
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("enter the amount of numbers you would like to find the average of: ");
int arraylength = Int32.Parse(Console.ReadLine());
int[] AverageArray = new int[arraylength];
////filling the array with user input
for (int i = 0; i < AverageArray.Length; i++)
{
Console.Write("enter the numbers you wish to find the average for: ");
AverageArray[i] = Int32.Parse(Console.ReadLine());
}
//printing out the array, without the -1 the array prints out more one number than it should, don't know why
Console.WriteLine("here is your array: ");
for (int i = 0; i < AverageArray.Length -1 ; i++)
{
Console.WriteLine(AverageArray[i]);
}
Console.WriteLine(Calcs.FindAverage(AverageArray));
Console.ReadLine();
}
}
//Method to find the average is another class for learning porpoises
class Calcs
{
public static double FindAverage(int[] averageNumbers)
{
int arraySum = 0;
for (int i = 0; i < averageNumbers.Length; i++)
arraySum += averageNumbers[i];
return arraySum / averageNumbers.Length;
}
}
}
I've tried debugging, your code is working OK. It's just you don't need the ArrayLength-1 in the second loop. Use ArrayLength instead.
static void Main(string[] args)
{
Console.WriteLine("enter array length ");
int arraylength = Int32.Parse(Console.ReadLine());
int[] AverageArray = new int[arraylength];
for (int i = 0; i < AverageArray.Length; i++)
{
Console.Write("enter the numbers you wish to find the average for: ");
AverageArray[i] = Int32.Parse(Console.ReadLine());
}
Console.WriteLine("here is your array: ");
for (int i = 0; i < AverageArray.Length ; i++)
{
Console.WriteLine(AverageArray[i]);
}
Console.WriteLine("here is the result");
Console.WriteLine(Calcs.FindAverage(AverageArray));
Console.ReadLine();
}
Well I think Visual Studio C#(Sharp) Will give you an error on the second statement of code before the for loop,Because the Array uses the constant variable for the index size.
Console.WriteLine("enter array length ");
const int arraylength = Int32.Parse(Console.ReadLine());
int[] AverageArray = new int[arraylength];
also Check Calcs does not exist in the current context.