0% found this document useful (0 votes)
5 views

Unit-5 Functions & Preprocessor Directives

Uploaded by

clipsviral190
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Unit-5 Functions & Preprocessor Directives

Uploaded by

clipsviral190
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 83

UNIT-5

FUNCTIONS and Preprocessor


Directives
INTRODUCTION
Function is a self-contained block of program statements
that performs a particular task.

C has two types of function, its library function and


user-define function.

printf and scanf, getch belong to the category of library


functions. main is an example of user-define function.

The main difference between these two function are


that library function are not require to be written by user
whereas a user-define function has to be developed by
the user at the time of writing program.
INTRODUCTION

When the compiler encounters a function call,


instead of executing the next statement in the
calling function, the control jumps to the
statements that are a part of the called function.
INTRODUCTION
After the called function is executed, the control
is returned back to the calling program.

main() func1()
{ {
………….. Statement
………….. Block;
func1(); }
…………
………..
return 0;
}
INTRODUCTION
It is not necessary that the main() can call only
one function, it can call as many functions as it
wants and as many times as it wants. For
example, a function call placed within a for loop,
while loop or do-while loop may call the same
function multiple times until the condition holds
true.
INTRODUCTION
It is not that only the main() can call another
functions. Any function can call any other
function. In the fig. one function calls another,
and the other function in turn calls some other
function.
INTRODUCTION

main() func1() func2() func3()


{ { { {
………….. ……….. ……….. ………..
………….. ………… ………… …………
func1(); func2(); func3(); ………..
………… ……….. ……….. ……….
……….. ………. ………. return;
return 0; return; return; }
} } }
Advantage of UDF
• In program writing functions avoids rewriting
the same code over and over.

• User-define function becomes easier to write


programs and keep track of what they are doing in
the program. Like one main activity transfer into
separate activity.

• User-define function are used to reduce length of


program.
WHY DO WE NEED FUNCTIONS?
Dividing the program into separate well defined
functions facilitates each function to be written
and tested separately.

Understanding, coding and testing multiple


separate functions are far easier than doing the
same for one huge function.
TERMINOLOGY OF FUNCTIONS
A function, f that uses another function g, is
known as the calling function and g is known as
the called function.
The inputs that the function takes are known as
arguments
When a called function returns some result back
to the calling function, it is said to return that
result.
TERMINOLOGY OF FUNCTIONS
The calling function may or may not pass
parameters to the called function. If the called
function accepts arguments, the calling function
will pass parameters, else not.
FUNCTION DECLARATION
• All identifiers in C need to be declared before
they are used. This is true for functions as well as
variables.

For functions the declaration needs to be before


the first call of the function. A full declaration
includes the return type , function name and the
type of the arguments. This is also called the
function prototype or function Declaration.
FUNCTION DECLARATION
The general format for declaring a function that accepts
some arguments and returns some value as result can be
given as:

return_data_type function_name(data_type variable1,


data_type variable2,..);

No function can be declared within the body of another


function.
Example, float avg ( int a, int b);
FUNCTION DECLARATION
• The types must match the types of
parameters in the function definition, in
numbers and order.
• The use of parameters names in the
declaration is optional.
• If the function has no return data type, the list
is written as a void.
• The parameters list must be separated by
commas.
FUNCTION CALL
The function call statement invokes the function.

When a function is invoked the compiler jumps


to the called function to execute the statements
that are a part of that function.
FUNCTION CALL
Once the called function is executed, the
program control passes back to the calling
function.
Function call statement has the following syntax.
function_name(variable1, variable2, …);
FUNCTION CALL
e.g.
void main()
{
int a;
a = add (25,23); // Function Call
printf (“%d”, a);
}
Generally, a function will process information
passed to it from the calling function of a
program and return a single value.
FUNCTION CALL
• A void function does not return any values.
• Information will be passed to the function
via special identifier or expression called
arguments or actual parameters.
• A parameter is a variable defined in a function
definition. This is also known as a formal
parameter.
Points to remember while calling the function:

