C# Language
Jump Statements
Jump statements are used to control the flow of a program by altering the sequence in which statements are executed. There are three main jump statements in C#: 'break', 'continue', and 'return'. Additionally, there's also the 'goto' statement, though its usage is generally discouraged.
'break' Statement:
for (int i = 0; i < 10; i++) { if (i == 5) { break; // Exit the loop when i reaches 5 } Console.WriteLine(i); }
⤏ The 'break' statement is primarily used to terminate the execution of a loop (e.g., 'for', 'while', 'do-while') or switch statement prematurely.
'continue' Statement:
for (int i = 0; i < 10; i++) { if (i % 2 == 0) { continue; // Skip even numbers } Console.WriteLine(i); }
⤏ The 'continue' statement is used to skip the rest of the loop's body and proceed to the next iteration of the loop.
'return' Statement:
int Add(int a, int b) { return a + b; // Exit the method and return the sum of a and b }
⤏ The 'return' statement is used to exit a method and optionally return a value.
'goto' Statement:
• The usage of 'goto' is generally discouraged because it can lead to complex and hard-to-read code. It can make the code less maintainable and harder to understand.
int i = 0; start: Console.WriteLine(i); i++; if (i < 5) { goto start; // Jump back to the 'start' label }
⤏ The 'goto' statement allows jumping to a labeled statement within the same method, bypassing normal flow control structures.
It's important to use these jump statements judiciously, as excessive use or improper usage can lead to code that is difficult to understand and maintain. In most cases, structured control flow constructs like loops and conditional statements are preferred over the use of 'goto'.
What's Next?
We've now entered the finance section on this platform, where you can enhance your financial literacy.