BIT104 SLM Library - SLM - Unit 05
BIT104 SLM Library - SLM - Unit 05
BIT104 SLM Library - SLM - Unit 05
Structure:
5.1 Introduction
Objectives
5.2 The goto Statement
5.3 The if statement
The if-else Statement
Nesting of if Statements
5.4 The switch Statement
5.5 The while Loop
5.6 The do…while Loop
5.7 The for Loop
The nesting of for Loops
5.8 The break Statement and continue Statement
5.9 Summary
5.10 Terminal Questions
5.11 Answers
5.12 Exercises
5.1 Introduction
In the previous unit, we discussed the data types that are supported in C
and the types of Input/output operators available in C. This unit will enable
us to use the various types of control statements for making a decision in
C programs.
C program is set of statements which are normally sequentially executed in
the order in which they appear. Statements are the set of instructions.
Following is the example of simple statement:
printf(“Hello World”);
y=x+1;
Block statements are simply groups of related statements that are treated
as a unit. The statements that make up a block are logically bound together.
Block statements are also called compound statements. A block is begun
with a {and terminated by its matching}. Block statements are used to group
multiple statements in branching and looping statements. Following is the
example of a block statement:
Sikkim Manipal University B2074 Page No.: 95
Principles of C Programming Unit 5
{
sum = sum + i;
i++;
}
By default, statements are executed in sequence, one after another. We can,
however, alter that sequence of flow of instruction by using control flow
constructs. Control flow instructions are of two types: Branching statements
and iteration statements.
Branching statements are used to transfer the program flow control from
one point to another. They can be categorized as conditional branching and
unconditional branching.
In the conditional controlled branching, a condition is given. This condition is
logically evaluated. Depending upon whether the condition evaluates to
either the true or the false state, appropriate branching is taken. Conditional
branching statement in C language are If, If-else, switch and conditional
operator statements. We already discussed about conditional operator
statement in unit 3.
Unconditional branching means transferring the control of the program to a
specified statement without any conditions. The goto, break, continue and
return statements are unconditional branching statement. We will discuss
goto, break and continue statement in this unit.
Iterations (Looping) is process of repeating statement or set of statements
again and again until specified condition hold true. We will also discuss
about the loops in this unit. Loops generally consist of two parts: one or
more control expressions which control the execution of the loop, and the
body, which is the statement or a set of statements that is executed over
and over again. C language provides following three looping statements:
1. while statement
2. do-while statement
3. for statement
In C language, a true/false condition can be represented as an integer. In C,
“false'' is represented by a value of 0 (zero), and “true'' is represented by
any value that is nonzero, preferably by value of 1(Since there are many
nonzero values)
Objectives:
After studying this unit, you should be able to:
discuss how to control the flow of execution of statements using control
flow instruction.
explain branch unconditionally from one point to another in the program.
discuss various looping statement available in C.
illustrate how to exit from the loop depending on some condition.
describe how to break the current iteration and continue with next
iteration of loop.
is met, the flow of control will jump to the statement that immediately follows
the label first. This happens unconditionally.
Note that a goto is used to break the normal sequential execution of the
program unconditionally. If the label is before the statement goto label; a
loop will be formed and some statements will be executed repeatedly. Such
a jump is known as a backward jump. On the other hand, if the label is
placed after the goto label; some statements will be skipped and the jump is
known as the forward jump.
We can use goto at the end of a program to direct the control to go to the
input statement, which read further data. Consider the following example
program:
Program 5.1: Program to find square root using unconditional
branching goto
main()
{
double a, b;
read:
printf(“enter the value of a\n”);
scanf(“%f”, &a);
if (a<0) goto read;
b=sqrt(a);
printf(“%f %f \n”,a, b);
goto read;
}
The program uses two goto statements, one at the end, after printing the
results to transfer the control back to the input statements and the other to
skip any further computation when the number is negative. This program
evaluates the square root of a series of numbers read from the terminal. At
the end of program there is the second unconditional goto statement and
the control is always transferred back to the input statement. In fact, this
program puts the computer in a permanent loop known as an infinite loop.
To avoid such kind of situation, it is preferable not to use a goto statement.
False
expression
?
True
Statement (‘s)
Next-
Statement
Example 5.1: Compare two variables x and max; if x is greater than max, x
gets assigned to max.
if(x > max)
max = x;
Program 5.2: Program to check two numbers for equality.
True False
expression
?
Next-
Statement
if(x > 0)
{
if(y > 0)
printf("Northeast.\n");
else printf("Southeast.\n");
}
else {
if(y > 0)
printf("Northwest.\n");
else printf("Southwest.\n");
}
When we have one if statement (or loop) nested inside another, it's a very
good idea to use explicit braces {}, as shown, to make it clear (both to us
and to the compiler) how they are nested and which else goes with which if.
It is also a good idea to indent the various levels, also as shown, to make
{
printf("C");
}
else {
if(grade >= 60)
{
printf("D");
}
else {
printf("F");
}
}
}
}
By examining the code this way, it should be obvious that exactly one of the
printf calls is executed, and that whenever one of the conditions is found
true, the remaining conditions do not need to be checked and none of the
later statements within the chain will be executed.
Program 5.4: Program to display the largest of three numbers
#include<stdio.h>
main()
{
int a,b,c,big;
printf (“Enter three numbers”);
scanf (“%d %d %d”, &a, &b, &c);
if (a>b) // check whether a is greater than b if true then
if(a>c) // check whether a is greater than c
big = a ; // assign a to big
else big = c ; // assign c to big
else if (b>c) // if the condition (a>b) fails check whether b is greater than
c
big = b ; // assign b to big
else big = c ; // assign C to big
printf (“Largest of %d,%d&%d = %d”, a,b,c,big);
}
// Simple Calculator
#include <stdio.h>
main()
{
int choice, numb1, numb2, ans;
printf("enter in two numbers -->");
scanf("%d %d", &numb1, &numb2); // Enter two numbers
printf(“Calculator Options: \n ”)
printf("1. Addition\n");
printf("2. Subtraction\n");
printf("Enter the choice\n");
scanf("%d", &choice); // Enter Option
switch( choice ) {
case 1: //performs addition if choice==1
ans = numb1 + numb2;
break;
case 2: // performs subtraction if choice == 2
ans = numb1 - numb2;
break;
default: printf("Invalid option selected\n");
ans =-1;
}
printf(“Answer is %d ", ans );
}
False
expression
?
True
Statement (‘s)
Next-
Statement
Here before executing the body of the loop that is statement (’s), the
expression evaluated. Therefore it is called an entry-controlled loop.
Example 5.4: The following example uses a while loop to continually read,
and then display, character input while the character input does not equal
‘\n’ (Enter key / new line character).
int c;
c = getchar();
while(c != ‘\n’)
{
putchar(c);
c = getchar();
}
Example 5.5: We can use while loop (as shown below), to print n (integer
variable holding the number of blank lines) blank lines on the screen.
while(n > 0)
{
printf("\n");
n = n - 1;
}
When n becomes zero, the loop finishes and control “falls out'' of while loop.
Main()
{
int num, large, n, i;
clrscr();
printf("enter number of numbers \n");
scanf(“%d”,&n);
large=0;
i=0;
while(i<n)
{
printf("\n enter number ");
scanf(“%d”, &num);
if(large<num)
large=num;
i++;
}
printf("\n large = %d”, large);
}
# include<stdio.h>
# include <math.h>
void main()
{
int n, i=1,count;
float acc, x, term, sum;
printf("enter the angle\n");
scanf(“%d”, &x);
x=x*3.1416/180.0;
printf(“\nenter the accuracy)";
scanf(“%f”, &acc);
sum=x;
term=x;
while ((fabs(term))>acc)
{
term=-term*x*x/((2*i)*(2*i+1));
sum+=term;
i++;
}
printf"\nsum of sine series is %f", sum);
}
is set at the very top of the loop. However, in this section, we are going to
see another statement used for looping, do-while, which puts the expression
at the bottom of the loop. Therefore, The while loop is called an entry-
controlled loop and do-While loop is called an exit-controlled loop. The do-
while loop takes the following form:
do
{
Statement(‘s)
}
while (expression);
Here, the statements inside the statement block are executed once, and
then expression is evaluated in order to determine whether the looping is to
continue. If the expression evaluates to a nonzero value, the do-while loop
continues; otherwise, the looping stops and execution proceeds to the next
statement following the loop. On using the do-while loop, the body of the
loop is always executed at least once irrespective of the expression. The
do-while loop is illustrated in figure 5.4. (Note: Next-statement is the
statement after while loop).
Statement (‘s)
True
expression
?
False
Next-
Statement
expression ? True
Next-Statement
have not met yet which would step, not over numeric values, but over the
elements of an array or other data structure.
Example 5.7: The powers-of-two using for loop is:
int x;
for(x = 2; x < 1000; x = x * 2)
printf("%d\n", x);
The initialization expression of for loop can contain more than one
statement separated by a comma. For example,
for ( i = 1, j = 2 ; j <= 10 ; j++ )
There is no fundamental difference between the while and for loops. We can
rewrite for loop as a while loop, moving the initialize and increment
expressions to statements before and within the loop:
expr1;
while(expr2)
{
Statement (‘s)
expr3;
}
Similarly, given the general while loop
while(expr) {
statement (‘s) }
all manipulate the same variable or data structure, using the initialize, test,
increment pattern. If they do not manipulate the same variable or do not
follow that pattern, it is preferable to use a while loop.
Program 5.9: A Program to find the factorial of a number
void main()
{
int M,N;
long int F=1;
clrscr();
printf(“enter the number\n”)";
scanf(“%d”,&N);
if(N<=0)
F=1;
else
{
for(M=1;M<=N;M++)
F*=M;
}
printf(“the factorial of the number is %ld”,F);
getch();
}
5.7.1 The Nesting of for Loops
Nesting of for loops, that is, one for statement within another for statement,
is allowed in C. For example, two loops can be nested as follows:
for(i=1;i<10;i++)
{
…….
…….
for(j=1;j<5;j++)
{
……
……
}
…….
}
………
The above program displays the numbers from 1 to 4 and prints the
message “Broke out of loop when 5 is encountered.
void main ( ) {
int x;
for (x=1; x<=10; x++)
{ if (x==5)
continue; /* skip remaining code in loop
only if x == 5 */
printf (“%d\n”, x);
}
printf(“\nUsed continue to skip”);
}
The above program displays the numbers from 1to 10, except the number 5.
Self-Assessment Questions
12. The for loop is an exit-controlled loop. (True/False)
13. Do the following two for loops have the same number of iterations?
for (j=0; j<8; j++);
for (k=1; k<=8; k++);
14. The _________statement is used to continue the next iteration of the
loop by skipping a part of the body of the loop.
5.9 Summary
Let us recapitulate important points discussed in this unit:
In C by default, statements are executed in sequence, one after another.
We can, however, modify that sequence by using control flow constructs.
C language possesses decision making capabilities and supports the
following statements known as the control or decision making
statements: goto, if, switch.
The goto statement is used to branch unconditionally from one point to
another in the program.
The simplest way to modify the control flow of a program based on
condition is with if statement. Switch statements serve as a simple way
to write long if statements when the requirements are met.
The most basic loop in C is the while loop. A while loop has one control
expression, and executes as long as that expression is true.
What will be the values of x and y if n assumes a value of (a) n=1 and
(b) n=0.
4. Rewrite the following without using compound relation:
if (grade<=59 && grade>=50)
second = second +1;
5. Write a program to check whether an input number is odd or even.
6. Write a C program to calculate the average of 10 numbers.
7. Write the output that will be generated by the following C program:
void main()
{
int i=0, x=0;
do
{
if (i%5 == 0)
{
x++;
printf(“%d\t”,
x);
}
++i;
} while (i<20);
printf(“\nx=%d”, x);
}
5.11 Answers
Self-Assessment Questions
1. label
2. true
3. false
4. No
5. true
6. default
7. false
8. No
9. true
10. do-while
11. false
12. false
13. yes
14. continue
Terminal Questions
1. In C, the simplest way to modify the control flow of a program is with if
statement. (Refer section 5.3 for more detail)
2. C has a built-in multiple-branch selection statement, called switch,
which successively tests the value of an integer expression against a
list of integer or character constants. (Refer section 5.4 for more detail)
3. (a) x=2, y=0
(b) x=1, y=0
(Refer section 5.3 for more detail about if statement)
4. if (grade<=59)
if (grade>=50)
second = second+1;
(Refer section 5.3 for more detail about if statement)
5. void main()
{
int no;
printf(“enter a number\n”);
scanf(“%d”,&no);
if (no%2==0)
printf(“even number\n”);
else printf(“odd number\n”);
}
(Refer section 5.3 for more detail about if statement)
6.
main()
{
int count; /* DECLARATION OF
float sum, average, number; VARIABLES */
sum = 0; / * INITIALIZATION OF
count = 0; VARIABLES*/
printf(“Enter Ten numbers: \n”)
while (count<10)
{
scanf(“%f”, &number);
sum = sum + number;
count = count + 1;
}
average = sum / N;
printf(“Sum = %f \n“, N, sum);
printf(“Average = %f”, average);
}
Output
Enter Ten numbers:
1
Sikkim Manipal University B2074 Page No.: 123
Principles of C Programming Unit 5
2.3
4.67
1.42
7
3.67
4.08
2.2
4.25
8.21
Sum= 38.799999
Average= 3.880000
(Refer section 5.5 - for more detail on while statement)
7. 1. 2 3 4
x=4
(Refer section 5.3 for more detail about if statement - and for while
statement - Refer section 5.5)
5.12 Exercises
1. Write a program to check whether a given number is odd or even using
switch statement.
2. Write a program to find the roots of a quadratic equation.
3. Compare the following statements
a) while and do…while
b) break and continue
4. Write a program to compute the sum of digits of a given number using
while loop.
5. Write a program that will read a positive integer and determine and
print its binary equivalent using do-while loop.
6. The numbers in the sequence
1 1 2 3 5 8 13 ………..
are called Fibonacci numbers. Write a program using do-while loop to
calculate and print the first n Fibonacci numbers.
7. Find errors, if any, in each of the following segments. Assume that all
the variables have been declared and assigned values.
(a)
while (count !=10);
{
count = 1;
sum = sum + x;
count = count + 1;
}
(b)
do;
total = total + value;
scanf(“%f”, &value);
while (value ! =999);
8. Write programs to print the following outputs using for loops.
(a) 1 b) 1
22 2 2
333 3 3 3
4444 4 4 4 4
9. Write a program to read the age of 100 persons and count the number
of persons in the age group 50 to 60. Use for and continue statements.