Module 4

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 29

MODULE : 4

WORKING WITH FUNCTIONS

Modular Approach

Modular programming is the process of

subdividing a computer program into separate sub-

programs. A module is a separate software

component. It can often be used in a variety of

applications and functions with other components

of the system.

Points which should be taken care of prior to

modular program development:

1. Limitations of each and every module should

be decided.

2. In which way a program is to be partitioned

into different modules.

3. Communication among different modules of

the code for proper execution of the entire

program.

Advantages :
1. Ease of Use :This approach allows

simplicity, as rather than focusing on the

entire thousands and millions of lines code

in one go we can access it in the form of

modules. This allows ease in debugging the

code and prone to less error.

2. Reusability :It allows the user to reuse the

functionality with a different interface

without typing the whole program again.

3. Ease of Maintenance : It helps in less

collision at the time of working on modules,

helping a team to work with proper

collaboration while working on a large

application.

Functions in C

A function is a set of statements that take inputs,

do some specific computation and produces

output.

The idea is to put some commonly or repeatedly

done task together and make a function so that


instead of writing the same code again and again

for different inputs, we can call the function.

The general form of a function is:

return_type function_name([ arg1_type arg1_name, ... ])

Code

int max(int x, int y)

    if (x > y)

      return x;

    else

      return y;

Why do we need functions?

 Functions help us in reducing code

redundancy. If functionality is performed at

multiple places in software, then rather than


writing the same code, again and again, we

create a function and call it everywhere.

This also helps in maintenance as we have

to change at one place if we make future

changes to the functionality.

 Functions make code modular. Consider a

big file having many lines of code. It

becomes really simple to read and use the

code if the code is divided into functions.

 Functions provide abstraction. For example,

we can use library functions without

worrying about their internal working.

FunctionDeclaration

A function declaration tells the compiler about the

number of parameters function takes, data-types

of parameters, and return type of function. Putting

parameter names in function declaration is

optional in the function declaration, but it is

necessary to put them in the definition.


ParameterPassingtofunctions

The parameters passed to function are

called actual parameters. For example, in the

above program 10 and 20 are actual parameters.

The parameters received by function are

called formal parameters. For example, in the

above program x and y are formal parameters.

There are two most popular ways to pass

parameters.
Pass by Value: In this parameter passing method,

values of actual parameters are copied to

function’s formal parameters and the two types of

parameters are stored in different memory

locations. So any changes made inside functions

are not reflected in actual parameters of caller.

Pass by Reference Both actual and formal

parameters refer to same locations, so any

changes made inside the function are actually

reflected in actual parameters of caller.

Parameters are always passed by value in C.

For example. in the below code, value of x is not

modified using the function fun().

Eg:1 #include <stdio.h>

void fun(int x)

x = 30;

}
int main(void)

int x = 20;

fun(x);

printf("x = %d", x);

return 0;

Output:

x = 20

eg :2 # include <stdio.h>

void fun(int *ptr)

*ptr = 30;

int main()

int x = 20;
fun(&x);

printf("x = %d", x);

return 0;

Output:

x = 30

Recursion

The process in which a function calls itself

directly or indirectly is called recursion and the

corresponding function is called a recursive

function.

Properties of Recursion:

 Performing the same operations multiple

times with different inputs.

 In every step, we try smaller inputs to make

the problem smaller.

 Base condition is needed to stop the

recursion otherwise infinite loop will occur.

// C code to implement Fibonacci series


#include <stdio.h>

// Function for fibonacci

int fib(int n)

