You are on page 1of 49

PROGRAMMING FOR PROBLEM SOLVING UNIT 3

MATRUSRI ENGINEERING COLLEGE


UNIT 3 NOTES
Unit – III
Arrays: 1-D arrays, 2-D arrays, Dynamic arrays, Character arrays and strings, String handling
functions
Functions: Concept of top-down approach, Functions- declaration, definition, calling,
Types – built-in and user-defined functions, Parameter passing techniques - call by value, call
by reference, Recursive functions, Passing arrays to functions, Storage classes.

Arrays: 1-D arrays

An array is defined as the collection of similar type of data items stored at contiguous
memory locations. Arrays are the derived data type in C programming language which
can store the primitive type of data such as int, char, double, float, etc. It also has the
capability to store the collection of derived data types, such as pointers, structure, etc.
The array is the simplest data structure where each data element can be randomly
accessed by using its index number.

C array is beneficial if you have to store similar elements. For example, if we want to
store the marks of a student in 6 subjects, then we don't need to define different
variables for the marks in the different subject. Instead of that, we can define an array
which can store the marks in each subject at the contiguous memory locations.

By using the array, we can access the elements easily. Only a few lines of code are
required to access the elements of the array.

Properties of Array
The array contains the following properties.

o Each element of an array is of same data type and carries the same size, i.e., int
= 4 bytes.
o Elements of the array are stored at contiguous memory locations where the first
element is stored at the smallest memory location.
o Elements of the array can be randomly accessed since we can calculate the
address of each element of the array with the given base address and the size
of the data element.

Advantage of C Array
1) Code Optimization: Less code to the access the data.
PROGRAMMING FOR PROBLEM SOLVING UNIT 3
2) Ease of traversing: By using the for loop, we can retrieve the elements of an array
easily.

3) Ease of sorting: To sort the elements of the array, we need a few lines of code only.

4) Random Access: We can access any element randomly using the array.

Disadvantage of C Array
1) Fixed Size: Whatever size, we define at the time of declaration of the array, we can't
exceed the limit. So, it doesn't grow the size dynamically like LinkedList which we will
learn later.

Declaration of C Array
We can declare an array in the c language in the following way.

1. data_type array_name[array_size];

Now, let us see the example to declare the array.

1. int marks[5];

Here, int is the data_type, marks are the array_name, and 5 is the array_size.

Initialization of C Array
The simplest way to initialize an array is by using the index of each element. We can
initialize each element of the array by using the index. Consider the following example.

1. marks[0]=80;//initialization of array
2. marks[1]=60;
3. marks[2]=70;
4. marks[3]=85;
5. marks[4]=75;
PROGRAMMING FOR PROBLEM SOLVING UNIT 3
C array example

#include<stdio.h>
int main(){
int i=0;
int marks[5];//declaration of array
marks[0]=80;//initialization of array
marks[1]=60;
marks[2]=70;
marks[3]=85;
marks[4]=75;
//traversal of array
for(i=0;i<5;i++){
printf("%d \n",marks[i]);
}//end of for loop
return 0;
}

Output

80
60
70
85
75

C Array: Declaration with Initialization


We can initialize the c array at the time of declaration. Let's see the code.

int marks[5]={20,30,40,50,60};

In such case, there is no requirement to define the size. So it may also be written
as the following code.

Example program

int marks[]={20,30,40,50,60};
#include<stdio.h>
int main()
{
int i=0;
PROGRAMMING FOR PROBLEM SOLVING UNIT 3
int marks[5]={20,30,40,50,60};//declaration and initialization of array
//traversal of array
for(i=0;i<5;i++)
{
printf("%d \n",marks[i]);
}
return 0;
}

Output

20
30
40
50
60

/* program to read an array of 10 numbers and print them*/

#include<stdio.h>
#include<conio.h>
void main ()
{
Int a[10],i;
Printf(“enter the 10 values”);
for(i=0;i<10;i++)
Scanf(“%d”,&a[i]);
Printf(“the given values are”);
for(i=0;i<10;i++)
Scanf(“%3d”,a[i]);
}
2./* Program to calculate the sum and average of six subject marks using
arrays */

void main()
{
int a[10],i,sum=0; float avg;
clrscr();
printf("Enter 6 subject marks :");
for(i=0; i<6;i++)
{
PROGRAMMING FOR PROBLEM SOLVING UNIT 3
Scanf(“%d”,&a[i]);
Sum=sum+a[i];
}
Printf(“sum=%d”,sum);
Avg=sum/6;
Printf(“avg=%f”,avg);
}
3./* Program to calculate maximum and minimum of given numbers */
void main()
{
int a[100],n,max=0,min,i;
printf("Enter total numbers :");
scanf("%d",&n);
printf("Enter %d numbers :",n);
for(i=0; i<n; i++)
{
scanf("%d",&a[i]);
}
min = max = a[0];
for(i=1; i<n; i++)
{
if(max<a[i])
max = a[i];
}
printf("Maximum Number = %d",max);
min=a[0];
for(i=1; i<n; i++)
{
if(min>a[i])
min = a[i];
}
printf("\nMinimum Number = %d",min);
}

4./*Program to search an element in an array*/

#include<stdio.h>
PROGRAMMING FOR PROBLEM SOLVING UNIT 3
int main()

int a[20],i,n,KEY,flag =0;

printf("Enter n:");

scanf("%d",&n);

printf("Enter %d elements:",n);

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

scanf("%d",&a[i]);

printf("Element to be searched:");

scanf("%d",&KEY);

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

if(a[i]==KEY)

printf("Elelement is found at %d",i);

flag = 1;

break;

if(flag == 0)
PROGRAMMING FOR PROBLEM SOLVING UNIT 3
printf("Element was not found");

return 0;

Two dimensional arrays


