[go: up one dir, main page]

0% found this document useful (0 votes)
178 views169 pages

Unit 3

- The document discusses two-dimensional arrays in C programming. - It explains how to declare, initialize, access elements of, and perform basic operations like addition and transpose on 2D arrays. - Examples are provided to demonstrate initializing, accessing elements, adding two matrices, finding the transpose of a matrix using 2D arrays.

Uploaded by

Raskshanna
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)
178 views169 pages

Unit 3

- The document discusses two-dimensional arrays in C programming. - It explains how to declare, initialize, access elements of, and perform basic operations like addition and transpose on 2D arrays. - Examples are provided to demonstrate initializing, accessing elements, adding two matrices, finding the transpose of a matrix using 2D arrays.

Uploaded by

Raskshanna
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/ 169

18CSS101J

PROGRAMMING FOR
PROBLEM SOLVING

UNIT 3
Course Learning Outcome (CLO – 3)

• Analyze programs that need storage and form single and


multi-dimensional arrays.
• Use preprocessor constructs in C.
Topics that will be covered in this Session

• Initializing and Accessing 2D Array


• Initializing Multidimensional Array
• Array Programs – 2D
• Array Contiguous Memory
• Array Advantages and Limitations
• Array construction for real time application common
programming errors
TWO DIMENSIONAL
ARRAY
Two Dimensional Array

• The simplest form of multidimensional array is the two-dimensional array.


• The 2D array is organized as matrices which can be represented as the
collection of rows and columns. It has two subscripts.
• 2D arrays are created to implement a relational database lookalike data
structure.
• It provides ease of holding the bulk of data at once which can be passed to
any number of functions wherever required.
• A two-dimensional array is pretty much a list of one-dimensional arrays.
• To declare a two-dimensional integer array of size [ x ][ y ].
2D Array - Declaration

• The syntax to declare the 2D array is,


datatype arrayname [x][y];
Where
datatype can be any valid C data type
arrayname will be a valid C identifier
x is number of rows
y is number of columns
2D – Declaration (Cont..)
• A two-dimensional array a, which contains three rows and four columns
can be shown:

• Every element in the array a is identified by an element name in the


form a[i][j], where 'i' and 'j' are the indexes that uniquely identify.
2D – Declaration (Cont..)
For Example,
int Employee[4][3];
• Here, we used int as the data type to declare an array. So, above C two dimensional array
will accept only integers. If you try to add float values, it will through an error.
• Employees – the name of the Two Dimensional Array in C
• The Row size of an Array is 4. It means Employees array will only accept four integer
values as rows.
o If we try to store more than 4 values, then it will throw an error.
o We can store less than 4. For Example, If we store two integer values, then the
remaining 2 values will assign to the default value (Which is 0).
• The Column size of an Array is 3. It means Employees array will only accept 3 integer
values as columns.
o If we try to store more than 3, it will throw an error.
o We can store less than 3. For Example, If we store 1 integer value, the remaining 2
values will be assigned to the default value (Which is 0).
2D Array - Initialization

• Multidimensional arrays may be used by specifying bracketed[] values for


each row.
• Below is an array with 3 rows and each row has 4 columns.
int a[3][4]={{0,1,2,3},{4,5,6,7},{8,9,10,11}};

