0% found this document useful (0 votes)
2 views24 pages

Seenu PSC Unit4 Functions Recursion PreProcsrcomnds

Modular programming is a technique that breaks down complex problems into smaller, manageable modules, making programs easier to understand and debug. In C, this is implemented through functions, which can be user-defined or predefined, allowing for organized code and efficient problem-solving. The document also covers function types, inter-function communication, scope, and storage classes in C programming.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views24 pages

Seenu PSC Unit4 Functions Recursion PreProcsrcomnds

Modular programming is a technique that breaks down complex problems into smaller, manageable modules, making programs easier to understand and debug. In C, this is implemented through functions, which can be user-defined or predefined, allowing for organized code and efficient problem-solving. The document also covers function types, inter-function communication, scope, and storage classes in C programming.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 24

UNIT-IV

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.

A.Seenu, CSE Dept, SVECW


C Functions are of two types
They are: a) User-defined Functions
b) Pre defined or Library or Built in Functions
a) User-Defined 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

A.Seenu, CSE Dept, SVECW


All the six elements are grouped into two parts, namely,

 Function header(function name, function type, list of parameters)


 Function body(Local variable declarations, Function statements, a return
statement)

A general format of a function definition to implement these two parts is given


below:

Syntax: return_type function_name(parameter list)


{
Local variable declarations;
Executable statement1;
Executable statement2;
……………
…………..
Return statement;
}
Function Header:

The function Header consists of the following three parts:

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.Seenu, CSE Dept, SVECW


calling program. They serve as input data to the function to carry out the specified
task. The parameters are also called as arguments.

Example: fun(int a, int b){ …. }

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){ …. }

Some compilers may also accept this type of declaration.

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:

1. Local declarations that specify the variables needed by the function.


2. Function statements that perform the task of the function
3. A return statement that returns the task of the function.(optional)

*Note : we can omit return statement if there is no return value.

b) Pre defined or Library or Built in Functions:

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.

A.Seenu, CSE Dept, SVECW


The functions scanf() and printf() are input, output library function defined in stdio.h header
file
To use a library function in our program we should know:
1) Name of the function and its purpose
2) Type and number of arguments it accepts
3) Type of the value it returns
4) Name of the header file to be included.

We use the an example of using a calculating a square root of a number.


1) Function name is sqrt for calculating square root of a number
2) It accepts integer as data type and one input parameter
3) It returns a integer value
4) It is included in the header file math.h

Example: Program used to print the square of a number.


#include<stdio.h>
#include<math.h>
void main()
{
Int x;
X=sqrt(16);
printf(“%d”,x);
}
In the above program there two library functions printf(),sqrt().
*Note : main() is not a library function.
A function, depending on whether arguments are present or not and whether a value is
returned or not, may belong to one of the following types.
1. Functions with no return type and no parameters.
2. Functions with no return type and with parameters.
3. Functions with return type and no parameters.
4. Functions with return type and with parameters.

1.FUNCTIIONS WITH NO RETURN TYPE AND NO PARAMETERS:

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

A.Seenu, CSE Dept, SVECW


function. In effect, there is no data transfer between the calling function and the called function.
Example: #include<stdio.h>
void sum(void);
int main(){
sum();
return 0;
}

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);
}

2. FUNCTIIONS WITH NO RETURN TYPE AND WITH PARAMETERS:


In this type there are parameters, so the calling function passes arguments to called function.
but it does not uses return type. Hence the called function does not receive any value. the calling
function does not receive any data from the called function. In other wards there is data
transfer between the calling function to the called function, but not from the called function to
the calling function.

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;
}

void sum(int a,int b){


int total;
total=a+b;
printf(“total=%d\n”,total);
}

3.FUNCTIIONS WITH RETURN TYPE AND NO PARAMETERS:


In this type there are no parameters, so the calling function does not passes arguments to
called function. but it uses return type. Hence the calling function does receive a value from
called function. In other wards there is no data transfer between the calling function to the called
function, but it does have a data transfer from the called function to the calling function.