Two dimensional Arrays Two dimensional array is used to represent the elements of
the matrix Two- dimensional array can be thought as a rectangular display of elements
with rows and columns. The two dimensional array is a collection of number of one-
dimensional arrays, which are placed one after another.

Syntax: Datatype var[rowsize][colsize];

Datatype is the type of elements of a matrix

Rowsize represents number of rows in the matrix.

colsize represents number of cols in the matrix.

Declaration:

int a[3][2];

Here 3 indicates the no. of rows and 2 indicates columns

Initialization:

int a[3][2] = { 21, 22, 23, 24, 25, 26};

The values are stored in the following pattern

Col0 Col1

Row0 21 22

Row1 23 24

Row2 25 26

The values are represented as


PROGRAMMING FOR PROBLEM SOLVING UNIT 3
a[0][0] = 21; a[0][1] = 22;

a[1][0] = 23; a[1][0] = 24;

a[2][0] = 25; a[2][1] = 26;

The total number of elements in two dimensional array is product of no. of rows and
no. of columns. Example : int a [3][2] ; stores 3x2=6 values conceptually stored in
matrix form.

/* Program to read elements of two-dimensional array and print them in


matrix format*/

void main()
{
int a[3][2],i,j;
clrscr();
printf("Enter elements of 3x2 matrix :");
for(i=0; i<3; i++)
{
for(j=0; j<2; j++)
{
scanf("%d",&a[i][j]);
}
}
printf("Given Elements are :\n");
for(i=0; i<3; i++)
{
for(j=0; j<2; j++)
{
printf("%3d",a[i][j]);
}
printf("\n");
}
}
Output:
Enter elements of 3x2 matrix : 1 5 2 6 3 7
Given elements
15
PROGRAMMING FOR PROBLEM SOLVING UNIT 3
26
37

/*program to add two matrices using two dimensional arrays */


#include<stdio.h>
int main()
{
int a[5][5],b[5][5],s[5][5],i,j,r1,c1,r2,c2;
printf("Enter the size of matrx A:");
scanf("%d%d",&r1,&c1);
printf("Enter the size of matrx B:");
scanf("%d%d",&r2,&c2);
if((r1!=r2)||(c1!=c2))
{
printf("Addition is not possible");
return 0;
}
printf("Elements of matrix A\n");
for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("Elements of matrix B\n");
for(i=0;i<r2;i++)
{
for(j=0;j<c2;j++)
{
scanf("%d",&b[i][j]);
}
}
for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
{
s[i][j] = a[i][j]+b[i][j];
PROGRAMMING FOR PROBLEM SOLVING UNIT 3
}
}
printf("\nThe resultant matrix \n");
for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
{
printf("%4d",s[i][j]);
}
printf("\n");
}
return 0;
}
Output
Enter the size of matrx A:2 2
Enter the size of matrx B:2 2
Elements of matrix A
12
45
Elements of matrix B
56
38
The resultant matrix
68
71
/* Program to perform multiplication of two matrices*/
#include<stdio.h>
int main()
{
int m, n, p, q, i, j, k;
int a[10][10], b[10][10], res[10][10];
printf("Enter the order of first matrix\n");
scanf("%d%d", & m, & n);
printf("Enter the order of second matrix\n");
scanf("%d%d", & p, & q);

if (n != p)
{
PROGRAMMING FOR PROBLEM SOLVING UNIT 3
printf("Matrix is incompatible for multiplication\n");
}
else
{
printf("Enter the elements of Matrix-A:\n");
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
{
scanf("%d", & a[i][j]);
}
}

printf("Enter the elements of Matrix-B:\n");


for (i = 0; i < p; i++)
{
for (j = 0; j < q; j++)
{
scanf("%d", & b[i][j]);
}
}

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


{
for (j = 0; j < q; j++)
{
res[i][j] = 0;
for (k = 0; k < p; k++)
{
res[i][j] += a[i][k] * b[k][j];
}
}
}

printf("The product of the two matrices is:-\n");

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


{
PROGRAMMING FOR PROBLEM SOLVING UNIT 3
for (j = 0; j < q; j++)
{
printf("%d\t", res[i][j]);
}
printf("\n");
}
}

return 0;
}
Output
Enter the order of first matrix
2
2
Enter the order of second matrix
2
2
Enter the elements of Matrix-A:
2
2
2
2
Enter the elements of Matrix-B:
2
2
2
2
The product of the two matrices is:-
8 8
8 8
/* program to check whether a matrix is an identity matrix or
not */

