Programming Modules

You might also like

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

PROGRAMMING MODULES

As earlier mentioned, modular programming is the process of subdividing a computer program


into separate sub-programs. A module is a separate program component. It can often be used in a
variety of applications and functions with other components of the system. Similar functions are
grouped in the same unit of programming code and separate functions are developed as separate
units of code so that the code can be reused by other applications.

Object-oriented programming (OOP) is compatible with the modular programming concept to a


large extent. Modular programming enables multiple programmers to divide up the work and
debug pieces of the program independently.

Some of the commonly used modules in programming are: header files, functions prototypes,
definitions and invocations, files, classes, Java Beans, etc.

1. FUNCTIONS

A function is a group of statements that together perform a specific task. Every C/C++/Java
program has at least one function, which is main(), and all the most trivial programs can define
additional functions. You can divide up your code into separate functions i.e functions are the
building blocks of a program. They are also known as sub-programs.

Functions are used in a program for various reasons such as the following:

 Avoid repetition of codes.


 Increases program readability.
 Divide a complex problem into simpler ones.
 Reduces chances of error.
 Modifying a program becomes easier by using function.
 Easier to manage

To use a function in a program, it will require a declaration or what is popularly known as a


prototype. Just like a blueprint, the prototype gives basic structural information: it tells the
compiler what the function will return, what the function will be called, as well as what
arguments can be passed to the function.

Some functions are intrinsic. This means they are already defined within the language. They are
inbuilt into the language. They don’t need to be defined again. These functions include pow(),
sqrt(), rand(), max(), min(), printf(), scanf(), main(), etc. eg double b=sqrt(a); - means that
calculate the square root of value a, and store the result in variable b.

Most functions in a program are however extrinsic. This means the programmer has to define the
function himself/herself.

The general syntax for declaring a function therefore is:

return_type function_name( parameter list )

1
{
body of the function
}

Thus a function definition in C programming consists of a function header and a function body.
Here are all the parts of a function:

 Return Type − A function may return a value. The return type is the data type of the
value the function returns. Some functions perform the desired operations without
returning a value. In this case, the return_type is the keyword void.
 Function Name − This is the actual name of the function. The function name and the
parameter list together constitute the function signature.
 Parameters − A parameter is like a placeholder. When a function is invoked, you pass a
value to the parameter. This value is referred to as actual parameter or argument. The
parameter list refers to the type, order, and number of the parameters of a function.
Parameters are optional; that is, a function may contain no parameters.
 Function Body − The function body contains a collection of statements that define what
the function does.

An example of a real function definition is as given below:

int ADD(int a, int b)// int is the return type, ADD is the function name, a&b are parameters
{
int total = a+b;// return(a+b);
return (total);
}
As mentioned earlier, every C program must contain the main() function. This is because it is
where execution takes place. Other functions can be defined either before, or after the main()
function. However, whether these functions are defined before, or after the main() function, they
are all invoked (or called) within the main() function.

Calling a Function

While creating a C function, you give a definition of what the function has to do. To use a
function, you will have to call that function to perform the defined task.

When a program calls a function, the program control is transferred to the called function. A
called function performs a defined task and when its return statement is executed or when its
function-ending closing brace is reached, it returns the program control back to the main
program.

To call a function, you simply need to pass the required parameters along with the function
name, and if the function returns a value, then you can store the returned value.

Example programs:

2
1. Write a program that uses a function called mult(), used to capture 2 numbers and
displays their product.

#include <stdio.h>
int mult ( int x, int y );//function declaration, uses informal parameters

int main()
{
int a;
int b;

printf( "Please input two numbers to be multiplied: " );


scanf( "%d", &a );
scanf( "%d", &b );
printf( "The product of your two numbers is %d\n", mult( a, b ) );//uses actual parameters
getchar();
}

int mult (int x, int y)//uses formal parameters


{
return x * y;
}

