Date post: | 09-Apr-2018 |
Category: |
Documents |
Upload: | ravitejabavandla |
View: | 225 times |
Download: | 1 times |
of 69
8/8/2019 Functions and Macros
1/69
Computer Science: A Structured Programming Approach Using C 1
Functions
All c programs have at least one functionthat is the main.
When the program grows into larger, mayhave many disadvantages.
1. Difficult to write a larger programs
2. Difficult to identify the logical errors and
correct.3. Difficult to read and understand.
4. Larger programs prone for more errors.
8/8/2019 Functions and Macros
2/69
Computer Science: A Structured Programming Approach Using C 2
A program is divided into a main module and its related
modules.
Each module is in turn divided into sub modules until the
resulting modules are smaller; that is, until they are not
further division.
The process of subdividing a problem into manageable partscalled top-down design.
8/8/2019 Functions and Macros
3/69
Computer Science: A Structured Programming Approach Using C 3
FIGURE 4-2 Structure Chart
8/8/2019 Functions and Macros
4/69
Computer Science: A Structured Programming Approach Using C 4
->If any module has sub modules that is called as callingmodule and sub modules are called called modules.
->one module is communicate with other module throughcalling module.
-> the function which is calling other function is calledcalling function.
->A function whom it called is called called function-> A called function receives control from the a calling
function, when it completes its task, it returns control to
the calling function.-> the main function called by the operating system, in
turn main function calls the other function to do sometask.
8/8/2019 Functions and Macros
5/69
Computer Science: A Structured Programming Approach Using C 5
A large program divided into series ofindividual related programs called
modules. These modules are calledfunctions.
Functions are classified into two categories
1. Library functions ( built-in functions).
2. User-defined functions
8/8/2019 Functions and Macros
6/69
Computer Science: A Structured Programming Approach Using C 6
Library (built in) functions
C is a library it is a collection of various types of functionswhich perform some standard and predefined tasks.
This are part of the c compiler that have been written forgeneral purpose are called library functions.
exampleprintf()scanf()sqrt()
Advantage1.No need to write the code because the functions are
already available so it makes the programmers job mucheasier.
2. these functions are used anywhere in the program.
8/8/2019 Functions and Macros
7/69
Computer Science: A Structured Programming Approach Using C 7
User defined functions
The functions are written by theprogrammer to achieve some work
8/8/2019 Functions and Macros
8/69
Computer Science: A Structured Programming Approach Using C 8
Advantages of function
1. Readability of the program can beincreased. Problem can be easilyunderstandable.
2. Reuse- the function written in oneprogram can also used in other program.
(reduce the size).
1. Makes the program easy for testing,coding and debugging.
2. Saves time as well as space.
8/8/2019 Functions and Macros
9/69
Computer Science: A Structured Programming Approach Using C 9
FIGURE 4-3 Structure Chart for a C Program
8/8/2019 Functions and Macros
10/69
Computer Science: A Structured Programming Approach Using C 10
4-3 User-Defined Functions
LikeLike everyevery otherother variablevariable inin C,C, functionsfunctions mustmust bebe bothboth
declareddeclared andand defineddefined.. TheThe functionfunction declarationdeclaration givesgives
thethe returnreturn typetype andand functionfunction namename needsneeds toto bebe defineddefined
laterlater.. TheThe functionfunction definitiondefinition containscontains thethe codecode forfor aafunctionfunction..
Function Definition
Function Declaration
The Function Call
Topics discussed in this section:Topics discussed in this section:
8/8/2019 Functions and Macros
11/69
Computer Science: A Structured Programming Approach Using C 11
Definition
A function is a self- contained block of codethat performs a particular task.
It takes some data from the main programand may or may not returns a value.
8/8/2019 Functions and Macros
12/69
Computer Science: A Structured Programming Approach Using C 12
A function name is used three times: for declaration, in acall, and for definition.
NoteNote
8/8/2019 Functions and Macros
13/69
Computer Science: A Structured Programming Approach Using C 13
Function declaration
Funtion prototype(syntax)
Return_type function_name (argument list);
8/8/2019 Functions and Macros
14/69
Computer Science: A Structured Programming Approach Using C 14
Definition
Syntax for the function definitionReturntype function_name(argument list/parameters list)argument list declaration{local variable declarations:Statements;return(expression);}//function.
All the parts are not essential.
Argument list and declaration optional.Return statement is also optional.
8/8/2019 Functions and Macros
15/69
Computer Science: A Structured Programming Approach Using C 15
main(){-----------
----------
func1();
---------
--------
funct2();--------
---------
funct3();---------
-------
}//main
func1(){----------
-----------
}func1func2(){--------
--------
}//func2fucn3(){----------
---------
}//func3
8/8/2019 Functions and Macros
16/69
Computer Science: A Structured Programming Approach Using C 16
Return type- the type of value return by thecalled function after its task finished off
Function _name- give name to the functionas naming the variables.
Argument list/parameters-
contains the validnames separated by commas and mustenclosed in parenthesis
8/8/2019 Functions and Macros
17/69
Computer Science: A Structured Programming Approach Using C 17
main()\\calling function
{
func1();
printf(we are in main\n);}//main
func1()\\ called funciton
{printf(we are in func1\n);
}//func1
8/8/2019 Functions and Macros
18/69
Computer Science: A Structured Programming Approach Using C 18
Points to remember
1. C program must have at least one function
2. If program have one function it must be main
3. If program have more than function, in which one mustbe main because program execution starts from thatonly.
4. We can use unlimited no of functions in one program.
5. Each function is called in the sequence we havespecified in the main function.
6. After each function task is over the control passed to thecalling function(main()).
7
8/8/2019 Functions and Macros
19/69
Computer Science: A Structured Programming Approach Using C 19
main(){printf(\n I am calling other functions);func1();
func2();func3();Printf(all functions are called\n);}//mainfunc1(){printf(in func1\n);}//func1
func2(){printf(in func2\n);}//func2func3(){printf(in func1\n);}//func3
Output:
I am calling other functionin func1in func2in func3all functions are called.
8/8/2019 Functions and Macros
20/69
Computer Science: A Structured Programming Approach Using C 20
7 One function can also call the other function which has alreadybeen called.main()
{printf(I am in main\n); outputfunc1(); I am in mainprintf(I back in main\n); in func1}//mainfunc1() In func2{ In func3printf(in func1\n); I back in func2func2(); I back in func1printf(I back in func1\n); I back in main}//func1func2(){printf(In func2\n);func3();printf(I back in func2\n);}//func2func3(){printf(in fac3\n);}//func3
8/8/2019 Functions and Macros
21/69
Computer Science: A Structured Programming Approach Using C 21
FIGURE 4-5 Declaring, Calling, and Defining Functions
8/8/2019 Functions and Macros
22/69
Computer Science: A Structured Programming Approach Using C 22
FIGURE 4-6 voidFunction with Parameters
8/8/2019 Functions and Macros
23/69
Computer Science: A Structured Programming Approach Using C 23
PROGRAM 4-2 voidFunction with a Parameter
8/8/2019 Functions and Macros
24/69
Computer Science: A Structured Programming Approach Using C 24
PROGRAM 4-2 voidFunction with a Parameter
8/8/2019 Functions and Macros
25/69
Computer Science: A Structured Programming Approach Using C 25
PROGRAM 4-2 voidFunction with a Parameter
8/8/2019 Functions and Macros
26/69
Computer Science: A Structured Programming Approach Using C 26
FIGURE 4-7 Non-void Function without Parameters
8/8/2019 Functions and Macros
27/69
Computer Science: A Structured Programming Approach Using C 27
FIGURE 4-8 Calling a Function That Returns a Value
8/8/2019 Functions and Macros
28/69
Computer Science: A Structured Programming Approach Using C 28
PROGRAM 4-3 Read a Number and Square It
8/8/2019 Functions and Macros
29/69
Computer Science: A Structured Programming Approach Using C 29
PROGRAM 4-3 Read a Number and Square It
8/8/2019 Functions and Macros
30/69
Computer Science: A Structured Programming Approach Using C 30
PROGRAM 4-3 Read a Number and Square It
8/8/2019 Functions and Macros
31/69
Computer Science: A Structured Programming Approach Using C 31
PROGRAM 4-3 Read a Number and Square It
8/8/2019 Functions and Macros
32/69
Computer Science: A Structured Programming Approach Using C 32
FIGURE 4-9 Function Definition
8/8/2019 Functions and Macros
33/69
Computer Science: A Structured Programming Approach Using C 33
Categories of functions
Based on the functions return type and itsarguments the functions are categorized into 4different types.
1. Functions with no arguments and no returnvalues
2.Functions with no arguments and return values
3. Functions with arguments and no return values4. Functions with arguments and return values
8/8/2019 Functions and Macros
34/69
Computer Science: A Structured Programming Approach Using C 34
1. Functions with no arguments
and no return values* This type of function has no arguments,meaning that it does not receive any data fromthe calling function.
Simillary this type of function will not return anyvalue.
Here the calling function does not receive anydata from the called function. In effect, there isno data transfer between the calling functionand the called function.
8/8/2019 Functions and Macros
35/69
Computer Science: A Structured Programming Approach Using C 35
Example//C program to find sum of two numbers using functions with no arguments and
no return values
#include void sum (); void main () { clrscr (); sum (); /*calling function */ getch (); } void sum () { int x, y, z; printf (\n Enter the values of x and y: ); scanf (%d%d, &x, &y); z=x+y; printf (\n The sum = %d,z); }
8/8/2019 Functions and Macros
36/69
Computer Science: A Structured Programming Approach Using C 36
2. FUNCTIONS WITH NO ARGUMENTS AND RETURN VALUES
There are two ways that a function terminatesexecution and returns to the caller.
1. When the last statement in the function has
executed and conceptually the functions ending} is encountered.
2. Whenever it faces return statement.
there is no data transfer from the calling functionto the called function. But, there is data transferfrom called function to the calling function.
8/8/2019 Functions and Macros
37/69
Computer Science: A Structured Programming Approach Using C 37
example// C program to find sum of two numbers using functions with no arguments and return values
#include int sum ();
void main () { int c; clrscr (); c=sum (); /*calling function */ printf (\n The sum = %d, c); getch (); } int sum () { int x, y;
printf (\n Enter the values of x and y: ); scanf (%d%d, &x, &y); return (x+y); }
8/8/2019 Functions and Macros
38/69
Computer Science: A Structured Programming Approach Using C 38
3. FUNCTIONS WITH ARGUMENTS AND NO RETURN VALUES
In this category there is data transfer from the calling function to thecalled function using parameters. But, there is no data transfer fromcalled function to the calling function.
Function arguments The arguments that are supplied in to two categories 1. actual arguments/parameters 2. formal arguments/parameters
Actual arguments/parameters Actual parameters are the expressions in the calling functions.
These are the parameters present in the calling statement (functioncall).
formal arguments/parameters formal parameters are the variables that are declared in the header
of the function definition. These list defines and declares that willcontain the data received by the function. These are the valueparameters, copies of the values being passed are stored in thecalled functions memory area.
Note:Actual and Formal parameters must match exactly in type,order, and number. Their names however, do not need to match.
8/8/2019 Functions and Macros
39/69
Computer Science: A Structured Programming Approach Using C 39
->the values of actual arguments are assigned to the formal arguments.func1(x1, x2, x3,xn);
| | | |
func1(y1, y2, y3,yn)
->In case, the actual arguments are more than the formal arguments , extraactual arguments are discarded.
-> on other hand, the formal arguments are more, the extra formal argumentsare initialized to some garbage values.
-> if any mismatch found in their data type may also takes some value. No
error is reported.
8/8/2019 Functions and Macros
40/69
Computer Science: A Structured Programming Approach Using C 40
example//C program to find sum of two numbers using functions with arguments and no return values
#include void sum (int ,int ); void main () { int a, b; clrscr (); printf (\n Enter the values of a and b: );
scanf (%d%d, &a, &b); sum (a, b); /*calling function */ getch (); } void sum (int x, int y) { int z; z=x+y; printf (\n The Sum =%d, z); }
8/8/2019 Functions and Macros
41/69
Computer Science: A Structured Programming Approach Using C 41
4. FUNCTIONS WITH ARGUMENTS AND RETURN
VALUES
In this category there is data transferbetween the calling function and calledfunction.
8/8/2019 Functions and Macros
42/69
Computer Science: A Structured Programming Approach Using C 42
example
//C program to find sum of two numbers using functions with arguments and return values
#include
int sum (int ,int ); void main () { int a, b; clrscr (); printf (\n Enter the values of a and b: ); scanf (%d%d, &a, &b); c=sum (a, b); /*calling function */ printf (\n The Sum =%d, c); getch (); }
int sum (int x, int y) { int z; return x+y; }
8/8/2019 Functions and Macros
43/69
Computer Science: A Structured Programming Approach Using C 43
Note: generally we are using functions with argumentsand return values (category 4) in our applications. Whybecause the job of a function is to perform a well-
defined task, it carries inputs and sends result afterexecuted. In real world the programming teams codesthe modules (functions) according to the input
(arguments) given by the team coordinators.
8/8/2019 Functions and Macros
44/69
Computer Science: A Structured Programming Approach Using C 44
Recursion
In c, a function calls itself is called recursion.I
t is a repetitive process where function is called itself.Ex:-main(){printf(recursion\n);main();
}//mainoutput:recursion..
. Any problem that can be solved recursively can also be solved iteratively
(using loop). Recursive functions are slow and takes a lot of memory space
compared to iterative functions.
8/8/2019 Functions and Macros
45/69
Computer Science: A Structured Programming Approach Using C 45
Example: Recursive factorial function//C program to find the factorial using recursion.fact (n)= n(n-1)(n-2)----1fact(5)= 5*4*3*2*1=120
#include #includelong int factorial(long int x);main(){long int n,fact;printf(enter the number\n);scanf(%ld, &n);fact=factorial(n);printf(factorial of a number=%ld,fact);}//mainfactorial(long int x){long int f;if(x==1)return 1;elsef= x*factorial(x-1);return(f);}//factorial()
8/8/2019 Functions and Macros
46/69
Computer Science: A Structured Programming Approach Using C 46
Factorial of a number using non-recursive function (iterative method)long int factorial(int x);main(){
long int n,fact;printf(enter n value\n);scanf(%ld,&n);fact=factorial(n);printf(factorial value=%ld,fact);}//mainfactorial(int x);
{long int f=1,i;for(i=x;i>=1;i--)f=f*i;return (f);}//factorial();
Out putenter n value5factorial value= 120
8/8/2019 Functions and Macros
47/69
Computer Science: A Structured Programming Approach Using C 47
Return statement
1. When return statement encounter the control transferred back to thecalling function.
2. It returns the value present in its parenthesis to the calling function.
3. We can use any number of return statements in the functions. Howeverit returns only single value.
4. Return statement need not be present at end of the function.
5. Function should return only one value at a time.
return (a,b);-> invalid gives the error.
8/8/2019 Functions and Macros
48/69
Computer Science: A Structured Programming Approach Using C 48
Scope and life time of variable in functions
Scope of the variable:- determines whatparts of the program can have access thevariable or what parts of the program avariable is available for use (active).
Life time of a variable (longitivity)
How long the variable retains its valueduring execution of a program (alive)
8/8/2019 Functions and Macros
49/69
Computer Science: A Structured Programming Approach Using C 49
Storage classes in c
The variables are stored in computer.
- Basically variables are stored in computer in two locations.
- 1. memory 2. registers.
- Location of the variable to store is determined by the storage
classes.- It also tells us the following
1. where the variable would be stored.
2. what is initial value of the variable, if variable is not initializedwhile declaring.
3. what is the scope of the variable; i.e in which functions thevalue of the variable would be available.
4. what is the life of a variable; i.e how long variable would beexist.
8/8/2019 Functions and Macros
50/69
Computer Science: A Structured Programming Approach Using C 50
There are four storage classes:
1. Auto storage class
2. Static storage class
3. Extern storage class4. Register storage class
8/8/2019 Functions and Macros
51/69
8/8/2019 Functions and Macros
52/69
Computer Science: A Structured Programming Approach Using C 52
Features of auto variable when they declared
Storage Memory
Default initial value garbage value
Scope local to the block
in which variabledefined
Life remains within theblock in whichvariable defined.
8/8/2019 Functions and Macros
53/69
Computer Science: A Structured Programming Approach Using C 53
Example- auto
main(){auto int x=10;{auto int x=20;
{auto int x=30;printf(%d,x);// 30
}printf(%d,x);//20
}Printf(%d,x);//10}//main
8/8/2019 Functions and Macros
54/69
Computer Science: A Structured Programming Approach Using C 54
Static storage classes
syntax-
static type identifier;
A variable with a static extent is created andinitialized to its value when the function
executed for first time and destroyed when it is
exit from the function. This is true no matter
how many times the declaration is encountered
during the execution.
8/8/2019 Functions and Macros
55/69
Computer Science: A Structured Programming Approach Using C 55
Features of static variable
- Storage -------- Memory
- Default initial value ----- zero
- Scope ------------ Local to the block inwhich the variable is defined.
- Life --------- value of the variable persistsbetween different function calls.
- Once memory is allocated to the staticvariable is persists its value until he end ofthe program
8/8/2019 Functions and Macros
56/69
Computer Science: A Structured Programming Approach Using C 56
example
main(){demo1();demo1();demo1();
}//maindemo1(){static int i=1;
printf(%d\n,i);i++;
}//demo1()output:123
8/8/2019 Functions and Macros
57/69
Computer Science: A Structured Programming Approach Using C 57
Auto example
main(){demo1();demo1();demo1();
}//maindemo1(){auto int i=1;
printf(%d\n,i);i++;
}//demo1()output:111
8/8/2019 Functions and Macros
58/69
Computer Science: A Structured Programming Approach Using C 58
Extern (external storage classes)
Syntaxextern type identifier;extern int i;features
- This variables or also called global variables.- These are declared outside of any function.- Storage memory- Default initial value- 0- Scope- global can access even outside of the function.- Life- through out the program execution.- Any variable defined outside of the function by default
treated as extern variable.
8/8/2019 Functions and Macros
59/69
Computer Science: A Structured Programming Approach Using C 59
exampleint i;main()
{
printf(\n%d=,i);
demo1();
demo1();
demo2();
demo2();
}//main
demo1()
{i++;
printf(\n%d,i);
}//demo1()
demo2()
{
i--;printf(\n%d,i);
}//demo2()
Output
0
12
1
0
8/8/2019 Functions and Macros
60/69
Computer Science: A Structured Programming Approach Using C 60
Register storage class
- Special case of the auto storage class
- Syntax
register type identifier;
- storage- registers
- default initial value- garbage value
- scope local to the block in which the variable
is defined.- life value persists within the block in which
the variable is defined.
8/8/2019 Functions and Macros
61/69
Computer Science: A Structured Programming Approach Using C 61
Preprocessor directives-macros
Preprocessor:- a program used to process asource code before the compilation.
-
Preprocessor has several features calledpreprocessor directives which are startwith a symbol #.
- Preprocessor directives can placed any
where in the program.
8/8/2019 Functions and Macros
62/69
Computer Science: A Structured Programming Approach Using C 62
Macro expansion
The following syntax is used to define a macro:
#define macro_name() macro_body
#define is a define directive, macro_name is a valid C identifier.macro_body isused to specify how the name is replaced in the program before it is compiled.
Macro_name- macro definition.
Macro_body- macro expansion.Ex:-
# define PI 3.14
main()
{
float area, r= 2.8;
area = PI * r*r;printf(area= %d,area);
}//main
8/8/2019 Functions and Macros
63/69
Computer Science: A Structured Programming Approach Using C 63
What is the purpose of macro
Preprocessor replaces the every occurrence of PI in theprogram before compilation.
Before compilation, preprocessor checks for the macroname used in the directives, when it finds replace
macro name with the macro body. Once this process over the preprocessor handover to the
compiler.
A constant value appears many times through out theprogram, you may need to be changed later. manuallyyou need to change each occurrence of that constant.however, if u define that constant using the macro ,youonly need to make one change in the macro body.
8/8/2019 Functions and Macros
64/69
Computer Science: A Structured Programming Approach Using C 64
It is customized to use the macro namesin capital letters.
Macro names and macro body separatedby space.
Space between # and define is optional.
Macro definition never end withsemicolon.
8/8/2019 Functions and Macros
65/69
Computer Science: A Structured Programming Approach Using C 65
- # define directive is used to define operators.# define PLUS +
main(){int c;c= 10 PLUS 20;}//main()- # define directive could be used even to replace a condition.- Ex:- #define EX a>b- main()- {- int a=10,b=20;-
if (EX)- printf(a is big\n);- else- printf(b is big);- }//main-
8/8/2019 Functions and Macros
66/69
8/8/2019 Functions and Macros
67/69
Computer Science: A Structured Programming Approach Using C 67
Macros with arguments
Macro can also have arguments as same as function
have.//C program Illustrating usage of Macro
#include
#define square(x) (x*x)
int main()
{
int a=10;
printf("\nThe square of %d=%d",a,square(a));
return 0 ;}
OUTPUT
The square of 10=100
8/8/2019 Functions and Macros
68/69
Computer Science: A Structured Programming Approach Using C 68
Dont leave space between the macro name and its arguments.ex:- SQUARE (n) Macro body should be enclosed within parenthesis.ex:-#define SQUARE(n) n*nmain(){int a;a=64/SQUARE(4);printf(a=%d,a);
}//main- Macros can split into multiple lines, with a \(back slash) present at the end of the
each line.ex:#define ABC for(i=0;i
8/8/2019 Functions and Macros
69/69
macros versus functions
In a macro name is encountered the preprocessorreplaces it with macro body without thinking, someliteral way, whereas in function call the control passed toa called function with some arguments, it perform sometask and at end return some value to the calling
function. Macros make the program run faster but increase the
program size, whereas functions make the programsmaller and compact (less space).
Passing arguments to a function and getting back the
returned value would take time and make the programslow this is avoided in macros, since it has already beenreplaced with is macro body before compilation.