How could I store decimals in a collection c#? [duplicate] - c#

This question already has answers here:
Add new item in existing array in c#.net
(20 answers)
Closed 3 years ago.
I am trying to write a program that could catch user input of string type. Every time there is a space within this string, the program needs to get that part of the string and try to parse it to a decimal. The entries might be numbers that might be separated by a comma rather than just plain integers, that is why I would be using decimals instead of integers.
This is what I tried so far:
static void Main(string[] args)
{
Console.WriteLine("C# Exercise!" + Environment.NewLine);
Console.WriteLine("Please enter two numbers seperated by space to start calculating: ");
string[] input = Console.ReadLine().Split(' ');
//Currently allows for more than one value... I am not necessarily looking for a solution to this problem however.
Console.WriteLine(Environment.NewLine + "Result: ");
//Create the collection of decimals:
decimal[] numbers = { };
numbers[0] = 1.0m;//<-- Results in a System.IndexOutOfRangeException
for (int i = 0; i < input.Length; i++)
{
Console.WriteLine(input[i]);//<-- This value needs to be converted to a decimal and be added to a collection of decimals
}
/*decimal numberOne = ?? //<-- First decimal in the collection of decimals
decimal numberTwo = ?? //<-- Second decimal in the collection of decimals
Console.WriteLine(SumTrippler.Calculate(numberOne, numberTwo));*/
Console.WriteLine(SumTrippler.Calculate(decimal.Parse("0.5"), (decimal)0.5));//<-- Irrelevant method
Console.ReadKey();
}
How could I get two decimals as user input from the user and process this data by passing it to the method at the bottom of my program?
Edit: Closing this question because you are trying to relate a question that adds a string to a list is not a solid reason. I am not trying to add a string to a list.

You can use Array.ConvertAll() to convert string into decimal
var numbers = Array.ConvertAll(Console.ReadLine().Split(' '), decimal.Parse);
//Now you can iterate through decimal array
for (int i = 0; i < numbers.Length; i++)
{
Console.WriteLine(numbers[i]);
}
Your code will look like,
using System;
using System.Linq;
public static void Main(string[] args)
{
Console.WriteLine("C# Exercise!");
Console.WriteLine("Please enter two numbers seperated by space to start calculating: ");
var numbers = Array.ConvertAll(Console.ReadLine().Split(' '), decimal.Parse);
Console.WriteLine("Result: ");
for (int i = 0; i < numbers.Length; i++)
{
Console.WriteLine(numbers[i]);
}
decimal numberOne = numbers.FirstOrDefault();
decimal numberTwo = numbers.LastOrDefault(); //Your second element will be last element in array
Console.WriteLine(SumTrippler.Calculate(numberOne, numberTwo));
Console.ReadKey();
}

