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

Ch 05 Functions and Macros

Uploaded by

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

Ch 05 Functions and Macros

Uploaded by

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

Matrix Computers (Page 1 of 15)

10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan


9414752750, 9414930104, 9414244351, 0141-2399633

Chapter 5 Function and Macros


Introduction: -
Functions are used to perform certain actions. Sometimes we have to write same code
again and again but using the function we have to write code only once within curly braces and
that code can be called again and again. Functions are important for reusing the code. Define
the code once, and use it many times. A function is a block of code which only runs when it is
called. We can pass data into a function and data is known as parameters.
Function allows a large program to be broken down into a number of smaller components.
These components are reusable. It avoids rewriting the code over & over. Breaking down of logic
into separate functions make the entire process of writing & debugging easier.

Type of Functions: -
1. Pre-defined Functions: -
Functions defined previously in the library are called as library functions. These functions
are declared in header files (.h) files and defined in (.lib) files. We can call them by
including their header files in our programs.

Example of pre-defined library function pow: -


#include<stdio.h> //header file for printf and scanf
#include<math.h> //header file for pow function
int main(){
int n, p, ans;
printf(“Enter number and its power”);
scanf(“%d%d”,&n,&p);
RIX
AT
M

ans = pow(n,p); //function call


printf(“%d”,ans);
return(0);
}

Commonly Used Pre-defined Library Functions: -

stdio.h: -
printf() Sends the formatted output to stdin.
scanf(). Scans and formats input from stdin.
putchar() Outputs a character on stdout.
getchar() gets a character from stdin.
puts() Outputs string and appends a newline character.
gets() Get a string from stdin.
fflush() Flushes a stream
fopen() Opens a stream
fclose( ) Closes a stream
feof() Tests if end-of-file has been reached on a stream
fprintf() Sends formatted output to stream
fscanf() Scans and formats input from a stream.
fputs() Outputs a string to a stream
fgets() Gets a string from a stream
Matrix Computers (Page 2 of 15)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633

fputc() Outputs a character to a stream


fgetc() Gets a character from a stream
fwrite() Writes to a stream.
fread() Reads data from a stream
fseek() Sets the file pointer to a particular position.
ftell() Returns the current position of the file pointer.
remove() Removes a file
rename() Renames a file

conio.h: -
getch() gets a character from console but does not echo to the screen
getche() gets a character from console, and echoes to the screen
putch() Outputs character to the text window on the screen

stdlib.h: -
exit() Terminates the program.
itoa() converts an integer to a string.
ftoa() converts a float to a string
atoi() Converts string of digits to integer.
atof() converts a string to a floating point
random() Returns a random number between 0 and number – 1
randomize() initializes random number generator.
abs() gets the absolute value of an integer

math.h: -
RIX
AT
M

pow() Calculates the power of a number


sqrt() Calculates the square root of a number
ceil() Returns the largest integer in given list.
floor() Returns the smallest integer in given list.
sin() Calculates the sine value of an angle. Accepts the angle value in radians
cos() Calculates the cosine Accepts the angle value in radians
tan() Calculates the tangent value of an angle. Accepts the angle value in
asin() Calculates the inverse of sin Accepts the angle value in radians
acos() Calculates the inverse of cos Accepts the angle value in radians
atan() Calculates the inverse of tan Accepts the angle value in radians

string.h: -
strlen() Function to calculate the length of the string
strcpy() Function to copy a string to another string
strcat() Function to concatenate(merge) strings.
strupr() Converts the given string to uppercase
strlwr() Converts the given string to lowercase
strrev() Function to reverse the given string.
strcmp() Function to compare two strings.
stricmp() Function to compare two strings ignoring their case.
strstr() Finds the first occurrence of string in another string.
Matrix Computers (Page 3 of 15)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633

User Defined Functions: -


Functions defined by us are known as User Defined Functions. If we need a function and
that function is not available in any header file then we can create our own function.

Syntax of Functions: -
The syntax of function can be divided into 3 parts:
1. Function Declaration or prototype
2. Function Calls
3. Function Definition

1. Function Declaration: -
We must declare a function before call otherwise compiler will give an error. There is no
need to declare a function if we define the function before call. The declaration is also called as
prototype. The declaration of a function is not necessary if the output type is an integer value. In
some C compilers declaration is not required for all the function.