Function name and type of arguments in the


function call must be same as that given in the
function declaration and function header of the
function definition.

Names of variables in function declaration,


function call and header of function definition
may vary.
Points to remember while calling the function:

If the return type of the function is not void, then


the value returned by the called function may be
assigned to some variable as given below.
variable_name = function_name(variable1, variable2,
…);
FUNCTION DEFINITION
Function definition includes function name,
function type, parameters, local variable
declaration, function statement, return
statement elements.
FUNCTION DEFINITION
General format of Function Definition

Return type function_name (parameter) Function Header


{
local_variable declaration;

statement 1; Function Body


statement 2;

return statement;
}
FUNCTION DEFINITION
Function Header : It is a part of function definition.
It is similar to the function prototype declaration but
does not require the semicolon at the end.

The list of variable in the function header is also


referred to as the formal parameter list. It consists
of three parts.

(1)Return data type


(2)The name of function
(3)The formal parameters of the function.
FUNCTION DEFINITION

Function Body : The function body contains local


variable declaration and all valid statement of
that functions.
• It has also return statement if any function
returns a value to calling function.
• If the type of return is void then there must be
no expression appearing in the return.
Type of UDF

There are mainly four types of UDF

1)No Argument No Return


2)No Argument With Return
3)With Argument No Return
4)With Argument With Return
1)No Argument No Return
These are the functions, which do not take any data item
from calling function, in the form of parameters and do
not return anything to calling function, after execution.
As these functions do not contain any parameters, a pair
of empty braces follows the name of the function.

#include<stdio.h>
#include<conio.h>
void sum();
void main()
{
clrscr();
sum();
getch();
}
1)No Argument No Return
void sum()
{
int a,b,c;
printf("\n Enter Value 1 :");
scanf("%d",&a);

printf("\n Enter Value 2 :");


scanf("%d",&b);

c=a+b;
printf("\n Sum is %d",c);
}
2)No Argument With Return
This type of functions does not take any value from the calling
function. After execution, they return some value to the main
function. The data type of returned value determines the return
type of function

#include<stdio.h>
#include<conio.h>
int sum();
void main()
{
int z;
clrscr();
z=sum();
printf("\n Sum is :%d",z);
getch();
}
2)No Argument With Return
int sum()
{
int a,b,c;
printf("\n Enter Value 1 :");
scanf("%d",&a);

printf("\n Enter Value 2 :");


scanf("%d",&b);

c=a+b;
return c;
}
3)With Argument No Return
This type of functions take some value from the calling
function (usually main()) to the called function.
However, the functions of this type does no take any
value from the called function to the calling function as
we did in previous case. The values, which are passed
with the function call are called as "parameters" or
"arguments".
#include<stdio.h>
#include<conio.h>
void sum(int a,int b);
void main()
{
int a,b;
clrscr();
printf("\n Enter Value 1 :");
scanf("%d",&a);
3)With Argument No Return

printf("\n Enter Value 2 :");


scanf("%d",&b);

sum(a,b);
getch();
}

void sum(int a,int b)


{
int c;
c=a+b;
printf("\n Sum is : %d",c);
}
4)With Argument With Return
This type of functions take some value from the calling
function (usually main()) to the called function.
However, the functions of this type take any value from
the called function to the calling function.
#include<stdio.h>
#include<conio.h>
int sum(int a,int b);
void main()
{
int a,b,z;
clrscr();
printf("\n Enter Value 1 :");
scanf("%d",&a);
4)With Argument With Return
printf("\n Enter Value 2 :");
scanf("%d",&b);

z=sum(a,b);
printf("\n Sum is %d",z);
getch();
}

int sum(int a,int b)


{
int c;
c=a+b;
return c;
}
RETURN STATEMENT

The return statement is used to terminate the execution of


a function and return control to the calling function. When
the return statement is encountered, the program
execution resumes in the calling function at the point
immediately following the function call.

Programming Tip: It is an error to use a return statement


in a function that has void as its return type.
return expression ;
RECURSIVE FUNCTIONS

