Friday 23 November 2012

Making Decisions in C

Programming with C Unit 6

Unit 6 Making Decisions in C
Structure
6.0 Introduction
6.1 The goto statement
Self Assessment Questions
6.2 The if statement
Self Assessment Questions
6.3 The ifelse
statement
6.4 Nesting of if statements
Self Assessment Questions
6.5 The conditional expression
Self Assessment Questions
6.6 The switch statement
Self Assessment Questions
6.7 Summary
6.8 Terminal Questions
6.9 Answers to Self Assessment Questions
6.10 Answers to Terminal Questions
6.11 Exercises
6.0 Introduction
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.
Programming with C Unit 6
Sikkim Manipal University Page No. 80
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
Objectives
At the end of this unit, you will be able to:
· Control the flow of execution of statements using twoway
decision.
· Control the flow of execution of statements using multipath decision.
· Branch unconditionally from one point to another in the program.
· Evaluate the conditional expressions.
6.1 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:
Programming with C Unit 6
Sikkim Manipal University Page No. 81
goto label; label:
statement;
label:
statement;
goto label;
(i) Forward jump (ii) Backward jump
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:
Program 6.1: Program showing unconditional branching
main()
{
double a, b;
read:
Programming with C Unit 6
Sikkim Manipal University Page No. 82
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.
Self Assessment Questions
(i) The goto requires a _________ in order to identify the place where the
branch is to be made.
(ii) State true or false
goto is an unconditional branching statement.
6.2 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
Programming with C Unit 6
Sikkim Manipal University Page No. 83
use code like this to keep track of the maximum value of x we'd seenfor
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 )
{
statemen 1;
statement 2;
statement n;
}
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 6.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 */
Programming with C Unit 6
Sikkim Manipal University Page No. 84
number = number;
/* If it is negative then convert it into positive. */
printf (“The absolute value is % d \n”, number);
}
Self Assessment Questions
(i) State true or false
The series of statements enclosed by braces after the expression in
simple if statement is itself a simple expression statement.
6.3 The ifelse
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 )
statement(s)
else
statement(s)
Programming with C Unit 6
Sikkim Manipal University Page No. 85
(if there are more than one statements, they should be enclosed within
braces).
Program 6.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”);
}
6.4 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:
if(x > 0)
{
if(y > 0)
printf("Northeast.\n");
else printf("Southeast.\n");
}
else {
Programming with C Unit 6
Sikkim Manipal University Page No. 86
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:
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,
Programming with C Unit 6
Sikkim Manipal University Page No. 87
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");
}
else {
if(grade >= 60)
{
printf("D");
}
else {
printf("F");
}
Programming with C Unit 6
Sikkim Manipal University Page No. 88
}
}
}
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.
6.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
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);
}
Programming with C Unit 6
Sikkim Manipal University Page No. 89
Self Assessment Questions
(i) In the cascaded if/else/if/else/... chain, each else clause is another
_______statement.
6.5 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.
Self Assessment Questions
(i) State true or false
The conditional operator does not produce a lvalue.
Programming with C Unit 6
Sikkim Manipal University Page No. 90
6.6 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 thisvalue:
Code to execute if <variable> == thisvalue
break;
case thatvalue:
Code to execute if <variable> == thatvalue
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:
Programming with C Unit 6
Sikkim Manipal University Page No. 91
int a = 10;
int b = 10;
int c = 20;
switch ( a ) {
case b:
/* Code */
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;
Programming with C Unit 6
Sikkim Manipal University Page No. 92
printf( "1. Play game\n" );
printf( "2. Load game\n" );
printf( "3. Play multiplayer\n" );
printf( "4. Exit\n" );
printf( "Selection: " );
scanf( "%d", &input );
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
Programming with C Unit 6
Sikkim Manipal University Page No. 93
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.
Self Assessment Questions
i) The condition of a switch statement is a _______.
ii) State true or false
switch statement is an unconditional branching statement.
6.7 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.
6.8 Terminal Questions
1. State whether true or false
A switch expression can be of any type.
2. Consider the following program segment:
x=1;
y=1;
if (n>0)
x=x+1;
y=y1;
printf(“%d %d”,x,y);
Programming with C Unit 6
Sikkim Manipal University Page No. 94
What will be the values of x and y if n assumes a value of (a) 1 and
(b) 0.
3. State whether true or false
A program stops its execution when a break statement is encountered.
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.9 Answers to Self Assessment Questions
6.1 i) label
ii) true
6.2 i) false
6.4 i) if
6.5 i) true
6.6 i) value
ii) false
6.10 Answers to Terminal Questions
1. false
2. (a) x=2, y=0
(b) x=1, y=0
3. false
4. if (grade<=59)
if (grade>=50)
second = second+1;
5. void main()
{
int no;
Programming with C Unit 6
Sikkim Manipal University Page No. 95
printf(“enter a number\n”);
scanf(“%d”,&no);
if (no%2==0)
printf(“even number\n”);
else printf(“odd number\n”);
}
6.11 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 ifelse
statement.
5. Write a program to find the roots of a quadratic equation.

No comments:

Post a Comment