return_type function_name(data_types of arguments separated with comma);

2. Function Call: -
A function call is a statement that instructs the compiler to execute the function. We use
the function name and parameters in the function call. The function call is the way of using the
function. A function is declared once, defined once but can be used a number of times in the
same program. When the compiler encounters the function call, the control of the program is
transferred to the function definition the function is then executed line by line and a value is
RIX
AT
M

returned at the end. If function main() calls a function sum() then main() is the calling function
and sum() is called function.
In the below example, the first sum function is called and 10,30 are passed to the sum
function. After the function call sum of a and b is returned and control is also returned back to
the main function of the program

3. Function Definition: -
The function definition consists of actual statements which are executed when the
function is called (i.e. when the program control comes to the function). A C function is
Matrix Computers (Page 4 of 15)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633

generally defined and declared in a single step because the function definition always starts
with the function declaration so we do not need to declare it explicitly. The function definition
does not terminate with a semicolon. A function may have more than one return statement but
any one will work. It can be used as:
if (a!=0)
return(a);
else
return(1);
While it is possible to pass any number of arguments to a function, the called statement returns
only one value at a call. The return statement can be used as:
return;
or
return(value);
The first return without any value, it acts much as the closing of the braces of the function
definition.
The below example serves as both a function definition and a declaration.
RIX
AT
M

Example of function to calculate the sum of two numbers (Function defined


before call):
int sum( int x, int y){ //Function Definition or Process
int z;
z = x + y;
return(z);
}
int main(){
int a,b,ans;
printf(“Enter two numbers: “);
scanf(“%d %d”,&a,&b);
ans= sum(a,b); //Function Call
printf(“ sum is %d”, ans);
return(0);
}

Example of function to calculate the sum of two numbers (Function defined


after call):
int sum(int, int); // Function Prototype or Declaration
int main(){
int a,b,ans;
Matrix Computers (Page 5 of 15)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633

printf(“Enter two numbers: “);


scanf(“%d %d”,&a,&b);
ans= sum(a,b); //Function Call
printf(“ sum is %d”, ans);
return(0);
}
int sum( int x, int y){ //Function Definition or Process
int z;
z = x + y;
return(z);
}

Multiple Return: -
We can’t return multiple values from a function. If we try to return multiple values then
only the last value will be returned because comma operator works from left to right but returns
right most value.
int f1(int a, int b, int c){
return a, b, c;
}
int main(){
int ans;
ans=f1(5,6,7);
printf(“%d”, ans); // 7
}
RIX
AT
M

void function: -
If a function does not return any value, then it is called as void function. void is a keyword
in c and it denotes type less datatype. It means nothing.

int sqr(int x){


return x*x;
}
int main(){
int n,ans;
printf(“Enter a number”);
scanf(“%d”,&n);
ans=sqr(n);
printf(“%d”,ans);
return(0);
}

It is better to return the result from the function sqr to main function and then print in main
function but if we want to print the result in the function sqr then we can use void like this.
void sqr(int x){
printf(“%d”,x*x);
}
int main(){
Matrix Computers (Page 6 of 15)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633

int n;
printf(“Enter a number”);
scanf(“%d”,&n);
sqr(n);
return(0);
}
It is not a better option to print the result in function but sometimes there are multiple
results and we can’t return multiple values from a function to main function then we can print all
results in function itself like this: -
void swap(int x,int y){
int t=x;
x=y;
y=t;
printf(“After swap values are %d,%d”,x,y);
}
int main(){
int a,b;
printf(“Enter 2 integers:”);
scanf(“%d%d”,&a,&b);
swap(a,b);
return(0);
}
Note: - We can’t return multiple values from a function but using pointer we can return multiple
values which will be covered in pointer chapter later.
RIX
AT
M

Actual parameter and Formal parameter: -


When we pass any local variable in a function then the copy of the value of that variable
will be passed in the function not original variable.
void increment(int y){
y++;
}
int main(){
int x=5;
increment(x);
printf(“%d”,x); //5
return(0);
}
Here x is the actual parameter and y is the formal parameter. x an y are two different
variables in memory so if we increment y this will not effect the value of x so x will be 5 only. But
if we return value of y from the function and update in x in main function then it will print 6.
int increment(int y){
y++;
return y;
}
int main(){
int x=5;
x=increment(x);
Matrix Computers (Page 7 of 15)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633

printf(“%d”,x); //6
return(0);
}

