Sometimes we will want to exit a loop or prematurely end the current iteration of the loop. We use break to break out of the loop and continue to tell the computer to continue the loop from the start of the next iteration.
The break statement
John wants to tell the computer to exit counting in a sequence when the square of the current counter becomes 9. He writes the following code:
#include <stdio.h>
int main(void){
int i = 10;
while (i>0){
printf("i = %d\n",i);
i--;
if (i*i==9){
printf("Breaking out of the loop...(i=%d -> i^2=%d)\n",i,i*i);
break;
}
}
return 0;
}
The continue statement
David wants to write a program where the cube of every number between 1 and 10 are summed. He wants to exclude the cubes of 5 and 7:
#include <stdio.h>
int main(void){
int i;
int sum = 0;
for(i=1;i<=10;i++){
if(i==5||i==7){
continue;
}
// the following line is skipped if i is 5 or 7
sum+=i*i*i;
}
printf("The sum of the cubes of 1 to 10 except those of 5 and 7 is %d\n",sum);
return 0;
}
Whenever the value of i matches 5 or 7, the sum will not be made to include the cube of i.
The goto statement
Looping behaviour can be achieved by the use of C’s goto statement. We place a label before a section of code and tell the computer to go to that section where the label is.
The Euclidean algorithm
The goto statement can be used to write a more readable form of the Euclidean algorithm:
#include <stdio.h>
int main(void){
int original_a = 14, original_b = 256;
int a = original_a, b = original_b, quot, rem;
// declaring label called 'start'
start:
quot = b/a;
rem = b%a;
printf("%d = %d x %d + %d\n",b,quot,a,rem);
if (rem==0){
printf("The HCF of %d and %d is %d\n",original_a,original_b,a);
}else{
b = a;
a = rem;
// jumping back to the 'start' label
goto start;
}
return 0;
}
Notice that we do not declare any variables after the label. The algorithm is based on the fact that for an equation:
$$b=qa+r$$
the highest common factor (HCF) of b and a is the HCF of a and r
$$HCF(b,a)=HCF(a,r)$$
The algorithm is terminated when we get the HCF of a and a remainder of 0:
$$HCF(a,0)=\color{royalblue}a$$
This a is the HCF of the two numbers we started with.