0% found this document useful (0 votes)
15 views22 pages

Unit 5 - V1

This document is a course outline for C Programming at Manipal University Jaipur, focusing on flow control statements including the goto, if, switch, and conditional expressions. It provides an introduction to decision-making in C, explaining how to control the execution flow of programs using various control structures. The unit also includes examples, self-assessment questions, and exercises to reinforce learning objectives related to flow control in programming.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views22 pages

Unit 5 - V1

This document is a course outline for C Programming at Manipal University Jaipur, focusing on flow control statements including the goto, if, switch, and conditional expressions. It provides an introduction to decision-making in C, explaining how to control the execution flow of programs using various control structures. The unit also includes examples, self-assessment questions, and exercises to reinforce learning objectives related to flow control in programming.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

C Programming Manipal University Jaipur (MUJ)

BACHELOR OF COMPUTER APPLICATIONS


SEMESTER 1

C PROGRAMMING

Unit 5: Flow of Control Part 1 1


C Programming Manipal University Jaipur (MUJ)

Unit 5
Flow of Control Part 1
Table of Contents

SL Fig No / Table SAQ /


Topic Page No
No / Graph Activity
1 Introduction - -
3-4
1.1 Objectives - -
2 The goto statement - 1 5-7
3 The if statement - 2
3.1 The if-else statement - - 8 - 14
3.2 Nesting of if statements - -
4 The conditional expression - - 15
5 The switch statement - 3 16 - 19
6 Summary - - 20
7 Terminal Questions - - 20
8 Answers to Self Assessment Questions - - 21
9 Answers to Terminal Questions - - 21 -22
10 Exercises - - 22

Unit 5: Flow of Control Part 1 2


C Programming Manipal University Jaipur (MUJ)

1. INTRODUCTION

In the previous unit, you studied about the data types that are supported in C and the types
of Input/output operators available in C. This unit will enable you to use the various types of
control statements for making a decision in C. Statements are the “steps'' of a program. Most
statements compute and assign values or call functions, but we will eventually meet several
other kinds of statements as well. By default, statements are executed in sequence, one after
another. We can, however, modify that sequence by using control flow constructs such that a
statement or group of statements is executed only if some condition is true or false. This
involves a kind of decision making to see whether a particular condition has occurred or not
and then direct the computer to execute certain statements accordingly.

C language possesses such decision making capabilities and supports the following
statements known as the control or decision making statements.

• if statement
• switch statement
• goto statement
• conditional operator statement

You will also study 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 set of statements which is executed over and over.

As far as C is concerned, a true/false condition can be represented as an integer. (An integer


can represent many values; here we care about only two values: “true'' and “false.'' The study
of mathematics involving only two values is called Boolean algebra, after George Boole, a
mathematician who refined this study.) In C, “false'' is represented by a value of 0 (zero), and
“true'' is represented by any value that is nonzero. Since there are many nonzero values (at
least 65,534, for values of type int), when we have to pick a specific value for “true,'' we'll
pick 1.

Unit 5: Flow of Control Part 1 3


C Programming Manipal University Jaipur (MUJ)

Do…while loop is used in a situation where we need to execute the body of the loop before
the test is performed. The for loop is used to execute the body of the loop for a specified
number of times. The break statement is used to exit any loop.

1.1. Objectives:

After studying this subject, you should be able to:

❖ control the flow of execution of statements using two-way decision and multipath
decision.
❖ branch unconditionally from one point to another in the program.
❖ evaluate the conditional expressions.

Unit 5: Flow of Control Part 1 4


C Programming Manipal University Jaipur (MUJ)

2. THE GOTO STATEMENT

C supports the goto statement to branch unconditionally from one point to another in the
program. Although it may not be essential to use the goto statement in a highly structured
language like C, there may be occasions when the use of goto might be desirable.

The goto requires a label in order to identify the place where the branch is to be made. A
label is any valid variable name, and must be followed by a colon. The label is placed
immediately before the statement where the control is to be transferred. The general forms
of goto and label statements are shown below:

