break & continue keyword within for, while, do while loops
Notes:
I. Optimizing memory : [Starts at: 00min:00sec]
II. break within for, while, do while loops : [Starts at: 06min:00sec]
III. continue within for, while, do while loops : [Starts at: 16min:37sec]
I. Optimizing memory : [Starts at: 00min:00sec]
Example Code:
using UnityEngine;
public class ControlsDemo : MonoBehaviour
{
void Start ()
{
/*
byte sum = 0;
for (byte i = 0; i < 5; i++)
{
// as byte + byte result to int
// we can not assign an int to a byte memory
sum = sum + i; // error : type cast needed
}
Debug.Log ("Sum =" + sum);
*/
// Solution
byte sum = 0;
for (byte i = 0; i < 5; i++)
{
sum = (byte)(sum + i);
}
Debug.Log ("Sum =" + sum); // 10
}
}
II. break within for, while, do while loops : [Starts at: 06min:00sec]
On execution, it skips any below statement(s) and
moves the control outside the nearest loop.
Note: break keyword is used inside switch and looping statements
Example Code:
using UnityEngine;
public class LoopingStatements : MonoBehaviour {
void Start () {
/*
// C# break statement in for loop demo
for (int i = 0; i < 10; i++) {
if (i == 1) {
break;
} v
Debug.Log ("Hello Unity");
}
*/
/*
// C# break statement in while loop demo
int i = 0;
while ( i < 10 ) {
if (i == 1) {
break;
}
Debug.Log ("Hello Unity");
i++;
}
*/
// C# break statement in do while loop demo
int i = 0;
do {
if (i == 1) {
break;
}
Debug.Log ("Hello Unity");
i++;
} while (i < 10);
}
}
III. continue within for, while, do while loops : [Starts at: 16min:37sec]
On execution, it skips any below statement(s) and
continues the current loop.
Note: continue keyword is used inside looping statements
Example Code:
using UnityEngine;
public class LoopingStatements : MonoBehaviour {
void Start () {
/*
// C# continue statement within for loop
for (int i = 0; i < 5; i++) {
if (i == 1) {
continue; // moves control to 4th part (ie. i++)
}
Debug.Log ("Hello Unity");
}
*/
/*
// C# continue statement within while loop
int i=0;
while(i < 5) {
i++; v
if (i == 1) {
continue; // moves control to while condition
}
Debug.Log ("Hello Unity");
}
*/
// C# continue statement within do while loop
int i=0;
do {
i++;
if (i == 1) {
continue; // moves control to while condition
}
Debug.Log ("Hello Unity");
} while(i < 5) ;
}
}
Note:
continue within for loop moves control to 4 th part
continue within while and do while moves control to while part