Explore 100's Of Free Video Tutorials

Keep Learning, Keep Coding & Keep Sharing

Find sum of two arrays & Swapping two array elements

Notes:

I. Program to find sum of two array elements: [Starts at: 02min:11sec]
II. Program to swap two array elements: [Starts at: 13min:14sec]

I. Program to find sum of two array elements: [Starts at: 02min:11sec]

1) Program to find sum of two numbers: [Starts at: 02min:11sec]

Example Code:
using UnityEngine;
public class ArraysDemo : MonoBehaviour
{
void Start ()
{
int a = 10;
int b = 20;
int c = 0;
c = a + b;
Debug.Log (c);
}
}

2) Program to find sum of two array elements: [Starts at: 04min:15sec]

Example Code:

using UnityEngine;
public class ArraysDemo : MonoBehaviour {
void Start () {
// addition of 2 arrays
int[] a = new int[3]{ 1, 2, 3 };
int[] b = new int[3]{ 1, 2, 3 };
int[] c = new int[3];

/*
c [0] = a [0] + b [0];
c [1] = a [1] + b [1];
c [2] = a [2] + b [2];
*/
/*
Debug.Log (c [0]);
Debug.Log (c [1]);
Debug.Log (c [2]);
*/

for (int i = 0; i < c.Length; i++) {
c [i] = a [i] + b [i];
Debug.Log (c [i]);
}
}
}

II. Program to swap two array elements: [Starts at: 13min:14sec]

1) Program to swap two numbers: [Starts at: 13min:14sec]

Example Code:

using UnityEngine;
public class ArraysDemo : MonoBehaviour {
void Start () {
// Swapping 2 variable values
int a=10,b=20;
Debug.Log (string.Format ("Before swapping: a={0} and b={1}", a, b));

int temp = a;
a = b;
b = temp;
Debug.Log (string.Format ("After swapping: a={0} and b={1}", a, b));

}
}

2) Program to swap two array elements: [Starts at: 18min:02sec]

Example Code:

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

// Swapping 2 variable values
int[] a = new int[2]{1,2};
int[] b = new int[2]{ 3,4};
Debug.Log ("Before swap a array is");
for (int i = 0; i < a.Length; i++) {
Debug.Log(a[i]);
}

for (int i = 0; i < a.Length; i++) {
int temp = a [i];
a [i] = b [i];
b [i] = temp;
}

Debug.Log ("After swap a array is");
for (int i = 0; i < a.Length; i++) {
Debug.Log(a[i]);
}

}
}