The label can be anywhere in the program either before the goto or after the goto label;
statement.

During execution of the program when a statement like

goto first;

is met, the flow of control will jump to the statement immediately following the label first.
This happens unconditionally.

Note that a goto breaks the normal sequential execution of the program. 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.

A goto is often used at the end of a program to direct the control to go to the input statement,
to read further data. Consider the following example:

Unit 5: Flow of Control Part 1 5


C Programming Manipal University Jaipur (MUJ)

Program 5.1: Program showing unconditional branching


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;
}

This program is written to evaluate the square root of a series of numbers read from the
terminal. 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.

Due to the unconditional goto statement at the end, 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.

Unit 5: Flow of Control Part 1 6


C Programming Manipal University Jaipur (MUJ)

SELF-ASSESSMENT QUESTIONS - 1

1. The goto requires a _________ in order to identify the place where the branch is to be
made.
2. goto is an unconditional branching statement. (True/False)

Unit 5: Flow of Control Part 1 7


C Programming Manipal University Jaipur (MUJ)

3. THE IF STATEMENT

The simplest way to modify the control flow of a program is with an if statement, which in
its simplest form looks like this:

if(x > max)

max = x;

Even if you didn't know any C, it would probably be pretty obvious that what happens here
is that if x is greater than max, x gets assigned to max. (We'd use code like this to keep track
of the maximum value of x we'd seen--for each new x, we'd compare it to the old maximum
value max, and if the new value was greater, we'd update max.)

More generally, we can say that the syntax of an if statement is:

if( expression )

statement

where expression is any expression and statement is any statement.

What if you have a series of statements, all of which should be executed together or not at all
depending on whether some condition is true? The answer is that you enclose them in
braces:

if( expression )

statement 1;

statement 2;

statement n;

Unit 5: Flow of Control Part 1 8


C Programming Manipal University Jaipur (MUJ)

As a general rule, anywhere the syntax of C calls for a statement, you may write a series of
statements enclosed by braces. (You do not need to, and should not, put a semicolon after
the closing brace, because the series of statements enclosed by braces is not itself a simple
expression statement.)

Program 5.2: Program to calculate the absolute value of an integer


# include < stdio.h > void main ( )
{
int number;
printf (“Type a number:”);
scanf (“%d”, & number);
if (number < 0) /* check whether the number is a negative number */ number
= - number; /* If it is negative then convert it into positive. */
printf (“The absolute value is % d \n”, number);
}

3.1. The if-else statement

An if statement may also optionally contain a second statement, the “else clause,'' which is
to be executed if the condition is not met. Here is an example:
if(n > 0)
average = sum / n;
else {
printf("can't compute average\n");
average = 0;
}
The first statement or block of statements is executed if the condition is true, and the second
statement or block of statements (following the keyword else) is executed if the condition is
not true. In this example, we can compute a meaningful average only if n is greater than 0;
otherwise, we print a message saying that we cannot compute the average. The general
syntax of an if statement is therefore

if( expression )

Unit 5: Flow of Control Part 1 9


C Programming Manipal University Jaipur (MUJ)

statement(s)

else

statement(s)

(if there are more than one statements, they should be enclosed within braces).

Program 5.3: To find whether a number is negative or positive


#include < stdio.h >
void main ( )
{
int num;
printf (“Enter the number”);
scanf (“%d”, &num);
if (num < 0)
printf (“The number is negative”)
else
printf (“The number is positive”);
}

3.2. Nesting of if statements

It's also possible to nest one if statement inside another. (For that matter, it's in general
possible to nest any kind of statement or control flow construct within another.) For
example, here is a little piece of code which decides roughly which quadrant of the compass
you're walking into, based on an x value which is positive if you're walking east, and a y value
which is positive if you're walking north:

Unit 5: Flow of Control Part 1 10


