array without pre-defined size - c#

I'm really really new to C# and i'm trying to write a code that calculate the average of N numbers,so the program asks the user how many numbers do u have and based on the number that user enters it builds an array.
I don't know how to implement this into code, I mean as far as I know yet arrays must be defined with their size.
can anyone help me please?

Use a list, for example:
List<int> numbers = new List<int>();
numbers.Add(5);
Though if you ask the user the number of numbers, then you can just initialize the array to that length:
Console.Write("How many numbers do you have?: ");
int numberOfNumbers = int.Parse(Console.ReadLine()); // get user input, parse it
int[] items = new int[numberOfNumbers];
for (int i = 0; i < numberOfNumbers; ++i)
{
Console.Write("Enter number: ");
items[i] = int.Parse(Console.ReadLine());
}
Hopefully you can apply these examples to your own scenario. If you have any questions, let me know in the comments.
Note that it's safer to use TryParse as that actually checks if the number is valid, but for the sake of keeping the answer short, I've used Parse.

Related

Someone help me explain part of this for loop please

I have this code that lets you enter 4 values and it prints the highest value you entered.
I understand everything up until the second for loop, how does it print the highest value? I'm rather new to c# and this is part of a school assignment.
The part of code which is within "**" is what I don't really understand.
int[] inputNum = new int[4];
for(int i = 0; i < 4; i++)
{
Console.Write("Enter number: ");
inputNum[i] = int.Parse(Console.ReadLine());
}
**int inputMax = 0;
for(int i2 = 0; i2 < inputNum.Length; i2++)
{
if(inputNum[i2] > inputMax)
{
inputMax = inputNum[i2];
}**
}
Console.WriteLine($"Highest value number: {inputMax}");
The second loop goes over the numbers that were inputted in the first loop and for each iteration checks if the current number is larger than the previous maximum, and if it is, saves it in inputMax. Once the loop is done, you'll be left with the largest number in that variable.
To be honest, though, this problem doesn't really need both loops. If the only requirement is to input four numbers and print out the largest one, there's no need to save them to an array, and you could just perform this check on each number that's inputted.

C# Program that generates 20 random numbers and search the array for a number (Continued)

I am reposting this and edited it because I somehow can't see the answers for the old one.
Old Question: I want to make a program that generates 20 random numbers and search the array for a number. If one of the 20 random numbers was typed in the input the output should say "it is here". If the number is not in the ReadLine it should say"Yes it is there".I want to know how to make all 20 random numbers to be able to search. The code right now can only search the number on the right. Even if the input is one of the 20 random numbers except for the one on the right it would say "No it is not here."
NEW: I want to make this work by having 2 for loops one for creating an array and 1 for searching the number. I have edited this program to have 2 for loops but the output is strange as you see on the picture. Please help me by editing this code to complete work but still have 2 for loops again one for creating an array and 1 for searching the number.
public static void Main(string[] args)
{
Random random = new Random();
int[] myIntArray = new int[100];
for (int i=0; i <20; i++)
{
int x = random.Next(100);
myIntArray[i] = x;
Console.Write(myIntArray[i] + " ");
}
Console.Write("\nType a number to search for:");
bool isValueFound = false;
int z = Convert.ToInt32(Console.ReadLine());
for (int i = 0; i <20; i++)
{
if (z==myIntArray[i])
{
Console.WriteLine("Yes it is there.");
}
else
Console.WriteLine("No it is not here.");
}
Console.ReadKey();
}
if (z==myIntArray[i])
{
Console.WriteLine("Yes it is there.");
}
else
Console.WriteLine("No it is not here."); <- The problem is here
}
At every number, if it is not a match you are printing 'No'. You should rather utilize isValueFound variable that you defined, You can do the following:
Don't print anything in the loop
When there is a match sent isValueFound to true, and break the loop
Outside the second loop, check the isValueFound to decide whether it is a found or not-found.
Additionally, you have a good opportunity to learn the Binary search as well. Happy coding!

display user input from do while loop C#

