Say I have an array that has 5 values int[] gear = new int[] {5,4,3,2,1}; and I also have a variable that I use to get the value I want int currentGear = 0; Now I would like to step through the array under a certain condition with this code:
if(rpm > shiftRPM && currentGear < gear.Length)
currentGear++;
Console.WriteLine( gear[cuurentGear] );
However, using that code I am able to go past the array length because gear.Length is 5, but array's are zero indexed(i.e. the max number I can have is 4).
So my solution is to just add 1 to currentGear in the if statement, but this for loops works as expected:
for(int i=0; i<gear.Length;i++;)
Console.Write(gear[i]);
And outputs: 5 4 3 2 1 with no errors.
Also, if I Console.Write(gear.Length); it outputs 5, so clearly my error is with my if statement allowing my index to pass gear.Length since 4 < 5 and 5 is out of range.
Is there a better way to increment my array index variable than doing this:
if(rpm > shiftRPM && (currentGear+1) < gear.Length)
currentGear++;
or is that the best way to handle this situation?
Your solution is basically the best way. The maximum value of an index is in fact Length-1, not Length, so when you only check that currentGear is less than Length, you are not really guarding against it getting too large.
why not initialize currentGear as:
var currentGear = -1;
Related
The code where it reads Messages from MCU and stores them in an array of 8 bytes[0]~[7],
specifically storing the first 4 elements in the first half, indexes [0] ~[3], and the next four elements in the next half, indexes [4] ~[7]
Is there any easier way to do it?
halfbytelength = 4;
bytelength =8;
case 0:
for (index = 0; index <halfbytelength; index += 1)
{
Array1[index] = msg[index];
}
for (index = halfbytelength; index < bytelength; index += 1)
{
Array2[index - halfbytelength] = msg[index];
}
MainArray[0] = ASCIIEncoding.ASCII.GetString(Array1);
MainArray[1] = ASCIIEncoding.ASCII.GetString(Array2);
There should be no need to write the loop to copy bytes yourself. You could for example use spans to slice the array.
var array1 = msg.AsSpan().Slice(0, 4).ToArray();
var array2 = msg.AsSpan().Slice(4, 4).ToArray();
I would say that it is significantly easier to read. Or add an extension method to convert a span to string directly.
Or you could use Array.Copy
Array.Copy(msg, 0, array1, 0, 4);
Array.Copy(msg, 4, array2, 0, 4);
But I find that less easy to read.
With regards to performance I would not expect a huge difference. I would expect converting the array to a string to take more time than copying a few bytes. But any method that avoid allocations might have some advantage if it is run in a tight loop.
Assuming that bytelength stays even, you can do the following to replace your 2 loops with 1:
for (int index = 0; index < halfbytelength; ++index)
{
Array1[index] = msg[index];
Array2[index] = msg[index + halfbytelength];
}
Note: as #JeremyLakeman commented below, using Array.Copy might be faster.
Your code will also be shorter (1 line per array, with no loops).
(assuming that msg,Array1,Array2 are of array type - which you didn't specify in your question).
I am taking a class in c# programming and cannot figure out how to do the following. I have spent hours researching and nobody else seems to have the same issues.
The question is:
Write a function named, evenOrOdd, that will accept three parameters. The first parameter is the integer array used in the above function. The second parameter is the string array from step 2 and the third parameter is an integer indicating the size of the two arrays. This function will perform the following tasks:
This function will loop through the first array, checking each value to see if it is even or odd.
For each item in the integer array, the function will then place the appropriate value, “even” or “odd”, in the corresponding position of the string array.
Hint: Using the modulus operator, (also called the modulo), to divide the number by 2 will result in either a remainder of 0 or 1. A remainder of 0 indicates an even number and a remainder of 1 indicates an odd number. The modulus operator for all of the languages in this class is %.
After calling both functions, print the maximum number determined by findMax as well as the array index position of the largest number. Next, the program will loop through the two arrays and print the integer from integer array followed by the corresponding “even” or “odd” value from the string array
I do not understand how to populate the second string array with "even" or "odd".
The two arrays should be something like this:
array1 [1,2,3,4,5,6,7,8,9,10]
then run through a loop to determine if the values are even or odd and then assign the values to the second array so it is something like this:
array2 [odd,even,odd,even,odd,even,odd,even,odd,even]
I am confused how I "link" these two arrays together so that it know index of array 1=index of array 2.
You don't have to "link" the arrays together. You can use a variable which contains the current index and use it for both arrays. Like this:
for (int i = 0; i < array1.Length; i++){
//array1[i]...
//array2[i] = ...
}
This way, you can check if the number at index i in array 1 is even or odd and then modify the index i of array 2 accordingly.
Instead of array1.Length, you can also use the third argument of the method.
It looks like a code challenge. I highly recommend you find your own way to understand and solve this kind of problem and the fundamental concepts behind it as well.
One way to code the EvenOrOdd method:
public void EvenOrOdd(int[] numbers,
string[] natures, int size)
{
for(int i=0; i < size; i++)
if(numbers[i] % 2 == 0)
natures[i] = "even";
else
natures[i] = "odd";
}
One wat to code FindMax Function:
public static (int MaxValue, int MaxIndex) FindMax(int[] numbers)
{
int major = int.MinValue;
int majorIndex = -1;
for(int i=0; i < numbers.Length; i++)
if(numbers[i] > major)
{
major = numbers[i];
majorIndex = i;
}
return (major, majorIndex);
}
Check it in dotnetFiddle
I have code which checks if a word if a palindrome or not. Within the for loop there is a -1 value. Can someone explain to me why -1 is used after the name.Length in c#
public static void Main()
{
string name = "Apple";
string reverse = string.Empty;
for (int i = name.Length - 1; i >= 0; i--)
{
reverse +=name[i];
}
if (name == reverse)
{
Console.WriteLine($"{name} is palindrome");
}else
{
Console.WriteLine($"{name} is not palindrome");
}
That's because whoever wrote the code, wanted to write:
reverse += name[i];
String operator [] takes values from 0 upto (string's length-1). If you pass length or more, you will get an exception. So, code's author had to ensure that i==Length won't be ever passed there. So it starts from Length-1 and counts downwards.
Also, note that the other bound of i is 0 (>=, not >, so 0 is included), so the loop visits all values from 0 to length-1, so it visits all characters from the string. Job done.
However, it doesn't have to be written in that way. The only thing is to ensure that the string operator [] wont see values of of its range. Compare this loop, it's identical in its results:
for (int i = name.Length; i >= 1; i--)
{
reverse += name[i-1];
}
Note that I also changed 0 to 1.
Of course, it's also possible to write a loop with the same effects in a lot of other ways.
The first element in an array is at the index 0 (array[0]). Because the indexing starts at 0 instead of 1 it means that the final element in the array will be at index array.Length-1.
If you had the word and then your array would look like:
name[0] = 'a'
name[1] = 'n'
name[2] = 'd'
the name.Length would equal 3. As you can see, there isn't an element at index 3 in the array so you need to subtract 1 from the length of the array to access the last element.
The for loop in your example starts with the last element in the array (using i as the index). If you tried to set i to i = name.Length then you would get an index out of bounds error because there isn't an element at the position name.Length.
String operator [] takes values from 0. The first element in an string is at the index 0, so we need to adjust by subtracting one.
For Example:
string str = "test";
int length = str.length; //Length of the str is 4. (0 to 3)
Assume that I have an array of integers with a specific size (say 1000)
I want to find the index of an item in this array, given the sum of all items in the array before this item (or including this item).
for example assume that I have the following array:
int[] values={1,2,3,1,3,6,4,8,2,11}
Input value is 6, then I need to return the index 2 (zero based indexing for 3 in above example) and when given 10, I should return the index 4.
What is the fastest way to do this? in C++ and c#?
If you need to do it only once, then the naive way is also the fastest way: walk the array, and keep the running total. Once you reach the target sum, return the current index.
If you need to run multiple queries for different sums, create an array and set up sums in it, like this:
var sums = new int[values.Length];
sums[0] = values[0];
for (int i = 1 ; i < sums.Length ; i++) {
sums[i] = sums[i-1] + values[i];
}
If all values are positive, you can run binary search on sums to get to the index in O(log(n)).
learn BST, it's will the fastest algo for your problem:
http://en.wikipedia.org/wiki/Binary_search_tree
What is the difference between these two methods and when would you use one instead of the other?
int[,] array = new int[4,3];
int length0 = array.GetLength(0);
int upperbound0 = array.GetUpperBound(0);
MSDN says that GetLength return the number of elements where as GetUpperBound determine the max index, but how could this be different since arrays are initialized with elements for each index?
Take a look at this (rarely used) method. From Docs:
public static Array CreateInstance(Type elementType, int[] lengths, int[] lowerBounds)
Creates a multidimensional Array of the specified Type and dimension lengths, with the specified lower bounds.
With it, you can create an array with indices from -5 ... +5. If you ever use this kind of array, then GetUpperBound() suddenly becomes a lot more useful than GetLength()-1. There also exists a GetLowerBound().
But the C# support for this kind of arrays is low, you cannot use []. You would only need those methods in combination with the Array.GetValue() and SetValue() methods.
Array.Length returns the length of the array (number of elements) you need
to subtract 1 from it to get the UpperBound.
Array.GetUpperBound(0) returns the upper bound of the array, you can use it
as is.
GetUpperBound returns the highest index in the array, the GetLength returns the number of elements of the array.
i.e. GetUpperBound = GetLength - 1
Generally, array.GetUpperBound(0) = array.Length - 1, but since we can create arrays that have a Nonzero lower bound, that is not always true.
I realise this is an old question but I think it's worth emphasising that GetUpperBound returns the upper boundary of the specified dimension. This is important for a multidimensional array as in that case the two functions are not equivalent.
// Given a simple two dimensional array
private static readonly int[,] USHolidays =
{
{ 1, 1 },
{ 7, 4 },
{ 12, 24 },
{ 12, 25 }
};
The Length property will output 8 as there are 8 elements in the array.
Console.WriteLine(USHolidays.Length);
However, the GetUpperBound() function will output 3 as the upper boundary of the first dimension is 3. In other words I can loop over array indexes 0, 1, 2 and 3.
Console.WriteLine(USHolidays.GetUpperBound(0));
for (var i = 0; i <= USHolidays.GetUpperBound(0); i++)
{
Console.WriteLine("{0}, {1}", USHolidays[i, 0], USHolidays[i, 1]);
}
if lower bound of your array is 0 then you can use either of them without any confusion but i would recommend array.length-1 as it is widely used. however, if the lower bound of your array is less than 0 then you should use array.GetUpperBound(0) because in this case array.length-1 != array.getUpperBound(0)