C Programming Manipal University Jaipur (MUJ)

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 you 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 you and to the compiler) how they're
nested and which else goes with which if. It's also a good idea to indent the various levels,
also as shown, to make the code more readable to humans. Why do both? You use indentation
to make the code visually more readable to yourself and other humans, but the compiler
doesn't pay attention to the indentation (since all whitespace is essentially equivalent and is
essentially ignored). Therefore, you also have to make sure that the punctuation is right.

Here is an example of another common arrangement of if and else. Suppose we have a


variable grade containing a student's numeric grade, and we want to print out the
corresponding letter grade. Here is the code that would do the job:

Unit 5: Flow of Control Part 1 11


C Programming Manipal University Jaipur (MUJ)

if(grade >= 90)


printf("A");
else if(grade >= 80)
printf("B");
else if(grade >= 70)
printf("C");
else if(grade >= 60)
printf("D");
else printf("F");

What happens here is that exactly one of the five printf calls is executed, depending on which
of the conditions is true. Each condition is tested in turn, and if one is true, the corresponding
statement is executed, and the rest are skipped. If none of the conditions is true, we fall
through to the last one, printing “F''.

In the cascaded if/else/if/else/... chain, each else clause is another if statement. This may
be more obvious at first if we reformat the example, including every set of braces and
indenting each if statement relative to the previous one:
if(grade >= 90)
{
printf("A");
}
Else {
if(grade >= 80)
{
printf("B");
}
else {
if(grade >= 70)
{
printf("C");

Unit 5: Flow of Control Part 1 12


C Programming Manipal University Jaipur (MUJ)

}
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.
But once you've convinced yourself of this and learned to recognize the idiom, it's generally
preferable to arrange the statements as in the first example, without trying to indent each
successive if statement one tabstop further out.

Program 5.4: Program to print 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

Unit 5: Flow of Control Part 1 13


C Programming Manipal University Jaipur (MUJ)

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);
}

SELF-ASSESSMENT QUESTIONS - 2

3. The series of statements enclosed by braces after the expression in simple if


statement is itself a simple expression statement. (True/False)
4. In the cascaded if/else/if/else/... chain, each else clause is another_______ statement.

Unit 5: Flow of Control Part 1 14


C Programming Manipal University Jaipur (MUJ)

4. THE CONDITIONAL EXPRESSION

The conditional operator (?:) takes three operands. It tests the result of the first operand and
then evaluates one of the other two operands based on the result of the first. Consider the
following example:

E1?E2:E3

If expression E1 is nonzero (true), then E2 is evaluated, and that is the value of the
conditional expression. If E1 is 0 (false), E3 is evaluated, and that is the value of the
conditional expression. Conditional expressions associate from right to left. In the following
example, the conditional operator is used to get the minimum of x and y:

a = (x < y) ? x : y; /* a= min(x, y) */

There is a sequence point after the first expression (E1). The following example's result is
predictable, and is not subject to unplanned side effects:

i++ > j ? y[i] : x[i];

The conditional operator does not produce a lvalue. Therefore, a statement such as

a ? x : y = 10 is not valid.

Unit 5: Flow of Control Part 1 15


C Programming Manipal University Jaipur (MUJ)

5. THE SWITCH STATEMENT

The switch case statements are a substitute for long if statements that compare a variable
to several "integral" values ("integral" values are simply values that can be expressed as an
integer, such as the value of a char). The basic format for using switch case is outlined below.
The value of the variable given into switch is compared to the value following each of the
cases, and when one value matches the value of the variable, the computer continues
executing the program from that point. switch ( <variable> ) {
case this-value:
Code to execute if <variable> == this-value
break;
case that-value:
Code to execute if <variable> == that-value
break;
...
default:
Code to execute if <variable> does not equal the value following any of the cases
break;
}

