Seenu PSC Unit4 Functions Recursion PreProcsrcomnds
Seenu PSC Unit4 Functions Recursion PreProcsrcomnds
Modular Programming
Modular programming is about if the size of the problem to be solved is too big then
the complexity of problem increases and requires lengthy program to implement it. Lengthy
programs are complex to understand and difficult to Debug. So Modular Programming is all
about Dividing a Large Complex Problem in to a number of smaller problems, to which we can
easily find the solutions. When we combine these small Solutions that will solve our Large
Problem. This concept is called Modularity. The big program is divided into smaller parts called
as modules. Dividing the program into a main module and its related modules is called as top-
down design. The above approach of solving the problems is called as designing top-down
structured programs. In C language Modular Programming is Implemented with Functions.
Modular Programming
The main module is known as calling module and the sub module is known as called module.
Functions
Introduction
In C, the idea of top-down design is done using functions. A C Program is collection of
one or more functions, Every program must have at least one function i.e) main function. The
execution of any C program always starts and ends with main, but it can call other functions to
do special tasks.
A function in C (including main) is a Self contained block of statements to do a specific task.
Function performs the task only when it is called. A called function receives control from the
calling function. When the called function completes its task, it returns control to the calling
function. It may or may not return a value to the caller.
Note: The function main is called by the operating system, main in turn calls other functions.
Users can create their own functions for performing any specific task of the program.
These types of functions are called user-defined functions. main() is an example of user-
defined function. Every function must be both declared and defined. The function
declaration, which needs to be done before the function call, gives the whole picture of the
function that needs to be defined later. The function definition, which is traditionally coded
after the function that makes the call, contains the code needed to complete the task.
Note : A function name is used three times : for declaration, in a call, and for definition
To create and use these functions, we should know about these three things
1. Function Definition
2. Function Declaration
3. Function Call
For Example:
// Function Declaration
void display(void);
int main(void) void display(void)
{ {
//statements printf(“SVECW\n”);
display(); // Function Call
return 0; }
}
Output: SVECW
Function Declaration :
A function definition, also known as function implementation shall include the
following elements;
1. Function name
2. Function type
3. List of parameters
4. Local variable declarations
5. Function statements and
6. A return statement
1. Return Type
2. Function Name
3. List of parameters
Return Type:
The Return type specifies the type of value(like float or double) that the function is
expected to return to the program calling the function. If the return type is not
explicitly specified, C will assume that it is an integer type. If the function is not
returning anything, then we need to specify the return type as void. void is one of
the data type. The value returned is the output produced by the function.
Function Name:
The function name is any valid C identifier and therefore must follow the same
rules of formation as other variable names in C. The name should be meaningful for
the task performed by the function. However, care must be taken to avoid
duplicating library routine names or operating system commands.
List of Parameters:
The parameter list declares the variables that will receive the data sent by the
A function need not always receive values from the calling program. In such
cases, functions have no formal parameters. To indicate the parameter list is
empty, we use the keyword void between the parentheses as
Example: fun(void){ …. }
Example: fun()
Function Body:
The function body contains the local declarations and statements necessary for
performing the required task. The body enclosed in braces, contains three parts, in
the order given below:
C has the facility to provide library functions for performing some operations. These
functions are predefined and exists in the C library functions. For example sqrt() is a
mathematical library function which is used to finding out the root of any number defined in
math.h header file. The source code of the library functions is not given to the user. These
functions are precompiled and the users gets only the object code. This object code is linked
to the object code of your program by the linker. Different categories of library functions are
grouped together in separate library files. When a library function in our program is called
then the linker selects the code of that function from the library file and adds it to the
program. Any function will have function definition, declarations and call.
Library Function:
1. Function Definition – Predefined, precompiled
2. Function Declaration– In header files(files with .h extension)
3. Function Call _ By the programmer.
In this type there are no arguments, so it does not receive any data from the calling function.
Similarly, there is no return type, the calling function does not receive any data from the called
void sum(void){
int x,y,total;
printf(“enter x and y values=\n”);
scanf(“%d%d”,&x,&y);
total=x+y;
printf(“sum=%d\n”,total);
}
Example: #include<stdio.h>
void sum(int a,int b);
int main(){
int x,y;
printf(“enter x and y values=\n”);
scanf(“%d%d”,&x,&y);
sum(x,y);
return 0;
}
Example: #include<stdio.h>
int sum(void);
int main(){
int sum(void){
int x,y;
printf(“enter x and y values=\n”);
scanf(“%d%d”,&x,&y);
return(x+y);
}
4.FUNCTIIONS WITH RETURN TYPE AND WITH PARAMETERS:
In this type there are parameters, so the calling function does passes arguments to called
function and it also uses return type. Hence the calling function does receive a value from
called function. In other wards there is data transfer between the calling function to the called
function and as well as it does have a data transfer from the called function to the calling
function.
Example: #include<stdio.h>
int sum(int a,int b);
int main(){
int x,y,total;
printf(“enter x and y values=\n”);
scanf(“%d%d”,&x,&y);
total=sum(x,y);
printf(“total=%d\n”,total);
return 0;
}
int sum(int a,int b){
return(a+b);
}
Downward Flow:
In downward communication, the calling function sends data to the called
function. No data flows in the opposite direction. In this strategy, copies of the data items
are passed from the calling function to the called function. The called function may change
the values passed, but the original values in the calling function remain untouched.
Example: call-by-value
#include<stdio.h>
void main()
{
int x=2,y=3,z=0;
add(x,y);
}
void add(intx,int y)
{
int z;
z=x+y;
printf(“%d”,z);
}
Upward Flow:
Upward communication occurs when the called function sends data back to the called
function without receiving any data from it.
Example: call-by-reference
#include<stdio.h>
void main()
int x=2,y=3,z=0;
modify(&x, &y);
printf((“%d%d”,x,y);
*x=10;
*y=20;
Bi-directional Flow:
void main()
int x=2,y=3,z=0;
modify(&x, &y);
printf((“%d%d”,x,y);
*x=*x+10;
*y=*y+20;
// Block scope
}
STORAGE CLASSES:
The Storage classes are used to describe Four Properties of any variable. These four properties
are
1) Storage area
2) Initial value
3) Scope
4) Life time
The concept of storage class modifiers is used for the purpose of efficient utilization of
variables . These are used to tell the compiler how the variable that follows should be
stored.
Auto: The variables generally declared in any function are called automatic variables. Even
if the storage class is not specified they become auto by default.
Example :
int main(){
int a,b,c;
is equal to
auto int a,b,c;
The scope of these variables is that they are active only within the function or a block in which
they are declared. These are also called as ‘Local Variables’.
Ex Pgm: #include<stdio.h>
void main()
{
auto int x=2;
printf(“%d”,x);
}
Static: The variables that are declared and initialized in a function are normally initializing
the variables for every function call and process further, but if we expect the function should
initialize only once and process further then we go to the declaration of variable to be static.
void add()
{
x++;
Printf(“%d”,x);
}
Output: 1 2 3
Register: The variables generally declared in functions normally allocate the memory in the
stack memory. The variables declared using register allocate the memory in CPU registers.
The speed of Register type of memory is more than the speed of stack memory. The
declaration looks like this.
Example: register int a,b,c;
The scope of these variables is that they are active only within the functions in which they are
declared. Generally loop variables are declared using register storage class
Extern: The variables declared in a file are to be referenced by the variables in another files
then such kind of variables can be accessed among the files by declaring the variable to be
extern;
Storage area: Memory
Initial value: Zero
Scope: throw out the Program.
Life time: Until the end of the execution of main program.
Example program:
first.c second.c
#include<stdio.h> int m;
#include”second.c” void add()
extern int m; {
int main() printf(“%d”, m+m);
{ }
m=2;
add();
}
TYPE QUALIFIERS:
Type Qualifiers are used to qualify types, modifying the properties of variables in certain
ways.
Constant Type Qualifier: The keyword for the constant type qualifier is const. A constant
variable is a read-only variable. A simple constant is show below
Example :const double pi = 3.14;
Volatile Type Qualifier: The volatile qualifier tells the computer that a variable may be
changed by entities other than this program. Such as a variable declared for storing and
updating date needs to be changed externally according to system’s time.
Example: volatile double seconds;
Restrict Type Qualifier: The restrict qualifier , which is used only with pointers, indicates that
the pointer is only the initial way to access the dereferenced data.
RECURSION
Recursion is a repetitive process in which a function calls itself. The process of repetition can
be done in two ways using programming. They are
Iterative Definition
Recursive Definition
Iterative Definition:
Repeating a set of statements using loops is referred as Iteration.
Recursive Definition:
A repetitive function is defined recursively whenever the function appears within the
definition itself. The recursive function has two elements : each call either solves one part of
the problem or it reduces the size of the problem. The statement that solves the problem is
known as the base case. The rest of the function is known as the general case. Each
recursive function must have a base case.
Example: Finding Factorial of a number using recursive function.
Let the number be 4, then
4! =4x3x2x1
If n is the number then
n!=nx(n-1)x(n-2)x(n-3)x(n-4)……x(n-n)
or
n!=nx(n-1)!
(n-1)!=(n-1) x (n-2)!
(n-2)!=(n-2)x(n-3)!
………………………………………
(n-n)!=1
In combining the base and general cases into a function, we must pay careful attention to
the logic. The base case, when reached, must terminate without a call to the recursive
function; that is, it must execute a return.
Program:
#include<stdio.h>
int factorial(int );
int main()
{
int n,result;
printf(“enter the number”);
scanf(“%d”,&n);
result=factorial(n);
int factorial(int n)
{
if(n==0)
return 1;
Else
return(nxfactorial(n-1));
}
Factorial=120
Limitations of Recursion:
1. Recursive solutions may involve extensive overhead because they use function calls.
2. Each time you make a call, you use up some of your memory allocation.
The C Compiler is made of four functional parts: a preprocessor, compiler, linker and loader.
The preprocessor executes all the commands that starts with #. Preprocessor expands the Source
code. The Compiler converts the C program into in to machine code or object code.
The preprocessor can be thought of as a smart editor. Like a smart editor, it inserts, includes,
excludes, and replaces text based on commands supplied by the programmer.
File Inclusion:
The file inclusion copies one or more files into programs. The files are usually header
files that contain function and data declarations for the program, but they can contain any
valid C statement.
The first format is used to direct the preprocessor to include header files from the standard
directory like C:\Program Files\turboc2\ . In this format, the name of the header file is enclosed
in angular brackets.
#include<filename.h>
The second format makes the preprocessor look for the header files in the user-defined
directory. In this format, the name of the file pathname is enclosed in double quotes.
#include “filename.h”
Macro Definition:
A macro definition command associates a name with a sequence of tokens. The name
is called the macro name and the tokens are referred to as the macro body .
Syntax: #define macro_name body
The body is the text that is used to specify how the name is replaced in the program
Macros are similar to Functions.We simulate a function with a macro, the macro
definition replaces the function definition. The macro name serves as the
header and the macro body serves as the function body. The name of the macro
is used in the program to replace the function call.
Ex:
void flush(void); void flush(void)
int main(void) {
{ printf(“flush”);
……. }
flush();
…………..
}
c) Macros simulate functions with parameters:
Example:
#define \
PRODUCT (x,y) x * y
e) Undefining Macros
Once defined, a macro command cannot be redefined. Any attempt to redefine
it will result in a compilation error. However it is possible to redefine a macro by
first undefining it, using the #undef command and defining it again as show
below:
#define SIZE 10
….
#undef SIZE
#define SIZE 20
_ _FILE_ _ Provides a string constant containing the name of the source file
Conditional Compilation:
Conditional compilation allows us to control the compilation process by including or
excluding statements.
Two-way commands
The two-way command tells the preprocessor to select between two choices.
General Syntax:
#if expression
Code to be included if expression is true
#else
Code to be included if expression is false
#endif
The expression is a constant value that evaluates to zero or non-zero. If the value is non-zero,
it is interpreted as true and the code after #if is included. If it is zero, it is interpreted as false
and the code after #else is executed.
#if part or #else part may be empty.
Sets the next line of the program to 100. that can be checked by the
predefined command LINE__.
Usage two: #line 100 “Myprogram.c”
Sets the next line number to 100 and creates a name for the program
that can be checked by the predefined macro call __FILE
Error Command:
The error command is of the form
#error message
It is used to print the message detected by the preprocessor .
Example:
int main()
{
int i,a[5];
printf(“enter the elements”);
for(i=0;i<5;i++)
scanf(“%d”,&a[i]);
printarray(a);
}
void printarray(int arr[5])
{
For(i=0;i<5;i++)
printf(“%d”,arr[i]);