You have to initialize the array with the required number of fields (which can't be changed afterwards)
decimal[] numbers = new decimal[input.Length];
numbers[0] = 1.0m; // no more System.IndexOutOfRangeException

Related

Convert string vol to variable name [duplicate]

This question already has answers here:
Get property value from string using reflection
(24 answers)
string to variable name
(4 answers)
Closed 6 months ago.
I would be thankful if someone help me to resolve some task.
I need to create several variables using cycle "for".
I ask users how many numbers will they input, and declare it like variable "countVariables".
Next step, using cycle "for" I want to create new variables using counter cycle`s "for".
For example, name of created var must be like "num1", "num2", "num3" etc. I try do it using a code below.
I understand, that it isn't good solution, but I need to resolve task just using this way.
Console.WriteLine("Input count of numbers: ");
ushort.TryParse(Console.ReadLine(), out ushort countVariables);
for (int i = 1; i <= countVariables; i++)
{
string tmp = "num" + i;
int tmp.name = Console.ReadLine();
}
You can't do it using variables as you've mentioned but you can use Arrays instead. After reading number of times to repeat, you can create an array based on that then access values by index:
Console.WriteLine("Input count of numbers: ");
ushort.TryParse(Console.ReadLine(), out ushort countVariables);
var data = new string[countVariables];
for (int i = 1; i <= countVariables; i++)
{
string tmp = "num" + i;
data[i] = Console.ReadLine();
}
Later after the for loop you can access your values using data[0], data[1]... or use another for loop for looping over the values.
You can use a Dictionary for storing the data:
var data = new Dictionary<int, string>();
Console.WriteLine("Input count of numbers: ");
ushort.TryParse(Console.ReadLine(), out ushort countVariables);
for (int i = 1; i <= countVariables; i++)
{
var val = Console.ReadLine();
data.Add(i, val);
}
Write out number on index '4':
Console.WriteLine(data[4]);

For loop not iterating for each input C# - beginner question

I'm new to C# and I'm trying to calculate the average of 4 numbers from the user I've gotten this far but i'm having issues in the input stage. I wanted to use a for loop to iterate for every number printing "Enter number one:" > user puts 2, its accumulates... Then is asks for the next one "Enter number two" adds to sum and so on until all for numbers have been added. However instead of taking each number at a time. The output for this program is:
number 1number 2number 3number 4:
Question: Why isn't it stopping at each iteration to allow the user to input a number?
namespace Hello
{
class Program
{
static void Main(string[] args)
{
double sum;
for (int i = 1; i <= 4; i++)
Console.Write("Enter number {0}:", i);
sum = +Convert.ToDouble(Console.ReadLine());
}
}
}
Try this:
double sum;
for (int i = 1; i <= 4; i++) {
Console.Write("Enter number {0}:", i);
sum += Convert.ToDouble(Console.ReadLine());
}
You forgot to enclose your for loop in curly braces.

How to generate a number from first or last digits of an array and check if it is divisible by a certain number in C#?

I am a beginner in C# and I am struck with this problem. To question is as follows
You are given an array of size n that contains integers. Here, n is an even number. You are required to perform the following operations:
1. Divide the array of numbers in two equal halves
Note: Here, two equal parts of a test case are created by dividing the array into two equal parts.
2. Take the first digit of the numbers that are available in the first half of the array (first 50% of
the test case)
3. Take the last digit of the numbers that are available in the second half of the array (second 50% of
the test case)
4. Generate a number by using the digits that have been selected in the above steps
Your task is to determine whether the newly-generated number is divisible by 11.
And this is my code-
using System;
namespace IsDivisible
{
class Program
{
static void Main(string[] args)
{
int n = Convert.ToInt32(Console.ReadLine());
int div = 0, digit;
string str = " ";
string[] numArray = Console.ReadLine().Split(' ');
int[] arr = new int[n];
for (int i = 0; i < n; i++)
{
arr[i] = Convert.ToInt32(str[i]);
if (i <= n / 2)
{
while (arr[i] >= 10)
{
div = arr[i] / 10;
}
str += div;
}
else
{
digit = arr[i] % 10;
str += digit;
}
}
long newNumber = Convert.ToInt64(str);
if (newNumber % 11 == 0)
Console.WriteLine("YES");
else
Console.WriteLine("NO");
Console.Read();
}
}
}```
It has no errors during compile time in visual studio. The code is not printing anything after I input the array and I am unable to figure out what's wrong. Please help.

Array compare, school task doesn't work [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
First post here so tell me if I did something wrong :)
So I have this code:
static void Main(string[] args)
{
//declaring first array
Console.Write("Enter the size of the first the array: ");
int sizeOne = Int32.Parse(Console.ReadLine());
int[]firstArray = new int[sizeOne];
//fill it from console
for (int counter = 0; counter<=sizeOne - 1; counter++)
{
Console.Write("Please enter a value: ");
firstArray[counter] = Int32.Parse(Console.ReadLine());
//for test
// Console.WriteLine(firstArray[counter]);
}
//declaring second array
Console.Write("Enter the size of the second array: ");
int sizeTwo = Int32.Parse(Console.ReadLine());
int[] secondArray = new int[sizeTwo];
//fill it from console
for (int counter = 0; counter <= sizeTwo - 1; counter++)
{
Console.Write("Please enter a value: ");
firstArray[counter] = Int32.Parse(Console.ReadLine());
//for test
// Console.WriteLine(secondArray[counter]);
}
//compare size and values, as sidenote it could write not equal even
//when the user inputs two arrays with different lengths to save time :)
if (firstArray.Length == secondArray.Length)
{
for (int counter = 0; counter <= sizeOne; counter++)
{
if ((firstArray[counter]) != (secondArray[counter]))
{
Console.WriteLine("The two arrays aren't equal");
break;
}
else
{
Console.WriteLine("The two arrays are equal");
}
}
}
else
{
Console.WriteLine("The two arrays aren't equal");
}
}
It should compare the arrays by length, and elements. It does if two arrays have different length but at equal number of elements it always writes not equal. What did I miss?
Thank you for help in advance!
It's a typo, or copy-paste error, whatever you want to call it. In your 2nd loop, when you are supposed to populate secondArray, you are populating firstArray by mistake. This means that secondArray only ever has zeroes. You probably got lucky (or unlucky) that firstArray was always equal or larger in size than secondArray. Otherwise you would have gotten an exception, which may have helped you to spot your mistake.
Note that once you fix it, you will also get an out of bounds exception, because your comparing loop uses the counter <= sizeOne condition, which is wrong. It should be counter < sizeOne, otherwise you will go past the end of the array.
Just modify the loop a bit:
You need a Boolean flag, that indicates if there are mismatches. Otherwise it would print "The two arrays are equal" if just the first element(s) matches.
if (firstArray.Length == secondArray.Length)
{
bool areEqual = true;
for (int counter = 0; counter < firstArray.Length; counter++)
{
if ((firstArray[counter]) != (secondArray[counter]))
{
areEqual = false;
//Console.WriteLine("The two arrays aren't equal");
break;
}
// This would get executed if the first elements are equal, but others are not
//else
//{
// Console.WriteLine("The two arrays are equal");
//}
}
if (areEqual)
Console.WriteLine("The two arrays are equal");
else
Console.WriteLine("The two arrays aren't equal");
}
And then there is of course a build in function (in .NET) called SequenceEqual that does compare two arrays:
using System.Linq;
...
bool areEqual = firstArray.SequenceEqual(secondArray);
if (areEqual)
Console.WriteLine("The two arrays are equal");
else
Console.WriteLine("The two arrays aren't equal");
See NetFiddle
There is also a Typo: You're filling the firstArray twice.
//fill it from console
for (int counter = 0; counter <= sizeTwo - 1; counter++)
{
Console.Write("Please enter a value: ");
// **Must be secondArray**
firstArray[counter] = Int32.Parse(Console.ReadLine());
//for test
// Console.WriteLine(secondArray[counter]);
}

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();
}
}
}

Categories