You are on page 1of 47

Lecture IV

Control Structure cont…


Introduction
In real life we are often faced with situations where we are required

to make a choice between a number of alternatives rather than only


one or two. For example, which school to join or which hotel to visit
or still harder which girl to marry (you almost always end up making
a wrong decision is a different matter altogether!).

C provides a special control statement that allows us to handle such


cases effectively; rather than using a series of if statements. This
control instruction is in fact the topic of this lecture. Towards the end
of the lecture we would also study a keyword called goto, and
understand why we should avoid its usage in C programming.
Decisions Using switch

 The control statement that allows us to make a decision from the


number of choices is called a switch, or more correctly a switch-
case-default, since these three keywords go together to make up
the control statement. They most often appear as follows:
switch ( integer expression )
{
case constant 1 :
do this ;
case constant 2 :
do this ;
case constant 3 :
do this ;
default :
do this ;
}
 The integer expression following the keyword switch is any C
expression that will yield an integer value. It could be an integer
constant like 1, 2 or 3, or an expression that evaluates to an integer.
The keyword case is followed by an integer or a character constant.
Each constant in each case must be different from all the others.
The “do this” lines in the above form of switch represent any valid C
statement.
Note

 What happens when we run a program containing a switch? First,


the integer expression following the keyword switch is evaluated.
The value it gives is then matched, one by one, against the constant
values that follow the case statements. When a match is found, the
program executes the statements following that case, and all
subsequent case and default statements as well. If no match is
found with any of the case statements, only the statements following
the default are executed. A few examples will show how this control
structure works.
Consider the following program
main( )
{
int i = 2 ;
switch ( i )
{
case 1 :
printf ( "I am in case 1 \n" ) ;
case 2 :
printf ( "I am in case 2 \n" ) ;
case 3 :
printf ( "I am in case 3 \n" ) ;
default :
printf ( "I am in default \n" ) ;
}
 The output is definitely not what we expected! We didn’t expect the
second and third line in the above output. The program prints case 2
and 3 and the default case. Well, yes. We said the switch executes
the case where a match is found and all the subsequent cases and
the default as well.

 If you want that only case 2 should get executed, it is up to you to


get out of the switch then and there by using a break statement.
The following example shows how this is done. Note that there is no
need for a break statement after the default, since the control
comes out of the switch anyway.
main( )
{
int i = 2 ;
switch ( i )
{
case 1 :
printf ( "I am in case 1 \n" ) ;
break ;
case 2 :
printf ( "I am in case 2 \n" ) ;
break ;
case 3 :
printf ( "I am in case 3 \n" ) ;
break ;
default :
printf ( "I am in default \n" ) ;
}
}
The Tips and Traps

 A few useful tips about the usage of switch and a few pitfalls to be
avoided:

 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" ) ;
}
}
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" ) ;
}
Note

 In fact here when we use ‘v’, ‘a’, ‘x’ they are actually replaced by the
ASCII values (118, 97, 120) of these character constants.

Note
 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" ) ;
}
}
The goto Keyword

 Avoid goto keyword! They make a C programmer’s life miserable.


There is seldom a legitimate reason for using goto, and its use is
one of the reasons that programs become unreliable, unreadable,
and hard to debug. And yet many programmers find goto seductive.

 In a difficult programming situation it seems so easy to use a goto to


