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

Module 3

The document provides an overview of arrays in C programming, detailing their definition, properties, and classifications, including single and multi-dimensional arrays. It explains how to declare, initialize, and access array elements, along with examples of reading and writing array data using loops. Additionally, it covers the syntax for declaring and initializing both single and two-dimensional arrays, along with sample C programs demonstrating their usage.

Uploaded by

Tanmay Shankar
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 views27 pages

Module 3

The document provides an overview of arrays in C programming, detailing their definition, properties, and classifications, including single and multi-dimensional arrays. It explains how to declare, initialize, and access array elements, along with examples of reading and writing array data using loops. Additionally, it covers the syntax for declaring and initializing both single and two-dimensional arrays, along with sample C programs demonstrating their usage.

Uploaded by

Tanmay Shankar
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/ 27

Principles of Programming using C 22POP13

MODULE-III
ARRAYS
3.1 Arrays
 An Array is a special and powerful data structure and it is used to store, process and print
large amounts of data.
 “An array is a collection of similar type of items (elements) stored sequentially
(continuously) one after the other in memory”.

Ex: 1. int A[5] ; // Array of 5 Integers

A[0] 10

m
A[1] 20
A[2] 30
A[3] 40
A[4] 50

co
 The Elements in the Array A can be accessed using the common name A, but with different
index.
 The Element ‘10’ is called 0th Element and it can be accessed using the Subscript 0 (called
Index ‘0’) along with name of the array ‘A’.
e.
2. char B[5]; //Array of 5 Characters

B[0] ‘A’
dg

B[1] ‘r’
B[2] ‘r’
B[3] ‘a’
B[4] ‘y’
3. float C[5]; //Array of 5 floats
ue

C[0] 12.56
C[1] 234.20
C[2] 215.60
C[3] 322.50
vt

C[4] 123.45

 An ‘Index’ is also called as Subscript ([ ]). It is used to indicate the position of an


element in the Array.

Basic Properties of the Arrays


1. All the elements in an array should be of the same data type.
2. The elements are stored continuously in the memory. (For example, in the array char B[5] , if
the first address is 1000 then the data is stored contiguously in the addresses 1000, 1001,
1002 and so on).
3. The Subscript (index) of first item is always zero.
4. Each element of an array is accessed using the name of the Array, but with different
subscript.

Dept.of CS&E-BIET, DVG 1


Principles of Programming using C 22POP13
5. The Index of the Array is always an Integer number can’t be float.
Ex: a [1] or a [5].
a [1.5] is an Error.

3.2 Classification of Arrays


1. Single Dimensional Array
2. Multi-Dimensional Array

3.2.1 Single Dimensional Array


Definition:
Single dimensional array (One-dimensional array) is a linear list consisting of
related data items of same data type and in the memory, all the data items are stored

m
contiguously in memory locations one after the other.
Or
An array with one index is called as Single dimensional array (One-dimensional
array)

co
Declaration of Single dimensional arrays
 As we declare the variables before they are used in a program, an array must also be declared
and defined before it is used using following syntax.
 Syntax
e.
data_type array_name[size];

Where,
data_type: data type can be int, float, char etc.
dg

array_name: name of the array which is a valid C variable.


size: it is the number of elements in the array.
Complete declaration ends with Semicolon.

Ex: int Marks[5];


ue

Declares Marks as an array consisting of 5 elements of integer data type.

Ex: int Marks[5];

1000 35 Marks[0]
data type array_name 1002 45 Marks[1]
vt

1004 65 Marks[2]
1006 55 Marks[3]
char name[5]; 1008 75 Marks[4]

Memory location Array name

 5 memory locations are reserved. sizeof(int) is 2 bytes, 2*5=10 bytes are reserved.
 5 memory locations are reserved. sizeof(char) is 1 bytes 1*5=5 bytes are reserved.

Dept.of CS&E-BIET, DVG 2


Principles of Programming using C 22POP13
Initialization of Single dimensional arrays
 Once an array is declared it must be initialized with some values using Initialization.
“Process of assigning the values to the individual elements of an array is called as
Initialization of an array”.

Syntax data_type array_name[size]={v1,v2, ---- ,vn};

data_type: it can be int, float, char etc.


array_name: it is the name of the array.
size: it is the number of elements in the array.
v1,v2, ---- ,vn are the values and should be enclosed within ‘{‘ and ‘}’ separated by commas.