{ // Stop condition

if (n == 0)

return 0;

// Stop condition

if (n == 1 || n == 2)

return 1;

// Recursion function

else

return (fib(n - 1) + fib(n - 2));

// Driver Code

int main()

// Initialize variable n.
int n = 5;

printf("Fibonacci series "

"of %d numbers is: ",

n);

// for loop to print the fibonacci series.

for (int i = 0; i < n; i++) {

printf("%d ", fib(i));

return 0;

Output

Fibonacci series of 5 numbers is: 0 1 1 2 3

WORKING
// C code to implement factorial

#include <stdio.h>

// Factorial function

int f(int n)

// Stop condition

if (n == 0 || n == 1)

return 1;

// Recursive condition

else
return n * f(n - 1);

// Driver code

int main()

int n = 5;

printf("factorial of %d is: %d", n, f(n));

return 0;

Output

factorial of 5 is: 120

WORKING
How Arrays are Passed to Functions in C

In C, when we pass an array to a function say

fun(), it is always treated as a pointer by fun(). The

below example demonstrates the same. 


#include <stdio.h>

void fun(int *arr, int n)

int i;

for (i=0; i<n; i++)

printf("%d ", arr[i]);

}
// Driver program

int main()

int arr[] = {1, 2, 3, 4, 5, 6, 7, 8};

int n ;

fun(arr, n);

return 0;

Output

1 2 3 4 5 6 7 8

Structures in C

A structure is a key word that create user defined

data type in C/C++. A structure creates a data type

that can be used to group items of possibly

different types into a single type. 

 
struct address

char name[50];

char street[100];

char city[50];

char state[20];
int pin;

};

How to declare structure variables?  

A structure variable can either be declared with

structure declaration or as a separate declaration

like basic types. 

// A variable declaration with structure declaration.

struct Point

int x, y;

} p1; // The variable p1 is declared with 'Point'

// A variable declaration like basic data types

struct Point

int x, y;
};

int main()

struct Point p1; // The variable p1 is declared like a

normal variable

How to initialize structure members?  

Structure members cannot be initialized with

declaration. For example the following C program

fails in compilation. 

 struct Point

int x = 0; // COMPILER ERROR: cannot initialize

members here

int y = 0; // COMPILER ERROR: cannot initialize

members here

};
Structure members can be initialized using curly

braces ‘{}’. For example, following is a valid

initialization. 

struct Point

   int x, y;

};

int main()

   // A valid initialization. member x gets value 0 and y

   // gets value 1.  The order of declaration is followed.

   struct Point p1 = {0, 1};

How to access structure elements?  

Structure members are accessed using dot (.)

operator. 

#include<stdio.h>
struct Point

   int x, y;

};

int main()

   struct Point p1 = {0, 1};

   // Accessing members of point p1

   p1.x = 20;

   printf ("x = %d, y = %d", p1.x, p1.y);

   return 0;

Union in C

Like Structures, union is a user defined data type. In

union, all members share the same memory location.


#include <stdio.h>

// Declaration of union is same as structures

union test {

int x, y;

};

int main()

// A union variable t

union test t;
t.x = 2; // t.y also gets value 2

printf("After making x = 2:\n x = %d, y = %d\n\

n",

t.x, t.y);

t.y = 10; // t.x is also updated to 10

printf("After making y = 10:\n x = %d, y = %d\n\

n",

t.x, t.y);

return 0;

Output:

After making x = 2:

x = 2, y = 2

After making y = 10:

x = 10, y = 10

Storage Classes in C
Storage Classes are used to describe the features

of a variable/function. These features basically

include the scope, visibility and life-time which

help us to trace the existence of a particular

variable during the runtime of a program.

C language uses 4 storage classes, namely:

o 1. Automatic variables are allocated memory automatically at runtime.

o The visibility of the automatic variables is limited to the block in which they
are defined.

The scope of the automatic variables is limited to the block in which they are
defined.

o The automatic variables are initialized to garbage by default.

o The memory assigned to automatic variables gets freed upon exiting from the
block.
o The keyword used for defining automatic variables is auto.

o Every local variable is automatic in C by default.

EXAMPLE
#include <stdio.h>  
int main()  
{  
int a; //auto  
char b;  
float c;   
printf("%d %c %f",a,b,c); // printing initial default value of automatic variables a, b, an
d c.   
return 0;  
1. }  

2.External
o The external storage class is used to tell the compiler that the variable defined as
extern is declared with an external linkage elsewhere in the program.
o The variables declared as extern are not allocated any memory. It is only declaration
and intended to specify that the variable is declared elsewhere in the program.
o The default initial value of external integral type is 0 otherwise null.
o We can only initialize the extern variable globally, i.e., we can not initialize the
external variable within any block or method.
o An external variable can be declared many times but can be initialized at only once.
o If a variable is declared as external then the compiler searches for that variable to be
initialized somewhere in the program which may be extern or static. If it is not, then
the compiler will show an error.

EXAMPLE