take the control where you want. However, almost always, there is a
more elegant way of writing the same program using if, for, while
and switch. These constructs are far more logical and easy to
understand.
Example with Goto
main( )
{
int goals ;
printf ( "Enter the number of goals scored against Nigeria" ) ;
scanf ( "%d", &goals ) ;
if ( goals <= 5 )
goto sos ;
else
{
printf ( “ All the soccer players should learnt C\n" ) ;
}
sos :
printf ( “Get ready for next match!" ) ;
}
Execise 1

 What would be the output of the following programs:


(a) main( ) {
char suite = 3 ;
switch ( suite )
{
case 1 :
printf ( "\nDiamond" ) ;
case 2 :
printf ( "\nSpade" ) ;
default :
printf ( "\nHeart") ;
}
printf ( "\nI thought one wears a suite" ) ;
}
(b)main( ) {
int c = 3 ;
switch ( c )
{
case 'v' :
printf ( "I am in case v \n" ) ;
break ;
case 3 :
printf ( "I am in case 3 \n" ) ;
break ;
case 12 :
printf ( "I am in case 12 \n" ) ;
break ;
default :
printf ( "I am in default \n" ) ;
}
(c )main( ) {
int i = 1 ;
switch ( i - 2 )
{
case -1 :
printf ( "\nFeeding fish" ) ;
case 0 :
printf ( "\nWeeding grass" ) ;
case 1 :
printf ( "\nmending roof" ) ;
default :
printf ( "\nJust to survive" ) ;
}
}
Exercise 2
 Point out the errors, if any, in the following programs:

(a) main( ) {
int suite = 1 ;
switch ( suite ) ;
{
case 0 ;
printf ( "\nClub" ) ;
case 1 ;
printf ( "\nDiamond" ) ;
}
}
(c) main( ) {
float a = 3.5 ;
switch ( a )
{
case 0.5 :
printf ( "\nThe art of C" ) ;
break ;
case 1.5 :
printf ( "\nThe spirit of C" ) ;
break ;
case 2.5 :
printf ( "\nSee through C" ) ;
break ;
case 3.5 :
printf ( "\nSimply c" ) ;
}
}
Function in c
What is a Function

 A function is a self-contained block of statements that perform a


coherent task of some kind. Every C program can be thought of as a
collection of these functions. As we noted earlier, using a function is
something like hiring a person to do a specific job for you.
Sometimes the interaction with this person is very simple;
sometimes it’s complex.
 Suppose you have a task that is always performed exactly in the
same way—say a bimonthly servicing of your motorbike. When you
want it to be done, you go to the service station and say, “It’s time,
do it now”. You don’t need to give instructions, because the
mechanic knows his job. You don’t need to be told when the job is
done. You assume the bike would be serviced in the usual way, the
mechanic does it and that’s that.
 Let us now look at a simple C function that operates in much the
same way as the mechanic. Actually, we will be looking at two
things—a function that calls or activates the function and the
function itself.


USES OF C FUNCTIONS
 C functions are used to avoid rewriting same logic/code again and
again in a program.

 There is no limit in calling C functions to make use of same


functionality wherever required.

 We can call functions any number of times in a program and from


any place in a program.

 A large C program can easily be tracked when it is divided into


functions.

 The core concept of C functions are, re-usability, dividing a big task


into small pieces to achieve the functionality and to improve
understandability of very large C programs.
Example of C Function
#include<stdio.h>
#include<stdlib.h>
void function();
int main( )
{
function(); // call function from the main
system("pause");
}
void function ()
{
printf("Welcome to function\n");
}
Passing Parameter to a Function
void add(int,int);
int main( )
{
add(10,20);
system("pause");
}
void add(int a,int b)
{
printf("%d\n", a+b);

}
Returning value from Method
int add(int,int,int);
int main( )
{
int sum;
sum=add(100,200,100);
printf("the add is %d",sum);
system("pause");
}

int add(int a,int b,int c)


{
return a+b+c;
}
Example of Function
#include<stdio.h>
float square ( float x ); // function prototype/declaration
int main( )
{
float m, n ;
printf ( "\nEnter some number for finding square \n");
scanf ( "%f", &m ) ;
// function call
n = square ( m ) ;
printf ( "\nSquare of the given number %f is %f",m,n );
}
float square ( float x ) // function definition
{
float p ;
p=x*x;
return ( p ) ;
}
Example of Swap using Function
void swap(int a, int b);
int main()
{
int m = 22, n = 44;
// calling swap function by value
printf(" values before swap m = %d \nand n = %d", m, n);
swap(m, n);
}
void swap(int a, int b)
{
int tmp;
tmp = a;
a = b;
b = tmp;
printf(" \nvalues after swap m = %d\n and n = %d", a, b);
}
Recursive Function in C
• We have seen so far that a function, such as main, can call another
function to perform some computation.

• In C, a function can also call itself. Such types of functions are called
recursive functions. A function, f, is also said to be recursive if it calls
another function, g, which in turn calls f.

• Although it may sound strange for a function to call itself, it is in fact


not so strange, as many mathematical functions are defined
recursively.
Example of Recursive Factorial
Tracing of Recursive Functions
Example of Fibonacci Function
More on Function
 You can write functions to define specific tasks that may be used at
many points in a program. These are sometimes referred to as
programmer-defined functions. The actual statements defining
the function are written only once, and the statements are hidden
from other functions.Functions are invoked by a function call,
which specifies the function name and provides information (as
arguments) that the called function needs to perform its
designated task. A common analogy for this is the hierarchical form
of management. A boss (thecalling function or caller) asks a
worker (the called function) to perform a task and report back
when the task is done.
 #include<stdio.h>
// function prototype, also called function declaration
float square ( float x );
// main function, program starts from here
int main( )
{ float m, n ;
printf ( "\nEnter some number for finding square \n");
scanf ( "%f", &m ) ;
// function call
n = square ( m ) ;
printf ( "\nSquare of the given number %f is %f",m,n ); }
float square ( float x ) // function definition
{
float p ;
p=x*x;
return ( p ) ; }
int square( int y ); /* function prototype */
/* function main begins program execution */
int main( void )
{
int x;
for ( x = 1; x <= 10; x++ ) {
printf(“%d”, square(x)); */ function call
} end of for loop
int square(int y) // function definition
{
return y*y;
}
Detail on the program
Function square is invoked or called in main within

printf( "%d ", square( x ) ); /* function call */

Function square receives a copy of the value of x in the parameter y


Then square calculates y * y . The result is passed back to function
printf in main where square was invoked, and printf displays the
result. This process is repeated10 times using the for repetition
statement.
More Example
int maximum( int x, int y, int z ); /* function prototype */
int main()
{
int number1;
int number2;
int number3;
printf( "Enter three integers: " );
scanf( "%d%d%d", &number1, &number2, &number3 );
Printf(“Maximum is %d\n”,maximum(number1,number2,number3));
return 0;
}
int maximu(int x,int y,int z)
{ int max=x;
if (y>max){ max=y;} /* if y larger than max, assign y to max*/
if(z>max){ max=z;} /* if z larger than max, assign z to max*/
return max;
}
Exercise
 Write a program in C to compute sum of two number by
using function

 Write a program in C to compute Minimum of 3 numbers


when user entered the 3 numbers from the keyboard by
using function

 Write a program in C to compute the cube of numbers


from 1 to 10 by using function(the use of loop isrequired)

 Write compute sum of even numbers from 1 to 20 by


using function.
Exercise
Write a program of the pseudocode below by using Swicth-Case
if student’s grade is greater than or equal to 90
Print “A”
else
If student’s grade is greater than or equal to 80
Print “B”
else
If student’s grade is greater than or equal to 70
Print “C”
else
If student’s grade is greater than or equal to 60
Print “D”
else
Print “F”
Exercise 1

Write a Program in C by using recursive function to Compute the


fibonacci series when user entered a number from the keyboard and
using function.
Exercise 2

Write a program that takes two numbers to determine the maximum


number between the numbers. The user will enter the 2 numbers
from the keyboard and using function.
Exercise 3
Write a program to calculate the sum of Even number from 2 to 40 by
using function.
Questions
Quiz 1
 Write a C program to display the largest of any three numbers.
 Write C program to compute the sum and average of any 20
numbers entered through the keyboard.(You are expected to use a
loop statement.

You might also like