m
Ex: 1. int a[5] = {10, 20, 30, 40, 50};
 The compiler allocates 5 memory locations and these locations are initialized with the integer
values in the order specified.

co
a[0] 10
a[1] 20
a[2] 30
a[3]
40
a[4]
50
2. int a[5] = {10, 20};
e.
10 20 0 0 0
dg
a[0] a[1] a[2] a[3] a[4]
 When the numbers of initial values are lesser than declared array size then those many
elements will be initialized and other memory locations are automatically initialized to 0’s, in
case of numeric arrays.
 It is ‘partial array initialization’.
ue

3. int a[ ] = {10, 20, 30, 40, 50};

Size not specified


 If we have not specified the size then the compiler will calculate the size of the array based
on the number of initial values.
vt

4. char a[6] = {‘A’, ‘r’, ‘r’, ‘a’, ‘y’, ‘\0’};

A r r a y \0
a[0] a[1] a[2] a[3] a[4] a[5]

5. char b[ ] = “COMPUTER”; //String Initialization


C O M P U T E R \0

Null character at the end of the string

Dept.of CS&E-BIET, DVG 3


Principles of Programming using C 22POP13
Reading/Writing Single dimensional arrays
 We can easily read and write the array elements using for loop.
 Reading the elements of an array from the keyboard can be done using for loop and
“scanf( )” function.
 Writing/Displaying the elements of an array to the screen can be done using for loop and
“printf( )” function.

 C code or C instruction to read ‘n’ elements of an array is shown below:


for(i=0;i<n;i++)
{
scanf(“%d”,&a[i]);
}

m
 C code or C instruction to display/write ‘n’ elements of an array is shown below:

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

co
printf(“%d\n”,a[i]);
}

Example C programs of Single dimensional array


1. Write a C Program to read n items from keyboard and display them on the monitor.
#include<stdio.h>
e.
void main( )
{
int n,a[10],i;
printf(“Enter the size of array:”); Output:
dg

scanf(“%d”,&n); Enter the size of array:


printf(“Enter the array elements:\n”); 5
for(i=0;i<n;i++) Enter the array elements:
{ 12345
scanf(“%d”,&a[i]); Entered elements are:
} 1
ue

printf(“\nEntered elements are:\n”); 2


for(i=0;i<n;i++) 3
{ 4
printf(“%d\n”,a[i]); 5
}
}
vt

2. Write a C program to find the sum and average of n array elements.


#include<stdio.h>
void main( )
{ Output:
int n,a[10],i,sum=0; Enter the size of array:
float avg=0; 3
printf(“Enter the number of elements in the array:”); Enter the array elements:
scanf(“%d”,&n); 12
printf(“Enter the array elements:\n”); 34
for(i=0;i<n;i++) 50
{ Sum= 96
scanf(“%d”,&a[i]); Average =32
}

Dept.of CS&E-BIET, DVG 4


Principles of Programming using C 22POP13
for(i=0;i<n;i++)
{
sum=sum+a[i];
}
avg=sum/n;
printf(“Sum=%d\n Average=%f”,sum,avg);
}
3. Write a C program to find the largest of ‘n’ numbers in the array.
#include<stdio.h>
void main( )
{
int n,a[20],i,large=-1; Output:
printf(“Enter the size of array:\n”); Enter the size of array:
scanf(“%d”,&n); 5

m
printf(“Enter the array elements:\n”); Enter the array elements:
for(i=0;i<n;i++) 10
{ 20
scanf(“%d”,&a[i]); 30

co
} 40
for(i=0;i<n;i++) 50
{ The largest number in the
if(a[i]>large) array is= 50
{
large=a[i];
e.
}
}
printf(“The largest number in the array is=%d\n”,large);
}
dg

4. Write a C program to print the smallest of ‘n’ numbers in the array.


#include<stdio.h>
void main( )
{
int n,a[20],i,small=9999; Output:
printf(“Enter the number of elements in the array:\n”); Enter the size of array:
ue

scanf(“%d”,&n); 5
printf(“Enter the array elements:\n”); Enter the array elements:
for(i=0;i<n;i++) 10
{ 20
scanf(“%d”,&a[i]); 30
}
vt

40
for(i=0;i<n;i++) 50
if(a[i]<small) The largest number in the
{ array is= 10
small=a[i];
}
printf(“The smallest number in the array is=%d”,small);
}
3.2.2 Two dimensional arrays (Multi-dimensional arrays)
 Arrays which are specified with 2 subscripts (2 set of square brackets [ ][ ]) are called 2-