1. #include <stdio.h>  
2. int main()  
3. {  
4. extern int a; // Compiler will search here for a variable a defined and initialize
d somewhere in the pogram or not.   
5. printf("%d",a);  
6. }  
7. int a = 20;  

3.Static
o The variables defined as static specifier can hold their value between the multiple
function calls.
o Static local variables are visible only to the function or the block in which they are
defined.
o A same static variable can be declared many times but can be assigned at only one
time.
o Default initial value of the static integral variable is 0 otherwise null.
o The visibility of the static global variable is limited to the file in which it has declared.
o The keyword used to define static variable is static.

EXAMPLE
#include<stdio.h>  
static char c;  
static int i;  
static float f;   
static char s[100];  
void main ()  
{  
printf("%d %d %f %s",c,i,f); // the initial default value of c, i, and f will be printed.   
}  
4.Register
o The variables defined as the register is allocated the memory into the CPU registers
depending upon the size of the memory remaining in the CPU.
o We can not dereference the register variables, i.e., we can not use &operator for the
register variable.
o The access time of the register variables is faster than the automatic variables.
o The initial default value of the register local variables is 0.
o The register keyword is used for the variable which should be stored in the CPU
register. However, it is compiler?s choice whether or not; the variables can be stored
in the register.
o We can store pointers into the register, i.e., a register can store the address of a
variable.
o Static variables can not be stored into the register since we can not use more than
one storage specifier for the same variable.

EXAMPLE 
#include <stdio.h>  
int main()  
{  
register int a; // variable a is allocated memory in the CPU register. The initial default 
value of a is 0.   
printf("%d",a);  
}  

C Library Functions

The Standard Function Library in C is a huge library of sub-libraries, each of


which contains the code for several functions. In order to make use of these
libraries, link each library in the broader library through the use of header
files. The definitions of these functions are present in their respective header
files. In order to use these functions, we have to include the header file in the
program
C/C++ Preprocessors

As the name suggests, Preprocessors are programs that process our source
code before compilation. There are a number of steps involved between
writing a program and executing a program in C / C++.
You can see the intermediate steps in the above diagram. The source code
written by programmers is first stored in a file, let the name be “program.c“.
This file is then processed by preprocessors and an expanded source code
file is generated named “program.i”. This expanded file is compiled by the
compiler and an object code file is generated named “program.obj”. Finally,
the linker links this object code file to the object code of the library functions
to generate the executable file “program.exe”. 

Preprocessor programs provide preprocessor directives that tell the compiler


to preprocess the source code before compiling. All of these preprocessor
directives begin with a ‘#’ (hash) symbol. The ‘#’ symbol indicates that
whatever statement starts with a ‘#’ will go to the preprocessor program to
get executed. Examples of some preprocessor directives
are: #include, #define, #ifndef etc. Remember that the # symbol only
provides a path to the preprocessor, and a command such as include is
processed by the preprocessor program. For example, #include will include
extra code in your program. We can place these preprocessor directives
anywhere in our program. 

There are 4 Main Types of Preprocessor Directives:  


1. Macros
2. File Inclusion
3. Conditional Compilation
4. Other directives
Let us now learn about each of these directives in detail. 
1. Macros

Macros are pieces of code in a program that is given some name. Whenever
this name is encountered by the compiler, the compiler replaces the name
with the actual piece of code. The ‘#define’ directive is used to define a
macro.

2.File Inclusion

This type of preprocessor directive tells the compiler to include a file in the
source code program. There are two types of files that can be included by
the user in the program: 

Header files or Standard files: These files contain definitions of pre-defined


functions like printf(), scanf(), etc. These files must be included to work with
these functions. Different functions are declared in different header files. 

3. Conditional Compilation
Conditional Compilation directives are a type of directive that helps to
compile a specific portion of the program or to skip the compilation of some
specific part of the program based on some conditions. This can be done
with the help of the two preprocessing commands ‘ifdef‘ and ‘endif‘. 

.4.Other Directives 

Apart from the above directives, there are two more directives that are not
commonly used. These are: 
#undef Directive: The #undef directive is used to undefine an existing
macro.
#pragma Directive: This directive is a special purpose directive and is used
to turn on or off some features. This type of directives are compiler-specific,
i.e., they vary from compiler to compiler.

You might also like