Traversing arrays using for and foreach in loops
Notes:
I. Different ways of declaring and initializing arrays : [Starts at:00min:00sec]
II. Traversing arrays in forward direction : [Starts at:09min:45sec]
III. Traversing arrays in reverse direction : [Starts at:18min:31sec]
IV. Traversing arrays using foreach in loop : [Starts at:22min:13sec]
I. Different ways of declaring and initializing arrays : [Starts at:00min:00sec]
Example Code:
int[] num1 = new int[5];
int[] num2;
num2 = new int[5];
// Single step
int[] num3 = new int[5]{10,20,30,40,50};
int[] num4 = new int[]{ 10, 20, 30, 40, 50, 60 };
int[] num5 = { 10, 20, 30, 40, 50, 60 };
// Two steps
int[] num6;
num6 = new int[5]{ 10, 20, 30, 40, 50 };
int[] num7;
num7 = new int[]{10,20,30,40,50 };
int[] num8;
//num8 = {10,20,30,40,50}; // error
II. Traversing arrays in forward direction : [Starts at:09min:45sec]
Example Code:
using UnityEngine;
public class ArraysDemo : MonoBehaviour {
void Start () {
// Initializing arrays
int[] numbers = new int[5]{10,20,30,40,50};
// Traversing an array in forward direction
for (int i = 0; i < numbers.Length; i++) {
Debug.Log (numbers [i]); // 10,20,30,40,50
}
int[] numbers2;
numbers2 = new int[5]{60,70,80,90,100};
// Traversing an array
for (int i = 0; i < numbers2.Length; i++) {
Debug.Log (numbers2 [i]); // 60,70,80,90,100
}
}
}
III. Traversing arrays in reverse direction : [Starts at:18min:31sec]
Example Code:
using UnityEngine;
public class ArraysDemo : MonoBehaviour {
void Start () {
// initializing arrays
int[] numbers = new int[5]{10,20,30,40,50};
// Looping through array elements in reverse order
for (int i = numbers.Length - 1; i >= 0; i--) {
Debug.Log (numbers [i]); // 50,40,30,20,10
}
int[] numbers2;
numbers2 = new int[5]{60,70,80,90,100};
// Traversing an array in reverse direction
for (int i = numbers2.Length - 1; i >= 0; i--) {
Debug.Log (numbers2 [i]); // 100,90,80,70,60
}
}
}
IV. Traversing arrays using foreach in loop : [Starts at:22min:13sec]
Example Code:
using UnityEngine;
public class ArraysDemo : MonoBehaviour {
void Start () {
// initializing arrays
int[] numbers = new int[5]{10,20,30,40,50};
// Loop through array elements
foreach (int item in numbers) {
Debug.Log (item); // 10,20,30,40,50
}
int[] numbers2;
numbers2 = new int[5]{60,70,80,90,100};
// traversing an array
foreach (int item in numbers2) {
Debug.Log (item); // 60,70,80,90,100
}
}
}