• The inside braces, which indicates the wanted row, are optional.
• The following initialization is the same to the previous example −
int a[3][4]={{0,1,2,3,4,5,6,7,8,9,10,11}};
Accessing 2D Array Elements
• To access elements of a two-dimensional array we use array name with
row index value and column index value of the element that to be
accessed.
• The row and column index values must be in separate square braces. In
the case of the two-dimensional array, the compiler assigns separate index
values for rows and columns.
• An element in a two-dimensional array is accessed by using the subscripts,
i.e., row index and column index of the array. For example −
int val = a[2][3];
• The above statement will take the 4th element from the 3rd row of the
array.
Processing of 2D Array
• A two-dimensional can be considered as a matrix. Two loops are used to
process a two-dimensional array as shown below:
for(i=0;i<rows;i++)
{
for(j=0;j<cols;j++)
{ .
.
}
}
where rows → number of rows in the matrix
cols → number of columns in the matrix
2D Array Memory representation
2D Array Memory representation (Cont..)
2D Array - Example
#include<stdio.h> for(i=0;i<rows;i++)
int main() {
{ for(j=0;j<cols;j++)
int rows,cols,i,j; {
int a[10][10]; printf("%d\t",a[i][j]);
printf("How many rows : "); }
scanf("%d",&rows); printf("\n");
printf("How many columns : "); } Output:
scanf("%d",&cols); return 0;
printf("Enter the elements of the matrix\n"); } How many rows : 2
for(i=0;i<rows;i++) How many columns : 2
{
Enter the elements of the
for(j=0;j<cols;j++)
{ matrix
scanf("%d",&a[i][j]); 5 10 8 4
} The matrix you've entered is
} 5 10
printf("The matrix you've entered is\n"); 8 4
2D Array – Example
// To add & subtract two matrices scanf(“%d”,&b[i][j]); for(j=0;j<cols;j++)
#include<stdio.h> } {
int main() { } printf("%d\t",d[i][j]);
int rows,cols,i,j; }
for(i=0;i<rows;i++)
int a[10][10],b[10][10],c[10][10],d[10][10]; printf("\n");
{
printf("MATRIX ADDITION\n\n"); } return 0;
for(j=0;j<cols;j++)
printf("How many rows : "); }
{
scanf("%d",&rows);
c[i][j]=a[i][j]+b[i][j];
printf("How many columns : ");
scanf("%d",&cols);
d[i][j]=a[i][j]-b[i][j]; Output:
}
printf("Enter the elements of the first matrix\n");
} MATRIX ADDITION
for(i=0;i<rows;i++)
printf("Result of Addition\n"); How many rows : 2
{ How many columns : 2
for(i=0;i<rows;i++)
for(j=0;j<cols;j++) Enter the elements of the first matrix
{ 2 5 8 9
{
for(j=0;j<cols;j++) Enter the elements of the second matrix
scanf("%d",&a[i][j]);
{ 1 2 3 4
}
printf("%d\t",c[i][j]);
} Result of Addition
} 3 7
printf(“Enter the elements of the second matrix \n”);
printf("\n"); 11 13
for(i=0;i<rows;i++)
}
{ Result of Subtraction
printf("Result of Subtraction\n"); 3 3
for(j=0;j<cols;j++)
for(i=0;i<rows;i++) 5 5
{
{
2D Array – Example
// To find the transpose of a matrix printf("The transpose of the matrix is\n");
#include<stdio.h> for(j=0;j<cols;j++)
int main() {
{ for(i=0;i<rows;i++)
int rows,cols,i,j; {
int a[10][10]; printf("%d\t",a[i][j]);
printf("How many rows : "); }
scanf("%d",&rows); printf("\n");
printf("How many columns : "); }
scanf("%d",&cols); return 0;
printf("Enter the elements of the matrix\n"); }
Output:
for(i=0;i<rows;i++)
{ How many rows : 3
for(j=0;j<cols;j++) How many columns : 3
Enter the elements of the matrix
{ 5 6 8 7 9 5 6 4 8
scanf("%d",&a[i][j]);
The transpose of the matrix is
} 5 7 6
6 9 4
} 8 5 8
2D Array – Example
// To find the sum of all the {
elements of a matrix scanf("%d",&a[i][j]);
sum=sum+a[i][j];
}
#include<stdio.h>
}
int main()
printf("Sum of all the elements = %d\n",sum);
{
return 0;
int rows,cols,i,j,sum=0;
}
int a[10][10];
printf("How many rows : ");
scanf("%d",&rows); Output:
printf("How many columns : ");
How many rows : 3
scanf("%d",&cols); How many columns : 3
printf("Enter the elements of the matrix\n"); Enter the elements of the matrix
5 6 8 7 9 5 6 4 8
for(i=0;i<rows;i++)
{ Sum of all the elements = 58
for(j=0;j<cols;j++)
2D Array – Example
// To find the sum of diagonal elements of a
square matrix sum=sum+a[i][j];
}
#include<stdio.h> }
int main() }
{ printf("Sum of diagonal elements = %d\n",sum);
int rc,i,j,sum=0; return 0;
int a[10][10]; }
printf("How many rows & columns in a square matrix : ");
scanf("%d",&rc);
printf("Enter the elements of the matrix\n"); Output:
for(i=0;i<rc;i++)
{ How many rows & columns in a
for(j=0;j<rc;j++)
square matrix : 3
Enter the elements of the matrix
{
5 6 8 7 9 5 6 4 8
scanf("%d",&a[i][j]);
if(i==j) Sum of diagonal elements = 22
{
MULTI DIMENSIONAL
ARRAY
Multi Dimensional Array

• In C programming an array can have two, three, or even ten or more


dimensions.
• The maximum dimensions a C program can have depends on which
compiler is being used.
• More dimensions in an array means more data be held, but also means
greater difficulty in managing and understanding arrays.
Multi Dimensional Array - Declaration
• A multidimensional array is declared using the following syntax:
type array_name[d1][d2][d3][d4]………[dn];
Where each d is a dimension, and dn is the size of final dimension.
Examples:
int table[5][5][20];
float arr[5][6][5][6][5];
• In Example 1:
• int designates the array type integer.
• table is the name of our 3D array.
• Our array can hold 500 integer-type elements. This number is reached
by multiplying the value of each dimension. In this case: 5x5x20=500.
THREE DIMENSIONAL
ARRAY
Three Dimensional Array
• If an array has three subscript, then it is called three dimensional array.
3D Array - Declaration
• The basic syntax or, the declaration of dimensional array in C
Programming is

Data_Type Array_Name[Tables][Row_size][Column-size];

• Data_type: It will decide the type of elements it will accept. For example,
If we want to store integer values then we declare the Data Type as int, If
we want to store Float values then we declare the Data Type as float etc
• Array_Name: This is the name you want to give it to Multi Dimensional
array in C.
3D Array – Declaration (Cont..)

• Tables: It will decide the number of tables an array can accept. Two
Dimensional Array is always a single table with rows and columns. In
contrast, Multi Dimensional array in C is more than 1 table with rows and
columns.
• Row_Size: Number of Row elements an array can store. For example,
Row_Size =10, the array will have 10 rows.
• Column_Size: Number of Column elements an array can store. For
example, Column_Size = 8, the array will have 8 Columns.
3D Array – Declaration (Cont..)
For Example:
int Employees[2][4][3];
• Here, we used int as the data type to declare an array. So, the above array
will accept only integers. If you try to add float values, it throws an error.
• Employees is the array name
• The number of tables = 2. So, this array will hold a maximum of 2 levels of
data (rows and columns).
• The Row size of an Array is 4. It means Employees array only accept 4
integer values as rows.
• If we try to store more than 4, it throws an error.
• We can store less than 4. For Example, If we store 2 integer values, the
remaining two will assign with the default value (Which is 0).
3D Array – Declaration (Cont..)
For Example:
int Employees[2][4][3];
• The Column size of an Array is 3. It means Employees array will only
accept 3 integer values as columns.
• If we try to store more than 3, it throws an error.
• We can store less than 3. For Example, If we store 1 integer values, the
remaining 2 values will assign with the default value (Which is 0).
• Finally, Employees array can hold a maximum of 24 integer values (2 * 4 *
3 = 24).
3D Array - Initialization
• We can initialize the C Multi Dimensional Array in multiple ways.
• First Approach of Multi Dimensional Array in C

• Here, We have 2 tables and the 1st table holds 4 Rows * 3 Columns, and the
2nd table also holds 4 Rows * 3 Columns
• The first three elements of the first table will be 1st row, the second three
elements will be 2nd row, the next three elements will be 3rdrow, and the
last 3 elements will be 4th row.
• Here we divided them into 3 because our column size = 3, and we
surrounded each row with curly braces ({}). It is always good practice to
use the curly braces to separate the rows.
3D Array – Initialization (Cont..)
• Second Approach of Multi Dimensional Array in C.

• Here, We did not mention the row size. But, the compiler is intelligent
enough to calculate the size by checking the number of elements inside the
row. We can also write
3D Array – Initialization (Cont..)
• Third Approach for Multi Dimensional Array in C

• Here, we declared Employees array with row size = 4 and column size = 3.
But we only assigned 1 column in the 1st row and 2 columns in the 2nd
row of the first table. In these situations, the remaining values will assign
to default values (0 in this case).
• The above Multi Dimensional array in C will be:
3D Array – Initialization (Cont..)
• Third Approach for Multi Dimensional Array in C

• Here, we declared Employees array with row size = 4 and column size = 3.
But we only assigned 1 column in the 1st row and 2 columns in the 2nd
row of the first table. In these situations, the remaining values will assign
to default values (0 in this case).
• The above Multi Dimensional array in C will be:
Accessing 3D Array
• We can access the C Multi Dimensional array elements using indexes.
• Index starts at 0 and ends at n-1, where n is the size of a row or column.
• For example, if an Array_name[4][8][5] will store 8-row elements and 5
column elements in each table where table size = 4.
• To access 1st value of the 1st table, use Array_name[0][0][0], to access 2nd
row 3rd column value of the 3rd table then use Array_name[2][1][2] and to
access the 8th row 5th column of the last table (4th table), use
Array_name[3][7][4].
Accessing 3D Array (Cont..)
3D Array – Example
// To read a 3D array as input and to print it for(i=0;i<tab;i++)
#include<stdio.h> { printf("\n\nTABLE %d\n\n",(i+1));
int main() { for(j=0;j<rows[i];j++)
int a[10][10][10],rows[10],cols[10],tab,i,j,k; { for(k=0;k<cols[i];k++)
printf("How many tables : "); { printf("%d\t",a[i][j][k]);
scanf("%d",&tab); } printf("\n");
for(i=0;i<tab;i++) } }
return 0;
Output:
{ How many tables : 2
printf("How many rows in table %d : ",(i+1)); } How many rows in table 1 :2
How many columns in table 1 :2
scanf("%d",&rows[i]); Enter 4 elements in Table 1 : 2 4 6 8
printf("How many columns in table %d : ",(i+1)); How many rows in table 2 :2
How many columns in table 2 :2
scanf("%d",&cols[i]); Enter 4 elements in Table 2 : 1 3 5 7
printf("Enter %d elements in Table %d : The table you’ve entered
",(rows[i]*cols[i]),(i+1));
Table 1
for(j=0;j<rows[i];j++)
2 4
{ for(k=0;k<cols[i];k++) 6 8
{ scanf("%d",&a[i][j][k]);
Table 1
} } } 1 3
5 7
printf("The tables you've entered\n");
3D Array – Example
// To get the total number of colleges in a university, name of all scanf("%s",studname[i][j][k]);
the colleges, courses offered, list of students registered and print
all the details } } }

#include<stdio.h> printf("University Details\n");