[You can use the following online compiler:


https://www.tutorialspoint.com/compile_c_online.php]

This program begins with the only necessary include file. Next is the prototype of the function.
Notice that it has the final semi-colon! The main function returns an integer, which you should
always have to conform to the standard. You should not have trouble understanding the input and
output functions if you've followed the previous tutorials.

Notice how printf actually takes the value of what appears to be the mult function. What is really
happening is printf is accepting the value returned by mult, not mult itself. The result would be
the same as if we had use this print instead
printf( "The product of your two numbers is %d\n", x * y );
The mult function is actually defined below main. Because its prototype is above main, the
compiler still recognizes it as being declared, and so the compiler will not give an error about
mult being undeclared. As long as the prototype is present, a function can be used even if there is
no definition. However, the code cannot be run without a definition even though it will compile.

Prototypes are declarations of the function, but they are only necessary to alert the compiler
about the existence of a function if we don't want to go ahead and fully define the function. If
mult were defined before it is used, we could do away with the prototype--the definition
basically acts as a prototype as well.

3
Return is the keyword used to force the function to return a value. Note that it is possible to have
a function that returns no value. If a function returns void, the return statement is valid, but only
if it does not have an expression. In other words, for a function that returns void, the statement
"return;" is legal, but usually redundant. (It can be used to exit the function before the end of the
function.)

The getchar() function reads a single character from the standard input stream stdin, regardless of
what it is, and returns it to the program. This function is not always entirely necessary.

2. Write a program using a function called large, which captures 2 numbers, compares them
and returns the larger of the 2 numbers.

#include<stdio.h>

int large(int num1, int num2) {

/* local variable declaration */


int result;

if (num1 > num2)


result = num1;
else
result = num2;

return result;
}

int main()
{
int x;
int y;

printf( "Please input two numbers to be multiplied: " );


scanf( "%d", &x );
scanf( "%d", &y );
printf( "The largest of your two numbers is %d\n", large( x, y ) );
getchar();
}

EX:

Write a program that uses two functions named AVERAGE and EXPO such that the
AVERAGE() function captures 3 numbers and displays their average, while the EXPO()

4
function captures 2 numbers and displays the first number raised to the power of the second. The
2 functions should be within the same program.

Call by value vs call by reference

The call by value method of passing arguments to a function copies the actual value of an
argument into the formal parameter of the function. In this case, changes made to the parameter
inside the function have no effect on the argument.

By default, C programming uses call by value to pass arguments. In general, it means the code
within a function cannot alter the arguments used to call the function. Consider the function
swap() definition as follows.

/* function definition to swap the values */


void swap(int x, int y) {

int temp;

temp = x; /* save the value of x */


x = y; /* put y into x */
y = temp; /* put temp into y */

return;
}

Now, let us call the function swap() by passing actual values as in the following example −

#include <stdio.h>

/* function declaration */
void swap(int x, int y);

int main () {

/* local variable definition */


int a = 100;
int b = 200;

printf("Before swap, value of a : %d\n", a );


printf("Before swap, value of b : %d\n", b );

/* calling a function to swap the values */


swap(a, b);

printf("After swap, value of a : %d\n", a );


printf("After swap, value of b : %d\n", b );

return 0;
}
void swap(int x, int y) {

int temp;

5
temp = x; /* save the value of x */
x = y; /* put y into x */
y = temp; /* put temp into y */

return;
}

Let us put the above code in a single C file, compile and execute it, it will produce the following
result −

Before swap, value of a : 100


Before swap, value of b : 200
After swap, value of a : 100
After swap, value of b : 200

This shows that there are no changes in the values, though they had been changed inside the
function.

The call by reference method of passing arguments to a function copies the address of an
argument into the formal parameter. Inside the function, the address is used to access the actual
argument used in the call. It means the changes made to the parameter affect the passed
argument.

To pass a value by reference, argument pointers are passed to the functions just like any other
value. So accordingly you need to declare the function parameters as pointer types as in the
following function swap(), which exchanges the values of the two integer variables pointed to,
by their arguments.

/* function definition to swap the values */


void swap(int *x, int *y) {

int temp;
temp = *x; /* save the value at address x */
*x = *y; /* put y into x */
*y = temp; /* put temp into y */

return;
}

Let us now call the function swap() by passing values by reference as in the following example −

#include <stdio.h>

int main () {

/* local variable definition */


int a = 100;
int b = 200;

printf("Before swap, value of a : %d\n", a );

6
printf("Before swap, value of b : %d\n", b );

/* calling a function to swap the values */


swap(&a, &b);

printf("After swap, value of a : %d\n", a );


printf("After swap, value of b : %d\n", b );

return 0;
}
void swap(int *x, int *y) {

int temp;

temp = *x; /* save the value of x */


*x = *y; /* put y into x */
*y = temp; /* put temp into y */

return;
}

Let us put the above code in a single C file, compile and execute it, to produce the following
result −

Before swap, value of a : 100


Before swap, value of b : 200
After swap, value of a : 200
After swap, value of b : 100

This shows that the change has reflected outside the function as well, unlike call by value where
the changes do not reflect outside the function.

Program Scope

A scope in any programming is a region of the program where a defined variable can have its
existence and beyond that variable it cannot be accessed. There are three places where variables
can be declared in C programming language −

 Inside a function or a block which is called local variables.


 Outside of all functions which is called global variables.
 In the definition of function parameters which are called formal parameters.

Local Variables

Variables that are declared inside a function or block are called local variables. They can be used
only by statements that are inside that function or block of code. Local variables are not known
to functions outside their own. The following example shows how local variables are used. Here
all the variables a, b, and c are local to main() function.

#include <stdio.h>

7
int main () {

/* local variable declaration */


int a, b;
int c;

/* actual initialization */
a = 10;
b = 20;
c = a + b;

printf ("value of a = %d, b = %d and c = %d\n", a, b, c);

return 0;
}

Global Variables

Global variables are defined outside a function, usually on top of the program. Global variables
hold their values throughout the lifetime of your program and they can be accessed inside any of
the functions defined for the program.

A global variable can be accessed by any function. That is, a global variable is available for use
throughout your entire program after its declaration. The following program show how global
variables are used in a program.

#include <stdio.h>

/* global variable declaration */


int g;

int main () {

/* local variable declaration */


int a, b;

/* actual initialization */
a = 10;
b = 20;
g = a + b;

printf ("value of a = %d, b = %d and g = %d\n", a, b, g);

return 0;
}

A program can have same name for local and global variables but the value of local variable
inside a function will take preference. Here is an example −

#include <stdio.h>

8
/* global variable declaration */
int g = 20;

int main () {

/* local variable declaration */


int g = 10;

printf ("value of g = %d\n", g);

return 0;
}

When the above code is compiled and executed, it produces the following result −

value of g = 10

Formal Parameters

Formal parameters, are treated as local variables within a function and they take precedence over
global variables. Following is an example:

#include <stdio.h>

/* global variable declaration */


int a = 20;

int main () {

/* local variable declaration in main function */


int a = 10;
int b = 20;
int c = 0;

printf ("value of a in main() = %d\n", a);


c = sum( a, b);
printf ("value of c in main() = %d\n", c);

return 0;
}

/* function to add two integers */


int sum(int a, int b) {

printf ("value of a in sum() = %d\n", a);


printf ("value of b in sum() = %d\n", b);

return a + b;
}

When the above code is compiled and executed, it produces the following result −

9
value of a in main() = 10
value of a in sum() = 10
value of b in sum() = 20
value of c in main() = 30

Initializing Local and Global Variables

When a local variable is defined, it is not initialized by the system, you must initialize it yourself.
Global variables are initialized automatically by the system when you define them as follows −

Data Type Initial Default Value


int 0
Char '\0'
float 0
double 0
pointer NULL

It is a good programming practice to initialize variables properly, otherwise your program may
produce unexpected results, because uninitialized variables will take some garbage value already
available at their memory location.

2. FILES

A file is a place on disk where a group of related data is stored.


When the program is terminated, the entire data is lost in C programming. If you want to keep
large volumes of data, it is time consuming to enter the entire data. But, if a file is created, this
information can be accessed using few commands.

There are large numbers of functions to handle file I/O in C language. In this tutorial, you will
learn to handle standard I/O (High level file I/O functions) in C.

High level file I/O functions can be categorized as:


1. Text file
2. Binary file

File Operations
1. Creating a new file
2. Opening an existing file
3. Reading from and writing information to a file
4. Closing a file
5. Delete a file.

Working with files

10
While working with files, you need to declare a pointer of type file. This declaration is needed
for communication between file and program.
FILE *ptr;

Opening a file
Opening a file is performed using library function fopen(). The syntax for opening a file in
standard I/O is:
ptr=fopen("fileopen","mode")

For Example:
fopen("E:\\cprogram\program.txt","w");

/* --------------------------------------------------------- */
E:\\cprogram\program.txt is the location to create file.
"w" represents the mode for writing.
/* --------------------------------------------------------- */
Here, the program.txt file is opened for writing mode.

Opening Modes in Standard I/O


File Mode Meaning of Mode During Inexistence of file
R Open for reading. If the file does not exist, fopen() returns NULL.
If  the file exists, its contents are overwritten. If
w Open for writing.
the file does not exist, it will be created.
Open for append. i.e, Data is
A If the file does not exists, it will be created.
added to end of file.
Open for both reading and
r+ If the file does not exist, fopen() returns NULL. 
writing.
Open for both reading and If  the file exists, its contents are overwritten. If
w+
writing. the file does not exist, it will be created.
Open for both reading and
a+ If the file does not exists, it will be created.
appending.
 
Closing a File
The file should be closed after reading/writing of a file. Closing a file is performed using library
function fclose().
fclose(ptr); //ptr is the file pointer associated with file to be closed.

The Functions fprintf() and fscanf() functions.


The functions fprintf() and fscanf() are the file version of printf() and scanf(). The only
difference while using fprintf() and fscanf() is that, the first argument is a pointer to the structure
FILE

Writing to a file

11
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n;
FILE *fptr;
fptr=fopen("C:\\program.txt","w");
if(fptr==NULL){
printf("Error!");
exit(1);
}
printf("Enter n: ");
scanf("%d",&n);
fprintf(fptr,"%d",n);
fclose(fptr);
return 0;
}
This program takes the number from user and stores in file. After you compile and run this
program, you can see a text file program.txt created in C drive of your computer. When you open
that file, you can see the integer you entered.
Similarly, fscanf() can be used to read data from file.