I have some code below that is almost finished, but the last thing I want to do is for the console app to display the number they have gotten from the user
EX: if user input 1, 3, 5
the console will display
The number you have inserted are:
One
Three
Five
Is it possible to do that ?
Thanks
static void Main (string []args)
{
string again;
do
{
Console.Clear();
Console.WriteLine("Insert Random number");
int number = int.Parse(Console.ReadLine());
Console.WriteLine("Would you like to Insert another number ?(Enter Y for yes /Enter any other key to exit)");
again = Console.ReadLine();
} while (again == "Y");
Console.WriteLine("The number you have inserted are: ");
Console.ReadKey();
}
First, you need a place to keep all the numbers you collected. Given this code, you may be expected to use an array, but real code is more likely to use a generic List<int>. Declare it near the beginning of the Main method like this:
List<int> numbers = new List<int>();
Add each number to it after Parse()-ing like this:
numbers.Add(number);
Then, in between the final WriteLine() and ReadKey() calls, you need to loop through the collected numbers:
int i = 0;
for (int i = 0; i < numbers.Length; i++)
{
Console.WriteLine($"{i+1}. {numbers[i]}");
}
What you won't be able to do in a simple way is convert the digit 1 to the text value One. There's nothing built into C# or .Net to do that part for you. Since this code looks like a learning exercise, I'll leave you to attempt that part on your own.

How to fill the array of integers from console input

Let's say I know how many numbers will user put in. I have an int array and I want to fill it with integers user put in devided by particular character, for example space. I managed to solve it this way.
int[] numbers = new int[5];
string[] input = Console.ReadLine().Split(' ');
for (int i = 0; i < numbers.Length; ++i)
numbers[i] = int.Parse(input[i]);
I want to ask you, is there any other, better way to do this?
You could use Linq:
var numbers = Console.ReadLine().Split(' ').Select(token => int.Parse(token));
// if you must have it as an array...
int[] arr = numbers.ToArray();
This basically does the same thing as your code, it's just more concise.
You could also make your code more robust by handling cases where the user inputs something that's not a number (which would cause int.Parse() to throw an exception).
Suggestion 1: if you would like to read all values from single line delimited by space, then i would suggest you to use command line arguments. so that you can atleast avoid using String array in your program as command line arguments are stored into the Main() method String array argument.
Suggestion 2: while parsing the values into Int it would be nice to check wether parsing is successfull or not, so that if the parsing failes(due to invalid integer) then we can store zero or some default value.
Int32.TryParse() allows you to let you know wether parsing is sucessfull or not.
Try This:
static void Main(string[] args)
{
int[] numbers = new int[args.Length];
int temp;
for(int i=0;i<args.Length;i++)
{
if (Int32.TryParse(args[i],out temp))
{
numbers[i] = temp;
}
else
{
numbers[i] = 0;
}
}
}
Let me try, just read console line and split by space. use ConvertAll method fro Array class.
int[] myArray = Array.ConvertAll(Console.ReadLine().Split(' '), int.Parse);
Even though the return value from Console.Read() returns an integer, it isn't quite that simple. It will return the integer representation of the characters you type in.
In order to retrieve the number of elements, as your code attempts to do. You should refactor a small portion into this:
Console.WriteLine("enter no of elements");
c = int.Parse(Console.ReadLine());
Please note that this piece of code can throw exceptions if what you type in isn't a number
You can use StringTokenizer to tokenize the whole line and then use parseInt().

Comparing in Array

