C 'break', 'continue' and 'goto' Statements to Control Program Flow

    0 Votes

In the previous chapter about loops, we've learned how to make a code block run more than once using different loop structures. But what if you want to stop the loop at specific conditions or you want to skip the body of loop for a specific condition? 'break' and 'continue' statements helps you to achieve them. 'break' statement is also used with 'switch' statements. In this chapter let's look into 'break' and 'continue'statements in detail.

'break' Statement in C

The keyword 'break' allow us to exit the entire 'switch' statement or jump out of a loop without waiting for the test condition to be false.

'break' Statement Example in C

Let’s take a look at an example of how to use 'break' statement with 'for'loop.
#include<stdio.h>
void main()
{
    int i;
    int number;

    printf("Enter a number:");
    scanf("%d", &number);

    for(i = 2; i < number; i++)
    {
        if((number % i) == 0)
        {
            printf("%d is not prime", number);
            break;
        }
    }
}

The above program will check if the input number is a prime or not and if the number is not prime, program will print stating so. The program starts with index variable 'i' initialized with the value 2 (which gets incremented in each cycle of loop) and checks if the input number is divisible by 'i'. If it is divisible by any number other than 1 and itself, then it's not a prime and we don't need to try remaining values. So, after 'printf' statement, the 'break' will take the program control out of 'for' loop.

When 'break' statement is used within a loop, it takes the control out of only the immediate loop. Let's look at an example of 'break' statement with nested 'for' loop to understand more about this.

Also Read - Top C Interview Questions and Answers for Freshers & Advanced C Interview Questions and Answers

The program given below prints the non-prime numbers between 5 and 20 using a nested loop. The outer loop iterates from 5 to 20 and the inner loop checks if the number is prime or not. If number is not prime, inner loop prints that and the 'break' statement takes the control out of inner loop. That means, control is taken back to the outer loop, which begin to process with the next value for loop variable 'i'

#include<stdio.h>
void main()
{
    int i, j;

    for(i = 5; i <= 20; i++)
    {
        for(j = 2; j <  i; j++)
        {
            if((i % j) == 0)
            {
                printf("%d\n", i);
                break;
            }    
        }
    }
}

'continue' Statement in C

In the previous section we've seen that how to use 'break' statement to exit the loop on particular condition. Now let's see how to skip a particular cycle of a loop? You can use 'continue' statement inside a loop block for that purpose. The 'continue' statement does not terminate the loop. It just skips the remaining statements in the body of the loop for the current pass and then next pass is started. To use 'continue', you just have to include the keyword 'continue' followed by a semicolon.

Also Read - Top Embedded C Interview Questions and Answers & C++ Interview Questions and Answers

Example of 'Continue' Statement in C

The below example has an array of integers as input and it iterates over each number checking if each number of negative or positive. If it's positive, the program calculates the square of the number, else it goes to the next number.

#include <stdio.h>

int main(void) {
	int a[5] = {1, -2, 3, -4, 5};
	int i;
	for (i = 0; i < 5; i++ ) {
		if (a[i] < 0) 
			continue;
		printf("%d * %d = %d\n", a[i], a[i], a[i] * a[i]);
	}
	return 0;
}

Output:
    1 * 1 = 1
    3 * 3 = 9
    5 * 5 = 25

The program iterates over each number and when the number is less than 0, the 'continue' statement is executed and control goes to the next iteration of loop.

 

'goto' Statement

The 'goto' statement is used to transfer the control of execution of the program to another part of the program where a particular label is defined. The 'goto' statement is used alongside a label and has the general form goto label;

The label is the identifier which defines where the control should go on the execution of 'goto' statement. The target statement block must be labelled like - label: statement /statement block

Example of 'goto' Statement in C

Take look at the following simple program.

#include<stdio.h>
void main()
{
    int i;
    for(i = 0; i < 10; i++)
    {
        if(i == 5)
        {
            goto out; 
        }
        printf("%d\n", i);
    }

    out: 
        printf("I am tired now\n");
}

This program will print the values 0 to 4 and when value of 'i' reaches 5, execution jumps to the statement with label 'out'. Then it will just print the string "I am tired now" and will exit from the program.

One advantage of 'goto' statement is that unlike 'break', 'goto' can exit from all nested loops. Also, if you use 'goto' correctly, you can write a block that loops multiple times without using for, while or do...while loop. Following piece of code is an example of that.

int i = 0;
a:
if(i < 10)
{
    printf("%d\n", i);
    i++;
    goto a;
}
Planning to do an MBA?
A quick all-in-one MBA entry manual for MBA Aspirants. Book covers
  • Possible MBA Tests & Exam Preparation
  • Tips to choose right MBA Program
  • Essay, Resume & Letter of Recommendation
  • MBA Interview Preparation
  • MBA Financial Planning
Price - 6.99$
 

Popular Videos

How to speak to people

How to speak so that people want to listen.

Got a tip or Question?
Let us know

Related Articles

C Overview and Basic Syntax
Data Types in C Language
C Qualifiers - Constant and Volatile type Qualifier
C Type Casting with examples - float to int / int to char / int to long
C Constants and Literals
C Operators - Arithmetic, Assignment, Relational and Logical
C Operators - Bitwise Operators and Conditional Operators
C Operator Precedence and Associativity Table with Examples
C Input and Output Statements
C Format Specifiers for printf and scanf
C Decision Making Control Structures - 'if', 'if - else', nested 'if', 'switch'
Loops in C - for, while and do...while Loops
C Preprocessor Directives and Macros
C Functions Tutorial with Examples
C Arrays - Dynamic, 2d and Multidimensional with Examples
C Strings - Internal Working and Functions with example
C Pointers basics explained with examples
Structures in C Programming with Example
Unions in c programming with example
C Storage Class Specifiers - auto, register, static and extern