Example: #include<stdio.h>
int sum(void);
int main(){

A.Seenu, CSE Dept, SVECW


int total;
total=sum();
printf(“total=%d\n”,total);
return 0;
}

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);
}

Inter function Communication:


The Calling and called function are two separate entities, they need to communicate to
exchange data. The data flow between the calling and called functions can be divided into
three strategies

Calling Calling Calling


Function Function Function

Called Called Called


Function Function Function

A.Seenu, CSE Dept, SVECW


DOWNWARD FLOW UPWARD FLOW BI-DIRECTIONAL FLOW

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);

A.Seenu, CSE Dept, SVECW


voidmodify(int *x,int *y)

*x=10;

*y=20;

Bi-directional Flow:

A.Seenu, CSE Dept, SVECW


The strategy described for the upward direction can easily be augmented to allow the
communication in both directions. The only difference is that the indirect reference must be
used in both sides of the assignment variable.
#include<stdio.h>

void main()

int x=2,y=3,z=0;

modify(&x, &y);

printf((“%d%d”,x,y);

void modify(int *x,int *y)

*x=*x+10;

*y=*y+20;

A.Seenu, CSE Dept, SVECW


SCOPE:
Scope determines the region of the program in which a defined object is
visible – that part of the program in which we can use the object’s name. Scope pertains to
any object that can be declared such as a variable or a function declaration.
#include<stdio.h>
void main()
{
int x=2,y=3,z=0;
add(x,y);
//main scope
if()
{
// if scope
}
}
void add(intx,int y) //global scope
{ //
…………..
//Function’s scope
{

// Block scope
}

Variable declared in global scope are called as global variables


Variables declared in main function or sub-function are local variables to those respective
functions

A.Seenu, CSE Dept, SVECW


SCOPE RULES:
Scope Rules define the characteristics of the variables that are defined. It
includes the following three characteristics of variables. They are
1. Scope
2. Visibility
3. Life Time

Scope : The region of a program in which a variable is available for use.


Visibility: The program’s ability to access a variable from the memory.
Life Time: The Life time of a variable is the duration of time in which a variable exists in
the memory during execution.
Rules of use:
1) The scope of a global variable is the entire program file
2) The scope of a local variable begins at point of declaration and ends at the end
of the block or function in which it is declared.
3) The scope of a formal function argument is its own function.
4) The life time of an ‘auto’ variable declared in ‘main’ is the entire program
execution time, although its scope is only the ‘main’ function.
5) The life of an ‘auto’ variable declared in a function ends when the function is
exited.
6) A ‘static’ local variable, although its scope is limited to its function, its
lifetime extends till the end of program execution.
7) All Variables have visibility in their scope, provided they are not declared
again.
8) If a variable is re declared within its scope again, it loses its visibility in the
scope of the re declared variable

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.

A.Seenu, CSE Dept, SVECW


The General declaration form is
Storage_class Data type variable name;
There are four storage classes supported by C. They are
1) Auto
2) Register
3) Static
4) Extern

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.

For all auto variables:

Storage area: Memory


Initial value: Garbage value
Scope: Within the block where it is declared.
Life time: Until the execution control lies in the block.

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.

Storage area: Memory


Initial value: Zero
Scope: the value of a static variable persist between different function calls.
Life time: Until the end of the execution of program.

A.Seenu, CSE Dept, SVECW


Example: static int x;
The scope of these variables is within the function in which they are declared.
Ex pgm: :#include<stdio.h>
void main()
{
add();
add();
add();

void add()
{

static int x=0;

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;

Storage area: CPU registers.


Initial value: Garbage value
Scope: Within the block where it is declared.
Life time: Until the execution control lies in the block.

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

A.Seenu, CSE Dept, SVECW


Example Program: #include<stdio.h>
void main()
{
register int i;
for(i=0;i<n;i++)…..}

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.

A.Seenu, CSE Dept, SVECW


Example: restrict int * ptr;

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

4!=4x3! n=nx(n-1)! If n=4


3!=3x2! n=nx(n-1)! If n=3
2!=2x1! n=nx(n-1)! If n=2
1!=1x0! n=nx(n-1)! if n=1
0!=1 n1=1 if n=0

A.Seenu, CSE Dept, SVECW


In the above example ,
n=nx(n-1)! Is considered as general case as it is valid for all n values
n!=1 is considered as base case as the value of 0! and 1! are 1 with

which calculating the factorial terminates.


Base case: factorial(0)
General case: nxfactorial(n-1).
The execution order is as follows
4! = 4x3! (4x6=24)
3! = 3x2! (3x2=6)
2! = 2!x1 (2x1=2)
1! = 1x0! (1x1=1)
0!=1 (1=1)

The following are the rules for designing a recursive function:


1. First, determine the base case
2. Then, determine the general case
3. Finally, combine the base case and general case into a function

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);

A.Seenu, CSE Dept, SVECW


printf(“factorial=%d”,result);
}