A recursion function is one that calls itself directly or


indirectly to solve a smaller version of its task until a final
call which does not require a self-call.

• In C, it is possible for the functions to call


themselves. A function is called ‘recursive’ if a
statement within the body of a function calls the same
function. Sometimes called ‘circular definition’,
recursion is thus the process of defining something in terms
of itself.
RECURSIVE FUNCTIONS

• Let us now see a simple example of recursion.


Suppose we want to calculate the factorial value of an
integer. As we know, the factorial of a number is the
product of all the integers between 1 and that number.

• For example, 4 factorial is 4 * 3 * 2 * 1. This can also


be expressed as 4! = 4 * 3! where ‘!’ stands for factorial.
Thus factorial of a number can be expressed in
the form of itself.
RECURSIVE FUNCTIONS

recursive case, in which first the problem at hand is


divided into simpler sub parts. Second the function calls
itself but with sub parts of the problem obtained in the
first step. Third, the result is obtained by combining the
solutions of simpler sub-parts.
Therefore, recursion is defining large and complex
problems in terms of a smaller and more easily solvable
problem.
FINDING FACTORIAL OF A NUMBER USING RECURSION

#include<stdio.h>
int Fact(int n);
void main()
{ int num;
scanf(“%d”, &num);
printf(“\n Factorial of %d = %d”, num, Fact(num));
getch();
}
int Fact(int n)
{ int p;
if(n==1)
return 1;
else
p= (n * Fact(n-1));
return p;
}
PROS AND CONS OF RECURSION

PROS:
Recursive solutions often tend to be shorter and simpler
than non-recursive ones.
Code is clearer and easier to use
Recursion represents like the original formula to solve a
problem.
Follows a divide and conquer technique to solve
problems
PROS AND CONS OF RECURSION

CONS:
For some programmers and readers, recursion is a difficult
concept.
Aborting a recursive process in midstream is slow and
sometimes time consuming.
Using a recursive function takes more memory and time to
execute as compared to its non-recursive counter part.
It is difficult to find bugs, particularly when using global
variables
MATHEMETICAL FUNCTIONS

1. abs ( ) This function returns the absolute value of


an integer. The absolute value of a number is always
positive. Only integer values are supported in C.

2. floor ( ) This function returns the nearest integer


which is less than or equal to the argument passed
to this function.
MATHEMETICAL FUNCTIONS

3. round ( ) This function returns the nearest


integer value of the float/double/long double
argument passed to this function. If decimal value is
from “.1 to .5”, it returns integer value less than the
argument. If decimal value is from “.6 to .9”, it
returns the integer value greater than the argument.
4. ceil ( ) This function returns nearest integer value
which is greater than or equal to the argument
passed to this function.
MATHEMETICAL FUNCTIONS

5. sin ( ) This function is used to calculate sine value.

6. cos ( ) This function is used to calculate cosine.

7. exp ( ) This function is used to calculate the


exponential “e” to the xth power.
MATHEMETICAL FUNCTIONS

8. tan ( ) This function is used to calculate tangent.

9. log ( ) This function is used to calculates natural


logarithm.

10. log10 ( ) This function is used to calculates base 10


logarithm.
MATHEMETICAL FUNCTIONS

11. sqrt ( ) This function is used to find square root of


the argument passed to this function.

12. pow ( ) This is used to find the power of the given


number.
EXAMPLE
#include<stdio.h>
#include<conio.h>
#include<math.h>

void main()
{
int a=-5;
clrscr();

printf("\n Abs value is : %d",abs(a));


getch();
}
CHARACTER FUNCTIONS
Function Usage Example
isalnum(int c) Checks whether character c is an alphanumeric isalnum(‘A’);
character
isalpha(int c) Checks whether character c is an alphabetic isalpha(‘z’);
character
iscntrl(int c) Checks whether character c is a control scanf(“%d”,&c);
character(backspace,esc,enter and all function iscntrl(c);
keys)
isdigit(int c) Checks whether character c is digit isdigit(3)