dimensional arrays.
 Arrays with two or more dimensions are called Multi-dimensional arrays.
 In 2-Dimensional Array, the first index indicates the ‘row size’( the number of rows)
and second index indicates the ‘column size’( the number of columns).

Dept.of CS&E-BIET, DVG 5


Principles of Programming using C 22POP13
Ex: int a[10][10]; //Two-dimensional array
int b[3][4][5]; //Three-dimensional array

Declaration of Two-dimensional arrays


 As we declare the variables before they are used in a program, an array must also be declared
before it is used using the following syntax.
Syntax:
data_type array_name [row_size][col_size];

data_type: It can be int, float, char etc.


array_name: It is the name of the array.
row_size: It is the number of rows in the array.

m
col_size: It is the number of columns in the array.
Semicolon is must at the end.

 The size used during declaration of the array is useful to reserve the specified memory

co
locations.

Ex: int a [2][4]; a[0][0] a[0][1] a[0][2] a[0][3]


col_size Col.0 Col.1 Col.2 Col.3
Row 0
Data type row_size
e.Row 1

Array name a[1][0] a[1][1] a[1][2] a[1][3]


dg
 The array ‘a’ is a 2-dimensional array with 2 rows and 4 columns. This declaration informs
the compiler to reserve 8 locations (2*4=8 locations, 2*8=16 bytes in total) continuously one
after the other.

Initialization of 2-dimensional arrays


 As we initialize a variable to the required value, we can initialize the individual elements of
ue

the array during initialization.


Syntax

data_type array_name[row_size][col_size]={
{a1,a2, ---- ,an},
vt

{b1,b2, ---- ,bn},


..…………...,
{z1,z2, ---- ,zn}
};

data_type: It can be int, float, char etc.


array_name: It is the name of the array.
row_size: It is the number of rows in the array.
col_size: It is the number of columns in the array.
a1 to an are the values assigned to 1st row, b1 to bn are the values assigned to 2nd row and so on.

Ex: 1. int a[4][3]= {{11,22,33}, {44,55,66},{77,88,99},{10,20,30} };


The array has 4 rows and 3 columns.

Dept.of CS&E-BIET, DVG 6


Principles of Programming using C 22POP13
Columns

0 1 2
0 11 22 33
1
44 55 66
Rows 2
3 77 88 99
10 20 30

2. int a[4][3]= {
{11,22},
{33,4},
{55,66},
{77,88}

m
};
The array has 4 rows and 3 columns.
Columns

co
0 1 2
0 11 22 0
1 //This is a partial array initialization
33 44 0
Rows 2
3 55 66 0
77 88 0
e.
Reading/Writing Two dimensional arrays
 To read the 2-dimensional array, we have to use two for loops along with scanf(), where the
dg

outer for loop indicates the number of rows to be read and the inner for loop indicates the
number of columns to be read.
 To read the ‘n’ array elements of Two dimensional array:
for(i=0;i<m;i++)
ue

{
for(j=0;j<n;j++)
{
scanf(“%d”,&a[i][j]);
}
}
vt

 To write/print the 2-dimensional array elements, we have to use two for loops along with
printf(), where the outer for loop indicates the number of rows to be printed and the inner for
loop indicates the number of columns to be printed.
 To print the ‘n’ array elements of Two dimensional array:
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf(“%d\t”,a[i][j]);
}
printf(“\n”);
}

Dept.of CS&E-BIET, DVG 7


Principles of Programming using C 22POP13
Example Programs:
1. Write a C Program to read and print 2-dimensional array.
#include<stdio.h>
void main( )
{
int a[10][10],i,j,m,n;
printf(“Enter the number of Rows and Columns of the Array:\n”);
scanf(“%d%d”,&m,&n);
printf(“Enter the Array elements:\n”);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++) Output:

m
{ Enter the number of Rows and
scanf(“%d”,&a[i][j]); Columns of the Array:
2 2
}
Enter the Array elements:
} 1

co
printf(“Entered array elements are:\n”); 2
for(i=0;i<m;i++) 3
{ 4
for(j=0;j<n;j++) Entered array elements are:
{ 1 2
e. 3 4
printf(“%d\t”,a[i][j]);
}
}
dg
printf(“\n”);
}
}
ue
vt

Dept.of CS&E-BIET, DVG 8