int main() { for(i=0;i<n_cols;i++)

char colname[10][10],course[10][10][10],studname[10][10][10][10]; { printf("%s\n",colname[i]);

int i,j,k,n_cols,n_course[10],n_stud[10][10]; for(j=0;j<n_course[i];j++)

printf("How many colleges in the University : "); { printf("\t%s\n",course[i][j]);

scanf("%d",&n_cols); for(k=0;k<n_stud[i][j];k++)

printf("Give the details of all the colleges\n"); { printf("\t %d. %s\n",(k+1),studname[i][j][k]);

for(i=0;i<n_cols;i++) } printf("\n");

{ printf("College Name : "); } } }

scanf("%s",colname[i]);
printf("No of courses offered in %s : ",colname[i]);
scanf("%d",&n_course[i]);
printf("Give the details of all courses\n");
for(j=0;j<n_course[i];j++)
{ printf("Course Name : ");
scanf("%s",course[i][j]);
printf("No of students registered for %s",course[i][j]);
scanf("%d",&n_stud[i][j]);
printf("Give the names of all the students\n");
for(k=0;k<n_stud[i][j];k++)
{ printf("Name : ");
ARRAY CONTIGUOUS
MEMORY
Array Contiguous Memory

• When Big Block of memory is reserved or allocated then that memory


block is called as Contiguous Memory Block.
• Alternate meaning of Contiguous Memory is continuous memory.
• Suppose inside memory we have reserved 1000-1200 memory addresses
for special purposes then we can say that these 200 blocks are going to
reserve contiguous memory.

How to allocate contiguous memory:


• Using static array declaration.
• Using alloc() / malloc() function to allocate big chunk of memory
dynamically.
Contiguous Memory Allocation
• Two registers are used while implementing the contiguous memory
scheme. These registers are base register and limit register.
• When OS is executing a process inside the main memory then content of
each register are as –
• Register - Content of register.
• Base register- Starting address of the memory location where process
execution is happening.
• Limit register- Total amount of memory in bytes consumed by process.
• When process try to refer a part of the memory then it will firstly refer the
base address from base register and then it will refer relative address of
memory location with respect to base address.
ARRAY ADVANTAGES
AND LIMITATIONS
Advantages of Array

• It is better and convenient way of storing the data of same datatype with
same size.
• It allows us to store known number of elements in it.
• It allocates memory in contiguous memory locations for its elements.
• It does not allocate any extra space/ memory for its elements. Hence there
is no memory overflow or shortage of memory in arrays.
• Iterating the arrays using their index is faster compared to any other
methods like linked list etc.
• It allows to store the elements in any dimensional array - supports
multidimensional array.
Limitations of Array
A) Static Data
• Array is Static data Structure
• Memory Allocated during Compile time.
• Once Memory is allocated at Compile Time it Cannot be changed during
Run-time.

B) Can hold data belonging to same Data types


• Elements belonging to different data types cannot be stored in array
because array data structure can hold data belonging to same data type.
• Example : Character and Integer values can be stored inside separate array
but cannot be stored in single array
Limitations of Array
C) Inserting data in Array is Difficult
• Inserting element is very difficult because before inserting element in an
array have to create empty space by shifting other elements one position
ahead.
• This operation is faster if the array size is smaller, but same operation will
be more and more time consuming and nonefficient in case of array with
large size.

D) Deletion Operation is difficult


• Deletion is not easy because the elements are stored in contiguous
memory location.
• Like insertion operation , we have to delete element from the array and
after deletion empty space will be created and thus we need to fill the
space by moving elements up in the array.
Limitations of Array
E) Bound Checking
• If we specify the size of array as ‘N’ then we can access elements upto ‘N-1’ but in C if we
try to access elements after ‘N-1’ i.e Nth element or N+1th element then we does not get
any error message.
• Process of Checking the extreme limit of array is called Bound checking and C does not
perform Bound Checking.
• If the array range exceeds then we will get garbage value as result.
F) Shortage of Memory
• Array is Static data structure. Memory can be allocated at compile time only. Thus if after
executing program we need more space for storing additional information then we
cannot allocate additional space at run time.
• Shortage of Memory , if we don’t know the size of memory in advance
G) Wastage of Memory
• Wastage of Memory , if array of large size is defined.
ARRAY CONSTRUCTION
FOR REAL-TIME
APPLICATION COMMON
PROGRAMMING ERROR
(i) Constant Expression Require
#include<stdio.h> • If we changed the value of variable
void main() then array size is going to change.

{ • According to array concept, we are


allocating memory for array at
int i=10; compile time so if the size of array
int a[i]; is going to vary then how it is
} possible to allocate memory to an
array.
In this example we see what’s that
error? • i is initialized to 10 and using a[i]
does not mean a[10] because ‘i’ is
• We are going to declare an array Integer Variable whose value can
whose size is equal to the value of be changed inside program.
variable.
(i) Constant Expression Require (Cont..)
• Value of Const Variable Cannot be changed
we know that value of Const Variable cannot be changed once
initialized so we can write above example as below –
#include<stdio.h>
void main()
{
const int i=10;
int a[i];
}
or
int a[10];
(ii) Empty Valued 1D Array
#include<stdio.h> • Consider this example, we can see
void main() the empty pair of square brackets
means we haven’t specified size of
{ an 1D Array. In this example array
int arr[]; ‘arr’ is undefined or empty.
} • Size of 1D Array should be
Specified as a Constant Value.
Instead of it Write it as –
#include<stdio.h>
#include<stdio.h>
void main()
void main()
{
{
int a[] = {};// This also Cause
int a[] = {1,1}; an Error
} }
(iii) 1D Array with no bound checking
#include<stdio.h>
void main()
{
int a[5];
printf("%d",a[7]);
}
• Here Array size specified is 5.
• So we have Access to Following Array Elements –
a[0],a[1],a[2],a[3] and a[4].
• But accessing a[5] causes Garbage Value to be used because C Does not
performs Array Bound Check.
(iv) Case Sensitive
#include<stdio.h>
void main()
{
int a[5];
printf("%d",A[2]);
}

• Array Variable is Case Sensitive so A[2] does not print anything it Displays
Error Message : “Undefined Symbol A“
Applications of Array
• Arrays are used to Store List of values: In C Programming language,
single-dimensional arrays are used to store a list of values of the same
datatype.
• Arrays are used to Perform Matrix Operations: We use two-dimensional
arrays to create matrix. We can perform various operations on matrices
using two-dimensional arrays.
• Arrays are used to implement Search Algorithms: We use single-
dimensional arrays to implement search algorithms like Linear Search,
Binary Search
• Arrays are used to implement Sorting Algorithms: We use single-
dimensional arrays to implement sorting algorithms like Insertion Sort,
Bubble Sort, Selection Sort, Quick Sort, Merge Sort, etc.,
• Arrays are used to implement Data structures: We use single-dimensional
arrays to implement data structures like Stack Using Arrays and Queue
Using Arrays
18CSS101J
PROGRAMMING FOR
PROBLEM SOLVING

UNIT 3
Course Learning Outcome (CLO – 3)

• Analyze programs that need storage and form single and


multi-dimensional arrays.
• Use preprocessor constructs in C.
Topics that will be covered in this Session

