C++ JUMP STATEMENT

In C language there are 4 types of jump statements:

  1. Break Statement
  2. Continue Statement
  3. Goto Statement
  4. Return Statement

Break Statement: Break statement is used to terminate the loops like for, while, and do-while from the subsequent execution, it also terminates the switch statement.

syntax:

break;

EXAMPLE


#include <iostream>
using namespace std;

void findElement(int arr[], int size, int key)
{

	for (int i = 0; i < size; i++) {
		if (arr[i] == key) {
			cout << "Element found at position: " << (i + 1);
			break;
		}
	}
}

int main()
{
	int arr[] = { 1, 2, 3, 4, 5, 6 };
	int n = 6; // no of elements
	int key = 3; // key to be searched

	// Calling function to find the key
	findElement(arr, n, key);

	return 0;
}

Continue Statement: Continue statement is used to continue the next iteration of a loop, so the remaining statements are skipped within the loop.

Syntax:

continue;

Example: 

// program to print the value of i

#include <iostream>
using namespace std;

int main() {
    for (int i = 1; i <= 5; i++) {
        // condition to continue
        if (i == 3) {
            continue;
        }

        cout << i << endl;
    }

    return 0;
}

OUTPUT

1
2
4
5

Goto Statement: goto statement is used to transfer the normal flow of a program to the specified label in the program.

Note => The use of goto statement should be avoided as it usually violets the normal flow of execution. 

Syntax:

{
    ......
    goto sos
    ......
    ......
    sos:
    statements;
}

EXAMPLE:

# include <iostream>
using namespace std;

int main()
{
    float num, average, sum = 0.0;
    int i, n;

    cout << "Maximum number of inputs: ";
    cin >> n;

    for(i = 1; i <= n; ++i)
    {
        cout << "Enter n" << i << ": ";
        cin >> num;
        
        if(num < 0.0)
        {
           // Control of the program move to jump:
            goto jump;
        } 
        sum += num;
    }
    
jump:
    average = sum / (i - 1);
    cout << "\nAverage = " << average;
    return 0;
}

Return Statement: Return statement is used to end or terminate a function immediately with or without value and continues the flow of program execution from where it was called.

The function declared with void type does not return any value.

Syntax:

return; 
or
return value;

EXAMPLE


#include <iostream>
using namespace std;
void Print()
{
	int myFunction(int x, int y) {
  return x + y;
}

int main() {
  int z = myFunction(5, 3);
  cout << z;
  return 0;
}