Control Statements:
1. What should be data type of case labels of switch statement in C?
In C++ switch statement, the expression of each case label must be an integer constant expression.
For example, the following program fails in compilation.
/* Using non-const in case label */
#include<stdio.h>
int main()
{
int i = 10;
int c = 10;
switch(c)
{
case i: // not a "const int" expression
printf("Value of c = %d", c);
break;
/*Some more cases */
}
return 0;
}
Putting const before i makes the above program work.
#include<stdio.h>
int main()
{
const int i = 10;
int c = 10;
switch(c)
{
case i: // Works fine
printf("Value of c = %d", c);
break;
/*Some more cases */
}
return 0;
}
Note : The above fact is only for C++. In C, both programs produce an error. In C, using an integer literal does not
cause an error.
Program to find the largest number between two numbers using switch case:
#include<stdio.h>
int main()
{
int n1=10,n2=11;
// n1 > n2 (10 > 11) is false so using
// logical operator '>', n1 > n2 produces 0
// (0 means false, 1 means true) So, case 0
// is executed as 10 > 11 is false. Here we
// have used type cast to convert boolean to int,
// to avoid warning.
switch((int)(n1 > n2))
{
case 0:
printf("%d is the largest\n", n2);
break;
default:
printf("%d is the largest\n", n1);
}
// n1 < n2 (10 < 11) is true so using logical
// operator '<', n1 < n2 produces 1 (1 means true,
// 0 means false) So, default is executed as we
// don't have case 1 to be executed.
switch((int)(n1 < n2))
{
case 0:
printf("%d is the largest\n", n1);
break;
default:
printf("%d is the largest\n", n2);
}
return 0;
2)For Versus While
Question: Is there any example for which the following two loops will not work same way?
/*Program 1 --> For loop*/
for (<init-stmnt>; <boolean-expr>; <incr-stmnt>)
{
<body-statements>
}
/*Program 2 --> While loop*/
<init-stmnt>;
while (<boolean-expr>)
{
<body-statements>
<incr-stmnt>
}
Solution:
If the body-statements contains continue, then the two programs will work in different ways
See the below examples: Program 1 will print “loop” 3 times but Program 2 will go in an infinite loop.
Example for program 1
int main()
{
int i = 0;
for(i = 0; i < 3; i++)
{
printf("loop ");
continue;
}
getchar();
return 0;
}
Example for program 2
int main()
{
int i = 0;
while(i < 3)
{
printf("loop"); /* printed infinite times */
continue;
i++; /*This statement is never executed*/
}
getchar();
return 0;
}
3) A nested loop puzzle
Which of the following two code segments is faster? Assume that compiler makes no
optimizations.
/* FIRST */
for(i=0;i<10;i++)
for(j=0;j<100;j++)
//do something
/* SECOND */
for(i=0;i<100;i++)
for(j=0;j<10;j++)
//do something
Both code segments provide same functionality, and the code inside the two for loops would
be executed same number of times in both code segments.
If we take a closer look then we can see that the SECOND does more operations than the
FIRST. It executes all three parts (assignment, comparison and increment) of the for loop
more times than the corresponding parts of FIRST:
1. The SECOND executes assignment operations ( j = 0 or i = 0) 101 times
while FIRST executes only 11 times.
2. The SECOND does 101 + 1100 comparisons (i < 100 or j < 10) while the
FIRST does 11 + 1010 comparisons (i < 10 or j < 100).
3. The SECOND executes 1100 increment operations (i++ or j++) while the
FIRST executes 1010 increment operation.
Below C++ code counts the number of increment operations executed in FIRST and
SECOND, and prints the counts.
//program to count number of increment
//operations in FIRST and SECOND
#include<iostream>
using namespace std;
int main()
{
int c1 = 0, c2 = 0;
/* FIRST */
for(int i=0;i<10;i++,c1++)
for(int j=0;j<100;j++, c1++);
//do something
/* SECOND */
for(int i=0; i<100; i++, c2++)
for(int j=0; j<10; j++, c2++);
//do something
cout << " Count in FIRST = " <<c1 << endl;
cout << " Count in SECOND = " <<c2 << endl;
getchar();
return 0;
}
Output:
Count in FIRST = 1010
Count in SECOND = 1100
Below C++ code counts the number of comparison operations executed by FIRST and
SECOND
//program to count the number of comparison
//operations executed by FIRST and SECOND */
#include<iostream>
using namespace std;
int main()
{
int c1 = 0, c2 = 0;
/* FIRST */
for(int i=0; ++c1&&i<10; i++)
for(int j=0; ++c1&&j<100;j++);
//do something
/* SECOND */
for(int i=0; ++c2&&i<100; i++)
for(int j=0; ++c2&&j<10; j++);
//do something
cout << " Count fot FIRST " <<c1 << endl;
cout << " Count fot SECOND " <<c2 << endl;
getchar();
return 0;
}
Output:
Count fot FIRST 1021
Count fot SECOND 1201
4)switch statement in C
Switch is a control statement that allows a value to change control of execution.
// Following is a simple program to demonstrate syntax of switch.
#include <stdio.h>
int main()
{
int x = 2;
switch (x)
{
case 1: printf("Choice is 1");
break;
case 2: printf("Choice is 2");
break;
case 3: printf("Choice is 3");
break;
default: printf("Choice other than 1, 2 and 3");
break;
}
return 0;
}
Output:
Choice is 2
Following are some interesting facts about switch statement.
1) The expression used in switch must be integral type ( int, char and enum). Any other
type of expression is not allowed.
// float is not allowed in switch
#include <stdio.h>
int main()
{
float x = 1.1;
switch (x)
{
case 1.1: printf("Choice is 1");
break;
default: printf("Choice other than 1, 2 and 3");
break;
}
return 0;
}
Output:
Compiler Error: switch quantity not an integer
In Java, String is also allowed in switch (See this)
2) All the statements following a matching case execute until a break statement is
reached.
// There is no break in all cases
#include <stdio.h>
int main()
{
int x = 2;
switch (x)
{
case 1: printf("Choice is 1\n");
case 2: printf("Choice is 2\n");
case 3: printf("Choice is 3\n");
default: printf("Choice other than 1, 2 and 3\n");
}
return 0;
}
Output:
Choice is 2
Choice is 3
Choice other than 1, 2 and 3
// There is no break in some cases
#include <stdio.h>
int main()
{
int x = 2;
switch (x)
{
case 1: printf("Choice is 1\n");
case 2: printf("Choice is 2\n");
case 3: printf("Choice is 3\n");
case 4: printf("Choice is 4\n");
break;
default: printf("Choice other than 1, 2, 3 and 4\n");
break;
}
printf("After Switch");
return 0;
}
Output:
Choice is 2
Choice is 3
Choice is 4
After Switch
3) The default block can be placed anywhere. The position of default doesn’t matter, it is
still executed if no match found.
// The default block is placed above other cases.
#include <stdio.h>
int main()
{
int x = 4;
switch (x)
{
default: printf("Choice other than 1 and 2");
break;
case 1: printf("Choice is 1");
break;
case 2: printf("Choice is 2");
break;
}
return 0;
}
Output:
Choice other than 1 and 2
4) The integral expressions used in labels must be a constant expressions
// A program with variable expressions in labels
#include <stdio.h>
int main()
{
int x = 2;
int arr[] = {1, 2, 3};
switch (x)
{
case arr[0]: printf("Choice 1\n");
case arr[1]: printf("Choice 2\n");
case arr[2]: printf("Choice 3\n");
}
return 0;
}
Output:
Compiler Error: case label does not reduce to an integer constant
5) The statements written above cases are never executed After the switch statement, the
control transfers to the matching case, the statements written before case are not executed.
// Statements before all cases are never executed
#include <stdio.h>
int main()
{
int x = 1;
switch (x)
{
x = x + 1; // This statement is not executed
case 1: printf("Choice is 1");
break;
case 2: printf("Choice is 2");
break;
default: printf("Choice other than 1 and 2");
break;
}
return 0;
}
Output:
Choice is 1
6) Two case labels cannot have same value
// Program where two case labels have same value
#include <stdio.h>
int main()
{
int x = 1;
switch (x)
{
case 2: printf("Choice is 1");
break;
case 1+1: printf("Choice is 2");
break;
}
return 0;
}
Output:
Compiler Error: duplicate case value
4) Difference between while(1) and while(0)
In most computer programming languages, a while loop is a control flow statement that
allows code to be executed repeatedly based on a given boolean condition. The boolean
condition is either true or false
while(1)
It is an infinite loop which will run till a break statement is issued explicitly. Interestingly
not while(1) but any integer which is non-zero will give a similar effect as while(1).
Therefore, while(1), while(2) or while(-255), all will give infinite loop only.
while(1) or while(any non-zero integer)
{
// loop runs infinitely
}
A simple usage of while(1) can be in the Client-Server program. In the program, the server
runs in an infinite while loop to receive the packets sent from the clients.
But practically, it is not advisable to use while(1) in real-world because it increases the CPU
usage and also blocks the code i.e one cannot come out from the while(1) until the program
is closed manually. while(1) can be used at a place where condition needs to be true always.
C
// C program to illustrate while(1)
#include <stdio.h>
int main()
{
int i = 0;
while (1) {
printf("%d\n", ++i);
if (i == 5)
break; // Used to come
// out of loop
}
return 0;
}
C++
#include <iostream>
using namespace std;
int main()
{
int i = 0;
while (1) {
cout << ++i << "\n";
if (i == 5)
// Used to come
// out of loop
break;
}
return 0;
}
Output
1
2
3
4
5
while(0)
It is opposite of while(1). It means condition will always be false and thus code in while will
never get executed.
while(0)
{
// loop does not run
}
C
// C program to illustrate while(0)
#include<stdio.h>
int main()
{
int i = 0, flag=0;
while ( 0 )
{
// This line will never get executed
printf( "%d\n", ++i );
flag++;
if (i == 5)
break;
}
if (flag==0)
printf ("Didn't execute the loop!");
return 0;
}
C++
#include <iostream>
using namespace std;
int main() {
int i = 0, flag=0;
while ( 0 )
{
// This line will never get executed
cout << ++i << "\n";
flag++;
if (i == 5)
break;
}
if (flag==0)
cout << "Didn't execute the loop!";
return 0;
}
Output
Didn't execute the loop!
1. goto statement
The goto statement is a jump statement which is sometimes also referred to as unconditional
jump statement. The goto statement can be used to jump from anywhere to anywhere within
a function.
Syntax:
Syntax1 | Syntax2
----------------------------
goto label; | label:
. | .
. | .
. | .
label: | goto label;
In the above syntax, the first line tells the compiler to go to or jump to the statement marked
as a label. Here label is a user-defined identifier which indicates the target statement. The
statement immediately followed after ‘label:’ is the destination statement. The ‘label:’ can
also appear before the ‘goto label;’ statement in the above syntax.
Below are some examples on how to use goto statement:
Examples:
Type 1: In this case, we will see a situation similar to as shown in Syntax1 above.
Suppose we need to write a program where we need to check if a number is even or
not and print accordingly using the goto statement. Below program explains how to
do this:
C
// C program to check if a number is
// even or not using goto statement
#include <stdio.h>
// function to check even or not
void checkEvenOrNot(int num)
{
if (num % 2 == 0)
// jump to even
goto even;
else
// jump to odd
goto odd;
even:
printf("%d is even", num);
// return if even
return;
odd:
printf("%d is odd", num);
}
int main() {
int num = 26;
checkEvenOrNot(num);
return 0;
}
C++
// C++ program to check if a number is
// even or not using goto statement
#include <iostream>
using namespace std;
// function to check even or not
void checkEvenOrNot(int num)
{
if (num % 2 == 0)
// jump to even
goto even;
else
// jump to odd
goto odd;
even:
cout << num << " is even";
// return if even
return;
odd:
cout << num << " is odd";
}
// Driver program to test above function
int main()
{
int num = 26;
checkEvenOrNot(num);
return 0;
}
Output:
26 is even
Type 2:: In this case, we will see a situation similar to as shown in Syntax1 above.
Suppose we need to write a program which prints numbers from 1 to 10 using the
goto statement. Below program explains how to do this.
C
// C program to print numbers
// from 1 to 10 using goto statement
#include <stdio.h>
// function to print numbers from 1 to 10
void printNumbers()
{
int n = 1;
label:
printf("%d ",n);
n++;
if (n <= 10)
goto label;
}
// Driver program to test above function
int main() {
printNumbers();
return 0;
}
C++
// C++ program to print numbers
// from 1 to 10 using goto statement
#include <iostream>
using namespace std;
// function to print numbers from 1 to 10
void printNumbers()
{
int n = 1;
label:
cout << n << " ";
n++;
if (n <= 10)
goto label;
}
// Driver program to test above function
int main()
{
printNumbers();
return 0;
}
Output:
1 2 3 4 5 6 7 8 9 10
Disadvantages of using goto statement:
The use of goto statement is highly discouraged as it makes the program logic very
complex.
use of goto makes the task of analyzing and verifying the correctness of programs
(particularly those involving loops) very difficult.
Use of goto can be simply avoided using break and continue statements.
7) Continue Statement
Continue is also a loop control statement just like the break statement. continue statement is opposite to that of
break statement, instead of terminating the loop, it forces to execute the next iteration of the loop.
As the name suggest the continue statement forces the loop to continue or execute the next iteration. When the
continue statement is executed in the loop, the code inside the loop following the continue statement will be
skipped and next iteration of the loop will begin.
Syntax:
continue;
Example:
Consider the situation when you need to write a program which prints number from 1 to 10 and but not 6. It is
specified that you have to do this using loop and only one loop is allowed to use.
Here comes the usage of continue statement. What we can do here is we can run a loop from 1 to 10 and every
time we have to compare the value of iterator with 6. If it is equal to 6 we will use the continue statement to
continue to next iteration without printing anything otherwise we will print the value.
Below is the implementation of the above idea:
C
// C program to explain the use
// of continue statement
#include <stdio.h>
int main() {
// loop from 1 to 10
for (int i = 1; i <= 10; i++) {
// If i is equals to 6,
// continue to next iteration
// without printing
if (i == 6)
continue;
else
// otherwise print the value of i
printf("%d ", i);
}
return 0;
}
C++
// C++ program to explain the use
// of continue statement
#include <iostream>
using namespace std;
int main()
{
// loop from 1 to 10
for (int i = 1; i <= 10; i++) {
// If i is equals to 6,
// continue to next iteration
// without printing
if (i == 6)
continue;
else
// otherwise print the value of i
cout << i << " ";
}
return 0;
}
Output:
1 2 3 4 5 7 8 9 10
The continue statement can be used with any other loop also like while or do while in a similar way as it is used
with for loop above.
Exercise Problem:
Given a number n, print triangular pattern. We are allowed to use only one loop.
Input: 7
Output:
*
* *
* * *
* * * *
* * * * *
* * * * * *
* * * * * * *
Solution : Print the pattern by using one loop | Set 2 (Using Continue Statement)
8)Break Statement
The break in C or C++ is a loop control statement which is used to terminate the loop. As soon as the break
statement is encountered from within a loop, the loop iterations stops there and control returns from the loop
immediately to the first statement after the loop.
Syntax:
break;
Basically break statements are used in the situations when we are not sure about the actual number of iterations for
the loop or we want to terminate the loop based on some condition.
We will see here the usage of break statement with three different types of loops:
1. Simple loops
2. Nested loops
3. Infinite loops
Let us now look at the examples for each of the above three types of loops using break statement.
1. Simple loops: Consider the situation where we want to search an element in an array. To do this, use a loop
to traverse the array starting from the first index and compare the array elements with the given key.
Below is the implementation of this idea:
C
// C program to illustrate
// Linear Search
#include <stdio.h>
void findElement(int arr[], int size, int key)
{
// loop to traverse array and search for key
for (int i = 0; i < size; i++) {
if (arr[i] == key) {
printf("Element found at position: %d", (i + 1));
}
}
}
int main() {
int arr[] = { 1, 2, 3, 4, 5, 6 };
// no of elements
int n = 6;
// key to be searched
int key = 3;
// Calling function to find the key
findElement(arr, n, key);
return 0;
}
C++
// CPP program to illustrate
// Linear Search
#include <iostream>
using namespace std;
void findElement(int arr[], int size, int key)
{
// loop to traverse array and search for key
for (int i = 0; i < size; i++) {
if (arr[i] == key) {
cout << "Element found at position: " << (i + 1);
}
}
}
// Driver program to test above function
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;
}
Output:
Element found at index: 3
The above code runs fine with no errors. But the above code is not efficient. The above code
completes all the iterations even after the element is found. Suppose there are 1000 elements in the
array and the key to be searched is present at 1st position so the above approach will
execute 999 iterations which are of no purpose and are useless.
To avoid these useless iterations, we can use the break statement in our program. Once the break
statement is encountered the control from the loop will return immediately after the condition gets
satisfied. So will use the break statement with the if condition which compares the key with array
elements as shown below:
C
// C program to illustrate
// using break statement
// in Linear Search
#include <stdio.h>
void findElement(int arr[], int size, int key)
{
// loop to traverse array and search for key
for (int i = 0; i < size; i++) {
if (arr[i] == key) {
printf("Element found at position: %d", (i + 1));
// using break to terminate loop execution
break;
}
}
}
int main() {
int arr[] = { 1, 2, 3, 4, 5, 6 };
// no of elements
int n = 6;
// key to be searched
int key = 3;
// Calling function to find the key
findElement(arr, n, key);
return 0;
}
C++
// CPP program to illustrate
// using break statement
// in Linear Search
#include <iostream>
using namespace std;
void findElement(int arr[], int size, int key)
{
// loop to traverse array and search for key
for (int i = 0; i < size; i++) {
if (arr[i] == key) {
cout << "Element found at position: " << (i + 1);
// using break to terminate loop execution
break;
}
}
}
// Driver program to test above function
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;
}
Output:
Element found at position: 3
2. Nested Loops: We can also use break statement while working with nested loops. If the break statement is
used in the innermost loop. The control will come out only from the innermost loop. Below is the example
of using break with nested loops:
C
// C program to illustrate
// using break statement
// in Nested loops
#include <stdio.h>
int main() {
// nested for loops with break statement
// at inner loop
for (int i = 0; i < 5; i++) {
for (int j = 1; j <= 10; j++) {
if (j > 3)
break;
else
printf("*");
}
printf("\n");
}
return 0;
}
C++
// CPP program to illustrate
// using break statement
// in Nested loops
#include <iostream>
using namespace std;
int main()
{
// nested for loops with break statement
// at inner loop
for (int i = 0; i < 5; i++) {
for (int j = 1; j <= 10; j++) {
if (j > 3)
break;
else
cout << "*";
}
cout << endl;
}
return 0;
}
Output:
***
***
***
***
***
In the above code we can clearly see that the inner loop is programmed to execute for 10 iterations.
But as soon as the value of j becomes greater than 3 the inner loop stops executing which restricts
the number of iteration of the inner loop to 3 iterations only. However the iteration of outer loop
remains unaffected.
Therefore, break applies to only the loop within which it is present.
3. Infinite Loops: break statement can be included in an infinite loop with a condition in order to terminate
the execution of the infinite loop.
Consider the below infinite loop:
C
// C program to illustrate
// using break statement
// in Infinite loops
#include <stdio.h>
int main() {
// loop initialization expression
int i = 0;
// infinite while loop
while (1) {
printf("%d ", i);
i++;
}
return 0;
}
C++
// CPP program to illustrate
// using break statement
// in Infinite loops
#include <iostream>
using namespace std;
int main()
{
// loop initialization expression
int i = 0;
// infinite while loop
while (1) {
cout << i << " ";
i++;
}
return 0;
}
Note: Please donot run the above program in your compiler as it is an infinite loop so you may have
to forcefully exit the compiler to terminate the program.
In the above program, the loop condition based on which the loop terminates is always true. So, the
loop executes infinite number of times. We can correct this by using the break statement as shown
below:
C
// C program to illustrate
// using break statement
// in Infinite loops
#include <stdio.h>
int main() {
// loop initialization expression
int i = 1;
// infinite while loop
while (1) {
if (i > 10)
break;
printf("%d ", i);
i++;
}
return 0;
}
C++
// CPP program to illustrate
// using break statement
// in Infinite loops
#include <iostream>
using namespace std;
int main()
{
// loop initialization expression
int i = 1;
// infinite while loop
while (1) {
if (i > 10)
break;
cout << i << " ";
i++;
}
return 0;
}
Output:
1 2 3 4 5 6 7 8 9 10
The above code restricts the number of loop iterations to 10.
Apart from this, break can be used in Switch case statements too.
Using range in switch case
You all are familiar with switch case in C/C++, but did you know you can use range of numbers instead of a
single number or character in case statement.
That is the case range extension of the GNU C compiler and not standard C or C++
You can specify a range of consecutive values in a single case label, like this:
case low ... high:
It can be used for ranges of ASCII character codes like this:
case 'A' ... 'Z':
You need to Write spaces around the ellipses … . For example, write this:
// Correct - case 1 ... 5:
// Wrong - case 1...5:
// C program to illustrate
// using range in switch case
#include <stdio.h>
int main()
{
int arr[] = { 1, 5, 15, 20 };
for (int i = 0; i < 4; i++)
{
switch (arr[i])
{
case 1 ... 6:
printf("%d in range 1 to 6\n", arr[i]);
break;
case 19 ... 20:
printf("%d in range 19 to 20\n", arr[i]);
break;
default:
printf("%d not in range\n", arr[i]);
break;
}
}
return 0;
}
Output:
1 in range 1 to 6
5 in range 1 to 6
15 not in range
20 in range 19 to 20
Exercise : You can try above program for char array by modifying char array and case statement.
Error conditions:
1. low > high : The compiler gives with an error message.
2. Overlapping case values : If the value of a case label is within a case range that has already been used in
the switch statement, the compiler gives an error message.