#include <stdio.h>
// In a square matrix, if all the main diagonal elements are 1's and
// all the remaining elements are 0's, it is called an Identity Matrix.
int main() {
int arr1[10][10];
PROGRAMMING FOR PROBLEM SOLVING UNIT 3
int r1, c1;
int i, j, yn = 1;

// Display the purpose of the program


printf("\n\n Check whether a given matrix is an identity matrix
:\n");
printf("-----------------------------------------------------------\n");

// Input the number of Rows for the matrix


printf("Input number of Rows for the matrix :");
scanf("%d", &r1);

// Input the number of Columns for the matrix


printf("Input number of Columns for the matrix :");
scanf("%d", &c1);

// Input elements into the matrix


printf("Input elements in the matrix :\n");
for(i = 0; i < r1; i++) {
for(j = 0; j < c1; j++) {
printf("element - [%d],[%d] : ", i, j);
scanf("%d", &arr1[i][j]);
}
}
// Display the matrix
printf("The matrix is :\n");
for(i = 0; i < r1; i++) {
for(j = 0; j < c1 ;j++) {
printf("% 4d", arr1[i][j]);
}
printf("\n");
}
// Check whether the matrix is an identity matrix or not
for(i = 0; i < r1; i++) {
for(j = 0; j < c1; j++) {
if (arr1[i][j] != 1 && arr1[j][i] != 0) {
yn = 0;
break;
PROGRAMMING FOR PROBLEM SOLVING UNIT 3
}
}
}

// Display the result


if(yn == 1)
{
printf(" The matrix is an identity matrix.\n\n");
} else {
printf(" The matrix is not an identity matrix.\n\n");
}

return 0;
}

Dynamic arrays
Dynamic arrays are a powerful data structure in programming that allows
for creating and manipulating arrays of varying sizes during runtime. In C,
dynamic arrays are implemented using pointers and memory allocation
functions, making them a valuable tool for optimizing memory usage and
creating efficient programs. In this article, we will explore the concept of
dynamic arrays in C, their advantages and disadvantages, and how to create
and manipulate them.

A dynamic array is an array whose size can be changed during runtime.


Unlike static arrays, which have a fixed size that is determined at compile time,
dynamic arrays can be resized as needed. It allows for more flexibility and better
memory management, as the size of the array can be adjusted to fit the amount of
data being stored.

Dynamic arrays are implemented using pointers and memory allocation


functions. In C, the most commonly used memory allocation functions
are malloc(), calloc(), and realloc(). These functions allow for the allocation and
deallocation of memory during runtime, which is necessary for creating and
manipulating dynamic arrays.

Creating Dynamic Arrays in C

To create a dynamic array in C, we must use memory allocation functions to allocate


memory for the array. The most commonly used memory allocation functions in C
are malloc(), calloc(), and realloc().
PROGRAMMING FOR PROBLEM SOLVING UNIT 3
Here is an example of how to create a dynamic array using malloc():

1. int *arr;
2. int size = 10;
3. arr = (int*) malloc(size * sizeof(int));

C malloc() method

Example

#include <stdio.h>

#include <stdlib.h>

int main()

int* ptr;

int n, i;

printf("Enter number of elements:");

scanf("%d",&n);

printf("Entered number of elements: %d\n", n);

ptr = (int*)malloc(n * sizeof(int));

if (ptr == NULL) {

printf("Memory not allocated.\n");

exit(0);

else {

printf("Memory successfully allocated using malloc.\n");

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

ptr[i] = i + 1;

printf("The elements of the array are: ");

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

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


PROGRAMMING FOR PROBLEM SOLVING UNIT 3
}

return 0;

Output:

Enter number of elements: 5


Memory successfully allocated using malloc.
The elements of the Array are: 1, 2, 3, 4, 5,

2. C calloc() method

In C, the "calloc" or "contiguous allocation" method is used to allocate a specified


number of blocks of memory of the specified type dynamically. It's fairly similar to
malloc(), but it has two key differences:

It sets the default value for every block to 0.

In comparison to malloc(), it has two parameters or arguments.

Syntax
ptr = (cast-type*)calloc(n, element-size);

here, n is the num of elements and element-size is the size of each element.

For Example:
ptr = (float*) calloc(25, sizeof(float));

This statement allocates contiguous space in memory for 25 elements, each with the
size of the float.
If space is insufficient, allocation fails, and it returns a NULL pointer.

Example
#include <stdio.h>
#include <stdlib.h>
int main() {
int* ptr;
int n, i;
n = 5;
printf("Enter total number of elements present in an array: %d\n", n);
ptr = (int*)calloc(n, sizeof(int));
if (ptr == NULL) {
printf("Memory not allocated.\n");
PROGRAMMING FOR PROBLEM SOLVING UNIT 3
exit(0);
}
else {
printf("Memory successfully allocated.\n");
for (i = 0; i < n; ++i) {
ptr[i] = i + 1;
}
printf("The elements in an array are: ");
for (i = 0; i < n; ++i) {
printf("%d, ", ptr[i]);
}
}

return 0;
}

Output
Enter the total number of elements present in an array: 5
Memory successfully allocated.
The elements in an Array are: 1, 2, 3, 4, 5,

3. C free() method
To dynamically de-allocate memory in C, use the "free" technique. Memory allocated
with the malloc() and calloc() procedures is not de-allocated on their own. As a result,
anytime dynamic memory allocation occurs, the free() function is employed. It frees up
memory, which helps to prevent memory waste.

Syntax
free(ptr);
Example
#include <stdio.h>
#include <stdlib.h>
int main()
{
int *ptr, *ptr1;
int n, i;
n = 5;
printf("Enter the total number of elements: %d\n", n);
ptr = (int*)malloc(n * sizeof(int));
ptr1 = (int*)calloc(n, sizeof(int));
// Check if the memory has been successfully
// allocated by malloc or not
if (ptr == NULL || ptr1 == NULL)
PROGRAMMING FOR PROBLEM SOLVING UNIT 3
{
printf("Memory not allocated.\n");
exit(0);
}
else
{
//memory has been successfully allocated
printf("Memory successfully allocated using malloc.\n");

// Free the memory


free(ptr);
printf("Malloc Memory successfully freed.\n");

// Memory has been successfully allocated


printf("\nMemory successfully allocated using calloc.\n");

// Free the memory


free(ptr1);
printf("Calloc Memory successfully freed.\n");
}
return 0;
}
Output
Enter the total number of elements: 5
Memory successfully allocated using malloc.
Malloc Memory successfully freed.

Memory successfully allocated using calloc.


Calloc memory successfully freed.
4. realloc() method

In C, the "realloc" or "re-allocation" method is used to alter the memory allocation of a


previously allocated memory dynamically. In other words, realloc can be used to
dynamically re-allocate memory if the memory originally allocated with malloc or calloc
is inadequate. The existing value is preserved after re-allocation of memory, and new
blocks are initialized with the default garbage value.

Syntax
ptr = realloc(ptr, newSize);

Where ptr is re-allocated-allocated with new size 'newSize.'

If space is insufficient, then allocation fails and returns a NULL pointer.

C example

#include <stdio.h>
PROGRAMMING FOR PROBLEM SOLVING UNIT 3
#include <stdlib.h>
int main() {
int* ptr;
int n, i;
n = 5;
printf("Enter the total number of elements: %d\n", n);
ptr = (int*)calloc(n, sizeof(int));
if (ptr == NULL) {
printf("Memory not allocated.\n");
exit(0);
}
else {
printf("Memory successfully allocated using calloc.\n");
for (i = 0; i < n; ++i) {
ptr[i] = i + 1;
}
printf("Elements are: ");
for (i = 0; i < n; ++i) {
printf("%d, ", ptr[i]);
}
n = 10;
printf("\n\nEnter the new size of an array: %d\n", n);
ptr = realloc(ptr, n * sizeof(int));

printf("Memory successfully re-allocated using realloc.\n");

for (i = 5; i < n; ++i) {


ptr[i] = i + 1;
}
printf("Elements are:");
for (i = 0; i < n; ++i) {
printf("%d, ", ptr[i]);
}
free(ptr);
}
return 0;
}
Output

Enter the total number of elements: 5


Memory successfully allocated using calloc.
Elements are: 1, 2, 3, 4, 5,

Enter the new size of an array: 10


Memory successfully re-allocatedre-allocated using realloc.
PROGRAMMING FOR PROBLEM SOLVING UNIT 3
Elements are: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,

Character arrays and strings

String is a sequence of characters that are treated as a single data


item and terminated by a null character '\0'. Remember that the C
language does not support strings as a data type. A string is actually
a one-dimensional array of characters in C language. These are often
used to create meaningful and readable programs.

For example: The string "home" contains 5 characters including


the '\0' character which is automatically added by the compiler at
the end of the string.

Declaring and Initializing a string variables:

char name[13] = "StudyTonight";

char name[10] = {'c','o','d','e','\0'};

// Illegal

char ch[3] = "hello";


PROGRAMMING FOR PROBLEM SOLVING UNIT 3
char str[4];

str = "hello";

String Handling Functions:

C language supports a large number of string handling functions


that can be used to carry out many of the string manipulations.
These functions are packaged in the string.h library. Hence, you
must include string.h header file in your programs to use these
functions.

The following are the most commonly used string handling


functions.

Method Description

strcat() It is used to concatenate(combine) two strings

strlen() It is used to show the length of a string

strrev() It is used to show the reverse of a string

strcpy() Copies one string into another

strcmp() It is used to compare two string

C String Length: strlen() function


The strlen() function returns the length of the given string. It doesn't count null
character '\0'.

1. #include<stdio.h>
2. #include <string.h>
PROGRAMMING FOR PROBLEM SOLVING UNIT 3
3. int main(){
4. char ch[20]={'m', 'a', 't', 'r', 'u', 's', 'r', 'i', '\0'};
5. printf("Length of string is: %d",strlen(ch));
6. return 0;
7. }
C Copy String: strcpy()
The strcpy(destination, source) function copies the source string in destination.

1. #include<stdio.h>
2. #include <string.h>
3. int main()
4. {
5. char ch[20]={'m', 'a', 't', 'r', 'u', 's', 'r', 'i', '\0'};
6. char ch2[20];
7. strcpy(ch2,ch);
8. printf("Value of second string is: %s",ch2);
9. return 0;
10. }
C String Concatenation: strcat()
The strcat(first_string, second_string) function concatenates two strings and result is
returned to first_string.

1. #include<stdio.h>
2. #include <string.h>
3. int main(){
4. char ch[10]={'h', 'e', 'l', 'l', 'o', '\0'};
5. char ch2[10]={'c', '\0'};
6. strcat(ch,ch2);
7. printf("Value of first string is: %s",ch);
8. return 0;
9. }

Output:

Value of first string is: helloc


PROGRAMMING FOR PROBLEM SOLVING UNIT 3
C Compare String: strcmp()
The strcmp(first_string, second_string) function compares two string and returns 0 if
both strings are equal.

Here, we are using gets() function which reads string from the console.

1. #include<stdio.h>
2. #include <string.h>
3. int main(){
4. char str1[20],str2[20];
5. printf("Enter 1st string: ");
6. gets(str1);//reads string from console
7. printf("Enter 2nd string: ");
8. gets(str2);
9. if(strcmp(str1,str2)==0)
10. printf("Strings are equal");
11. else
12. printf("Strings are not equal");
13. return 0;
14. }

Output:

Enter 1st string: hello


Enter 2nd string: hello
Strings are equal

C Reverse String: strrev()


The strrev(string) function returns reverse of the given string. Let's see a simple
example of strrev() function.

1. #include<stdio.h>
2. #include <string.h>
3. int main(){
4. char str[20];
5. printf("Enter string: ");
6. gets(str);//reads string from console
7. printf("String is: %s",str);
8. printf("\nReverse String is: %s",strrev(str));
9. return 0;
PROGRAMMING FOR PROBLEM SOLVING UNIT 3
10. }

Output:

Enter string: matrusri


String is: matrusri
Reverse String is: irsurtam

C String Lowercase: strlwr()


The strlwr(string) function returns string characters in lowercase. Let's see a simple
example of strlwr() function.

1. #include<stdio.h>
2. #include <string.h>
3. int main(){
4. char str[20];
5. printf("Enter string: ");
6. gets(str);//reads string from console
7. printf("String is: %s",str);
8. printf("\nLower String is: %s",strlwr(str));
9. return 0;
10. }

Output:

Enter string: JAVATpoint


String is: JAVATpoint
Lower String is: javatpoint

C String Uppercase: strupr()


The strupr(string) function returns string characters in uppercase. Let's see a simple
example of strupr() function.

1. #include<stdio.h>
2. #include <string.h>
3. int main(){
4. char str[20];
5. printf("Enter string: ");
6. gets(str);//reads string from console
7. printf("String is: %s",str);
8. printf("\nUpper String is: %s",strupr(str));
9. return 0;
PROGRAMMING FOR PROBLEM SOLVING UNIT 3
10. }

Output:

Enter string: javatpoint


String is: javatpoint
Upper String is: JAVATPOINT

Functions: Concept of top-down approach


There are six derived types in C: arrays, functions, pointer, structure, union and

enumerated types. The function type is derived from its return type.

DESIGNING STRUCTURED PROGRAMS (Top Down Design)

For larger programs, it is not possible to understand all aspects of such programs
without reducing them in to smaller parts. The planning for large programs is as
follows

i. Understand the problems as a whole

ii. Break it into simpler, understandable parts.

iii. Solve individual parts and combine them.


PROGRAMMING FOR PROBLEM SOLVING UNIT 3
Each part of a program is termed as module. The process of sub-dividing a problem
into manageable parts is called top-down design.

In top-down design, a program is divided into a main module and its related modules.
Each module in turn is divided into sub modules until the resulting modules are
intrinsic; that is until they are implicitly understood without further division. This
process is known as factoring.

Top-down design is usually done using a visual representation of the modules known
as a structure chart. The structure chart shows the relation between each module and
its submodules. The structure chart is read top-down, left-right. The reading starts
from main module followed by reading of sub-modules of main from left to right.

The main module is called calling module because it has sub modules. The sub
modules are known as called modules. Communication between modules in a
structure chart is allowed only through a calling module. No communication takes
place directly between modules that do not have a calling-called relationship. The
technique used to pas data to a function is known as parameter passing. The
parameters are contained in a list that is a definition of data passed to the function by
the caller.

Moving down and left, we then read Module 1. Module 1 ,Module 2 and Module 3 are
at the same level. The Main Module consists of three sub-modules. Module 1 is further
subdivided into three modules, Module 1a, Module 1b, and Module 1c. To write the
code for Module 1, we need to write code for its three sub-modules.

The main module is called calling module because it has sub modules. The sub
modules are known as called modules. Communication between modules in a
structure chart is allowed only through a calling module. No communication takes
place directly between modules that do not have a calling-called relationship.

How can Module 1a send data to Module 3b?


PROGRAMMING FOR PROBLEM SOLVING UNIT 3
It first sends data to Module 1, which in turn sends it to the Main Module, which passes
it to Module 3, and then on to Module 3b.

The technique used to pas data to a function is known as parameter passing. The
parameters are contained in a list that is a definition of data passed to the function by
the caller.

FUNCTIONS IN C

In C, idea of top-down is done using functions. A C program is made of one or more functions,
one and only one of which be called main. The execution of the program always starts with
main, but it can call other functions to do some part of job.

Definition: A function is an independent module that will be called to do a specific task.

A function is a self-contained block of code that carries out some specific and well-defined
task.

Advantages of functions:

1. Modular Programming It facilitates top down modular programming. In this programming


style, the high level logic of the overall problem is solved first while the details of each lower
level functions is addressed later. Problem can be factored into understandable and
manageable parts.

2. Code Reusability: It provides a way to reuse code that is required in more than one place
in a program. Functions can be reusable in other programs (Files).

3. Protecting data: Used to protect data. Local data in function is available only to function
when it is executing. When the function is not running, the data are not accessible.

4.Reduction of source code The length of the source program can be reduced by using
functions at appropriate places. This factor is critical with microcomputers where memory
space is limited.

5. Easier Debugging It is easy to locate and isolate a faulty function for further investigation.

Every function in C has the following...

• Function Declaration (Function Prototype)


• Function Definition
• Function Call

Function Declaration
PROGRAMMING FOR PROBLEM SOLVING UNIT 3
The function declaration tells the compiler about function name, the data type of the return
value and parameters. The function declaration is also called a function prototype. The
function declaration is performed before the main function or inside the main function or any
other function.

Function declaration syntax –


returnType functionName(parametersList);
In the above syntax, returnType specifies the data type of the value which is sent as a return
value from the function definition. The functionName is a user-defined name used to
identify the function uniquely in the program. The parametersList is the data values that are
sent to the function definition.

Function Definition
The function definition provides the actual code of that function. The function definition is
also known as the body of the function. The actual task of the function is implemented in
the function definition. That means the actual instructions to be performed by a function are
written in function definition. The actual instructions of a function are written inside the
braces "{ }". The function definition is performed before the main function or after the main
function.

Function definition syntax -


returnType functionName(parametersList)
{

Actual code...

Function Call
The function call tells the compiler when to execute the function definition. When a function
call is executed, the execution control jumps to the function definition where the actual code
gets executed and returns to the same functions call once the execution completes. The
function call is performed inside the main function or any other function or inside the function
itself.

Function call syntax -


functionName(parameters);
ADVANTAGES OF FUNCTIONS
PROGRAMMING FOR PROBLEM SOLVING UNIT 3
• Using funcions we can implement modular programming.

• Functions make the program more readable and understandable.

• Using functions the program implementation becomes easy.

• Once a function is created it can be used many times (code re-usability).

• Using functions larger programs can be divided into smaller modules.

Types of Functions in C
In C Programming Language, based on providing the function definition, functions are divided

into two types. Those are as follows...

• System Defined Functions

• User Defined Functions

System Defined Functions

The C Programming Language provides pre-defined functions to make programming easy.

These pre-defined functions are known as syatem defined functions. The system defined

function is defined as follows...

The system defined functions are also called as Library Functions or Standard
Functions or Pre-Defined Functions. The implementation of system defined functions is
already defined by the system.

In C, all the system defined functions are defined inside the header
files like stdio.h, conio.h, math.h, string.h etc., For example, the
funtions printf() and scanf() are defined in the header file called stdio.h.

Whenever we use system defined functions in the program, we must include the respective
header file using #include statement. For example, if we use a system defined
function sqrt() in the program, we must include the header file called math.h because the
function sqrt() is defined in math.h.

• System defined functions are declared in header files

• System defined functions are implemented in .dll files. (DLL stands for Dynamic Link

Library).

• To use system defined functions the respective header file must be included.
PROGRAMMING FOR PROBLEM SOLVING UNIT 3
User Defined Functions
• In C programming language, users can also create their own functions. The functions
that are created by users are called as user defined functions. The user defined
function is defined as follows...

• The function whose definition is defined by the user is called as user defined
function.

• That means the function that is implemented by user is called as user defined
function. For example, the function main is implemented by user so it is called as user
defined function.

• In C every user defined function must be declared and implemented. Whenever we


make function call the function definition gets executed. For example, consider the
following program in which we create a function called addition with two
paramenters and a return value.

Example Program
#include<stdio.h>
#include<conio.h>

void main(){
int num1, num2, result ;

int addition(int,int) ; // function declaration


clrscr() ;
printf("Enter any two integer numbers : ") ;
scanf("%d%d", &num1, &num2);

result = addition(num1, num2) ; // function call

printf("SUM = %d", result);


getch() ;
}

int addition(int a, int b) // function definition


PROGRAMMING FOR PROBLEM SOLVING UNIT 3
{

return a+b ;

In the above example program, the function declaration statement "int

addition(int,int)" tells the compiler that there is a function with name addition which takes

two integer values as parameters and returns an integer value. The function call statement

takes the execution control to the additon() definition along with values of num1 and num2.

Then function definition executes the code written inside it and comes back to the function

call along with return value.

In the concept of functions, the function call is known as "Calling Function" and the function

definition is known as "Called Function".

When we make a function call, the execution control jumps from calling function to called

function. After executing the called function, the execution control comes back to calling

function from called function. When the control jumps from calling function to called function

it may carry one or more data values called "Paramenters" and while coming back it may

carry a single value called "return value". That means the data values transferred from calling

function to called function are called as Parameters and the data value transferred from

called funcion to calling function is called Return value.

Based on the data flow between the calling function and called function, the functions are

classified as follows...

• Function without Parameters and without Return value

• Function with Parameters and without Return value

• Function without Parameters and with Return value

• Function with Parameters and with Return value

Function without Parameters and without Return value


In this type of functions there is no data transfer between calling function and called function.

Simply the execution control jumps from calling-function to called function and executes

called function, and finally comes back to the calling function. For example, consider the

following program...
PROGRAMMING FOR PROBLEM SOLVING UNIT 3
Example Program
#include<stdio.h>
#include<conio.h>

void main(){

void addition() ; // function declaration


clrscr() ;

addition() ; // function call


}

void addition() // function definition

int num1, num2 ;

printf("Enter any two integer numbers : ") ;

scanf("%d%d", &num1, &num2);

printf("Sum = %d", num1+num2 ) ;

Function with Parameters and without Return value


In this type of functions there is data transfer from calling-function to called function

(parameters) but there is no data transfer from called function to calling-function (return

value). The execution control jumps from calling-function to called function along with the

parameters and executes called function, and finally comes back to the calling function. For

example, consider the following program...

Example Program
#include<stdio.h>
#include<conio.h>

void main(){
int num1, num2 ;

void addition(int, int) ; // function declaration


clrscr() ;
printf("Enter any two integer numbers : ") ;
scanf("%d%d", &num1, &num2);

addition(num1, num2) ; // function call


PROGRAMMING FOR PROBLEM SOLVING UNIT 3
}

void addition(int a, int b) // function definition

printf("Sum = %d", a+b ) ;

Function without Parameters and with Return value


In this type of functions there is no data transfer from calling-function to called-function

(parameters) but there is data transfer from called function to calling-function (return value).

The execution control jumps from calling-function to called function and executes called

function, and finally comes back to the calling function along with a return value. For example,

consider the following program...

Example Program
#include<stdio.h>
#include<conio.h>
void main(){
int result ;

int addition() ; // function declaration


clrscr() ;

result = addition() ; // function call


printf("Sum = %d", result) ;
getch() ;
}

int addition() // function definition

int num1, num2 ;

printf("Enter any two integer numbers : ") ;

scanf("%d%d", &num1, &num2);

return (num1+num2) ;

Function with Parameters and with Return value


In this type of functions there is data transfer from calling-function to called-function

(parameters) and also from called function to calling-function (return value). The execution
PROGRAMMING FOR PROBLEM SOLVING UNIT 3
control jumps from calling-function to called function along with parameters and executes

called function, and finally comes back to the calling function along with a return value. For

example, consider the following program...

Example Program
#include<stdio.h>
#include<conio.h>
void main(){
int num1, num2, result ;

int addition(int, int) ; // function declaration


clrscr() ;
printf("Enter any two integer numbers : ") ;
scanf("%d%d", &num1, &num2);

result = addition(num1, num2) ; // function call


printf("Sum = %d", result) ;
getch() ;
}

int addition(int a, int b) // function definition

return (a+b) ;

• The parameters specified in calling function are said to be Actual Parameters.

• The parameters declared in called function are said to be Formal Parameters.

• The value of actual parameters is always copied into formal parameters.

Parameter Passing in C
When a function gets executed in the program, the execution control is transferred from

calling-function to called function and executes function definition, and finally comes back to

the calling function. When the execution control is transferred from calling-function to called-

function it may carry one or number of data values. These data values are called

as parameters.

Parameters are the data values that are passed from calling function to called

function.
PROGRAMMING FOR PROBLEM SOLVING UNIT 3
In C, there are two types of parameters and they are as follows...

• Actual Parameters
• Formal Parameters

The actual parameters are the parameters that are specified in calling function. The formal

parameters are the parameters that are declared at called function. When a function gets

executed, the copy of actual parameter values are copied into formal parameters.

In C Programming Language, there are two methods to pass parameters from calling function

to called function and they are as follows...

• Call by Value
• Call by Reference

Call by Value
In call by value parameter passing method, the copy of actual parameter values are copied

to formal parameters and these formal parameters are used in called function. The changes

made on the formal parameters does not effect the values of actual parameters. That

means, after the execution control comes back to the calling function, the actual parameter

values remains same. For example consider the following program...

Example Program
#include<stdio.h>
#include<conio.h>

void main(){
int num1, num2 ;

void swap(int,int) ; // function declaration


clrscr() ;
num1 = 10 ;
num2 = 20 ;

printf("\nBefore swap: num1 = %d, num2 = %d", num1, num2) ;

swap(num1, num2) ; // calling function


printf("\nAfter swap: num1 = %d\nnum2 = %d", num1, num2);
}
PROGRAMMING FOR PROBLEM SOLVING UNIT 3
void swap(int a, int b) // called function

int temp ;

temp = a ;

a=b;

b = temp ;

Call by Reference
In Call by Reference parameter passing method, the memory location address of the actual

parameters is copied to formal parameters. This address is used to access the memory

locations of the actual parameters in called function. In this method of parameter passing,

the formal parameters must be pointer variables.

That means in call by reference parameter passing method, the address of the actual

parameters is passed to the called function and is recieved by the formal parameters

(pointers). Whenever we use these formal parameters in called function, they directly access

the memory locations of actual parameters. So the changes made on the formal

parameters effects the values of actual parameters. For example consider the following

program...

Example Program
#include<stdio.h>
#include<conio.h>
void main(){
int num1, num2 ;

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


clrscr() ;
num1 = 10 ;
num2 = 20 ;
printf("\nBefore swap: num1 = %d, num2 = %d", num1, num2) ;

swap(&num1, &num2) ; // calling function

printf("\nAfter swap: num1 = %d, num2 = %d", num1, num2);


getch() ;
}
PROGRAMMING FOR PROBLEM SOLVING UNIT 3
void swap(int *a, int *b) // called function

int temp ;

temp = *a ;

*a = *b ;

*b = temp ;

Recursive functions
Recursion is the process of calling a function itself repeatedly until a
particular condition is met. A function that calls itself directly or indirectly is
called a recursive function and such kind of function calls are called recursive
calls.

In C, recursion is used to solve a complex problem. Using recursion we can


solve a complex problem in a small piece of code by breaking down the
problem. We can solve large numbers of problems using recursion for
example factorial of a number, generating Fibonacci series, generating
subsets etc.

Recursive Functions
A function that calls a copy of itself is called Recursive Function. The
recursive functions contain a call to themselves somewhere in the function
body. Moreover, such functions can contain multiple recursive calls
Basic Structure of Recursive Functions
The basic syntax structure of the recursive functions is:
type function_name (args) {
// function statements
// base condition
// recursion case (recursive call)
}

How recursion works?


void recurse()
{
... .. ...
recurse();
... .. ...
PROGRAMMING FOR PROBLEM SOLVING UNIT 3
}
int main()
{
... .. ...
recurse();
... .. ...
}

The recursion continues until some condition is met to prevent it.

To prevent infinite recursion, if...else statement (or similar approach) can be used
where one branch makes the recursive call, and other doesn't.

Example: Sum of Natural Numbers Using Recursion

#include <stdio.h>
int sum(int n);
int main()
{
int number, result;
printf("Enter a positive integer: ");
scanf("%d", &number);
result = sum(number);
PROGRAMMING FOR PROBLEM SOLVING UNIT 3
printf("sum = %d", result);
return 0;
}

int sum(int n)
{
if (n != 0)
// sum() function calls itself
return n + sum(n-1);
else
return n;
}
/* Program to find factorial of a given number using recursion*/

#include <stdio.h>
int fact (int);
int main()
{
int n,f;
printf("Enter the number whose factorial you want to calculate?");
scanf("%d",&n);
f = fact(n);
printf("factorial = %d",f);
}
int fact(int n)
{
if (n==0)
{
return 0;
}
else if ( n == 1)
{
return 1;
}
else
PROGRAMMING FOR PROBLEM SOLVING UNIT 3
{
return n*fact(n-1);
}
}

Output
Enter the number whose factorial you want to calculate?5
factorial = 120

Let's see an example to find the nth term of the Fibonacci series.

#include<stdio.h>
int fibonacci(int);
void main ()
{
int n,f;
printf("Enter the value of n?");
scanf("%d",&n);
f = fibonacci(n);
printf("%d",f);
}
int fibonacci (int n)
{
if (n==0)
{
return 0;
}
else if (n == 1)
{
return 1;
}
else
{
return fibonacci(n-1)+fibonacci(n-2);
}
}
PROGRAMMING FOR PROBLEM SOLVING UNIT 3

Output
Enter the value of n?12
144

Passing arrays to functions


In C, there are various general problems which requires passing more than one variable
of the same type to a function. For example, consider a function which sorts the 10
elements in ascending order. Such a function requires 10 numbers to be passed as the
actual parameters from the main function. Here, instead of declaring 10 different
numbers and then passing into the function, we can declare and initialize an array and
pass that into the function. This will resolve all the complexity since the function will
now work for any number of values.

As we know that the array_name contains the address of the first element. Here, we
must notice that we need to pass only the name of the array in the function which is
intended to accept an array. The array defined as the formal parameter will
automatically refer to the array specified by the array name defined as an actual
parameter.

Consider the following syntax to pass an array to the function.

functionname(arrayname);//passing array

First way:

1. return_type function(type arrayname[])

Declaring blank subscript notation [] is the widely used technique.

Second way:

1. return_type function(type arrayname[SIZE])

Optionally, we can define size in subscript notation [].

Third way:

1. return_type function(type *arrayname)

C language passing an array to function example

#include<stdio.h>
int minarray(int arr[],int size)
PROGRAMMING FOR PROBLEM SOLVING UNIT 3
{
int min=arr[0];
int i=0;
for(i=1;i<size;i++)
{
if(min>arr[i])
{
min=arr[i];
}
}//end of for
return min;
}//end of function

int main()
{
int i=0,min=0;
int numbers[]={4,5,7,3,8,9};//declaration of array

min=minarray(numbers,6);//passing array with size


printf("minimum number is %d \n",min);
return 0;
}

Output

minimum number is 3

C function to sort the array


#include<stdio.h>
void Bubble_Sort(int[]);
void main ()
{
int arr[10] = { 10, 9, 7, 101, 23, 44, 12, 78, 34, 23};
Bubble_Sort(arr);
}
void Bubble_Sort(int a[]) //array a[] points to arr.
{
int i, j,temp;
for(i = 0; i<10; i++)
PROGRAMMING FOR PROBLEM SOLVING UNIT 3
{
for(j = i+1; j<10; j++)
{
if(a[j] < a[i])
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
printf("Printing Sorted Element List ...\n");
for(i = 0; i<10; i++)
{
printf("%d\n",a[i]);
}
}

Output

Printing Sorted Element List ...


7
9
10
12
23
23
34
44
78
101

Storage classes
In C programming language, storage classes are used to define things like storage
location (whether RAM or REGISTER), scope, lifetime and the default value of a variable.

In the C programming language, the memory of variables is allocated either in computer


memory (RAM) or CPU Registers. The allocation of memory depends on storage classes.

In C programming language, there are FOUR storage classes and they are as follows...

1. auto storage class


2. extern storage class
3. static storage class
4. register storage class
PROGRAMMING FOR PROBLEM SOLVING UNIT 3
auto storage class
The default storage class of all local variables (variables declared inside block or function) is
auto storage class. Variable of auto storage class has the following properties...

Property Description

Keyword auto

Storage Computer Memory (RAM)

Default Value Garbage Value

Scope Local to the block in which the variable is defined

Life time Till the control remains within the block in which variable is defined

Example Program 1
#include<stdio.h>
#include<conio.h>
int main()
{
int i;
auto char c;
float f;
printf("i = %d\tc = %c\tf = %f",i,c,f);
return 0;
}

Example Program 2
#include<stdio.h>
#include<conio.h>
int main()
{
int a=10;
PROGRAMMING FOR PROBLEM SOLVING UNIT 3
{
int a=20;
printf("%d",a);
}
printf(" %d",a);
return 0;
}

Example Program 3
#include<stdio.h>
#include<conio.h>
int main()
{
{
int a=20;
printf("%d",a);
}
printf(" %d",a); //a is not visible here
return 0;
}

External storage class


The default storage class of all global varibles (variables declared outside function) is
external storage class. Variable of external storage class has the following properties...

Property Description

Keyword extern

Storage Computer Memory (RAM)

Default Value Zero


PROGRAMMING FOR PROBLEM SOLVING UNIT 3
Property Description

Scope Global to the program (i.e., Throughout the program)

Life time As long as the program’s execution does not comes to end

Example Program 1
#include<stdio.h>
#include<conio.h>
int i; //By default it is extern variable
int main()
{
printf("%d",i);
return 0;
}

Example Program 2
#include<stdio.h>
#include<conio.h>
extern int i; //extern variable
int main()
{
printf("%d",i);
return 0;
}

Static storage class


The static storage class is used to create variables that hold value beyond its scope until the

end of the program. The static variable allows to initialize only once and can be modified any

number of times. Variable of static storage class has the following properties...
PROGRAMMING FOR PROBLEM SOLVING UNIT 3
Property Description

Keyword static

Storage Computer Memory (RAM)

Default Zero
Value

Scope Local to the block in which the variable is defined

Life time The value of the persists between different function calls (i.e.,
Initialization is done only once)

Example Program 1
#include<stdio.h>
#include<conio.h>
static int a;
int main()
{
printf("%d",a);
return 0;
}

Example Program 2
#include<stdio.h>
#include<conio.h>

static int i=10;


int main()
{
i=25; //Assignment statement
printf("%d",i);
PROGRAMMING FOR PROBLEM SOLVING UNIT 3
return 0;
}

Register storage class


The register storage class is used to specify the memory of the variable that has to be

allocated in CPU Registers. The memory of the register variable is allocated in CPU Register

but not in Computer memory (RAM). The register variables enable faster accessibility

compared to other storage class variables. As the number of registers inside the CPU is very

less we can use very less number of register variables. Variable of register storage class has

the following properties...

Property Description

Keyword register

Storage CPU Register

Default Garbage Value


Value

Scope Local to the block in which the variable is defined

Life time Till the control remains within the block in which variable is
defined

Example Program 1
#include<stdio.h>
#include<conio.h>

int main(){
register int a,b;
scanf("%d%d",&a,&b);
printf("%d %d",a,b);
}
PROGRAMMING FOR PROBLEM SOLVING UNIT 3
The following table provides detailed properties of all storage classes...

Storage Memory Default


Class Keyword Location Value Scope Life Time

Automatic auto Computer Garbage Local to the Till the control


Memory Value block in which remains within
(RAM) the variable the block in
has defined which variable is
defined

External extern Computer Zero Global to the As long as the


Memory program (i.e., program’s
(RAM) Throughout execution does
the program) not come to end

Static static Computer Zero Local to the The value of the


Memory block in which persists between
(RAM) the variable different function
has defined calls (i.e.,
Initialization is
done only once)

Register register CPU Garbage Local to the Till the control


Register Value block in which remains within
the variable the block in
has defined which variable is
defined

You might also like