The condition of a switch statement is a value. The case says that if it has the value of
whatever is after that case then do whatever follows the colon. The break is used to break
out of the case statements. break is a keyword that breaks out of the code block, usually
surrounded by braces, which it is in. In this case, break prevents the program from falling
through and executing the code in all the other case statements. An important thing to note
about the switch statement is that the case values may only be constant integral
expressions. It isn't legal to use case like this: int a = 10;
int b = 10;
int c = 20;
switch ( a ) {
case b:
/* Code */

Unit 5: Flow of Control Part 1 16


C Programming Manipal University Jaipur (MUJ)

break;
case c:
/* Code */
break;
default:
/* Code */
break;
}

The default case is optional, but it is wise to include it as it handles any unexpected cases. It
can be useful to put some kind of output to alert you to the code entering the default case if
you don't expect it to. Switch statements serve as a simple way to write long if statements
when the requirements are met. Often it can be used to process input from a user.

Example: Below is a sample program, in which not all of the proper functions are actually
declared, but which shows how one would use switch in a program.
#include <stdio.h>
void playgame();
void loadgame();
void playmultiplayer();
int main()
{
int input;
printf( "1. Play game\n" );
printf( "2. Load game\n" );
printf( "3. Play multiplayer\n" );
printf( "4. Exit\n" );
printf( "Selection: " );
scanf( "%d", &input );

Unit 5: Flow of Control Part 1 17


C Programming Manipal University Jaipur (MUJ)

switch ( input ) {
case 1: /* Note the colon, not a semicolon */
playgame();
break;
case 2:
loadgame();
break;
case 3:
playmultiplayer();
break;
case 4:
printf( "Thanks for playing!\n" );
break;
default:
printf( "Bad input, quitting!\n" );
break;
}
getchar();
}

This program will compile, but cannot be run until the undefined functions are given bodies,
but it serves as a model (albeit simple) for processing input. If you do not understand this
then try mentally putting in if statements for the case statements. default simply skips out
of the switch case construction and allows the program to terminate naturally. If you do not
like that, then you can make a loop around the whole thing to have it wait for valid input. You
could easily make a few small functions if you wish to test the code.

Unit 5: Flow of Control Part 1 18


C Programming Manipal University Jaipur (MUJ)

SELF-ASSESSMENT QUESTIONS - 3

5. The conditional operator does not produce a lvalue. (True/False)


6. The condition of a switch statement is a _______.
7. Switch statement is an unconditional branching statement. (True/False)

Unit 5: Flow of Control Part 1 19


C Programming Manipal University Jaipur (MUJ)

6. SUMMARY

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 is with an if statement. switch statements serve as a simple way to write long if
statements when the requirements are met.

7. TERMINAL QUESTIONS

1. Consider the following program segment:


x=1;
y=1;
if (n>0)
x=x+1;
y=y-1;
printf(“%d %d”,x,y);

What will be the values of x and y if n assumes a value of (a) 1 and (b) 0.

2. Rewrite the following without using compound relation: if (grade<=59 && grade>=50)

second = second +1;

3. Write a program to check whether an input number is odd or even.

Unit 5: Flow of Control Part 1 20


C Programming Manipal University Jaipur (MUJ)

8. ANSWERS TO SELF ASSESSMENT QUESTIONS

1. label
2. true
3. false
4. if
5. true
6. value
7. false

9. ANSWERS TO TERMINAL QUESTIONS


1. (a) x=2, y=0

(b) x=1, y=0

2. if (grade<=59)
if (grade>=50)
second = second+1;
3. 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”);
}

4. 0 5 10 15

x = 30

5. 1 2 3 4

x=4

Unit 5: Flow of Control Part 1 21


C Programming Manipal University Jaipur (MUJ)

10. EXERCISES

1. Explain different types of if statements with examples.


2. Explain the syntax of switch statement with an example.
3. Write a program to check whether a given number is odd or even using switch
statement.
4. Write a program to find the smallest of 3 numbers using if-else statement.

Unit 5: Flow of Control Part 1 22

You might also like