isgraph() Checks whether character c is a graphical or isgraph(“x”);


printing character. The function excludes the
white space character.(all char except cntrl)
isprint(int c) Checks whether character c is a printing isprint(‘@’);
character. The function includes white space
character
CHARACTER FUNCTIONS
Function Usage Example
islower(int c) Checks whether the character is in lower case islower(‘k’);

isupper(int c) Checks whether the character is in uppercase isupper(‘k’);

ispunct(int c) Checks whether the character c is a ispunct(‘?’);


punctuation mark.

isspace(int c) Checks whether the character c is white space isspace(‘ ‘ );


character
isxdigit(int c) Checks whether the character c is a isxdigit(‘F’);
hexadecimal digit
tolower(int c) Converts the character c to lower case tolower(‘K’);
Returns k
toupper(int c) Converts the character c to upper case toupper(‘k’);
Returns K
ISALNUM
#include<stdio.h>
#include<conio.h>
#include<ctype.h>
void main()
{
char ch;
clrscr();
printf("\nEnter a character:");
scanf("%c",&ch);
if(isalnum(ch))
printf("\nCharacter is alphabetic or numeric");
else
printf("\nCharacter is neither alphabetic nor numeric");
fflush(stdin);
getch();
}
ISALPHA
#include<stdio.h>
#include<conio.h>
#include<ctype.h>

void main()
{
char ch;
clrscr();
printf("\nEnter a character:");
scanf("%c",&ch);
if(isalpha(ch))
printf("\nCharacter is alphabetic");
else
printf("\nCharacter is not alphabetic");
fflush(stdin);
getch();
}
ISDIGIT
#include<stdio.h>
#include<conio.h>
#include<ctype.h>

void main()
{
char ch;
printf("\nEnter a character:");
scanf("%c",&ch);
if(isdigit(ch))
printf("\nCharacter is a digit");
else
printf("\nCharacter is not a digit");
fflush(stdin);
getch();
}
ISXDIGIT
#include<stdio.h>
#include<conio.h>
#include<ctype.h>

void main()
{
char ch;
clrscr();
printf("\nEnter a character:");
scanf("%c",&ch);
if(isxdigit(ch))
printf("\nCharacter is hexadecimal");
else
printf("\nCharacter is not hexadecimal");
fflush(stdin);
getch();
}
ISGRAPH
#include<stdio.h>
#include<conio.h>
#include<ctype.h>

void main()
{
char ch;
clrscr();
printf("\nEnter a character:");
scanf("%c",&ch);
if(isgraph(ch))
printf("\nCharacter is not blank but printing");
else
printf("\nCharacter is blank");
fflush(stdin);
getch();
}
ISPRINT
#include<stdio.h>
#include<conio.h>
#include<ctype.h>

void main()
{

char ch;
clrscr();
printf("\nEnter a character:");
scanf("%c",&ch);
if(isprint(ch))
printf("\nCharacter is printable");
else
printf("\nCharacter is not printable");
fflush(stdin);
getch();
}
ISPUNCT
#include<stdio.h>
#include<conio.h>
#include<ctype.h>

void main()
{

char ch;
clrscr();
printf("\nEnter a character:");
scanf("%c",&ch);
if(ispunct(ch))
printf("\nCharacter is a punctuation");
else
printf("\nCharacter is not a punctuation");
fflush(stdin);
getch();
}
ISSPACE
#include<stdio.h>
#include<conio.h>
#include<ctype.h>

void main()
{
char ch;
clrscr();
printf("\nEnter a character:");
scanf("%c",&ch);
if(isspace(ch))
printf("\nCharacter is blank");
else
printf("\nCharacter is not blank");
fflush(stdin);
getch();
}
ISUPPER
#include<stdio.h>
#include<conio.h>
#include<ctype.h>

void main()
{
char ch;
clrscr();
printf("\nEnter a character:");
scanf("%c",&ch);
if(isupper(ch))
printf("\nCharacter is in uppercase");
else
printf("\nCharacter is not in uppercase");
fflush(stdin);
getch();
}
ISLOWER
#include<stdio.h>
#include<conio.h>
#include<ctype.h>

