Explore 100's Of Free Video Tutorials

Keep Learning, Keep Coding & Keep Sharing

Generating number series & storing in an array

Notes:

I. Generating number series 10,20,30,40,50 & : [Starts at: 00min:00sec]
II. Generating number series 60,70,80,90,100: [Starts at: 00min:00sec]
III. Sum of elements in an array : [Starts at: 23min:21sec]

I. Generating number series 10,20,30,40,50 & : [Starts at: 00min:00sec]

Example Code:

using UnityEngine;
public class ArraysDemo : MonoBehaviour
{
void Start ()
{
int[] numbers = new int[5];

//Generating number series 10 20 30 40 50
// 0 * 10 + 10 = 10
// 1 * 10 + 10 = 20
// 2 * 10 + 10 = 30
// 3 * 10 + 10 = 40
// 4 * 10 + 10 = 50
for (int i = 0; i < numbers.Length; i++)
{
numbers [i] = i * 10 + 10;
Debug.Log (numbers [i]);
}

//OR

int[] numbers2 = new int[5];
// (0 + 1) * 10 = 10
// (1 + 1) * 10 = 20
// (2 + 1) * 10 = 30
// (3 + 1) * 10 = 40
// (4 + 1) * 10 = 50
for (int i = 0; i < numbers.Length; i++)
{
numbers2[i] = (i + 1) * 10;
Debug.Log (numbers2[i]);
}
}
}

II. Generating number series 60,70,80,90,100

Example Code:

using UnityEngine;
public class ArraysDemo : MonoBehaviour
{
void Start ()
{
int[] numbers = new int[5];

//Generating number series 60,70,80,90,100
// 0 * 10 + 60 = 60
// 1 * 10 + 60 = 70
// 2 * 10 + 60 = 80
// 3 * 10 + 60 = 90
// 4 * 10 + 60 = 100
for (int i = 0; i < numbers.Length; i++)
{
numbers [i] = i * 10 + 60;
Debug.Log (numbers [i]);
}

//OR
int[] numbers2 = new int[5];
// (0 + 6) * 10 = 60
// (1 + 6) * 10 = 70
// (2 + 6) * 10 = 80
// (3 + 6) * 10 = 90
// (4 + 6) * 10 = 100
for (int i = 0; i < numbers.Length; i++)
{
numbers2[i] = (i + 6) * 10;
Debug.Log (numbers2[i]);
}
}
}

III. Sum of elements in an array : [Starts at: 23min:21sec]

Example Code:

using UnityEngine;
public class ArraysDemo : MonoBehaviour {
void Start () {

int[] healths = new int[5]{10,20,30,40,50};

int sumOfHealths = 0;

for (int i = 0; i < healths.Length; i++) {
sumOfHealths = sumOfHealths + healths [i];
}
Debug.Log (sumOfHealths); // 150

sumOfHealths = 0;
foreach (int item in healths) {
sumOfHealths = sumOfHealths + item;
}
Debug.Log (sumOfHealths); // 150


}
}