Lecture IV
Lecture IV
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
(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
USES OF C FUNCTIONS
C functions are used to avoid rewriting same logic/code again and
again in a program.
}
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");
}
• 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.