• String basics
• String Declaration and initialization
• String Functions: gets(), puts(), getchar(), putchar(), printf()
• String Functions: atoi, strlen, strcat, strcmp
• String Functions: sprint, sscanf, strrev, strcpy, strstr, strtok
• Arithmetic Characters on Strings
STRING BASICS
String Basics
• The string can be defined as the one-dimensional array of characters
terminated by a null ('\0’).
• The character array or the string is used to manipulate text such as word
or sentences.
• Each character in the array occupies one byte of memory, and the last
character must always be 0.
• The termination character ('\0') is important in a string since it is the only
way to identify where the string ends.
• When we define a string as char s[10], the character s[10] is implicitly
initialized with the null in the memory.
• Any group of characters (except double quote sign) defined between
double quotation marks is a string constant.
String Basics (Cont..)
• Example:
“Man is obviously made to think.”
• If we want to include a double quote in the string to be printed, then we
may use it with a back slash as shown below.
“\” Man is obviously made to think,\” said Pascal.”
• For example,
printf (“\” Well Done !”\”); will output the string
“ Well Done !”
• while the statement
printf(“ Well Done !”); will output the string
Well Done!
String Basics (Cont..)
• Strings in C are represented by arrays of characters.

• String is nothing but the collection of the individual array elements or


characters stored at contiguous memory locations.

I. Character array – 'P','P','S’

II. Double quotes - “PPS" is a example of String.

o If string contains the double quote as part of string then we can use
escape character to keep double quote as a part of string.

o “PPS" is a example of String.


String Basics (Cont..)
III Null Character
o The end of the string is marked with a special character, the null character,
which is a character all of whose bits are zero i.e., a NULL.
o String always Terminated with NULL Character (‘/0′)
char name[10] = {'P','P','S','\0’}
▪ NULL Character is having ASCII value 0
▪ ASCII Value of '\0' = 0
▪ As String is nothing but an array , so it is Possible to Access Individual
Character name[10] = "PPS";
o It is possible to access individual character
name[0] = 'P’;
name[1] = 'P’;
name[2] = 'S’;
name[3] = '\0';
String Basics (Cont..)
IV Memory
• Each Character Occupy 1 byte of Memory
• Size of "PPS" = Size of 'P’ +
= Size of 'P’ +
= Size of 'S' ;
• Size of "PPS” is 3 BYTES
• Each Character is stored in consecutive memory location.
Address of 'P' = 2000
Address of 'P' = 2001
Address of 'S' = 2002
String Basics (Cont..)
• Character strings are often used to build meaningful and readable
programs. The common operations performed on character strings include
the following:
• Reading and writing strings.
• Combining strings together.
• Copying one string to another.
• Comparing strings for equality.
• Extracting a portion of a string.
STRING DECLARATION
AND INITIALIZATION
String Declaration and Initialization
• C does not support strings as a data type.
• It allows us to represent strings as character arrays.
• A string variable is any valid C variable name and is always declared as an
array of characters.
• The general form of declaration of a string variable is:

char string_name[size];

• The size determines the number of characters in the string_name. Some


examples are as follows:

char city[10];
char name[30];
String Declaration and Initialization (Cont..)

Point Explanation
Significance We have declared array of character[i.e String]
Size of string 30 Bytes
Bound checking C Does not Support Bound Checking i.e if we store City with
size greater than 30 then C will not give you any error
Data type char
Maximum size 30
String Declaration and Initialization (Cont..)
Precautions to be taken while declaring Character Variable :
• String / Character Array Variable name should be legal C Identifier.
• String Variable must have Size specified.
char city[];
• Above Statement will cause compile time error.
• Do not use String as data type because String data type is included in later
languages such as C++ / Java. C does not support String data type
String city;
• When you are using string for other purpose than accepting and printing
data then you must include following header file in your code –
#include<string.h>
String Declaration and Initialization (Cont..)
• When the compiler assigns a character string to a character array, it
automatically supplies a null character (‘\0 ‘) at the end of the string.
• The size should be equal to the maximum number of characters in the
string plus one.
• character arrays may be initialized when they are declared.
• C permits a character array to be initialized in either of the following two
forms:
char city[9] = “NEW YORK”;
char city[9]= {‘N’,’E’,’W’,’ ‘,’Y’,’O’,’R’,’K’,’\0’};
• city had to be 9 elements long is that the string NEW YORK contains 8
characters and one element space is provided for the null terminator.
String Declaration and Initialization (Cont..)
• To initialize a character array without specifying the number of elements.
• The size of the array will be determined automatically, based on the
number of elements initialized.
• For example, the statement

char string[ ]= {‘G’,’O’,’O’,’D’,’\0’};

• defines the array string as a five element array.


• We can also declare the size much larger than the string size in the
initializer. That is, the statement.

char str[10] = “GOOD”; is permitted


String Declaration and Initialization (Cont..)
• The computer creates a character array of size 10, places the value
“GOOD” in it, terminates with the null character, and initializes all other
elements to NULL. The storage will look like

• The following declaration is illegal.


char str2[3] = “GOOD”;
• This will result in a compile time error. We cannot separate the
initialization from declaration. That is,

char str3[5]; char s1[4] = “abc”;


str3 = “GOOD”; char s2[4]; is not allowed.
S2 = s1; /*Error*/
STRING FUNCTIONS
gets(), puts(), getchar(),
putchar(), printf()
String Functions – gets()
• Reads a string from the keyboard.
• gets() function accepts single or multiple characters of string including
spaces from the standard input device until ENTER key is pressed. This
function in <stdio.h> header file.
Syntax: gets(var_name);
Where var_name is string or array of characters.
• gets() is also buffered function. It will read a string from the keyboard
until the user presses the Enter key from the keyboard.
• It will mark the null character (‘\0’) in the memory at the string when you
press the enter key.
• gets stops when either the newline character is read or when the end-of-
file(EOF) is reached, whichever comes first.
String Functions – puts()
• Writes a string to the screen. #include <stdio.h>
• puts() function displays or writes a int main()
string to the standard output {
device. char name[20];
printf("Enter the name");
• It appends a newline character to gets(name);
string. This function is defined in printf(“\n Name is:");
<stdio.h> header file. puts(name);
Syntax: puts(var_name); return 0;
} Output:
Where var_name is string or array of Enter the name
characters. Disney
Name is: Disney
String Functions – getchar()
• It reads a single character from input device i.e. stdin. This function is
defined in <stdio.h> header file.
Syntax: datatype getchar( );
Usage: var_name=getchar( );
Where var_name is of type int or char.
• The characters accepted by getchar( ) are buffered until RETURN is hit. It
is a buffered function. The buffered function gets the input from the
keyboard and store it in the memory buffer temporally until user press the
Enter key.
• It means getchar( ) requires Enter key to be pressed following the
character that you typed. It echoes typed character. If an end-of-file(EOF)
condition error occurs, getchar() returns EOF.
• The EOF macro is defined in <stdio.h> and is often equal to -1.
String Functions – putchar()
• It displays or writes a single character to the standard output device or
screen at the current cursor position. This function is defined in <stdio.h>
header file.
Syntax: int putchar(int c);
Usage: putchar( var_name);
Where var_name is of type int or char.
• The putchar( ) function returns the character written or EOF if an error
occurs.
String Functions – getchar() & putchar()
#include<stdio.h> #include<stdio.h>
int main() int main()
{ {
char x; char ch;
printf("Enter a character: ");
x=getchar(); ch=getchar();
putchar(x); printf("You have entered a character:
return 0; ");
} putchar(ch);
return 0;
Output: }
C
C Output:
Enter a Character: C
You have entered a character: C
String Functions – getchar() & putchar()
#include<stdio.h> //Accepting String
int main() #include<stdio.h>
{ int main()
char string[] = "C programming\n"; {
int i=0; int i=0;
while(string[i]!='\0’) char name[20];
{ printf("\nEnter the Name : ");
putchar(string[i]); while((name[i] = getchar())!='\n’)
i++; i++;
} return 0;
return 0; }
} Output:
Output: Enter the Name : Expression
C programming
String Functions – getchar() & putchar()
#include <stdio.h> printf("Reverse Number/String: ");
int main() while(--i>=0)
{ {
char ch; putchar(s[i]);
char s[10]; }
int i=0; return 0;
printf("Enter a number or string\n"); }
while((ch=getchar())!='\n’)
{ Output:
s[i]=ch; Enter a number or string
i++; Language
} Original Number/String: language
printf("Original Number/String: Reverse Number/String: egaugnal
%s\n",s);
String Functions – printf()
• It is a formatted output function. The printf() function is used to print the
data in specified format from the computer’s memory onto a standard
output device.
• This function can operate on any of the built-in data types. It can be used
to output any combination of numerical values, single character and
strings.

• You can specify the format in which data must be displayed on the screen.
It returns the number of characters actually displayed.
• The function is included in <stdio.h> file.
Syntax : printf(“format specifier”, arg1, arg2,….., argn);
String Functions – printf() - Example
#include <stdio.h> //Write a C Program to Get Numeric
int main() Input from User
{ #include<stdio.h>
char item[]="ABC"; int main()
{
int partno=12345; int i;
float cost=0.50; printf("Enter a value: ");
printf("%s%d%f",item,partno,cost); scanf("%d",&i);
return 0; printf( "\nYou entered: %d",i);
} return 0;
}
Output: Output:
ABC12345.500000 Enter a value: 54
You entered: 54
STRING FUNCTIONS
atoi, strlen, strcat, strcmp,
strcpy
String Functions – atoi
• The atoi() function in C takes a string (which represents an integer) as an
argument and returns its value of type int.
• The function is used to convert a string argument to an integer.
Syntax: int atoi(const char strn);
• Parameters: The function accepts one parameter strn which refers to the
string argument that is needed to be converted into its integer equivalent.
• Return Value: If strn is a valid input, then the function returns the
equivalent integer number for the passed string number. If no valid
conversion takes place, then the function returns zero.
String Functions – atoi (Cont..)
Significance :
• Can Convert any String of Number into Integer Value that can Perform the
arithmetic Operations like integer
• Header File : stdlib.h
Ways of Using Atoi Function :
• Way 1 : Passing Variable in Atoi Function
int num;
char marks[3] = "98";
num = atoi(marks);
printf("\nMarks : %d",num);
• Way 2 : Passing Direct String in Atoi Function
int num;
num = atoi("98");
printf("\nMarks : %d",num);
String Functions – atoi (Cont..)
OTHER INBUILT TYPECAST FUNCTIONS IN C PROGRAMMING
LANGUAGE:
• Typecasting functions in C language performs data type conversion from
one type to another.
• atof() Converts string to float
• atoi() Converts string to int
• atol() Converts string to long
• itoa() Converts int to string
• ltoa() Converts long to string
String Functions – atoi - Example
#include <stdio.h> printf("Integer value = %d\n", val);
#include <stdlib.h> return (0);
#include <string.h> }
int main()
{ Output:
int val;
Integer value = 12546
char strn1[] = "12546";
val = atoi(strn1); String value = C Programming
printf("String value = %s\n", strn1); Integer value = 0
printf("Integer value = %d\n", val);
char strn2[] = "C Programming";
val = atoi(strn2);
printf("String value = %s\n", strn2);
String Handling Functions
• The C library supports a large number of string-handling functions that
can be used to carry out many of the string manipulations discussed so far.
• Following are the most commonly used string handling functions:
String Functions – strcat()
• The strcat function joins two strings together. It takes the following form:
Syntax: strcat(string1,string2);
• string1 and string2 are character arrays. When the function strcat is
executed, string2 is appended to string1.
• It does so by removing the null character at the end of string1 and placing
string2 from there.
• The string at string2 remains unchanged. For example, consider the
following three strings:
String Functions – strcat() (Cont..)
• Execution of the statement • We must make sure that the size of
strcat(part1,part2); string1 is large enough to
will result in: accommodate the final string.
• strcat function may also append a
string constant to a string variable.
The following is valid:
strcat(part1,”GOOD”);
While the statement will result in: • C permits nesting of strcat
functions. For example, the
statement
strcat(strcat(string1,string2), string3);
• is allowed and concatenates all the
three strings together. The
resultant string is stored in string1.
String Functions – strcat() (Cont..)
Ways of Using Strcat Function :
• Way 1 : Taking String Variable as Parameter
char str1[20] = “Don” , str2[20] = “Bosqo”;
strcat(str1,str2);
puts(str1);

• Way 2 : Taking String Variable which is Already Initialized using Pointer


char *str1 = “Ind”,*str2 = “ia”;
strcat(str1,str2);// Result stored in str1 puts(str1); // Result : India

• Way 3 : Writing Function in printf Statement


printf(“nString: “, strcat(“Ind”,”ia”));
String Functions – strcmp()
• The strcmp function compares two strings identified by the arguments
and has a value 0 if they are equal.
• If they are not, it has the numeric difference between the first nonmatching
characters in the strings. It takes the form:
strcmp(string1, string2);
• string1 and string2 may be string variables or string constants. Examples
are:
strcmp(name1, name2);
strcmp(name1, “John”);
strcmp(“Rom”, “Ram”);
String Functions – strcmp() (Cont..)

• Our major concern is to determine whether the strings are equal; if not,
which is alphabetically above.
• The value of the mismatch is rarely important. For example, the statement
strcmp(“their”, “there”);
• will return a value of –9 which is the numeric difference between ASCII “i”
and ASCII “r”.
• That is, “i” minus “r” in ASCII code is –9.
• If the value is negative, string1 is alphabetically above string2.
String Functions – strcpy()
• The strcpy function works almost like a string-assignment operator. It
takes the following form:
strcpy(string1, string2);
• and assigns the contents of string2 to string1. string2 may be a character
array variable or a string constant.
• For example, the statement
strcpy(city, “DELHI”);
• will assign the string “DELHI” to the string variable city. Similarly, the
statement
strcpy(city1, city2);
• will assign the contents of the string variable city2 to the string variable
city1. The size of the array city1 should be large enough to receive the
contents of city2.
String Functions – strlen()
• This function counts and returns the number of characters in a string. It
takes the form
n = strlen(string);
• Where n is an integer variable, which receives the value of the length of
the string.
• The argument may be a string constant. The counting ends at the first null
character.
Point Explanation
No of Parameters 1
Parameter Taken Character Array Or String Return Type
Return Type Integer
Description Compute the Length of the String
Header file string.h
String Functions – strlen() (Cont..)
Different Ways of Using strlen() :
• There are different ways of using strlen function. We can pass different
parameters to strlen() function.

• Way 1 : Taking String Variable as Parameter


char str[20];
int length ;
printf("\nEnter the String : ");
gets(str);
length = strlen(str);
printf("\nLength of String : %d ", length);
Output:
Enter the String : hello
Length of String : 5
String Functions – strlen() (Cont..)
• Way 2 : Taking String Variable which is Already Initialized using Pointer
char *str = "priteshtaral";
int length ;
length = strlen(str);
printf("\n Length of String : %d ", length);
• Way 3 : Taking Direct String
int length ;
length = strlen("pritesh");
printf("\n Length of String : %d",length);
• Way 4 : Writing Function in printf Statement
char *str = "pritesh";
printf("\nLength of String : %d", strlen(str));
String Functions – Example
#include <stdio.h> l1 = strlen(s1);
#include <string.h> l2 = strlen(s2);
int main() l3 = strlen(s3);
{ printf("\ns1 = %s\t length= %d characters\n", s1, l1);
char s1[20],s2[20],s3[20]; printf("s2 = %s\t length = %d characters\n", s2, l2);
int x, l1,l2,l3; printf("s3 = %s\t length = %d characters\n", s3, l3);
printf("\n\nEnter two string constants \n"); return 0;
scanf("%s %s",s1,s2); }
x = strcmp(s1,s2); Output:
if(x!=0)
{
printf("\n\nStrings are not equal \n");
strcat(s1,s2);
}
else
printf("\n\nStrings are equal \n");
strcpy(s3,s1);
String Functions – Example
// Given string is palindrome or not left++;
#include <stdio.h> right--;
#include <string.h> }
int main() if(chk=='t’)
{ printf("\nThe string %s is a palindrome",str);
char chk='t', str[30]; else
int len, left, right; printf("\nThe string %s is not a
printf("\nEnter a string:"); palindrome",str);
scanf("%s",str); return 0;
len=strlen(str); }
left=0; Output:
right=len-1;
while(left < right && chk=='t’)
{
if(str[left] == str[right])
;
else
chk='f';
STRING FUNCTIONS
sprint, sscanf, strrev, strstr,
strtok
String Functions – sprintf
• The sprintf() function works similar to the printf() function except for one
small difference.
• Instead of sending the output to the screen as printf() does, this function
writes the output to an array of characters.
• It means this function writes the formatted text to a character array.
• The return value is equal to the number of characters actually placed into
the array.
Syntax:
sprintf (char Array[], “Control string” , var1, var2,…..varn);
String Functions – sprintf (Cont..)
• The sprintf (“string print formatted”) command takes first parameter as a
string to which to send output.
• It terminates the string with a null character. It returns the number of
characters stored in the string, not including the terminating null.
• This function will behave unpredictably if the string to which it is printing
overlaps any of its arguments.
• We have to make sure the size of the buffer to be written to is large enough
to avoid buffer overruns.
• If this is not done properly, it can result in a buffer overflow, causing the
program to crash at a minimum.
• At worst, a carefully crafted overflow can cause unexpected results.
• With sprintf (), you can combine several data variables into a character
array.
String Functions – sprintf (Cont..)
#include <stdio.h>
#include <string.h>
int main( )
{
int value = 50 ;
float flt = 7.25 ;
char c = 'Z' ;
char string[40]="programming" ;
printf ( " int value = %d \n char value = %c \n float value = %f", value, c, flt ) ;
printf("\n Before using sprint, data in string is %s",string);
sprintf ( string, "%d %c %f", value, c, flt );
printf("\n After using sprint, data in string is %s", string);
return 0;
}
String Functions – sscanf
• sscanf() function is a file handling function in C programming language
which is used to read formatted input from a string/buffer.
• The sscanf() function is identical to scanf() except that data is read from the
character array rather than stdin.
• The sscanf() function reads the values from a character array and stores
each value into variables of matching data type by specifying the matching
format specifier.
Syntax:
sscanf(char Array[], “Control String”, &var1, &var2…&varn);
String Functions – sscanf (Cont..)
#include <stdio.h>
int main( )
{
char buffer[30]="Fresh2refresh 5";
char name [20];
int age;
sscanf (buffer,"%s %d",name,&age);
printf ("Name : %s \n Age : %d \n",name,age);
return 0;
}
String Functions – strrev
• The C strrev function is a String Function, used to reverse the given string.
• The syntax for strrev() function is as follows
strrev(string);

#include<stdio.h>
#include<string.h> Output:
int main() String before strrev():Hello
{ String after strrev(): olleH
char name[30] = "Hello";
printf("String before strrev() :%s\n",name);
printf("String after strrev():%s", strrev(name));
return 0;
}
String Functions – strstr
• It is a two-parameter function that can be used to locate a sub-string in a
string. This takes the following forms:
strstr (s1, s2);
strstr (s1, “ABC”);
• The function strstr searches the string s1 to see whether the string s2 is
contained in s1.
• If yes, the function returns the position of the first occurrence of the sub-
string. Otherwise, it returns a NULL pointer.
• Example:
if (strstr (s1, s2) == NULL)
printf(“substring is not found”);
else
printf(“s2 is a substring of s1”);
String Functions – strstr (Cont..)
• We also have functions to determine the existence of a character in a string.
• The function call
strchr(s1, ‘m’);
• will locate the first occurrence of the character ‘m’ and the call
strrchr(s1, ‘m’);
• will locate the last occurrence of the character ‘m’ in the string s1.
String Functions – strstr (Cont..)
// Parameters as String initialized // Passing Direct Strings
using Pointers #include<stdio.h>
#include<stdio.h> #include<string.h>
#include<string.h> void main()
int main(void) {
{ char *ptr;
char *str1 = "c4learn.blogspot.com", ptr =
*str2 = "spot", *ptr; strstr("c4learn.blogspot.com","spot");
ptr = strstr(str1, str2); printf("The substring is: %sn", ptr);
printf("The substring is: %sn", ptr); }
return 0;
} Output: Output:
The substring is: spot.com The substring is: spot.com
String Functions – strtok
• The strtok() function is used to split a string into a series of tokens based
on a particular delimeter.
• A token is a substring extracted from the original string.

• Syntax:
char *strtok(char *str, const char *delim)
where, str: The string which is to be split
delim: The character on the basis of which the split will be done
• The function performs one split and returns a pointer to the token split up.
A null pointer is returned if the string cannot be split.
String Functions – strtok - Example
// Extracting a single token // Extracting all possible tokens
#include<stdio.h>
#include<stdio.h>
#include <string.h>
#include <string.h> int main() {
int main() { char string[50] = "Hello! We are learn
ing about strtok";
char string[50] = "Hello world"; char * token = strtok(string, " ");
char * token = strtok(string, " "); while( token != NULL ) {
printf( " %s\n", token ); printf( " %s\n", token );
token = strtok(NULL, " ");
return 0; }
} return 0;
Output: }
Hello
ARITHMETIC
CHARACTERS ON
STRINGS
Arithmetic characters on strings
• C Programming Allows you to Manipulate on String.
• Whenever the Character is variable is used in the expression then it is
automatically Converted into Integer Value called ASCII value.
• All Characters can be Manipulated with that Integer Value.
(Addition,Subtraction)
• Examples :
• ASCII value of : ‘a’ is 97
• ASCII value of : ‘z’ is 121
Arithmetic characters on strings (Cont..)
Possible Ways of Manipulation :

• Way 1:Displays ASCII value[ Note that %d in Printf]


char x = 'a’;
printf("%d",x); // Display Result = 97
• Way 2 :Displays Character value[Note that %c in Printf]
char x = 'a’;
printf("%c",x); // Display Result = a
• Way 3 : Displays Next ASCII value[ Note that %d in Printf ]
char x = 'a' + 1 ;
printf("%d",x); //Display Result = 98 (ascii of 'b' )
Arithmetic characters on strings (Cont..)
• Way 4 Displays Next Character value[Note that %c in Printf ]
char x = 'a' + 1;
printf("%c",x); // Display Result = 'b‘
• Way 5 : Displays Difference between 2 ASCII in Integer[Note %d in Printf ]
char x = 'z' - 'a’;
printf("%d",x);/*Display Result = 25
(difference between ASCII of z and a ) */
• Way 6 : Displays Difference between 2 ASCII in Char
char x = 'z' - 'a’;
printf("%c",x);
/*Display Result =( difference between ASCII of z and a ) */
18CSS101J
PROGRAMMING FOR
PROBLEM SOLVING

UNIT 3
Course Learning Outcome (CLO – 3)

• Analyze programs that need storage and form single and


multi-dimensional arrays.
• Use preprocessor constructs in C.
Topics that will be covered in this Session

• Functions declaration and definition


• Types: Call by value, Call by Reference
• Function with and without arguments and no return values
• Function with and without arguments and return values
• Passing array of functions with return type
• Recursion Functions
FUNCTIONS
DECLARATION AND
DEFINITION
Function
• A function is a self contained program segment that carries out some
specific, well-defined task.
• The use of functions allows a large program to be broken down into a
number of smaller components.
• C program can be modularized through the use of functions.
• A function will process information that is passed to it from the calling
portion of the program and return a single value.
• Information is passed to the function via special identifiers called
arguments, also called parameters, and returned via a return statement.
Why Function is used??
1. Modular and Structural Programming can be done
• We can divide c program in smaller modules.
• We can call module whenever require. e.g suppose we have written
calculator program then we can write 4 modules (i.e add, sub, multiply,
divide)
• Modular programming makes C program more readable.
• Modules once created , can be re-used in other programs.
2. It follows Top-Down Execution approach , So main can be kept very
small.
• Every C program starts from main function.
• Every function is called directly or indirectly through main
• Example : Top down approach. (functions are executed from top to
bottom)
Why Function is used?? (Cont..)
3. Individual functions can be easily built, tested
• As we have developed C application in modules we can test each and
every module.
• Unit testing is possible.
• Writing code in function will enhance application development
process.
4. Program development become easy
5. Frequently used functions can be put together in the customized library
• We can put frequently used functions in our custom header file.
• After creating header file we can re use header file. We can include
header file in other program.
Why Function is used?? (Cont..)
6. A function can call other functions & also itself
• Function can call other function.
• Function can call itself , which is called as “recursive” function.
• Recursive functions are also useful in order to write system functions.
7. It is easier to understand the Program topic
• We can get overall idea of the project just by reviewing function names.
How function works in C programming?
• C programming is modular programming language.
• We must divide C program in the different modules in order to create
more readable, eye catching ,effective, optimized code.
How function works in C programming?
• Firstly Operating System will call our main function.
• When control comes inside main function , execution of main starts (i.e
execution of C program starts)
• Consider, num = square(4);
• We have called a function square(4). [ See : How to call a function ? ].
• We have passed “4” as parameter to function.
• After execution control returned back to the calling function.
• Function will return 16 to the calling function.(i.e. main)
• Returned value will be copied into variable.
• printf will gets executed.
• main function ends.
• C program terminates.
Function - Definition
• A function definition, also known as function implementation shall
include the following elements:
1. function name;
2. function type;
3. list of parameters;
4. local variable declarations;
5. function statements; and
6. a return statement.
• All the six elements are grouped into two parts, namely,
• function header (First three elements); and
• function body (Second three elements).
Function – Definition (Cont…)
• A general format of a function definition to implement these two parts is
given below:

• The first line function_type function_name (parameter list) is known as


the function header and the statements within the opening and closing
braces constitute the function body, which is a compound statement.
Function – Definition (Cont…)
FUNCTION HEADER
• The function header consists of three parts:
o the function type (also known as return type),
o the function name, and
o the formal parameter list.
• A semicolon is not used at the end of the function header.
Function – Definition (Cont…)
NAME AND TYPE
• The function type specifies the type of value (like float or double) that the
function is expected to return to the program calling the function.
• If the return type is not explicitly specified, C will assume that it is an
integer type.
• If the function is not returning anything, then we need to specify the
return type as void.
• Void is one of the fundamental data types in C. It is a good programming
practice to code explicitly the return type, even when it is an integer.
• The value returned is the output produced by the function.
• The function name is any valid C identifier and therefore must follow the
same rules of formation as other variable names in C.
• The name should be appropriate to the task performed by the function.
Function – Definition (Cont…)
FORMAL PARAMETER LIST
• The parameter list declares the variables that will receive the data sent by
the calling program.
• They serve as input data to the function to carry out the specified task.
They represent the actual input values, they are often referred to as formal
parameters.
• These parameters can also be used to send values to the calling programs.
The parameters are also known as arguments. The parameter list contains
declaration of variables separated by commas and surrounded by
parentheses.
• Examples: float quadratic (int a, int b, int c) {. . . . }
double power (double x, int n) {. . . ..}
float mul (float x, float y) {. . . . }
int sum (int a, int b) {. . . . }
Function – Definition (Cont…)
FORMAL PARAMETER LIST
• A function need not always receive values from the calling program. In
such cases, functions have no formal parameters.
• To indicate that the parameter list is empty, we use the keyword void
between the parentheses as in
void printline (void)
{
....
}
• This function neither receives any input values nor returns back any value.
• Many compilers accept an empty set of parentheses, without specifying
anything as in
void printline ( )
• It is a good programming style to use void to indicate a nil parameter list.
Function – Definition (Cont…)
FUNCTION BODY
• The function body contains the declarations and statements necessary for
performing the required task.
• The body enclosed in braces, contains three parts, in the order given
below:
1. Local declarations that specify the variables needed by the function.
2. Function statements that perform the task of the function.
3. A return statement that returns the value evaluated by the function.
• If a function does not return any value (like the printline function), we can
omit the return statement.
Function – Definition (Cont…)
FUNCTION BODY
• Some examples of typical function definitions are:
Function Declaration
• All functions in a C program must be declared, before they are invoked.
• A function declaration (also known as function prototype) consists of four
parts.
o Function type (return type).
o Function name.
o Parameter list.
o Terminating semicolon.
• They are coded in the following format:
Function-type function-name (parameter list);
• This is very similar to the function header line except the terminating
semicolon. For example, mul function will be declared as:
int mul (int m, int n); /* Function prototype */
Function Declaration (Cont..)
Points to Note
• The parameter list must be separated by commas.
• The parameter names do not need to be the same in the prototype
declaration and the function definition.
• The types must match the types of parameters in the function definition, in
number and order.
• Use of parameter names in the declaration is optional.
• If the function has no formal parameters, the list is written as (void).
• The return type is optional, when the function returns int type data.
• The retype must be void if no value is returned.
• When the declared types do not match with the types in the function
definition, compiler will produce an error.
Function Declaration (Cont..)
• Equally acceptable forms of declaration of mul function are as follows:
int mul (int, int);
mul (int a, int b);
mul (int, int);
• When a function does not take any parameters and does not return any
value, its prototype is written as:
void display (void);
• A prototype declaration may be placed in two places in a program.
• Above all the functions (including main).
• Inside a function definition.
Function Declaration (Cont..)
• When we place the declaration above all the functions (in the global
declaration section), the prototype is referred to as a global prototype.
Such declarations are available for all the functions in the program.
• When we place it in a function definition (in the local declaration section),
the prototype is called a local prototype. Such declarations are primarily
used by the functions containing them.
• The place of declaration of a function defines a region in a program in
which the function may be used by other functions. This region is known
as the scope of the function.
• It is a good programming style to declare prototypes in the global
declaration section before main.
• It adds flexibility, provides an excellent quick reference to the functions
used in the program, and enhances documentation.
TYPES:
CALL BY VALUE
CALL BY REFERENCE
Function Call
• A function call is a postfix expression. The operator (. .) is at a very high
level of precedence.
• When a function call is used as a part of an expression, it will be evaluated
first, unless parentheses are used to change the order of precedence.
• In a function call, the function name is the operand and the parentheses set
(. .) which contains the actual parameters is the operator.
• The actual parameters must match the function’s formal parameters in
type, order and number. Multiple actual parameters must be separated by
commas.
• If the actual parameters are more than the formal parameters, the extra
actual arguments will be discarded.
• On the other hand, if the actuals are less than the formals, the unmatched
formal arguments will be initialized to some garbage.
• Any mismatch in data types may also result in some garbage values.
Function Call (Cont..)
• A function can be called by simply • This function is then executed line
using the function name followed by line as described and a value is
by a list of actual parameters (or returned when a return statement
arguments), if any, enclosed in is encountered. This value is
assigned to y.
parentheses. Example:
main( )
{
int y;
y = mul(10,5); /*Function call*/
printf(“%d\n”, y);
}
• When the compiler encounters a
function call, the control is
transferred to the function mul().
Function Call (Cont..)
• The function call sends two integer values 10 and 5 to the function.
int mul(int x, int y)
which are assigned to x and y respectively.
• The function computes the product x and y, assigns the result to the local
variable p, and then returns the value 50 to the main where it is assigned
to y again.
• There are many different ways to call a function. Listed below are some of
the ways the function mul can be invoked.
mul (10, 5)
mul (m, 5)
mul (10, n)
mul (m, n)
mul (m + 5, 10)
mul (10, mul(m,n))
mul (expression1, expression2)
Function Call (Cont..)
• A function which returns a value can be used in expressions like any other
variable. Each of the following statements is valid:
printf(“%d\n”, mul(p,q));
y = mul(p,q) / (p+q);
if (mul(m,n)>total) printf(“large”);
• A function cannot be used on the right side of an assignment statement.
For instance,
mul(a,b) = 15; is invalid.
• A function that does not return any value may not be used in expressions;
but can be called in to perform certain tasks specified in the function.
Function Call – Call by Value (Cont..)
• This method 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.
• While Passing Parameters using call by value , xerox copy of original
parameter is created and passed to the called function.
• Any update made inside method will not affect the original value of
variable in calling function.
• As their scope is limited to only function so they cannot alter the values
inside main function.
Function Call – Call by Value (Cont..)
Function Call – Call by Reference (Cont..)
• This method 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. This means that changes made to the parameter affect the
argument.
• 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 Call – Call by Reference (Cont..)
FUNCTION WITH AND
WITHOUT ARGUMENTS
AND NO RETURN VALUES
Category of Functions
• A function, depending on whether arguments are present or not and
whether a value is returned or not, may belong to one of the following
categories:
• Category 1: Functions with no arguments and no return values.
• Category 2: Functions with arguments and no return values.
• Category 3: Functions with arguments and one return value.
• Category 4: Functions with no arguments but return a value.
Functions with no arguments & no return values
• When a function has no arguments, it does not receive any data from the
calling function.
• Similarly, when it does not return a value, the calling function does not
receive any data from the called function.
• In effect, there is no data transfer between the calling function and the
called function.
• The dotted lines indicate
that there is only a transfer
of control but not data.
• A function that does not
return any value cannot be
used in an expression.
• It can only be used as an
independent statement.
Functions with no arguments & no return values

• A program with three user-defined functions


main is the calling function that calls
printline and value functions. Since both the
called functions contain no arguments, there
are no argument declarations.
• The value function calculates the value of
principal amount after a certain period of
years and prints the results.
• The following equation is evaluated
repeatedly:
value = principal(1+interest-rate)
Functions with no arguments & no return values

• The input data include principal amount, interest


rate and the period for which the final value is to
be calculated.
• The while loop calculates the final value and the
results are printed by the library function printf.
• When the closing brace of value( ) is reached, the
control is transferred back to the calling function
main.
• Since everything is done by the value itself there
is in fact nothing left to be sent back to the called
function.
• Return types of both printline and value are
declared as void.
Functions with arguments & no return values
• Function accepts argument but it does not return a value back to the calling Program .It is
Single ( One-way) Type Communication. Generally Output is printed in the Called
function.
• The nature of data communication between the calling function and the called function
with arguments but no return value.
The definitions of both the called functions to include
arguments as follows:
void printline(char ch)
void value(float p, float r, int n)
The arguments ch, p, r, and n are called the formal
arguments. The calling function can now send values to
these arguments using function calls containing
appropriate arguments. For example, the function call
value(500,0.12,5)
would send the values 500,0.12 and 5 to the function
void value( float p, float r, int n)
and assign 500 to p, 0.12 to r and 5 to n. The values 500, 0.12, and 5 are the actual arguments,
which become the values of the formal arguments inside the called function.
Functions with arguments & no return values
• The actual and formal arguments should match in number, type, and
order. The values of actual arguments are assigned to the formal
arguments on a one to one basis, starting with the first argument.
Functions with arguments & no return values

• The input prompt and scanf assignment statement have been


moved from value function to main.
• The variables principal, inrate, and period are declared in main
because they are used in main to receive data. The function call
value(principal, inrate, period);
passes information it contains to the function value.
• The function header of value has three formal arguments p,r, and
n which correspond to the actual arguments in the function call,
namely, principal, inrate, and period. On execution of the
function call, the values of the actual arguments are assigned to
the corresponding formal arguments. The following assignments
are accomplished across the function boundaries:
p = principal;
r = inrate;
n = period;
Functions with arguments & no return values

• The variables declared inside a function are known as local


variables and therefore their values are local to the function and
cannot be accessed by any other function.
• The function value calculates the final amount for a given period
and prints the results as before.
• Control is transferred back on reaching the closing brace of the
function.
• The function printline is called twice. The first call passes the
character ‘Z’, while the second passes the character ‘C’ to the
function. These are assigned to the formal argument ch for
printing lines
FUNCTION WITH AND
WITHOUT ARGUMENTS
AND RETURN VALUES
Functions with arguments & return values
• Different programs may require different output formats for display of
results.
• These shortcomings can be overcome by handing over the result of a
function to its calling function where the returned value can be used as
required by the program.
• A self-contained and independent function should behave like a ‘black
box’ that receives a predefined form of input and outputs a desired value.
Such functions will have two-way data communication.
Functions with arguments & return values

• The calculated value is passed on to main through


statement: return(sum);
• By default, the return type of value function is int, the
‘integer’ value of sum at this point is returned to main
and assigned to the variable amount by the functional
call amount = value (principal, inrate, period);
• The following events occur, in order, when the above
function call is executed:
1. The function call transfers the control along with
copies of the values of the actual arguments to
the function value where the formal arguments
p, r, and n are assigned the actual values of
principal, inrate and period respectively.
Functions with arguments & return values
2. The called function value is executed line by line in a
normal fashion until the return(sum); statement is
encountered. At this point, the integer value of sum is
passed back to the function call in the main and the
following indirect assignment occurs:
value(principal, inrate, period) = sum;
3. The calling statement is executed normally and the
returned value is thus assigned to amount, a float
variable.
4. Since amount is a float variable, the returned integer
part of sum is converted to floating-point
value.Another important change is the inclusion of
second argument to printline function to receive the
value of length of the line from the calling function.
Thus, the function call printline(‘*’, 52);
will transfer the control to the function printline and
assign the following values to the formal arguments ch,
and len:
ch = ‘*’ ;
len = 52;
Functions with no arguments & with return values
• There could be occasions where we • We can design similar functions
may need to design functions that and use in our programs. Example:
may not take any arguments but
returns a value to the calling
function.
• A typical example is the getchar
function declared in the header file
<stdio.h>.
• The getchar function has no
parameters but it returns an
integer type data that represents a
character.
Functions with no arguments & with return values
PASSING ARRAY TO
FUNCTIONS WITH
RETURN TYPE
Passing array to functions with return type
• An array name can be used as an argument to a function, thus permitting
the entire array to be passed to the function.
• When an array is passed to a function, the value of the array elements are
not passed to the function.
• The array name is interpreted as the address of the first array element.
This address is assigned to the corresponding formal argument when the
function is called.
• The formal argument therefore becomes a pointer to the first array
element.
• Arguments passed in this manner are said to be passed by reference.
• If an array element is altered within the function, the alteration will be
recognized in the calling portion of the program.
• Array can be passed to function by two ways Pass Entire array & Pass
Array element by element.
Passing array to functions with return type –
Pass Entire Array

• Here entire array can be passed as a argument to function .


• Function gets complete access to the original array .
• While passing entire array Address of first element is passed to function ,
any changes made inside function , directly affects the Original value .
• Function Passing method : “Pass by Address“
Passing array to functions with return type –
Pass Array Element by Element
• Here individual elements are passed to function as argument.
• Duplicate carbon copy of Original variable is passed to function. So any
changes made inside function does not affects the original value.
• Function doesn’t get complete access to the original array element.
• Function passing method is “Pass by Value“.
• Passing entire array to function :
• Parameter Passing Scheme : Pass by Reference
• Pass name of array as function parameter .
• Name contains the base address i.e ( Address of 0th element )
• Array values are updated in function .
• Values are reflected inside main function also.
Passing array to functions with return type

A program to find the average of a


list of numbers using functions.
Passing array to functions with return type

A program to reverse an array using


functions.
RECURSION FUNCTIONS
Recursion Functions
• Recursion is a process by which a function calls itself repeatedly, until
some specified condition has been satisfied.
• The process is used for repetitive computations in which each action is
stated in terms of a previous result. Many iterative problems can be
written in this form.
• In order to solve a problem recursively, two conditions must be satisfied.
1. The problem must be written in a recursive form
2. The problem statement must include a stopping condition.
• For example, we wish to calculate the factorial of a positive integer
quantity. We would normally express this problem as n! = 1 X 2 X 3 X … X
n, where n is the specified positive integer.
• A recursive statement of this problem is n! = n X (n-1)! in which the desired
action is expressed in terms of a previous result. We know that 1! = 1 by
definition. This provides a stopping condition for the recursion.
Recursion Functions – Factorial
• When a recursive program is executed, the recursive function calls
are not executed immediately. Rather, they are placed on a stack
until the condition that terminates the recursion in encountered.
• The function calls are then executed in reverse order, as they are
“popped” off the stack. Thus, when evaluating a factorial
recursively, the function calls will proceed in the following order:

n! = n X (n-1)! 1! = 1
(n-1)! = (n-1) X (n-2)! 2! = 2 X 1! = 2 X 1 = 2
(n-2)! = (n-2) X (n-3)1 3! = 3 X 2! = 3 X 2 = 6
….. 4! = 4 X 3! = 4 X 6 = 24
2! = 2 X 1! ...
n! = n X (n-1)! = ...
• This reversal in the order of execution is a characteristic of all
functions executed recursively.
• If a recursive function contains local variables, a different set of
local variables will be created during each call. The names of the
local variables will, of course, always be the same, as declared
within the function. However, the variables will represent a
different set of values each time the function is executed.
Recursion Functions – The tower of hanoi
• The Towers of Hanoi is a well-known children’s game, played with three
poles and a number of different sized disks. Each disk has a hole in the
center, allowing it to be stacked around any of the poles.
• Initially, the disks are stacked on the leftmost pole in the order of
decreasing size, i.e., the largest on the bottom and the smallest on the top.
Recursion Functions – The tower of hanoi
• The object of the game is to transfer the disks from the leftmost pole to the
rightmost pole, without ever placing a larger disk on top of a smaller disk.
• Only one disk may be moved at a time and each disk must always e placed
around one of the poles.
• The general strategy is to consider one of the poles to be origin, and
another to be the destination. The third pole will be used for intermediate
storage, thus allowing the disks to be moved without lacing a larger disk
over a smaller one.
• Assume there are n disks, numbered from smallest to largest as shown in
the figure. The problem can be stated in the following recursive manner:
1. Move the top n-1 disks from the left pole to the center pole.
2. Move the nth disk (the largest disk) to the right pole.
3. Move the n-1 disks on the center pole to the right pole.
Recursion Functions – The tower of hanoi

• In order to program this game we first label


the poles, so that the left pole is represented as
L, the center pole as C and the right pole as R.
• We then construct a recursive function called
transfer that will transfer n disks from the
origin, destination, and temporary storage,
respectively.
• The use of recursion is not necessarily the best
way to approach a problem, even though the
problem definition may be recursive in nature.
• A non-recursive implementation may be more
efficient in terms of memory utilization and
execution speed.
Recursion Functions – Fibonacci Series

You might also like