main function: -
main function is a user defined function. Every program must have a main function
because execution starts from main function. It is the first function to be called automatically. It
is possible to write complete program using only the main program but this is not a good option.
It will be difficult to understand and test the program as it becomes too large and too complex.
But if the same program is broken into small functions, then this program will be easy to
understand and test. We can write main function in two ways: -
1. Returning value from main function: -
We return 0 value to indicate that the program is successful and we return 1 or any
non zero value to indicate failure. It is good practice to return some value from main.
This 0 or 1 is of type int so we type int before main function.

int main(){

return(0);
}

2. Not returning any value from main function: -


If we do not want to return any value from main then we should type void before main
function. But this is not a good practice and some compilers don’t allow void main.
RIX
AT
M

void main(){

Note: - main function can also accepts arguments and this is called as command line arguments
and this will be covered after array.
int main(int argc, char *argv[]){

return(0);
}

Type of Function according to argument and return type: -


1. Function with arguments and with return value
2. Function with no arguments and no return value
3. Function with no arguments and with return value
4. Function with argument and with no return value

1. Function with arguments and with return value


int max(int, int); // Function Prototype or Declaration
int main(){
int a, b, ans;
Matrix Computers (Page 8 of 15)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633

printf(“Enter two numbers: “);


scanf(“%d %d”,&a,&b);
ans= max(a,b); //Function Call
printf(“ Max is %d”, ans);
return(0);
}
int max( int x, int y){ //Function Definition or Process
if(x>y)
return x;
return y;
}

2. Function with no arguments and no return value:


void display();
int main(){
display();
display();
}
void display(){
printf(“Hello World”);
}

3. Function with no arguments and with return value


int getInteger(){
int x;
RIX
AT
M

printf(“Enter a integer:”);
scanf(“%d”,&x);
return x;
}
int main(){
int n;
n=getInteger();
if(n%2==0)
printf(“Number is Even.”);
else
printf(“Number is Odd.”);
return(0);
}

4. Function with argument and with no return value:


void swap(int x,int y){
int t=x;
x=y;
y=t;
printf(“After swap values are %d,%d”,x,y);
}
int main(){
Matrix Computers (Page 9 of 15)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633

int a,b;
printf(“Enter 2 integers:”);
scanf(“%d%d”,&a,&b);
swap(a,b);
return(0);
}

Using global variable to share data: -


int x,y;
void swap(){
int t=x;
x=y;
y=t;
}
int main(){
printf(“Enter two integers:”);
scanf(“%d%d”,&x,&y);
swap();
printf(“After swap values are %d,%d”,x,y);
return(0);
}
Here x any y are global variables and we can access these variables in both functions.
So x and y used in main and swap functions are both same.

Advantages of Functions in C: -
RIX
AT
M

Functions in C is a highly useful feature of C with many advantages as mentioned below:


1. The function can reduce the repetition of the same statements in the program.
2. The function makes code readable by providing modularity to our program.
3. There is no fixed number of calling functions it can be called as many times as you
want.
4. The function reduces the size of the program.
5. Once the function is declared you can just use it without thinking about the internal
working of the function.

Disadvantages of Functions in C
The following are the major disadvantages of functions in C:
1. Cannot return multiple values.
2. Slow execution of the program due to multiple jumps in calling a function. When we
call a function program control will jump from call to definition and then when we
return value from function then it will jump back from definition to call.

Macro Function: -
We already know that it is time consuming to call a function but If the function is small
(mostly single line), we can solve this problem by using a macro function. Macro function is
defined by #define directive. Whenever a macro name is encountered by the compiler, it
Matrix Computers (Page 10 of 15)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633

replaces the name with the definition of the macro. Macro definitions should not be terminated
by a semi-colon(;). These macros are the same as a function call. It replaces the entire code
instead of a function name.

Example to find the maximum of two numbers using macro:


#define max(a,b) ((a)>(b)?(a):(b))
int main( ){
int a,b,ans;
printf(“Enter two numbers”);
scanf(“%d %d”,&a,&b);
ans = max(a,b);
printf(“max = %d”,ans);
return(0);
}

Example: -
#define sum(x,y) x+y
int main(){
printf(“\n%d”,sum(5,4));
printf(“\n%d”,sum(5,4)*sum(5,4)); //Output should be 81(9*9) but it will
//produce 29(5+4*5+4)
return(0);
}

So a pair of parentheses immediately after the macro name is necessary.


RIX
AT
M

Example: -
#define sum(x,y) (x+y)
int main(){
printf(“\n%d”,sum(5,4));
printf(“\n%d”,sum(5,4)*sum(5,4)); //81(5+4)*(5+4)
return(0);
}

Example: -
#define mult(x,y) (x*y)
int main(){
printf(“\n%d”,mult(5+4,5+4)); //output should be 81(9*9) but it will
//produce 29(5+4*5+4)
return(0);
}

All individual variables in the macro code should also enclosed in parenthesis.
Example: -
#define mult(x,y) ((x)*(y))
int main(){
Matrix Computers (Page 11 of 15)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633

printf(“\n%d”,mult(5+4,5+4)); //81
return(0);
}

If we put a space between the macro name and the parentheses in the macro definition, then
the macro will not work.
#define sum (x,y) (x+y) //wrong

A multi-line macro can also be defined by placing a backward slash at the end of each
line except the last. This feature permits a single macro to be represented as compound
statement.

#include <stdio.h>
#define display(num, str) { \
printf("%d", num); \
printf(" is"); \
printf(" %s number", str); \
printf("\n"); \
}
int main(){
int n;
printf("Enter a number: ");
scanf("%d", &n);
if(n%2==0)
display(n, "Odd");
RIX
AT
M

else
display(n, "Even");
return 0;
}

