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]);
}
Related
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.
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");
}
}
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
This question already has answers here:
How to let the user enter any amount of variable from Console
(3 answers)
Closed 7 years ago.
I am trying to learn C# on my own. I wanted to make a dice game that lets the user enter any number of dice that he or she wants. So if the user enters 10 dice, 10 list of the dice roll would appear next to each other. Here is where I can't figure it out. How can I let the user input any number of dice he or she wants? It would be impractical to use an array or list because I have to give each section of the 10 times or more. It would be nice to give a simple example.
static void Main(string[] args)
{
Random numbergen = new Random();
int dice1=0;
int dice2=1;
for (int counter = 0; counter <= 1; counter++)
{
while (dice1 != dice2)
{
dice1 = numbergen.Next(1, 7);
dice2 = numbergen.Next(1, 7);
if (dice1 == dice2)
{
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine(dice1 + "\t" + dice2);
counter++;
dice1 = 0;
dice2 = 1;
}
else if (dice1 != dice2)
{
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine(dice1 + "\t" + dice2);
}
if (counter ==1 )
{
break;
}
}
}
Console.ReadLine();
}
Most likely, you want a List<>, something like this:
int size = 10; // Or user input
List<int> dice = new List<int>(size);
The form of the constructor that takes an Int32 argument pre-allocates that many items in the list.
Then, rather than dice1 = numbergen.Next(1, 7);, you have dice[0] = ....
You'll obviously need a loop to generate the values and decide how you want to interpret your condition of two of them being equal (which will probably also require a loop of some sort), but if I'm understanding the question correctly, this should get you going.
(You can do something similar with an array, but lists are handy in other ways, as you can see from the first link.)
Alternatively, instead of pre-allocating and filling them in separately, you can allocate an empty list and then fill your items in with something more like:
int size = 10;
for (int i = 0; i < size; i++) {
dice.Add(numbergen.Next(1, 7));
}
That's probably preferred by most people, but the difference should be pretty much negligible for this sort of work.
(And while you're at it, change your for loop to a while and change counter to a bool with a more useful name...)
I have a method that needs to do a calculation based upon the length of an array. I am using the .length method for the calculation, but the method is doing arithmetic with the max length of the array (which I have declared as 10). This is the loop I am using to get data from the user. I know it isn't the ideal way to sort array data, but this is for a homework assignment, and it revolves around using the .Split method correctly (which isn't the problem I'm having).
for (int i = 0; i < MAX; i++)
{
Console.Write("Enter a name and a score for player #{0}: ", (i + 1));
string input = Console.ReadLine();
if (input == "")
{
// If nothing is entered, it will break the loop.
break;
}
// Splits the user data into 2 arrays (integer and string).
string[] separateInput = input.Split();
name [i] = separateInput[0];
score [i] = int.Parse(separateInput[1]);
}
Here is the method I am using to calculate the average score:
static void CalculateScores(int[] score)
{
int sum = 0;
int average = 0;
for (int i = 0; i < score.Length; i++)
{
sum += score[i];
average = sum / score.Length;
}
Console.WriteLine("The average score was {0}", average);
I am calling the method like this:
CalculateScores(score);
Edit: My arrays are declared:
int[] score = new int[MAX]; //MAX == 10.
string[] name = new string[MAX];
The CalculateScores method is doing the math as though score.Length is always 10, no matter how many different combinations of scores I input to the console. I can't figure out if it's because my loop to gather input has been done incorrectly, or my CalculateScores method is flawed. Thanks in advance.
Edit: to clarify, I am just confused at why I can't get the correct value out of CalculateScores.
Length always represents the size of the array, which if you've instantiated as 10, then it will always be 10, regardless of how many items you've filled.
There are lots of ways of solving your problem, but I'd go with the simple one of not using length in your calculation, but rather just storing the number of items in a separate variable:
int numItems = 0;
for(int i=0;i<MAX;i++)
{
Console.Write("Enter a name and a score for player #{0}: ", (i + 1));
string input = Console.ReadLine();
if (input == "")
{
break; // if nothing is entered, it will break the loop
}
numItems++;
...
}
static void CalculateScores(int[] score, int numItems)
{
// don't use Length at all, use numItems instead
}
Arrays are generally used for fixed sized data, so the Length property reflects how many items the array can hold rather than the amount of elements in the array. The simplest fix would be to use a List(T), which is used for variadic data, instead.
// A nice abstraction to hold the scores instead of two separate arrays.
public class ScoreKeeper
{
public string Name { get; set; }
public int Score { get; set; }
}
var scores = new List<ScoreKeeper>();
for (int i = 0; i < MAX; i++)
{
Console.Write("Enter a name and a score for player #{0}: ", (i + 1));
string input = Console.ReadLine();
if (input == "")
{
// If nothing is entered, it will break the loop.
break;
}
// Splits the user data into 2 arrays (integer and string).
string[] separateInput = input.Split();
scores.Add(new ScoreKeeper { Name = separateInput[0], Score = int.Parse(separateInput[1]) });
}
static void CalculateScores(ICollection<ScoreKeeper> scores)
{
// We take advantage of Linq here by gathering all the
// scores and taking their average.
var average = scores.Select(s => s.Score).Average();
Console.WriteLine("The average score was {0}", average);
}
checking maually:
int sum = 0;
int average = 0;
int length;
for (int i = 0; i < MAX; i++) {
if(name[i]!=string.empty) {
sum += score[i];
length=i+1;
}
}
average = sum / length;
Console.WriteLine("The average score was {0}", average);