Principles of Programming using C 22POP13
2. Write a C program to add 2 matrices A and B and store sum in C.
#include<stdio.h>
void main( )
{
int a[10][10],b[10][10],c[10][10],i,j,m,n;
printf(“Enter the size of matrix:\n”);
scanf(“%d%d”,&m,&n);
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]); Output:
} Enter the size of matrix:

m
} 2 2
printf(“Enter the elements of Matrix B:\n”); Enter the elements of Matrix A:
for(i=0;i<m;i++) 1 2
{ 3 4

co
for(j=0;j<n;j++) Enter the elements of Matrix B:
{ 5 6
scanf(“%d”,&b[i][j]); 7 8
} The Resultant Matrix C is:
} 6 8
for(i=0;i<m;i++)
e. 10 12
{
for(j=0;j<n;j++)
{
c[i][j]=a[i][j]+b[i][j];
dg

}
}
printf(“The Resultant Matrix C is:\n”);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
ue

{
printf(“%d\t”,c[i][j]);
}
printf(“\n”);
}
vt

3. Write a C program to find the largest of ‘n’ array elements in a 2-Dimensional array.
#include<stdio.h>
void main( )
{
int a[10][10],i,j,m,n,big=-1;
printf(“Enter the size of matrix:\n”);
scanf(“%d%d”,&m,&n);
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]);

Dept.of CS&E-BIET, DVG 9


Principles of Programming using C 22POP13
} Output:
} Enter the size of matrix:
for(i=0;i<m;i++) 2 2
{ Enter the elements of Matrix A:
for(j=0;j<n;j++) 10 20
{ 30 40
if(a[i][j]>big) The largest element is: 40
{
big=a[i][j];
}
}
}
printf(“The largest element is:%d\n”,big);
}

m
4. Write a C program to find the smallest of ‘n’ array elements in a 2-Dimensional array.
#include<stdio.h>
void main( )

co
{
int a[10][10],i,j,m,n,small=9999;
printf(“Enter the size of matrix:\n”);
scanf(“%d%d”,&m,&n);
printf(“Enter the elements of Matrix A:\n”);
e.
for(i=0;i<m;i++)
{
for(j=0;j<n;j++) Output:
dg
{ Enter the size of matrix:
2 2
scanf(“%d”,&a[i][j]);
Enter the elements of Matrix A:
} 10 20
} 30 40
for(i=0;i<m;i++) The largest element is: 10
{
ue

for(j=0;j<n;j++)
{
if(a[i][j]<small)
{
vt

small=a[i][j];
}
}
}
printf(“The smallest element is:%d\n”,small);
}

Dept.of CS&E-BIET, DVG 10


Principles of Programming using C 22POP13

m
co
e.
dg
ue
vt

Dept.of CS&E-BIET, DVG 11


Principles of Programming using C 22POP13

FUNCTIONS AND RECURSION


Function (Subroutine or subprogram)

✔ “Function is a small program or program segment that carryout some specific


well-defined tasks”.
Advantages of Functions
i. Reduces the Complexity.
✔ When a program contains more number of instructions (complex program), then such large

m
program can be divided into number of sub programs called as functions.
ii. Improves the Readability.
iii. Easy to debug the errors.
iv. Reusability: The set of instructions specifying the task performed by the function is written just

co
once but it can be used any number of times.
v. Easy to do the modifications.

Types of Functions
i. Library Functions/Pre-Defined/ Built-in Functions
e.
✔ C Library of C Compiler has a collection of various functions which perform some standard
and pre-defined tasks.
✔ These functions written by designers of C Compilers are called as Library
functions/Pre-Defined/Built-in functions.
dg

Ex: sqrt(n)- computes square root of n.


𝑦
pow(x,y)- computes 𝑥 .
printf()- used to print the data on the screen.
scanf()- used to read the data from the keyboard.
abs(x)- computes absolute value of x.
ue

Example: Write a C program to demonstrate the usage of Built-in functions.


#include<stdio.h>
#include<math.h>
void main() float sqrt(float num)
{ {
vt

float n,res; statement-1;


printf(“Enter the value of n:\n”); statement-2;
scanf(“%f”,&n); ……………
res=sqrt(n); return statement;
printf(“Square root=%f”,res); }
}

Dept.of CS&E-BIET, DVG 1


Principles of Programming using C 22POP13

Called Function and Calling Function


✔ A function that is called (invoked) by writing the name of the function is called “Called
Function”.
✔ The invoking function is called “Calling Function”.