Reading from file

#include <stdio.h>
int main()
{
int n;
FILE *fptr;
if ((fptr=fopen("C:\\program.txt","r"))==NULL){
printf("Error! opening file");
exit(1); /* Program exits if file pointer returns NULL. */
}
fscanf(fptr,"%d",&n);
printf("Value of n=%d",n);
fclose(fptr);
return 0;
}
If you have run program above to write in file successfully, you can get the integer back entered
in that program using this program.
Other functions like fgetchar(), fputc() etc. can be used in similar way.

Binary Files
Depending upon the way file is opened for processing, a file is classified into text file and binary
file.

12
If a large amount of numerical data it to be stored, text mode will be insufficient. In such case
binary file is used.
Working of binary files is similar to text files with few differences in opening modes, reading
from file and writing to file.

Opening modes of binary files


Opening modes of binary files are rb, rb+, wb, wb+,ab and ab+. The only difference between
opening modes of text and binary files is that, b is appended to indicate that, it is binary file.

Reading and writing of a binary file.


Functions fread() and fwrite() are used for reading from and writing to a file on the disk
respectively in case of binary files.
Function fwrite() takes four arguments, address of data to be written in disk, size of data to be
written in disk, number of such type of data and pointer to the file where you want to write.
fwrite(address_data,size_data,numbers_data,pointer_to_file);
Function fread() also take 4 arguments similar to fwrite() function as above.

Another simple example of writing the data to a text file testout.txt and then reading the data
from the file using C++ FileStream programming.

1. #include <fstream>  
2. #include <iostream>  
3. using namespace std;  
4. int main () {  
5.    char input[75];  
6.    ofstream os;  
7.    os.open("testout.txt");  
8.    cout <<"Writing to a text file:" << endl;  
9.    cout << "Please Enter your name: ";   
10.    cin.getline(input, 100);  
11.    os << input << endl;  
12.    cout << "Please Enter your age: ";   
13.    cin >> input;  
14.    cin.ignore();  
15.    os << input << endl;  
16.    os.close();  
17.    ifstream is;   
18.    string line;  
19.    is.open("testout.txt");   
20.    cout << "Reading from a text file:" << endl;   
21.    while (getline (is,line))  
22.    {  
23.    cout << line << endl;  
24.    }      

13
25.    is.close();  
26.    return 0;  
27. }  

Output:

Writing to a text file:


Please Enter your name: Nakul Jain
Please Enter your age: 22
Reading from a text file: Nakul Jain
22

14

You might also like