Unit 2
Loop
while statement:
The while loop in C is most fundamental loop statement. It repeats a statement or block while its controlling expression is true.
The general form is:
while(condition) {
// body of loop
}
The condition can be any boolean expression. The body of the loop will be executed if the conditional expression is true.
Here is more practical example.
The output of the program is:
tick 10
tick 9
tick 8
tick 7
tick 6
tick 5
tick 4
tick 3
tick 2
tick 1
do-while statement
The do-while loop always executes its body at least once, because its conditional expression is at the bottom of the loop.
Its general form is:
do{
// body of loop
} while(condition);
Each iteration of the do-while loop first executes the body of the loop and then evaluates the conditional expression. If this expression is true, the loop will repeat. Otherwise, the loop terminates. As with all of C’s loops, condition must be a Boolean expression.
The program presented in previous while statement can be re-written using do-while as:
//example program to illustrate do-while looping
#include <stdio.h>
int main ()
{
int n = 10;
do
{
printf("tick %d", n);
printf("\n");
n--;
}while (n > 0);
}
for loop
Here is the general form of the traditional for statement:
for(initialization; condition; iteration) {
// body
}
The program from previous example can be re-written using for loop as:
//example program to illustrate for looping
#include <stdio.h>
int main ()
{
int n;
for(n = 10; n>0 ; n--){
printf("tick %d",n);
printf("\n");
}
}
The output of the program is same as output from program in while loop.
There can be more than one statement in initialization and iteration section. They must be separated with comma.
//example program to illustrate more than one statement using the comma
// for looping
#include <stdio.h>
int main ()
{
int a, b;
for (a = 1, b = 4; a < b; a++, b--)
{
printf("a = %d \n", a);
printf("b = %d \n", b);
}
}
The output of the program is:
a = 1
b = 4
a = 2
b = 3
Here, the initialization portion sets the values of both a and b. The two comma separated statements in the iteration portion are executed each time the loop repeats.
Nested Loops
Loops can be nested as per requirement. Here is example of nesting the loops.
// nested loops
#include <stdio.h>
int main ()
{
int i, j;
for (i = 0; i < 8; i++)
{
for (j = i; j < 8; j++)
printf(".");
printf("\n");
}
}
Here, two for loops are nested. The number times inner loop iterates depends on the value of i in outer loop.
The output of the program is:
........
.......
......
.....
....
...
..
.
Multiple initialization inside for Loop in C
We can have multiple initialization in the for loop as shown below.
for (i=1,j=1;i<10 && j<10; i++, j++)
What’s the difference between above for loop and a simple for loop?
1. It is initializing two variables. Note: both are separated by comma (,).
2. It has two test conditions joined together using AND (&&) logical operator. Note: You cannot use multiple test conditions separated by comma, you must use logical operator such as && or || to join conditions.
3. It has two variables in increment part. Note: Should be separated by comma.
Example of for loop with multiple test conditions
#include <stdio.h>
int main()
{
int i,j;
for (i=1,j=1 ; i<3 || j<5; i++,j++)
{
printf("%d, %d\n",i ,j);
}
return 0;
}
The break statement is used to terminate the execution where number of iterations is not unknown. It is used in loop to terminate the loop and then control goes to the first statement of the loop. The break statement is also in switch case.
Structure of the break:
e.g.
When the compiler will reach to break it will come out and print the output. Output will be x=1,x=9,x=8,x=7,x=6,break.
The continue statement work like break statement but it is opposite of break. The Continue statement continues with execution of program by jumping from current code instruction to the next.
Structure of the break:
e.g.
Output is 1 2 3 4 5.
The do – while loop consist of consist of condition mentioned at the bottom with while. The do – while executes till condition is true. As the condition is mentioned at bottom do – while loop is executed at least once.
Structure of the do – while:
e.g.
Output is: 1 2 3 4 5 6 7 8 9 10.
In real life programming one comes across a situation when it is not known beforehand how many times the statements in the loop are to be executed. This situation can be programmed as shown below:
/* Execution of a loop an unknown number of times */
main( )
{
char another ;
int num ;
do
{
printf ( “Enter a number ” ) ;
scanf ( “%d”, &num ) ;
printf ( “square of %d is %d”, num, num * num ) ;
printf ( “\nWant to enter another number y/n ” ) ;
scanf ( ” %c”, &another ) ;
} while ( another == ‘y’ ) ;
}
And here is the sample output…
Enter a number 5
square of 5 is 25
Want to enter another number y/n y
Enter a number 7
square of 7 is 49
Want to enter another number y/n n
This program the do-while loop would keep getting executed till the user continues to answer y. The moment he answers n, the loop terminates, since the condition ( another == ‘y’ ) fails. Note that this loop ensures that statements within it are executed at least once even if n is supplied first time itself.
The same functionality if required, can also be accomplished using for and while loops as shown below:
/* odd loop using a for loop */
main( )
{
char another = ‘y’ ;
int num ;
for ( ; another == ‘y’ ; )
{
printf ( “Enter a number ” ) ;
scanf ( “%d”, &num ) ;
printf ( “square of %d is %d”, num, num * num ) ;
printf ( “\nWant to enter another number y/n ” ) ;
scanf ( ” %c”, &another ) ;
}
}
/* odd loop using a while loop */
main( )
{
char another = ‘y’ ;
int num ;
while ( another == ‘y’ )
{
printf ( “Enter a number ” ) ;
scanf ( “%d”, &num ) ;
printf ( “square of %d is %d”, num, num * num ) ;
printf ( “\nWant to enter another number y/n ” ) ;
scanf ( ” %c”, &another ) ;
}
}
There are 4 types of case control statements in C language. They are,
switch
break
continue
goto
1. SWITCH CASE STATEMENT IN C:
Switch case statements are used to execute only specific case statements based on the switch expression.
Below is the syntax for switch case statement.
switch (expression)
{
case label1: statements;
break;
case label2: statements;
break;
case label3: statements;
break;
default: statements;
break;
}
EXAMPLE PROGRAM FOR SWITCH..CASE STATEMENT IN C:
C
#include <stdio.h>
int main ()
{
int value = 3;
switch(value)
{
case 1:
printf(“Value is 1 \n” );
break;
case 2:
printf(“Value is 2 \n” );
break;
case 3:
printf(“Value is 3 \n” );
break;
case 4:
printf(“Value is 4 \n” );
break;
default :
printf(“Value is other than 1,2,3,4 \n” );
}
return 0;
}
#include <stdio.h>
int main ()
{
int value = 3;
switch(value)
{
case 1:
printf(“Value is 1 \n” );
break;
case 2:
printf(“Value is 2 \n” );
break;
case 3:
printf(“Value is 3 \n” );
break;
case 4:
printf(“Value is 4 \n” );
break;
default :
printf(“Value is other than 1,2,3,4 \n” );
}
return 0;
}
OUTPUT:
Value is 3
2. BREAK STATEMENT IN C:
Break statement is used to terminate the while loops, switch case loops and for loops from the subsequent execution.
Syntax: break;
EXAMPLE
#include <stdio.h>
int main()
{
int i;
for(i=0;i<10;i++)
{
if(i==5)
{
printf("\nComing out of for loop when i = 5");
break;
}
printf("%d ",i);
}
}
#include <stdio.h>
int main()
{
int i;
for(i=0;i<10;i++)
{
if(i==5)
{
printf("\nComing out of for loop when i = 5");
break;
}
printf("%d ",i);
}
}
COMPILE & RUN
OUTPUT:
0 1 2 3 4
Coming out of for loop when i = 5
3. CONTINUE STATEMENT IN C:
Continue statement is used to continue the next iteration of for loop, while loop and do-while loops. So, the remaining statements are skipped within the loop for that particular iteration.
Syntax : continue;
EXAMPLE PROGRAM FOR CONTINUE STATEMENT IN C:
C
#include <stdio.h>
int main()
{
int i;
for(i=0;i<10;i++)
{
if(i==5 || i==6)
{
printf("\nSkipping %d from display using " \
"continue statement \n",i);
continue;
}
printf("%d ",i);
}
}
#include <stdio.h>
int main()
{
int i;
for(i=0;i<10;i++)
{
if(i==5 || i==6)
{
printf("\nSkipping %d from display using " \
"continue statement \n",i);
continue;
}
printf("%d ",i);
}
}
COMPILE & RUN
OUTPUT:
0 1 2 3 4
Skipping 5 from display using continue statement
Skipping 6 from display using continue statement
7 8 9
4. GOTO STATEMENT IN C:
goto statements is used to transfer the normal flow of a program to the specified label in the program.
Below is the syntax for goto statement in C.
{
…….
go to label;
…….
…….
LABEL:
statements;
}
EXAMPLE PROGRAM FOR GOTO STATEMENT IN C:
C
#include <stdio.h>
int main()
{
int i;
for(i=0;i<10;i++)
{
if(i==5)
{
printf("\nWe are using goto statement when i = 5");
goto HAI;
}
printf("%d ",i);
}
HAI : printf("\nNow, we are inside label name \"hai\" \n");
}
#include <stdio.h>
int main()
{
int i;
for(i=0;i<10;i++)
{
if(i==5)
{
printf("\nWe are using goto statement when i = 5");
goto HAI;
}
printf("%d ",i);
}
HAI : printf("\nNow, we are inside label name \"hai\" \n");
}
COMPILE & RUN
OUTPUT:
0 1 2 3 4
We are using goto statement when i = 5
Now, we are inside label name “hai”
A few useful tips about the usage of switch and a few pitfalls to be avoided:
(a) The earlier program that used switch may give you the wrong impression that you can use only cases arranged in ascending order, 1, 2, 3 and default. You can in fact put the cases in any order you please. Here is an example of scrambled case order:
main( )
{
int i = 22 ;
switch ( i )
{
case 121 :
printf ( "I am in case 121 \n" ) ;
break ;
case 7 :
printf ( "I am in case 7 \n" ) ;
break ;
case 22 :
printf ( "I am in case 22 \n" ) ;
break ;
default :
printf ( "I am in default \n" ) ;
}
}
The output of this program would be:
I am in case 22
(b) You are also allowed to use char values in case and switch as shown in the following program:
main( )
{
char c = 'x' ;
switch ( c )
{
case 'v' :
printf ( "I am in case v \n" ) ;
break ;
case 'a' :
printf ( "I am in case a \n" ) ;
break ;
case 'x' :
printf ( "I am in case x \n" ) ;
break ;
default :
printf ( "I am in default \n" ) ;
}
}
The output of this program would be:
I am in case x
In fact here when we use ‘v’, ‘a’, ‘x’ they are actually replaced by the ASCII values (118, 97, 120) of these character constants.
(c) At times we may want to execute a common set of statements for multiple cases. How this can be done is shown in the following example.
main( )
{
char ch ;
printf ( "Enter any of the alphabet a, b, or c " ) ;
scanf ( "%c", &ch ) ;
switch ( ch )
{
case 'a' :
case 'A' :
printf ( "a as in ashar" ) ;
break ;
case 'b' :
case 'B' :
printf ( "b as in brain" ) ;
break ;
case 'c' :
case 'C' :
printf ( "c as in cookie" ) ;
break ;
default :
printf ( "wish you knew what are alphabets" ) ;
}
}
Here, we are making use of the fact that once a case is satisfied the control simply falls through the case till it
doesn’t encounter a break statement. That is why if an alphabet a is entered the case ‘a’ is satisfied and since there are no statements to be executed in this case the control automatically reaches the next case i.e. case ‘A’ and executes all the statements in this case.
(d) Even if there are multiple statements to be executed in each case there is no need to enclose them within a pair of braces (unlike if, and else).
(e) Every statement in a switch must belong to some case or the other. If a statement doesn’t belong to any case the compiler won’t report an error. However, the statement would never get executed. For example, in the following program the printf( ) never goes to work.
main( )
{
int i, j ;
printf ( "Enter value of i" ) ;
scanf ( "%d”, &i ) ;
switch ( i )
{
printf ( "Hello" ) ;
case 1 :
j = 10 ;
break ;
case 2 :
j = 20 ;
break ;
}
}
(f) If we have no default case, then the program simply falls through the entire switch and continues with the next instruction (if any,) that follows the closing brace of switch.
(g) Is switch a replacement for if? Yes and no. Yes, because it offers a better way of writing programs as compared to if, and no because in certain situations we are left with no choice but to use if. The disadvantage of switch is that one cannot have a case in a switch which looks like:
case i <= 20 :
All that we can have after the case is an int constant or a char constant or an expression that evaluates to one of these
constants. Even a float is not allowed. The advantage of switch over if is that it leads to a more structured program and the level of indentation is manageable, more so if there are multiple statements within each case of a switch.
(h) We can check the value of any expression in a switch. Thus
the following switch statements are legal.
switch ( i + j * k )
switch ( 23 + 45 % 4 * k )
switch ( a < 4 && b > 7 )
Expressions can also be used in cases provided they are constant expressions. Thus case 3 + 7 is correct, however, case a + b is incorrect.
(i) The break statement when used in a switch takes the control outside the switch. However, use of continue will not take the control to the beginning of switch as one is likely to believe.
(j) In principle, a switch may occur within another, but in practice it is rarely done. Such statements would be called nested switch statements.
else if statement can be defined as a control statement which controls the statement(s) to be executed on the basis of some conditions. Whenever the else if statement is used, the compiler or interpreter initially checks the condition whether it is true or false and if the condition is found to be true then, the corresponding statements are executed. If the condition is found to be false, it continues checking the next else if statement until the condition comes to be true or the control comes to the end of the else if ladder.
The syntax of else if ladder can be represented as
if( condition-1)
statement-1;
else if (condition-2)
statement-2;
else if (condition-3)
statement-3;
else if (condition-4)
statement-4;
else if (condition-n)
statement-n;
else
default statement;
Switch Case:
The switch case statement is similar to the else-if ladder as it provides multiple branching or multi-conditional processing. But, the basic difference between switch case and else if ladder is that the switch case statement tests the value of variable or expression against a series of different cases or values, until a match is found. Then, the block of code with in the match case is executed. If there are no matches found, the optional default case is executed.
The syntax of switch case can be represented as:
switch(expression)
{
case constant-1
block-1;
break;
case constant-2
block-2;
break;
case constant-3
block-3;
break;
case constant-n
block-n;
break;
default:
default_block;
}
statement-x;
Difference between switch case and else if ladder:
So, after going through the two control statements in brief, here are the main difference between switch case and else if ladder:
- In else if ladder, the control goes through the every else if statement until it finds true value of the statement or it comes to the end of the else if ladder. In case of switch case, as per the value of the switch, the control jumps to the corresponding case.
- The switch case is more compact than lot of nested else if. So, switch is considered to be more readable.
- The use of break statement in switch is essential but there is no need of use of break in else if ladder.
- The variable data type that can be used in expression of switch is integer only where as in else if ladder accepts integer type as well as character.
- Another difference between switch case and else if ladder is that the switch statement is considered to be less flexible than the else if ladder, because it allows only testing of a single expression against a list of discrete values.
- Since the compiler is capable of optimizing the switch statement, they are generally considered to be more efficient. Each case in switch statement is independent of the previous one. In case of else if ladder, the code needs to be processed in the order determined by the programmer.
- Switch case statement work on the basis of equality operator whereas else if ladder works on the basis of true false( zero/non-zero) basis
The goto
The goto is an unconditional jump type of statement. The goto is used to jump between programs from one point to another. The goto can be used to jump out of the nested loop.
Structure of the goto:
While executing program goto provides the information to goto instruction defined as a label. This label is initialized with goto statement before.
e.g.
When the compiler will come to goto label then control will goto label defined before the loop and output will be 1 2 3 4 5.
References:
The C Programming Language. 2nd Edition Book by Brian Kernighan and Dennis Ritchie
C Programming: A Modern Approach Book by Kim N. King
C Programming Absolute Beginner’s Guide book by S.D Perry