What are Jumping Statements in C explained with example?
In the C programming language, jumping statements are those that switch over control to another area of the programme.Jump statements are a subset of Control Statements in C that are used to break the program's usual flow. When encountered, it forces the programme to jump unconditionally to another area of the programme. It can be used to end any loop as well.
Types of Jumping Statements in C
C language provide the following jumping statements.
- Break Statement
- Continue Statement
- Goto Statement
- Return Statement
Break Statement : You can abruptly end a loop or switch statement by using the "break" statement. It ends the loop or switch expression that appears at its innermost position. For example, the following code will print the numbers 1 to 10, but will exit the loop when the number is equal to 5:
for (int i = 1; i <= 10; i++)
{
if (i == 5)
{
break;
}
printf("%d ", i);
}
Continue Statement : The "continue" statement is used to go on to the next iteration of a loop while skipping the current one. It causes the control to advance to the loop's following iteration. For example, the following code will print the numbers 1 to 10, but will skip printing the number 5:
for (int i = 1; i <= 10; i++)
{
if (i == 5)
{
continue;
}
printf("%d ", i);
}
Goto Statement : In goto statement control is transferred to a labeled statement using the "goto" statement. The code below, for instance, prints the numbers 1 through 10, but when the value is equal to 5, control moves to the labelled statement "end". It enables jumping between programme points indicated by labels .
for (int i = 1; i <= 10; i++)
{
if (i == 5)
{
goto end;
}
printf("%d ", i);
}
end:
printf("Reached end!");
Return Statement : In C, the "return" statement is used to end a function and, if requested, return a value to the calling function. It put a stop to the current function's execution and hands control back to the caller function. As an example, the following code creates the function "square," which returns the square of an integer as an input.
int square(int x)
{
int result = x * x;
return result;
}
In this example, when the function is called with an argument of 5, the variable "result" will be set to 25 and the "return" statement will cause the function to exit and return the value 25 to the calling function.
int main()
{
int num = 5;
int square_num = square(num);
printf("Square of %d is %d", num, square_num);
return 0;
}
Output: Square of 5 is 25
It is important to note that the return statement is mandatory in all the non-void functions. Also, the return statement should match the return type of the function.