There is something wrong with my code. I am teaching myself c# and one of the challenges in this chapter was to prompt the user for 10 numbers, store them in an array, than ask for 1 additional number. Then the program would say whether the additional number matched one of the numbers in the array. Now what I have below does work, but only if I enter in a comparison number that is less than 10 which is the size of the array.
I'm not sure how to fix it. I am not sure how to do the comparison. I tried a FOR loop first which kind of worked, but ran through the loop and displayed the comparison against all 10 numbers so you would get 9 lines of No! and 1 line of Yes!. I put in a break; which stopped it counting all 10 but if I entered the number 5 for comparison, then I would get 4 lines of No! and 1 of Yes!. The below has been the only way I could get it to work reliably but only as long as the number isn't out of the bounds of the array.
I can see why I get the error when the number is above 10, I just don't know what to use to compare it but still allow the user to enter in any valid integer. Any assistance would be great!
int[] myNum = new int[10];
Console.WriteLine("Starting program ...");
Console.WriteLine("Please enter 10 numbers.");
for (int i = 0; i <= 9; ++i)
{
Console.Write("Number {0}: ", i + 1);
myNum[i] = Int32.Parse(Console.ReadLine());
}
Console.WriteLine("Thank you. You entered the numbers ");
foreach (int i in myNum)
{
Console.Write("{0} ", i);
}
Console.WriteLine("");
Console.Write("Please enter 1 additional number: ");
int myChoice = Int32.Parse(Console.ReadLine());
Console.WriteLine("Thank you. You entered the number {0}.", myChoice);
int compareArray = myNum[myChoice - 1];
if (compareArray == myChoice)
{
Console.WriteLine("Yes! The number {0} is equal to one of the numbers you previously entered.", myChoice);
}
else
{
Console.WriteLine("No! The number {0} is not equal to any of the entered numbers.", myChoice);
}
Console.WriteLine("End program ...");
Console.ReadLine();
You were on the right track- you want to loop through the array in myNum and compare each element to the variable myChoice. If you don't want to print whether each element of the array is a match, create a new variable and use it to keep track of whether you've found a match or not. Then after the loop you can check that variable and print your finding. You'd usually use a bool variable for that- set it false to start, then true when you find a match.
bool foundMatch = false;
for (int i = 0; i < 10; i++) {
if (myNum[i] == myChoice) {
foundMatch = true;
}
}
if (foundMatch) {
Console.WriteLine("Yes! The number {0} is equal to one of the numbers you previously entered.", myChoice);
}
If you include the System.Linq namespace (or if you change the type of myNum to be something that implements ICollection<T>, like List<T>), you can use myNum.Contains(myChoice) to see if the value myChoice matches one of the values in myNum. array.Contains returns a boolean that is true if the specified value is found in the array and false if it is not.
You can update your code to use this like so:
//int compareArray = myNum[myChoice - 1]; // This line is no longer needed
if (myNum.Contains(myChoice))
{
Console.WriteLine("Yes! The number {0} is equal to one of the numbers you previously entered.", myChoice);
}
else
{
Console.WriteLine("No! The number {0} is not equal to any of the entered numbers.", myChoice);
}
If you're looking for numbers that are definitely between 1 and 10, then before you use
int compareArray = myNum[myChoice - 1];
check if it's over the value of 10. For example:
while(myChoice > 10)
{
Console.Write("Please choose a number less than or equal to 10: ");
myChoice = Int32.Parse(Console.ReadLine());
}
The benefit of putting it inside a while loop instead of an if tag means that, when the user enters another number, the value of myChoice will be rewritten, and compared against. If they enter a number over 10, it'll keep responding Please choose a number less than or equal to 10. until the number they input is below or equal to 10:` Then, your program will continue.
However, if you want to compare it against the array, rather than put in a fixed number comparison, consider the following while loop:
while(myChoice > myNum.Length)
{
Console.Write("Please choose a number less than or equal to {0}: ", myNum.Length);
myChoice = Int32.Parse(Console.ReadLine());
}
This will work for any sized array then, without you having to change the while loops content. By using this system, you can then ensure that you won't get an IndexOutOfBounds exception, so long as you subtract 1 when using it as an index.
You are looking to compare a final, 11th value and trying to determine if its in an array of 10 previous entries?
Try:
for(int i = 0; i < array.length - 1; i++;)
{
If(array[i] == input)
return true;
}
return false;
You should be able to figure out how to implement this completely yourself, as you did want to do it as an exercise.
Edit: If someone wants to check this or complete it in correct syntax, go ahead. I posted this rough outline from a phone.

Categories