Return Values With Arrays - c#

I am quite new to programming and I just need help with what I am doing wrong.
This is the code I have so far. Yes, this is for homework, but I am confused on what I have to do next.
In the CreateRandomlyFilledArray method, I have to create an allocated array. This method will take as it's only parameter an integer, The array is then created inside the method, filled with values that have been randomly created by the method. (values can be from 0 to 100).
The array will then be passed (as a parameter) to the PrintArray method, which will take as it's single parameter an array of integers, and will print out everything in the array.
class Returning_An_Array
{
public void RunExercise()
{
ArrayReturnMethods m = new ArrayReturnMethods();
int[] nums1;
nums1 = m.CreateRandomlyFilledArray(10);
m.PrintArray(nums1);
}
}
class ArrayReturnMethods
{
public int[] CreateRandomlyFilledArray( int size )
{
int[] newNums = new int[size];
for (int value = 0; value < newNums.Length; value++)
{
return newNums;
}
return newNums;
}
public void Printarray( int[] value )
{
for(int i = 0; i < value.Length; i++)
{
Console.WriteLine("value is: {0}", value[i]);
}
}
}
Thank you so much!!

Avoid asking homework question here. Especially when a bit of reading would solve your issue. Good luck with your homework. : )
class Program
{
/*
I assume you are trying to
1. Create an array of integers
2. Store random numbers (between 0 and 100) inside that array
3. Print the numbers in the array
You have alot of reading to do as theres alot of fundemental mistakes in both your approach and code.
*/
static void Main(string[] args)
{
// creating an array with random numbers
ArrayMethods m = new ArrayMethods();
int[] nums1;
nums1 = m.CreateRandomlyFilledArray(10);
m.Printarray(nums1);
}
class ArrayMethods
{
/*
- First you have to fill the array with random numbers
In your solution, you have created "CreateRandomlyFilledArray".
1. You created the a new array of integers which is good
2. The way you attempted to fill the new array is incorrect
*/
public int[] CreateRandomlyFilledArray(int size)
{
int[] newNums = new int[size];
Random numGen = new Random(); // This will be used to generate random numbers
for (int elementNum = 0; elementNum < newNums.Length; elementNum++)
{
// here we will put a random number in every position of the array using the random number generator
newNums[elementNum] = numGen.Next(0, 100); // we pass in you minimum and maximum into the next function and it will return a random number between them
}
// here we will return the array with the random numbers
return newNums;
}
/*
- This function prints out each item in an integer array
1. You do not need to a return value as you will not be returning any thing so, Use "void".
*/
public void Printarray(int[] value)
{
for (int i = 0; i < value.Length; i++)
{
Console.WriteLine("value is: {0}", value[i]);
}
}
}
}

Related

Get the biggest value of an array