Storage class decides the memory location of a variable. Memory location can be
1. Main Memory (RAM). 2. CPU registers. It decides the default value of a variable (Zero value
or garbage value). It also decides the scope & lifetime of a variable. Scope indicates the region
over which the variable’s declaration has an effect or in other words that particular variable can
be used. The four different kinds of scopes are global, function, block and prototype. There are
4 storage classes:-
1. Automatic storage class (auto)
2. Static storage class (static)
3. External storage class (extern)
4. Register storage class. (register)

Automatic storage class:-


Variable declared inside a function has by default automatic storage class. It is initialized
by garbage value. The declaration is given as: int a or auto int a;
void prn();
main()
{
Matrix Computers (Page 12 of 15)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633

int a=5;
printf(“%d ”, a);
prn();
prn();
prn();
}
void prn()
{
int a=10;
a++;
printf(“%d ”,a);
}
Output: 5 11 11 11
Here in the above example the two variables have the same name but they have different
scope. Variable a in prn() has local scope so every time prn() is called a new copy of a
will be generated.

Static storage class: -


Static storage class should be used only when a program requires the value of a variable
to persist between different function calls like in recursive function. The variable is declared as:
static int b; Static variable will have local scope and global lifetime. Static variable are defined
within individual functions and therefore have the same scope as automatic variables. They are
local to the functions in which they are default. They retain their values throughout the life of the
program. Thus if a function is exited and then re-entered at a later time, the static variables
defined within that function will return their former values.
RIX
AT
M

void prn();
main()
{
prn();
prn();
prn();
}
void prn()
{
static int a=10;
a++;
printf(“%d ”,a);
}
Output:11 12 13
In the above example only a single copy of variable a will be created and this single copy will be
used every time prn() is called, so it will increment the last function call value of variable a.

Extern storage class: -


Variable declared outside all the functions have external storage class. Extern storage
class should be used for only those variables which are being used by all the functions in the
programs, Now there is no need to pass a variable in all the functions. But it is also not advisable
to store all the variables as extern because it will remain active through out the life of the program
Matrix Computers (Page 13 of 15)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633

thus wasting a lot of memory unnecessarily. The external variables are declared as extern int
c; It is also used when the variables of one program have to be used in some other programs
also for example: -

File1.c File2.c
#include ”File2.c” extern int a; /*Variable declaration*/
int a; /*Variable definition */ void func()
main() {
{ a=10;
a= 5; }
func();
printf(“%d”,a);
}
Output: 10
Variable a will get memory in File1.c. Because it is defined outside the function so
it is called as external variable and its scope is global. It can also be used in another
file File2.c. variable a used in both files is same. But when we compile the File2.c
we have to imform the compiler that variable a will come from outside so we have
declared a as extern int a;(no memory allocation at this time), but if we declare it
as int a; then compiler will treat it as a new variable.