Example: in the above program main() function invokes sqrt() function, the function main() is
calling function and function sqrt() is called function.

ii. User-Defined/ Programmer Defined Functions


✔ The functions written by the programmer/user to do the specific tasks is called User-Defined/
Programmer Defined Functions.

m
✔ main( ) is the user defined function.

Elements of User-Defined Functions


✔ The three elements of user-defined functions are shown below:

co
i. Function Prototype/Declaration
ii. Function Definition
iii. Function Call
e.
Function Prototype/Declaration
✔ As we normally declare the variables before they are used, the functions also should be
declared before they are used.
✔ The process of declaring the functions before they are used (or called) in the program is
dg

called Function Prototype.


✔ The function prototype is also called as Function declaration.
✔ It is same as the Function Header but terminated with semicolon.
✔ It does not contain the body of the function.
Syntax
ue

return_type function_name(parameter list);

Where,
return_type: This is the data type of the value that the function is expected to return (int, float,
double, char).
vt

function_name: It is the name of the function. It can be any valid Identifier.


parameter list: The parameters are the list of variables enclosed within parenthesis. Variables
are separated by comma.

Ex: int add(int a,int b);


✔ The function prototype contains the following information in a single line terminated by
semicolon:
● The type of the value returned by the function.
● The name of the function.
● The number of parameters passed to that function.
● The type of each parameter.

Dept.of CS&E-BIET, DVG 2


Principles of Programming using C 22POP13

Function Definition
✔ The program module that is written to achieve a specific task is called function
definition.
✔ Each function definition consists of two parts:
⮚ Function Header
⮚ Function Body
Syntax: return_type function_name (parameter list)
{
declaration part;
executable part;
return statement;

m
}
return_type:
✔ This is the data type of the value that the function is expected to return (int, float, double,
char).

co
✔ If the function is not returning any value, then we need to specify the return type as ‘void’.
✔ The default return value of any function is integer.
function_name:
✔ It is the name of the function. It can be any valid Identifier.
Parameters:
e.
✔ The parameters are the list of variables enclosed within parenthesis. Variables are separated
by comma.
Data type of parameters
dg

Ex: int add ( int a, int b);

Parameter name
return type Function name
Function Body
ue

✔ Declaration part: All the variables used in the function body should be declared in this part.
✔ Executable par: This part contains the statements or instructions that perform the specified
activity.
✔ return statement: It is a keyword used to return the control to the calling function (main)
with/without a value.
vt

Syntax:
1.
// Returns control without sending any value to main program

2. // Returns control by sending value to main program

Ex: int add(int a,int b)


{
int sum; //variable declaration
sum=a+b; //executable statement
return sum; //return statement
}

Dept.of CS&E-BIET, DVG 3


Principles of Programming using C 22POP13

Function Call
✔ Once the function is defined, it has to be called so as to achieve the task. This method of
calling a function to achieve a specified task is called Function Call.
✔ The function can be called by writing the name of the function and passing the appropriate
number of arguments.
✔ The number of arguments in the function call and number of parameters in the function
definition must match.
✔ Also the order of arguments in the function call and parameters in the function definition
must match.

m
Example: add(m,n);

Example Program: Write a C program to perform the addition of two numbers using function

co
#include<stdio.h>
int add(int a,int b); /*Function Prototype*/
int add(int a,int b)
{
int sum;
sum=a+b;
e.
return sum;
}
void main()
dg