void main()
{
char ch;
clrscr();
printf("\nEnter a character:");
scanf("%c",&ch);
if(islower(ch))
printf("\nCharacter is in lowercase");
else
printf("\nCharacter is not in lowercase");
fflush(stdin);
getch();
}
TOLOWER
#include<stdio.h>
#include<conio.h>
#include<ctype.h>

void main()
{
char ch;
clrscr();
printf("\nEnter a character:");
scanf("%c",&ch);
printf("\nLowercase=%c",tolower(ch));
fflush(stdin);
getch();
}
TOUPPER
#include<stdio.h>
#include<conio.h>
#include<ctype.h>

void main()
{
char ch;
clrscr();
printf("\nEnter a character:");
scanf("%c",&ch);
printf("\nUppercase=%c",toupper(ch));
fflush(stdin);
getch();
}
THE PREPROCESSOR
DIRECTIVE
INTRODUCTION
The preprocessor is a program that processes the source
code before it passes through the compiler. It operates
under the control of preprocessor directive which is
placed in the source program before the main().

Before the source code is passed through the compiler,


it is examined by the preprocessor for any preprocessor
directives. In case, the program has some preprocessor
directives, appropriate actions are taken (and the source
program is handed over to the compiler.
INTRODUCTION
The preprocessor directives are always preceded by a hash
sign (#).

The preprocessor is executed before the actual compilation of


program code begins. Therefore, the preprocessor expands all
the directives and take the corresponding actions before any
code is generated by the program statements.

No semicolon (;) can be placed at the end of a preprocessor


directive.
INTRODUCTION
The advantages of using preprocessor directives in a C
program include:

•Program becomes readable and easy to understand


•Program becomes portable as preprocessor directives makes
it easy to compile the program in different execution
environments
•Due to the aforesaid reason the program also becomes more
efficient to use.
TYPES OF PREPROCESSOR DIRECTIVES
#define
To define preprocessor macros we use #define. The #define
statement is also known as macro definition or simply a
macro. There are two types of macros- object like macro and
function like macro.
TYPES OF PREPROCESSOR DIRECTIVES
Object like macro
An object-like macro is a simple identifier which will be
replaced by a code fragment. They are usually used to give
symbolic names to numeric constants. Object like macros do
not take any argument. It is the same what we have been
using to declare constants using #define directive. The
general syntax of defining a macro can be given as:
#define identifier string
The preprocessor replaces every occurrence of the identifier
in the source code by a string.
#define PI 3.14
Function-like macros
They are used to stimulate functions.
When a function is stimulated using a macro, the macro
definition replaces the function definition.

The name of the macro serves as the header and the macro
body serves as the function body. The name of the macro will
then be used to replace the function call.
Function-like macros
The function-like macro includes a list of parameters.
References to such macros look like function calls. However,
when a macro is referenced, source code is inserted into the
program at compile time.

The parameters are replaced by the corresponding


arguments, and the text is inserted into the program stream.
Therefore, macros are considered to be much more efficient
than functions as they avoid the overhead involved in calling
a function.
Function-like macros
The syntax of defining a function like macro can be given as
# define identifier(arg1,arg2,...argn) string
The following line defines the macro MUL as having two
parameters a and b and the replacement string (a * b):
#define MUL(a,b) (a*b)

Look how the preprocessor changes the following statement


provided it appears after the macro definition.
int a=2, b=3,c;
c = MUL(a,b);
RULES FOR USING MACROS
The macro name and the formal parameters are identifiers, so they must
be specified in accordance with the rules for identifiers in the c language.

Spaces, tabs, and comments are allowed to be used freely within a


#define directive. All the spaces, tabs, and comments are replaced by a
single space.

White space in between the identifier and the left parenthesis that
introduces the parameter list is not allowed.

The number of arguments in reference must match the number of


parameters in the macro definition.
#include
#include
An external file containing function, variables or macro
definitions can be included as a part of our program. This
avoids the effort to re-write the code that is already written.

The #include directive is used to inform the preprocessor to


treat the contents of a specified file as if those contents had
appeared in the source program at the point where the
directive appears.
#include
The #include directive can be used in two forms. Both forms
makes the preprocessor insert the entire contents of the
specified file into the source code of our program. However,
the difference between the two is the way in which they
search for the specified.
#include <filename>
This variant is used for system header files. When we include
a file using angular brackets, a search is made for the file
named filename in a standard list of system directories.
CONDITIONAL DIRECTIVES
A conditional directive is used instruct the preprocessor
to select whether or not to include a chunk of code in
the final token stream passed to the compiler. The
preprocessor conditional directives can test arithmetic
expressions, or whether a name is defined as a macro,
etc.

Conditional preprocessor directives can be used in the


following situations:

A program may need to use different code depending on


the machine or operating system it is to run on.
CONDITIONAL DIRECTIVES
The conditional preprocessor directives can be used to
exclude code from the program whose condition is always
false but is needed to keep it as a sort of comment for future
reference.
CONDITIONAL DIRECTIVES
#ifdef
#ifdef is the simplest sort of conditional preprocessor
directive and is used to check for the existence of macro
definitions. Its syntax can be given as:
#ifdef MACRO
controlled text
#endif
#ifdef MAX
int STACK[MAX];
#endif
CONDITIONAL DIRECTIVES
#include <stdio.h>
#define MACRO1
#define MACRO2

void main(void)
{
#ifdef MACRO1 // test whether MACRO1 is defined...
printf("\nMACRO1 Defined\n");
#endif

#ifdef MACRO2 // test whether MACRO2 is defined...


printf("\nMACRO2 Defined\n");
#endif
}
CONDITIONAL DIRECTIVES
#ifndef
The #ifndef directive is the opposite of #ifdef
directive. It checks whether the MACRO has not been defined
or if its definition has been removed with #undef.
#ifndef is successful and returns a non-zero value if
the MACRO has not been defined. Otherwise in case of
failure, that is when the MACRO has already been defined,
#ifndef returns false (0).
The general format to use #ifndef is the same as for #ifdef:
#ifndef MACRO
controlled text
#endif
CONDITIONAL DIRECTIVES
The #if Directive
The #if directive is used to control the compilation of portions of a source file. If the specified
condition (after the #if) has a nonzero value, the controlled text immediately following the
#if directive is retained in the translation unit.

The #if directive in its simplest form consists of


#if condition
controlled text
#endif
While using #if directive, make sure that each #if directive must be matched by a closing
#endif directive. Any number of #elif directives can appear between the #if and #endif
directives, but at most one #else directive is allowed. However, the #else directive (if
present) must be the last directive before #endif.
CONDITIONAL DIRECTIVES
#include<stdio.h>
#define NUM 10
void main()
{
#if((NUM%2)==0)
printf("\nNumber is Even");
#endif
}
CONDITIONAL DIRECTIVES
The #else Directive
The #else directive can be used within the controlled text of an #if
directive to provide alternative text to be used if the condition is false.
The general format of #else directive can be given as:

#if condition
Controlled text1
#else
Controlled text2
#endif
CONDITIONAL DIRECTIVES
#include<stdio.h>
#define NUM 11

void main()
{
#if((NUM%2)==0)
printf("\nNumber is Even");
#else
printf("\nNumber is Odd");
#endif
}
CONDITIONAL DIRECTIVES
The #elif Directive
The #elif directive is used when there are more than two possible alternatives. The #elif
directive like the #else directive is embedded within the #if directive and has the following
syntax:
#if condition
Controlled text1
#elif new_condition
Controlled text2
#else
Controlled text3
#endif
CONDITIONAL DIRECTIVES
THE #endif DIRECTIVE
The general syntax of #endif preprocessor directive which is used to end the conditional
compilation directive can be given as:

#endif

The #endif directive ends the scope of the #if , #ifdef , #ifndef , #else , or #elif directives.

You might also like