I have a textbox to write the position of an array and a textbox to write the value of that position. Every time I want to add a value and a position I click the button btnStoreValue
I created a function (CompareTwoNumbers) for another exercise that compares two numbers and returns the biggest
Using that function and avoiding the use of comparison characters like > and < I'm supposed to get the biggest value of the array
public partial class Form1 : ExerciseArray
{
int[] numbers = new int[10];
private int CompareTwoNumbers(int i, int j)
{
if (i < j)
{
return j;
}
return i;
}
private void btnBiggestValue_Click(object sender, EventArgs e)
{
//int n=1;
int counter = 0;
int highestPosition = CompareTwoNumbers(0, 1);
for(int i=0; i<10; i++){
//int j = CompareTwoNumbers(numbers[i], numbers[i+1])
//n = CompareTwoNumbers(numbers[n], numbers[i+1]
counter = CompareTwoNumbers(highestPosition, i);
}
txtBiggestValuePosition.Text= n.ToString();
txtBiggestValue.Text=numbers[n].ToString();
}
I've tried multiple things, using multiple variables, I tried to write it on paper to try to understand things better and I'm stuck. I don't know how is it possible to find that value using the function I created on the previous exercise (assuming the function I created is correct)
So, the core part of your question is that you want to know how to find the biggest number in an array using your helper function CompareTwoNumbers and then figure out what the value and position of the biggest number is.
Based on my understanding above, you have the framework almost set up correctly.
First off, CompareTwoNumbers should be updated to return a bool. Doing this will let you conditionally update your variables holding the biggest number value and position.
private int CompareTwoNumbers(int i, int j)
{
if (i < j)
{
return true;
}
return false;
}
To know what the largest value in an (unsorted) array is, you will need to iterate through every value. While doing so, you need to keep track of the value and position of the biggest value, only updating it when a bigger value is found.
private void btnBiggestValue_Click(object sender, EventArgs e)
{
// Store the bigget number's index and value
// We start with the first index and corresponding
// value to give us a starting point.
int biggestNumberIndex = 0;
int biggestNumber = numbers[0];
// Iterate through the array of numbers to find
// the biggest number and its index
for(int i=0; i<10; i++)
{
// If the current number is larger than the
// currently stored biggest number...
if(CompareTwoNumbers(biggestNumber, numbers[i])
{
// ...then update the value and index with
// the new biggest number.
biggestNumber = number[i];
biggestNumberIndex = i;
}
}
// Finally, update the text fields with
// the correct biggest value and biggest
// value position.
txtBiggestValuePosition.Text= biggestNumberIndex.ToString();
txtBiggestValue.Text=numbers[biggestNumberIndex].ToString();
}
This uses a Tuple to give you both the max index and max value from the same method:
public (int, int) FindMaxValue(int[] items)
{
int maxValue = items[0];
int maxIndex = 0;
for(int i=1;i<items.Length;i++)
{
if (items[i] > maxValue)
{
maxValue = items[i];
maxIndex = i;
}
}
return (maxIndex, maxValue);
}

How to add integers to an array and get a random number?

It's a favorite panel.
You can select numbers (with button click) and than I would like to add this number to an array and than get a random number from this array.
public int runs;
public int randomNumber;
public int[] favorites = new int[75];
public void RandomButton()
{
if (DataController.Instance.group == 3)
{
favorites[randomNumber] = UnityEngine.Random.Range(0, favorites.Length);
Debug.Log(favorites[randomNumber]);
}
}
public void b0()
{
for (runs = 0; runs < favorites.Length; runs++)
{
favorites[runs] = 0;
}
}
public void b1()
{
for (runs = 0; runs < favorites.Length; runs++)
{
favorites[runs] = 1;
}
}
I'm stuck , because I get random number between 0 - 75. I would like to have a random number from the "favorites" array after I click on the buttons.
What you are doing here
favorites[randomNumber] = UnityEngine.Random.Range(0, favorites.Length);
Is assign a random value between 0 and 74 to an item in your array .. depending on whatever value randomNumber has at that moment ...
What you rather want to do is actually access the value from the array using the random value as index like
randomNumber = favorites [UnityEngine.Random.Range(0, favorites.Length)];
Debug.Log(randomNumber);
However what difference will it make if you are filling your array with always the same numbers using b0 and b1?
After running these methods all elements are either 0 or 1 anyway ...
Anyway in your question you are also asking for how to Add a number.
You shouldn't use an array for this but rather a List<int> like
public List<int> favorites = new List<int>();
public void AddNumber(int newNumber)
{
favorites.Add(newNumber);
}
public void RandomButton()
{
if (DataController.Instance.group == 3)
{
randomNumber = favorites[UnityEngine.Random.Range(0, favorites.Count)];
Debug.Log(randomNumber);
}
}
if (DataController.Instance.group == 3)
{
var randomIndex = UnityEngine.Random.Range(0, favorites.Length);
Console.WriteLine(favorites[randomIndex]); // random item from your array
}
answer

How to pass an array between methods?

I'm following along in a book and trying the 'challenges'. Here I'm running into a problem with properly returning and passing an array between methods. Something goes wrong with returning the array, especially from the second method, and then passing it to third to print.
I understand the stack, heap, values and references on the conceptual level, but something clearly goes
wrong.
Each method appears to work otherwise.
using System;
namespace PracticeArray
{
class Program
{
static int[] GenerateNumbers()
{
Console.WriteLine("Enter a number to generate array from:");
string input = Console.ReadLine();
int inputNumber = Convert.ToInt32(input);
int[] generatedArray = new int[inputNumber];
for (int i = 0; i < generatedArray.Length; i++)
{
generatedArray[i] = i;
}
return generatedArray;
}
static int[] Reverse(int[] arrayToReverse)
{
int count = arrayToReverse.Length;
int[] arrayToReturn = new int[count];
count--;
for (int i = 0; i < arrayToReturn.Length; i++)
{
arrayToReturn[i] = arrayToReverse[count--];
}
return arrayToReturn;
}
static void PrintNumbers(int[] numbersToPrint)
{
foreach (int singleNumber in numbersToPrint)
{
Console.Write(singleNumber + ", ");
}
}
static void Main(string[] args)
{
int[] numbers = GenerateNumbers();
Reverse(numbers);
PrintNumbers(numbers);
}
}
}
The problem
The array you return is a new array:
Take a look in your Reverse function. You create a new array called arrayToReturn and return that array. You also never modify the original input array arrayToReverse.
static int[] Reverse(int[] arrayToReverse) // this input array is never modified
{
int count = arrayToReverse.Length;
// ...
arrayToReturn = new int[count]; // Here is the new array
// ...
return arrayToReturn; // you return the new array
}
Now look at where you called Reverse you passed in some generated numbers, but you ignore the return value of the function so you never find out what the new array is. Remember we already established above that you don't modify the elements of the input array. So numbers will remain unchanged.
static void Main(string[] args)
{
int[] numbers = GenerateNumbers();
Reverse(numbers); // you ignored the return value of `Reverse`
PrintNumbers(numbers); // These are the original unreversed numbers
}
To Fix
Option #1 - New variable to store the result
To fix this, store the array returned from Reverse in a variable and print those numbers.
static void Main(string[] args)
{
int[] numbers = GenerateNumbers();
int[] reversedNumbers = Reverse(numbers);
PrintNumbers(reversedNumbers);
}
Option #2 - Reuse the same variable to store the result
In this option you simply discard the original array by taking the new reversed numbers array returned from Reverse and assigning it to the numbers variable. After that assignment, numbers will refer to the reversed array that was returned from Reverse. The original array is orphaned and forgotten - eventually garbage collected.
static void Main(string[] args)
{
int[] numbers = GenerateNumbers();
// repurpose the `numbers` variable to store the result.
numbers = Reverse(numbers);
PrintNumbers(numbers);
}

random number gen, loop and store

How can I implement this so it is always ten numbers in length and how would I store n and r, loop 10 times, and store each loop aswell?
loop the random generator 10x to create 2x10 multiple 10 digit numbers.
namespace ConsoleApplication1
{
class Program
{
static void Main()
{
F();
F();
}
static Random _r = new Random();
static void F()
{
int n = _r.Next();
int r = _r.Next();
Console.WriteLine(n);
Console.WriteLine(r);
Console.ReadLine();
}
}
Something like this may be what you're looking for?
Though I'm not keen on the naming conventions, I'm not sure what these apply to, so can't exactly name them relevantly myself...
static int[] randomNumberArray0 = new int[10];
static int[] randomNumberArray1 = new int[10];
static Random random = new Random();
static void PopulateRandomNumberArrays()
{
for (int i = 0; i < 10; i++)
{
randomNumberArray0[i] = random.Next();
randomNumberArray1[i] = random.Next();
}
}
Update:
To execute this method then further output the values at a later time, try this:
static void PrintRandomNumberArrayValues(int[] array)
{
for (int i = 0; i < array.Length; i++)
{
Console.WriteLine("{0}", array[i]);
}
Console.WriteLine();
}
static void Main()
{
PopulateRandomNumberArrays();
PrintRandomNumberArrayValues(randomNumberArray0);
PrintRandomNumberArrayValues(randomNumberArray1);
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
}
Output would look something like this:
2044334973
153458690
1271210885
734397658
746062572
162210281
1091625245
123317926
410432738
989880682
866647035
481104609
834599031
1153970253
94252627
1041485031
1934449666
414036889
1886559958
2083967380
Further update:
For the generated values to be constrained to 10 digits in length, it means the minimum generated value must be larger than 999999999 and, since an int has a max value of 2,147,483,647, smaller or equal to that, so:
for (int i = 0; i < 10; i++)
{
randomNumberArray0[i] = random.Next(1000000000, int.MaxValue);
randomNumberArray1[i] = random.Next(1000000000, int.MaxValue);
}
I have a feeling this still may not satisfy your needs though, as what I see coming next is that the numbers should be able to be represented as 0000000001, for instance - let's see.
Yet another update:
As I thought, the value of numbers should not be constrained to our specified range, but rather only the output formatted appropriately; thus generation reverts to my original suggestion and printing is altered as so:
Console.WriteLine("{0:D10}", array[i]);
I guess you could use a list of tuples to store and return your results:
static List<Tuple<int,int>> F()
{
var results = new List<Tuple<int,int>> ();
for (int i = 0; i < 10; i++)
{
results.Add(new Tuple<int, int>(_r.Next(), _r.Next()));
}
return results;
}

Adding values to a C# array

Probably a really simple one this - I'm starting out with C# and need to add values to an array, for example:
int[] terms;
for(int runs = 0; runs < 400; runs++)
{
terms[] = runs;
}
For those who have used PHP, here's what I'm trying to do in C#:
$arr = array();
for ($i = 0; $i < 10; $i++) {
$arr[] = $i;
}
You can do this way -
int[] terms = new int[400];
for (int runs = 0; runs < 400; runs++)
{
terms[runs] = value;
}
Alternatively, you can use Lists - the advantage with lists being, you don't need to know the array size when instantiating the list.
List<int> termsList = new List<int>();
for (int runs = 0; runs < 400; runs++)
{
termsList.Add(value);
}
// You can convert it back to an array if you would like to
int[] terms = termsList.ToArray();
Edit: a) for loops on List<T> are a bit more than 2 times cheaper than foreach loops on List<T>, b) Looping on array is around 2 times cheaper than looping on List<T>, c) looping on array using for is 5 times cheaper than looping on List<T> using foreach (which most of us do).
Using Linq's method Concat makes this simple
int[] array = new int[] { 3, 4 };
array = array.Concat(new int[] { 2 }).ToArray();
result
3,4,2
If you're writing in C# 3, you can do it with a one-liner:
int[] terms = Enumerable.Range(0, 400).ToArray();
This code snippet assumes that you have a using directive for System.Linq at the top of your file.
On the other hand, if you're looking for something that can be dynamically resized, as it appears is the case for PHP (I've never actually learned it), then you may want to use a List instead of an int[]. Here's what that code would look like:
List<int> terms = Enumerable.Range(0, 400).ToList();
Note, however, that you cannot simply add a 401st element by setting terms[400] to a value. You'd instead need to call Add() like this:
terms.Add(1337);
By 2019 you can use Append, Prepend using LinQ in just one line
using System.Linq;
and then in NET 6.0:
terms = terms.Append(21);
or versions lower than NET 6.0
terms = terms.Append(21).ToArray();
Answers on how to do it using an array are provided here.
However, C# has a very handy thing called System.Collections
Collections are fancy alternatives to using an array, though many of them use an array internally.
For example, C# has a collection called List that functions very similar to the PHP array.
using System.Collections.Generic;
// Create a List, and it can only contain integers.
List<int> list = new List<int>();
for (int i = 0; i < 400; i++)
{
list.Add(i);
}
Using a List as an intermediary is the easiest way, as others have described, but since your input is an array and you don't just want to keep the data in a List, I presume you might be concerned about performance.
The most efficient method is likely allocating a new array and then using Array.Copy or Array.CopyTo. This is not hard if you just want to add an item to the end of the list:
public static T[] Add<T>(this T[] target, T item)
{
if (target == null)
{
//TODO: Return null or throw ArgumentNullException;
}
T[] result = new T[target.Length + 1];
target.CopyTo(result, 0);
result[target.Length] = item;
return result;
}
I can also post code for an Insert extension method that takes a destination index as input, if desired. It's a little more complicated and uses the static method Array.Copy 1-2 times.
Based on the answer of Thracx (I don't have enough points to answer):
public static T[] Add<T>(this T[] target, params T[] items)
{
// Validate the parameters
if (target == null) {
target = new T[] { };
}
if (items== null) {
items = new T[] { };
}
// Join the arrays
T[] result = new T[target.Length + items.Length];
target.CopyTo(result, 0);
items.CopyTo(result, target.Length);
return result;
}
This allows to add more than just one item to the array, or just pass an array as a parameter to join two arrays.
You have to allocate the array first:
int [] terms = new int[400]; // allocate an array of 400 ints
for(int runs = 0; runs < terms.Length; runs++) // Use Length property rather than the 400 magic number again
{
terms[runs] = value;
}
int ArraySize = 400;
int[] terms = new int[ArraySize];
for(int runs = 0; runs < ArraySize; runs++)
{
terms[runs] = runs;
}
That would be how I'd code it.
C# arrays are fixed length and always indexed. Go with Motti's solution:
int [] terms = new int[400];
for(int runs = 0; runs < 400; runs++)
{
terms[runs] = value;
}
Note that this array is a dense array, a contiguous block of 400 bytes where you can drop things. If you want a dynamically sized array, use a List<int>.
List<int> terms = new List<int>();
for(int runs = 0; runs < 400; runs ++)
{
terms.Add(runs);
}
Neither int[] nor List<int> is an associative array -- that would be a Dictionary<> in C#. Both arrays and lists are dense.
You can't just add an element to an array easily. You can set the element at a given position as fallen888 outlined, but I recommend to use a List<int> or a Collection<int> instead, and use ToArray() if you need it converted into an array.
If you really need an array the following is probly the simplest:
using System.Collections.Generic;
// Create a List, and it can only contain integers.
List<int> list = new List<int>();
for (int i = 0; i < 400; i++)
{
list.Add(i);
}
int [] terms = list.ToArray();
one approach is to fill an array via LINQ
if you want to fill an array with one element
you can simply write
string[] arrayToBeFilled;
arrayToBeFilled= arrayToBeFilled.Append("str").ToArray();
furthermore, If you want to fill an array with multiple elements you can use the
previous code in a loop
//the array you want to fill values in
string[] arrayToBeFilled;
//list of values that you want to fill inside an array
List<string> listToFill = new List<string> { "a1", "a2", "a3" };
//looping through list to start filling the array
foreach (string str in listToFill){
// here are the LINQ extensions
arrayToBeFilled= arrayToBeFilled.Append(str).ToArray();
}
Array Push Example
public void ArrayPush<T>(ref T[] table, object value)
{
Array.Resize(ref table, table.Length + 1); // Resizing the array for the cloned length (+-) (+1)
table.SetValue(value, table.Length - 1); // Setting the value for the new element
}
int[] terms = new int[10]; //create 10 empty index in array terms
//fill value = 400 for every index (run) in the array
//terms.Length is the total length of the array, it is equal to 10 in this case
for (int run = 0; run < terms.Length; run++)
{
terms[run] = 400;
}
//print value from each of the index
for (int run = 0; run < terms.Length; run++)
{
Console.WriteLine("Value in index {0}:\t{1}",run, terms[run]);
}
Console.ReadLine();
/*Output:
Value in index 0: 400
Value in index 1: 400
Value in index 2: 400
Value in index 3: 400
Value in index 4: 400
Value in index 5: 400
Value in index 6: 400
Value in index 7: 400
Value in index 8: 400
Value in index 9: 400
*/
If you don't know the size of the Array or already have an existing array that you are adding to. You can go about this in two ways. The first is using a generic List<T>:
To do this you will want convert the array to a var termsList = terms.ToList(); and use the Add method. Then when done use the var terms = termsList.ToArray(); method to convert back to an array.
var terms = default(int[]);
var termsList = terms == null ? new List<int>() : terms.ToList();
for(var i = 0; i < 400; i++)
termsList.Add(i);
terms = termsList.ToArray();
The second way is resizing the current array:
var terms = default(int[]);
for(var i = 0; i < 400; i++)
{
if(terms == null)
terms = new int[1];
else
Array.Resize<int>(ref terms, terms.Length + 1);
terms[terms.Length - 1] = i;
}
If you are using .NET 3.5 Array.Add(...);
Both of these will allow you to do it dynamically. If you will be adding lots of items then just use a List<T>. If it's just a couple of items then it will have better performance resizing the array. This is because you take more of a hit for creating the List<T> object.
Times in ticks:
3 items
Array Resize Time: 6
List Add Time: 16
400 items
Array Resize Time: 305
List Add Time: 20
I will add this for a another variant. I prefer this type of functional coding lines more.
Enumerable.Range(0, 400).Select(x => x).ToArray();
You can't do this directly. However, you can use Linq to do this:
List<int> termsLst=new List<int>();
for (int runs = 0; runs < 400; runs++)
{
termsLst.Add(runs);
}
int[] terms = termsLst.ToArray();
If the array terms wasn't empty in the beginning, you can convert it to List first then do your stuf. Like:
List<int> termsLst = terms.ToList();
for (int runs = 0; runs < 400; runs++)
{
termsLst.Add(runs);
}
terms = termsLst.ToArray();
Note: don't miss adding 'using System.Linq;' at the begaining of the file.
This seems like a lot less trouble to me:
var usageList = usageArray.ToList();
usageList.Add("newstuff");
usageArray = usageList.ToArray();
Just a different approach:
int runs = 0;
bool batting = true;
string scorecard;
while (batting = runs < 400)
scorecard += "!" + runs++;
return scorecard.Split("!");
int[] terms = new int[400];
for(int runs = 0; runs < 400; runs++)
{
terms[runs] = value;
}
static void Main(string[] args)
{
int[] arrayname = new int[5];/*arrayname is an array of 5 integer [5] mean in array [0],[1],[2],[3],[4],[5] because array starts with zero*/
int i, j;
/*initialize elements of array arrayname*/
for (i = 0; i < 5; i++)
{
arrayname[i] = i + 100;
}
/*output each array element value*/
for (j = 0; j < 5; j++)
{
Console.WriteLine("Element and output value [{0}]={1}",j,arrayname[j]);
}
Console.ReadKey();/*Obtains the next character or function key pressed by the user.
The pressed key is displayed in the console window.*/
}
/*arrayname is an array of 5 integer*/
int[] arrayname = new int[5];
int i, j;
/*initialize elements of array arrayname*/
for (i = 0; i < 5; i++)
{
arrayname[i] = i + 100;
}
To add the list values to string array using C# without using ToArray() method
List<string> list = new List<string>();
list.Add("one");
list.Add("two");
list.Add("three");
list.Add("four");
list.Add("five");
string[] values = new string[list.Count];//assigning the count for array
for(int i=0;i<list.Count;i++)
{
values[i] = list[i].ToString();
}
Output of the value array contains:
one
two
three
four
five
You can do this is with a list. here is how
List<string> info = new List<string>();
info.Add("finally worked");
and if you need to return this array do
return info.ToArray();
Here is one way how to deal with adding new numbers and strings to Array:
int[] ids = new int[10];
ids[0] = 1;
string[] names = new string[10];
do
{
for (int i = 0; i < names.Length; i++)
{
Console.WriteLine("Enter Name");
names[i] = Convert.ToString(Console.ReadLine());
Console.WriteLine($"The Name is: {names[i]}");
Console.WriteLine($"the index of name is: {i}");
Console.WriteLine("Enter ID");
ids[i] = Convert.ToInt32(Console.ReadLine());
Console.WriteLine($"The number is: {ids[i]}");
Console.WriteLine($"the index is: {i}");
}
} while (names.Length <= 10);

Categories

Resources