{
int result;
result=add(10,20);
printf(“sum=%d\n”,result);
getch();
ue

1. The function add() is called with two arguments 10 and 20.


2. The control is transferred to the function add() and the values 10 and 20 are received using
vt

variables a and b.
3. The result is computed by adding 10 and 20.
4. The result is returned to the main() and will be copied into the variable result.
5. The result is displayed on the screen.

✔ The ‘main()’ is always the “Calling Function”.


✔ The ‘add()’ function is called “Called Function”.

Dept.of CS&E-BIET, DVG 4


Principles of Programming using C 22POP13

Function Parameters
✔ “The list of variables defined in the function header within the parenthesis are called
Function parameters”.
✔ There are 2 types of parameters in ‘C’ functions.
i. Actual parameters
ii. Formal parameters

i. Actual or Real Parameters


✔ The variables that are used when a function is invoked are called actual parameters.
✔ Actual parameters are used in the Calling function when a function is invoked.
✔ Actual parameters send values or addresses to the formal parameters. Formal parameters

m
receive them and use the same values.
✔ Actual parameters can be constants, variables or expressions.
Ex: res = add (m, n);

co
ii. Formal or Dummy Parameters
✔ The variables defined in the function header or function definition are called formal
parameters.
✔ All the variables should be separately declared and each declaration must be separated by
commas.
e.
✔ The formal parameters receive values form the actual parameters.
✔ If the formal parameters receive the address from the actual parameters, then they should be
declared as pointers.
dg

✔ The formal parameters should be only variables. Expressions and constants are not allowed.
Ex: int add(int a,int b);

Example Program: C Program to define actual and formal parameters.


#include<stdio.h>
ue

int add(int a,int b) // Formal Parameters a, b


{
int sum;
sum=a+b;
vt

return sum;
}
void main()
{
int m,n,res;
printf(“Enter the values for m,n\n”);
scanf(“%d%d”,&m,&n);
res=add(m,n); // Actual parameters m,n
printf(“Sum=%d\n”,res);
}

Dept.of CS&E-BIET, DVG 5


Principles of Programming using C 22POP13

Location of Functions
✔ The placement of the function definition in relation to the main program is very important.
✔ There are a number of ways to arrange the main program and a function.

i. Functions immediately after #includes and #defines


✔ In this method, we can place the entire the function definition consisting of the function
header and function body in the beginning of the file immediately after #includes and
#defines if any.
✔ The definition of the function appears before the main programs call to the function. This is
called Top-down approach.
✔ In this situation, the function prototype is optional.

m
Syntax file method1.c

co
e.
✔ File method1.c contains a function followed by a main program.
Example Program
dg

#include<stdio.h>
#include<conio.h>
int add(int a,int b);

int add(int a,int b)


ue

{
int sum;
sum=a+b;
return sum;
}
vt

void main()
{
int m,n,res;
printf(“Enter the values for m,n:\n”);
scanf(“%d%d”,&m,&n);
res=add(m,n);
printf(“add(%d,%d)=%d\n”,m,n,res);
getch();
}

ii. Functions after main


✔ In this method, immediately after #includes and #defines, we write all function prototypes.
✔ Next, we write the main function that is followed by the function definitions.
Dept.of CS&E-BIET, DVG 6
Principles of Programming using C 22POP13
✔ Even though the function header comes after the main program, the function prototype
appears before the call to the function and it is called Bottom-up approach.
✔ Function prototype is compulsory in this method.

Syntax: file method2.c

m
✔ File method2.c contains a main program followed by a function.

co
Example Program
#include<stdio.h>
int add(int a,int b);
e.
void main()
{
int m,n,res;
dg

printf(“Enter the values for m,n:\n”);


scanf(“%d%d”,&m,&n);
res=add(m,n);
printf(“add(%d,%d)=%d\n”,m,n,res);
ue

int add(int a,int b)


{
vt

int sum;
sum=a+b;
return sum;
}
iii. Functions in Separate files (Separate Compilation)
✔ In this method, immediately after #includes and #defines we write all function prototypes.
✔ Next, we write the main function.
✔ All user function definitions will be in separate files.
✔ It puts the function in one file and the main program in another and compiles them separately.

Dept.of CS&E-BIET, DVG 7


Principles of Programming using C 22POP13
This is the way library functions are used.

Syntax: file method3.c file method4.c

separate file

✔ Here the file method3.c contains a main program and also a separate file.
✔ The file method4.c is a separate file containing a function and it performs some specific tasks

m
and returns the value or result to the main program in a file ‘method3.c’. i.e., a separate file.

Example Program

co
#include<stdio.h> main.c int add(int a,int b) add.c
#include<conio.h> {
int add(int a,int b); int sum;
sum=a+b;
void main() return sum;
e.
{ }
int m,n,res;
printf(“Enter the values for m,n:\n”);
dg
scanf(“%d%d”,&m,&n);
res=add(m,n);
printf(“add(%d,%d)=%d\n”,m,n,res);
}
ue

Categories of Functions
✔ Based on the parameters and return value, the functions have been classified into four categories.
vt

1. void and parameter less functions (Functions with no parameters and no return values)
2. non void and parameter less functions(Functions with no parameters and return values)
3. void with parameters functions (Functions with parameters and no return values)
4. non void with parameters functions (Functions with parameters and return values)

Dept.of CS&E-BIET, DVG 8


Principles of Programming using C 22POP13
1. void and parameter less functions (Functions with no parameters and no return values)
✔ In this category there is no data transfer between the calling function and the called function.
✔ So calling function cannot send values and hence called function cannot receive the data and
it will not send any parameter back to function.
Example: Program showing function call with no parameters and returns no value.
#include<stdio.h>
void add()
void main() {
{ int a=10, b= 20,sum;
add();

m
sum=a+b;
} printf(“Sum=%d”,sum);
/*No return value*/
}

co
2. non void and parameter less functions (Functions with no parameters and return values)
✔ In this category there is no data transfer from the calling function and the called function.
✔ But, there is data transfer from the called function to the calling function.
e.
✔ When the function returns a value, the calling function receives one value from the called
function.
dg
✔ We can write a function that has no parameters but returns an answer to the main program as
shown in the syntax.

Example: Program showing function call without parameters, with return value.
#include<stdio.h>
ue

int add()
void main() {
{ int res; int a=10, b= 20,sum;
res= add();
printf(“Sum=%d”,res); sum=a+b;
vt

} return sum;
}

3. void with parameters functions (Functions with parameters and no return values)
✔ In this category, there is a data transfer from the calling function to the called function using
parameters.
✔ But, there is no data transfer from the called function to the calling function

Dept.of CS&E-BIET, DVG 9


Principles of Programming using C 22POP13
Example: Program showing a function call with parameters and no return value.
#include<stdio.h>
void add(int m, int n)
void main() {
{
int a=10, b=20; int sum;
add(a,b);
sum= m + n;
} printf(“Sum=%d”,sum);
}

m
4. non void with parameters functions (Functions with parameters and return values)
✔ In this category, there is data transfer between the calling function and the called function.
✔ When parameters are passed, the called function can receive values from the calling function.

co
✔ When the function returns a value, the calling function can receive a value from the called
function.

Example: Program showing a function call with parameters and with returns value.
e.
#include<stdio.h>
void add(int m, int n)
void main() {
dg

{
int a=10, b=20, res; int sum;
res=add(a,b);
printf(“Sum=%d”, res); sum= m + n;
} return sum;
ue

Argument Passing or Parameter Passing Methods


✔ There are mainly two parameter passing mechanisms in ‘C’ functions. They are:
vt

i. Call by Value or Pass by Value


ii. Call by Address or Pass by Address

i. Call by Value or Pass by Value


✔ Calling (Invoking) a function by passing values or variables to the function is called as
call by value.
✔ The values of actual parameters are copied into formal parameters.
✔ Formal parameters contain only the copy of actual parameters. So, even if the values of the
formal parameters changes in the called function, the values of the actual parameters are not
changed.

Dept.of CS&E-BIET, DVG 10


Principles of Programming using C 22POP13
Example Program: Write a C program to add two numbers using call by value.
#include<stdio.h>
void add (int a, int b) // Formal parameters a = 10, b =20
{
int sum;
sum = a + b;
return sum;
}
void main()
{
int m=10,n=20, res;
res = add(m,n); // Actual parameter m=10, n =20

m
printf(“result = %d \n”, res);
}

ii. Call by Address or Pass by Address

co
✔ Call by address is done indirectly by passing the address of the variables in the function
call and changing the value of the variable through its address.
✔ In the called function, the formal parameters should be declared as pointers with the same
e.
type as the actual parameters.
✔ The addresses of actual parameters are copied into formal parameters. Using these addresses
the values of the actual parameters can be changed.
dg

✔ In call by reference if any change in formal parameters imply then there is a change in
actual parameters.

Example Program: Write a C program to add two numbers using call by reference.
#include<stdio.h>
ue

void add (int *a, int *b) // Formal parameters *a = 10, *b =20
{
int sum;
sum = *a + *b;
return sum;
vt

}
void main()
{
int m=10,n=20, res;
res = add(&m, &n); // Actual parameter m=10, n =20
printf(“result = %d \n”, res);
}

Dept.of CS&E-BIET, DVG 11


Principles of Programming using C 22POP13
Example Program: Write a C program to swap two numbers using call by reference.
#include<stdio.h>
void swap(int *a, int *b)
{
int temp;
temp=*a;
*a=*b;
*b=temp;
}
void main()
{
int m=10,n=20;

m
swap(&m,&n);
printf(“m=%d\n n=%d\n”,m,n);
}

co
Using Arrays with Functions
The arrays can be passed to functions using two methods:
i. Passing individual elements of the array
ii. Passing the whole array
e.
1. Passing individual elements of the array
✔ All array elements can be passed as individual elements to a function like any other variable.
Example program: Write a C program to print square of given array elements.
#include<stdio.h>
dg

void print_square(int x)
{
printf(“%d”, x*x);
}
void main()
ue

{
int n,a[10],i;
printf(“Enter the number of elements:”);
scanf(“%d”,&n);
printf(“\nEnter the array elements:\n”);
vt

for(i=0;i<n;i++)
{
scanf(“%d”,&a[i]);
}
printf(“Squares of array elements are:\n);
for(i=0;i<n;i++)
{
print_square(a[i]); //Passing each individual element of the array to the function
}
}

Dept.of CS&E-BIET, DVG 12


Principles of Programming using C 22POP13
2. Passing the whole array
✔ Suppose, we want to pass whole array to a function. In such situation, we must follow the
two rules:
1. The function must be called by passing only the name of the array.
2. In the function definition, the parameter must be declared as an array of the same type as that
of actual parameter. There is no need to specify the size of the array.

Example Program: Write a C program to read the array elements using functions.
#include<stdio.h>

m
void read_array(int a[ ], int n) // no need to specify the size of the array
{
int i;

co
for(i=0;i<n;i++)
{
scanf(“%d”,&a[i]);
}
e.
}
void main()
{
dg

int n,b[10],i;
printf(“Enter the number of elements:”);
scanf(“%d”,&n);
printf(“\nEnter the array elements:\n”);
ue

read_array (b, n); // function must be called by passing only the name of the array
printf(“The array elements are:\n);
for(i=0; i<n; i++)
{
vt

printf(“%d”, b[i]);
}
}

Dept.of CS&E-BIET, DVG 13


Principles of Programming using C 22POP13
Recursion
✔ “The process in which a function calls itself again and again is called as Recursion”.
✔ A function which calls itself again and again is called as Recursive function.
✔ While using recursion, user need to be careful to define exit condition from function; otherwise it
will go in infinite loop.
✔ Recursive functions are very useful to solve many mathematical problems like to calculate
factorial of a number, generating Fibonacci series, etc.
Syntax:
Void main() int recursion ()

{ {

m
recursion ( ); recursion ( );

} }

Example: Program to calculate factorial of a given number.

co
#include<stdio.h>
int factorial(int n)
{
if(n==1)
return 1;
e.
else
return (n*fact(n-1));
}
dg

void main()
{
int n,fact;
printf(“Enter a number=”);
scanf(“%d”,&n);
ue

fact=factorial(n);
printf(“\nFactorial of given number=%d”,fact);
}

Example: Program to calculate nCr value using recursion function.


vt

#include<stdio.h>
int factorial(int n)
{
if(n==1)
return 1;
else
return (n*fact(n-1));
}
void main()
{
int n,fact;
printf(“Enter a value for n and r”);
scanf(“%d”,&n);
Dept.of CS&E-BIET, DVG 14
Principles of Programming using C 22POP13
fact=factorial(n) / (factorial(n-r) * factorial(n));
printf(“\n nCr value =%d”,fact);
}

Example: C Program to find the Fibonacci series using recursive function.


#include<stdio.h>
int fibonacci (int n)
{
if( n = = 0)
return 0;
else if (n = = 1)
return 1;

m
else
return ( fibonacci (n-1) * fibonacci (n-2));
}

co
void main()
{
int n, i, result;
printf(“Enter a value for n ”);
scanf(“%d”, &n);
e.
printf(“ The Fibonacci series is: \n”);
for ( i =0; i < n ; i ++)
{
res = fibonacci (i);
dg

printf(“%d\n”, res);
}
}
ue
vt

Dept.of CS&E-BIET, DVG 15


Principles of Programming using C 22POP13

ASSIGNMENT QUESTIONS

1. Define function? Explain the declaration of function with example?


2. Explain the different Parameter used in function with example?
3. Explain the categories of functions with examples.
4. Explain the two parameter passing techniques used in functions.
5. Explain how to pass an array to function with example.

m
6. Define recursion? Explain the recursion with example.
7. Write a program to calculate nCr value using recursion.

co
8. Write a program to print the Fibonacci series using recursion.

9. Write a program to convert binary to decimal using recursion.

10. Write a C program to find factorial a given number using recursion.


e.
11. Write a C program to calculate gcd and lcm of 2 integers using functions.
dg
ue
vt

Dept.of CS&E-BIET, DVG 16

You might also like