coderz.py

Keep Coding Keep Cheering!

Jump Statement in C++

Accessing Elements

When encountered, jump statements are used to shift program control from one part of the program to any other part of the program unconditionally. In C++, jump statements are implemented using :

  • continue
  • break
  • return
  • goto
continue:

Within loops or iterative statements, continue statements are used. The continue statement’s goal is to skip the remaining statements of the current iteration of the loop and proceed to the next iteration.

Example:
// C++ program to demonstrate the
// continue statement
#include <iostream>
using namespace std;

// Driver code
int main()
{
	for (int i = 1; i < 10; i++) {

		if (i%2 == 0)
			continue;
		cout << i << " ";
	}
	return 0;
}
Output:
1 3 5 7 9 
break:

The break statement allows us to jump out of the loop instantly, without waiting to get back to the conditional test. When the break is encountered inside any loop, control automatically passes to the first statement after the loop. A break is usually associated with an if.

Example:
#include <iostream>
using namespace std;

// Driver code
int main()
{
	for (int i = 1; i < 10; i++) {

		if (i > 6)
			break;
		cout << i << " ";
	}
	return 0;
}
Output:
1 2 3 4 5 6 
return:

Return statements can be used anywhere in the function. The return statement’s goal is to halt the current function’s execution and return program control to the point from which it was called. If a return statement is used in the main function, then it will stop the compilation process of the program.

Example:
// C++ program to demonstrate the
// return statement
#include <iostream>
using namespace std;

// Driver code
int main()
{
	cout << "Begin ";

	for (int i = 0; i < 10; i++) {

		// Termination condition
		if (i == 5)
			return 0;
		cout << i << " ";
	}
	cout << "end";

	return 0;
}
Output:
Begin 0 1 2 3 4
goto :

This statement is used to transfer control to the tagged statement in the program. The tag is the valid identifier and placed just before the statement from where the control is transferred. The usage of the goto keyword should be avoided as it usually violates the normal flow of execution.

Example:

#include <iostream>
using namespace std;

int main()
{
	int n = 4;

	if (n % 2 == 0)
		goto label1;
	else
		goto label2;

label1:
	cout << "Even" << endl;
	return 0;

label2:
	cout << "Odd" << endl;
}
Output:
Even

Note: also read about Loops in C++

Follow Me

If you like my post please follow me to read my latest post on programming and technology.

https://www.instagram.com/coderz.py/

https://www.facebook.com/coderz.py

Leave a Comment

Your email address will not be published. Required fields are marked *

Advertisement