Jumping Statements in C++
In the previous lesson, we covered iterative statements such as entry controlled and exit controlled loops, which allow us to repeat a block of code multiple times. Now, let's explore jumping statements in C++, which provide a way to alter the flow of execution within a program. Jumping statements allow you to transfer control to different parts of the code, skip certain sections, or terminate the execution of a loop or function. In the next lesson, we will delve into arrays, a fundamental data structure in C++ that allows you to store and manipulate collections of elements.
The three jumping statements in C++ are:
-
break:
The
break
statement is used to exit from a loop or switch statement. When encountered, it immediately terminates the innermost loop or switch and transfers control to the next statement outside the loop or switch. -
continue:
The
continue
statement is used to skip the remaining code within the current iteration of a loop and move to the next iteration. It allows you to skip certain parts of the loop's body based on a specific condition. -
return:
The
return
statement is used to exit from a function and return a value to the caller. When encountered, it terminates the execution of the current function and returns the specified value (if any) back to the calling code.
Example Usage:
#include <iostream>
int main() {
for (int i = 1; i <= 10; i++) {
if (i == 5) {
break; // Exit the loop when i is equal to 5
}
if (i % 2 == 0) {
continue; // Skip even numbers and move to the next iteration
}
std::cout << i << " ";
}
return 0;
}
In the above example, the
break
statement is used to exit the loop when the variable
i
is equal to 5. The
continue
statement is used to skip even numbers and move to the next iteration. The output of this program will be:
1 3
.
Conclusion
Jumping statements in C++ provide a way to alter the flow of execution within a program. The
break
statement allows you to exit from a loop or switch, the
continue
statement allows you to skip certain parts of a loop, and the
return
statement allows you to exit from a function. Understanding and using jumping statements effectively can make your code more flexible and efficient. In the next lesson, we will dive into arrays, a powerful data structure that will expand your capabilities in C++ programming.