Register storage class: -


There are only 14 CPU registers available and even lesser than that can be used by us
as the microprocessor is using it. But the CPU registers are accessed by the computer very fast
and so the program is executed very fast. So, it will be best used for loop counters which have
RIX
AT
M

to be used a number of times. However if a register is not free, auto storage class is used and
the execution is carried on. The CPU registers are 2 bytes long. So their maximum range is
equal to that of int. float values can not be stored in register. Even if we say register float x, auto
is assumed for x. The variable for this class are declared as, register int d;

Summary: -
Storage Class Memory Default Value Scope Lifetime
Auto Main memory Garbage Local Local
(RAM)
Static Main memory Zero Local Global
(RAM)
Extern Main memory Zero Global Global
(RAM)
Register CPU Registers Garbage Local Local

Recursion: -
Recursion is the process of calling a function itself repeatedly until a particular condition
is met. A function that calls itself directly or indirectly is called a recursive function and such kind
of function calls are called recursive calls.
A function is called recursive if a statement within the body of a function calls the same
function. Sometimes called as 'circular definition', recursion is a function calling itself in the
Matrix Computers (Page 14 of 15)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633

definition. A recursive function should have two parts recursive statement & a termination
condition.
Suppose we want to calculate the factorial of an integer. As we know, the factorial of a
number is the product of all the integers between 1 and that number. Factorial of 4 can be
expressed as 4! = 4 * 3! Where ! stands for factorial. Thus the factorial of a number can be
expressed in the form of itself. Hence this can be programmed using recursion.

Example: -
int fact (int);
main()
{
int n,ans;
printf(“Enter a number: “);
scanf(“%d”,&n);
ans = fact(n); /*function call */
printf(“factorial = %d”,ans);
getch();
}
int fact(int n)
{
if(n= =0) /*terminating condition*/
return (1);
return (n*fact(n-1)); /*recursive statement*/
}
Now let us evaluate this program:
RIX
AT
M

Assuming the value of n is 3 when the control of the program is passed from the main()
function the function fact. Since n is not equal to 0 so the condition is false and the recursive
statement is executed.
3*fact(2)
now fact(2) is the calling function and thus the control of the program again reaches the
beginning of the definition. Still the terminating condition is false so the recursive statement is
executed.
2*fact(1)
again fact(1) is the calling function and thus the control of the program again reaches the
beginning of the definition. Still the terminating condition is false so the recursive statement is
executed.
1 * fact(0)
now the condition is true so the answer to the calling function(fact(0)) will be 1 and so on.
Thus the sequence of acts will be:
fact(3)=3 * fact(2)
fact(2)=2 * fact(1)
fact(1)=1 * fact(0)
When we use a recursive program a stack is used to organize the data. Stack is a Last
In First Out (LIFO) data structure. This means that the last item to be stored (push operation) in
the stack will be the first one to come (pop operation) out. In the above program when the fact(2)
is called the value 3 will be stored in the stack. Similarly when fact(1) is called the value 2 will be
stored at the top of 3 on the stack.
Matrix Computers (Page 15 of 15)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633

Now when the fact(0) returns 1. it will be multiplied to the first value in the stack i.e. 1.
This result will be multiplied to the second waiting value of the stack i.e. 2 and so on.
When a function in its definition calls another function it is called chaining. Recursion is a
special type of chaining where a function calls itself.
e.g.:
main()
{
printf(“Matrix\n”);
main();
}
when executed the program will give the output as :
Matrix
Matrix
Matrix
_
_

The execution of any recursive function can continue indefinitely so to bring the execution
to the end a terminating condition is applied.

Advantages of Recursion: -
The advantages of using recursive methods over other methods are:
1. Recursion can effectively reduce the length of the code.
2. Some problems are easily solved by using recursion like the tower of Hanoi and
tree traversals.
RIX
AT
M

3. Data structures like linked lists, trees, etc. are recursive in nature so recursive
methods are easier to implement for these data structures.

Disadvantages of Recursion: -
As with almost anything in the world, recursion also comes with certain limitations some of
which are:
1. Recursive functions make our program a bit slower due to function call overhead.
2. Recursion functions always take extra memory space.

You might also like