int factorial(int n)
{
if(n==0)
return 1;
Else
return(nxfactorial(n-1));
}

Output: enter the number

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.

A.Seenu, CSE Dept, SVECW


PREPROCESSOR COMMANDS:

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.

All preprocessor commands start with a hash sign(#).

We first discuss three major tasks of a preprocessor :


 file inclusion
 macro definition
 conditional compilation

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 preprocessor command is #include, and it has two different formats.

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

A.Seenu, CSE Dept, SVECW


before it is translated.
a) Coding Defined Constants:

The simplest application of a macro is to define a constant. The following


example defines command for constant definition. The name is SIZE and the
body is 9.
Ex: #define PI 3.14
b) Macros that simulate functions:

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:

A.Seenu, CSE Dept, SVECW


The macro definitions are used to simulate simple function with parameters.
This is done in two steps
1. The body of the macro replaces the macro call with the same
actual parameters used in the macro definition.
2. The actual parameters are replaced with formal parameters.

Example:

#define \
PRODUCT (x,y) x * y

Intmain(void) int main(void)


{ {
… …
P=PRODUCT(4,5); p=x * y;
… …
} }
d) Nested macros:
C handles nested macros by simply rescanning a line after macro expansion.
Therefore, if an expansion results in a new statement with a macro, the second macro
will be properly expanded.
Ex:
#define PRODUCT(a,b) (a)*(b)
#define SQUARE(a) PRODUCT(a,a)

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

A.Seenu, CSE Dept, SVECW


f) Predefined Macros:
C language defines a set of predefined macros which is show in the table.
COMMAND MEANING
_ _DATE_ _ Provides a string constant in the form “mm ddyyyy”

_ _FILE_ _ Provides a string constant containing the name of the source file

_ _LINE_ _ Provides an integer constant containing the current statement number in


the source file.
_ _TIME_ _ Provides a string constant in the form “hh mm ss”.

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.

If #if part is empty then


#if expression #if expression
Code for non-zero expression  code for non-zero expression
#else #endif
#endif
If #else part is empty then
#if expression
#else #if !expression

A.Seenu, CSE Dept, SVECW


Code for zero expression  code for zero expression
#endif #endif
Multi-way commands
Conditional compilation can also be multi-way, selecting one of the choices among several.
The multi-way selection is possible with the use of else-if construct.
General Syntax:
#if expression1
Code to be included if expression1 is true
#elif expression2
Code to be included if expression2 is true
#else
Code to be included if both expressions are false
#endif
Other commands
Line command
The line command, which is used in two formats, can set the line number and
the filename for the program.

Usage one: #line 100

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:

#error CHECK THE INPUT AGAIN

A.Seenu, CSE Dept, SVECW


PASSING ARRAYS TO FUNCTIONS:
An entire array can be transferred to a function as a parameter. To transfer an array to a
function, the array name is enough without subscripts as an actual parameters within the
function call.
The corresponding formal parameters are written in same fashion, and must be declared as an
array in formal parameters declaration.
General Syntax:
void funccall(int , int[]);
main() void funccall(x,arr[])
{ {
int a[10],n;
…… }
Funccall(n,a);
…..
}
Example Program demonstrating passing an array of 5 elements to function print array;
#include<stdio.h>

void printarray(int arr[5]);

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]);

A.Seenu, CSE Dept, SVECW

You might also like