0% found this document useful (0 votes)
61 views

Computer Programming Using C Unit IV Function and Arrays

The document discusses functions and arrays in C programming. It covers built-in and user-defined functions, function declaration, definition and calls, parameter passing by value and reference, recursive functions, linear and multidimensional arrays, and passing arrays to functions.

Uploaded by

vikas__cc
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
61 views

Computer Programming Using C Unit IV Function and Arrays

The document discusses functions and arrays in C programming. It covers built-in and user-defined functions, function declaration, definition and calls, parameter passing by value and reference, recursive functions, linear and multidimensional arrays, and passing arrays to functions.

Uploaded by

vikas__cc
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 52

Master of Science (Information Technology)

Computer Programming Using C


Unit - 4 Functions and arrays
Objectives
Introduction
Built-in and user-defined
Function declaration
Definition and function call
Parameter passing: call by value; call by reference
Recursive functions
Linear arrays
Multidimensional arrays
Passing arrays to functions
Arrays and strings.
Summary
Keywords
Self assessment
Review questions
Objectives
After going through this unit you will be able to:
 Built-in and user-defined
 Function declaration
 Definition and function call
 Parameter passing: call by value, call by reference
 Recursive functions

1
 Linear arrays
 Multidimensional arrays
 Strings: Arrays and strings, string manipulation using library functions
Introduction
An array in C Programming Language can be defined as number of memory locations, each of
which can store the same data type and which can be references through the same variable
name. An array is a collective name given to a group of similar quantities. These similar
quantities could be percentage marks of 100 students, number of chairs in home, or salaries of
300 employees or ages of 25 students. Thus an array is a collection of similar elements. These
similar elements could be all integers or all float sorall characters etc. Usually, the array of
characters is called a “string”, where as an array of integers or floats are called simply an
array. All elements of any given array must be of the same type i.e. we cannot have an array of
10 numbers, of which 5 are int and 5 are floats.
Collection of similar data elements is called array.
Array can be of three types:
1) One dimensional
2) Two dimensional
3) Multi dimensional
Numeric data are not the only data types that are processed on a computer. Very often the data
to be processed are in textual form such as words, names, addresses etc. This type of data care
Stored and processed using string type variables. C does not have an explicit string data type.
However, the same can be simulated using character array. This lesson deals with strings and
string manipulation as is done in C.
Built-in and user-defined
In C functions can be classified into two categories, namely, library functions and user-
defined functions. Main is an example of user defined function. Printf and scanf belong to the
category of library functions. The main distinction between user-defined and library function
is that the former are not required to be written by user while the latter have to be developed
by the user at the time of writing a program. However the user defined function can become
apart of the C program library.

2
General syntax for function declaration is, return type functionName(type1 parameter1, type2
parameter2,...);

Like any variable or an array, a function must also be declared before its used. Function
declaration informs the compiler about the function name, parameters is accept, and its return
type. The actual body of the function can be defined separately. It's also called as Function
Prototyping. Function declaration consists of 4 parts.
 Return type
 function name
 parameter list
 terminating semicolon

Return type
When a function is declared to perform some sort of calculation or any operation and is
expected to provide with some result at the end, in such cases, a return statement is added at
the end of function body. Return type specifies the type of value (int, float, char, double) that
function is expected to return to the program which called the function.
Note: In case your function doesn't return any value, the return type would be void.
Function Name
Function name is an identifier and it specifies the name of the function. The function name is
any valid C identifier and therefore must follow the same naming rules like other variables in
C language.
Parameter list
The parameter list declares the type and number of arguments that the function expects when
it is called. Also, the parameters in the parameter list receive the argument values when the
function is called. They are often referred as formal parameters.
Let's write a simple program with a main () function, and a user defined function to multiply
two numbers, which will be called from the main () function.
#include<stdio.h>

3
Int multiply (int a, int b); // function declaration
Int main ()
{
Int i, j, result;
Printf ("Please enter 2 numbers you want to multiply...");
Scanf ("%d%d", &i, &j);
Result = multiply (i, j); // function call
Printf ("The result of muliplication is: %d", result);
Return 0;
}
Int multiply (int a, int b)
{
Return (a*b); // function defintion, this can be done in one line
}
Definition of the function
Just like in the example above, the general syntax of function definition is, Return type
function Name (type1 parameter1, type2 parameter2...)
{
// function body goes here
}
The first line returntype function Name (type1 parameter1, type2 parameter2...) is known
as function header and the statement(s) within curly braces is called function body.
Note: While defining a function, there is no semicolon (;) after the parenthesis in the function
header, unlike while declaring the function or calling the function.
Function body

4
The function body contains the declarations and the statements (algorithm) necessary for
performing the required task. The body is enclosed within curly braces {...} and consists of
three parts.
Local variable declaration (if required).
Function statements to perform the task inside the function a return statement to return the
result evaluated by the function (if return type is void, then no return statement is required).
Function Call
We may call a function either directly or indirectly. When we call the function, we pass actual
arguments or values. Calling a functional is also known as function reference. There must be a
one toone correspondence between formal arguments declared and the actual arguments sent.
They should be of the same datat ype and in the same order.
Eg. Sum=f1 (20.5, 10); fun4 ();
Function Definition
The function definition can be written anywhere in the file with a proper declaration, followed
by the declaration of local variables and statements. The function definition consists of two
parts namely function declaration or heading and function body the function heading is similar
to function declaration, but will not terminate with a semicolon.
Let as assume that we wish to get two integers Pass them toa function add. Add the min the
add function. Return the value to the main function and print it the algorithm for solving
problem is given below:
Mainfunction Step 1: definefunction add Step 2: get2 integers
Step 3: calladd &Passthe2 values
Step 4: get thesum
Step 5: printthe value
Function add Step 1: getthe value Step 2: add them
Step 3: returnthe value to main
Thus we have dividedthe problem. The programis given below:
/*Example */
5
/*useoffunction*/
#include<stdio. h>
Main ()
{
Inta=0, b=0, sum=0;
Intadd (inta, intb); /*function declaration*/
Printf (“enter2integers\n”);
Scanf (“%d%d”, &a, &b);
Sum=add (a, b); /*functioncall*/
Printf (“sumof %d and %d=%d”, a, b, sum);
}
/*function definition*/
Int add (intc, intd) /*function declaration*/
{Inte; e=c+d; returne;
Result of program
Enter 2 integers
6667 4445
Sum of 6667 and 4445=11112
The explanation as to how the program works is given below:
On the filth statement (seventh line), the declaration of the function add is given. Note that the
function will return an integer. Hence there turn type is defined as int. The formal arguments
are defined as inta and intb. The function name is added. We cannot use a variable without
declaring it, as also a function with out telling the compiler about it.Function declaration
should appear at the beginning of the calling function. It hints to the compiler that the function
is going to all the function ads, later in the program. If the calling function is not going to pass
any arguments, then empty parent hese sare to be written after the function name. The parent

6
heses must be present be in the function declaration. This happens when the function is called
to performan operation without passing arguments. In this case, if a & bare part of the called
function (add) itself, then we need not pass any parameters. In such a case the function
declaration will be as follows assuming that the called function returnsan integer:
Intadd ();
In example, we get the values of a & b. After that we call the function add and assign the value
returned by the function toan already definedint variable sum as given below:
Sum= add (a, b);
Note that odd (a, b) is the function call or function reference. Here the return type is not to be
given. The types of the arguments are also not to be given. It is a simple statement without all
the elements of the function declaration. However, the function name and the names of the
arguments passed, if any, should be present in the function call. When the program sees a
function reference or functioncall, it looks for and calls the function and transfers the
arguments. The function definition consists of two parts i.e., the function declaration and
function body.The function declaration is a replica of the function declaration. The only
difference is that the declaration in the calling function will end with a semicolon and the
declaration in the called function will not end with a semicolon. As in main (), the entire
function body will be closed within braces. The whole function can be assumed to be one
program statement. This means that all the statements within the body will be execute done
after another before the program execution returns to the place in the main function from
where it was called.
The important points to be note dare:
a) The declaration must agree totally with the declaration in the called functioni.e.,there turn
data type, the function name, the argument type should all appear in the same order. The
declaration will not end with a semicolon.
b) You can also give the same name as in the calling function-in declaration statement or
function call--or different names to the arguments in the function declaration. Here we have
given the name scandd. What is important however is that the type of arguments should
appear, as it is in the declaration in the calling program? They must also appear in thesame
order.

7
c) At the time of execution, when the function encounters the closing brace}, it returns control
to the calling program and returns to the same place at which the function was called. In this
program we have a specific statement return (e) before the closingbrace.There fore the
program will go back to the main function with value ofe. This value will be substituted as
Sum= (returned value)
Therefore sum gets the value which is printed in the next statement. This is how the function
works. Assume now that the program gets a & b values, gets their sum1, gets c & dand gets
their sum 2 and then both the sums are passed to the function to get their total. The program
for doing this is given below:
/*Example */
/* Afunctioncalled manytimes*/
#include<stdio.h>
Main ()
{
Floata, b, c, d, sum1, sum2, sum3;
Floatadd (f1oata, floatb);/*function declaration*/
Printf (“enter2floatnumbers\n”);
Scanf (“%f%f”, &a, &b);
sum1 =add (a, b); /*function call*/ printf (“enter2 more floatnumbers\n”); scanf (“%f%f”,&c,
&d);
sum2 =add(c, d);/*function call*/
sum3 =add (sum1, sum2);/*function call*/
Printf (“sumof%fand %f=%f\n”, a, b, sum1);
Printf (“sumof %fand%f=%f\n”, c, d, sum2);
Printf (“sumof %fand%f=%f\n”, sum1, sum2, sum3);
}

8
/*function definition*/
Floatadd (floatc, floatd) /*functiondeclaration*/
{
Floate; e=c+d; returne;
}
Result of program
Enter 2 float numbers
1.5 3.7
Enter 2 more floatnumbers
5.6 8.9
Sum of 1.500000 and 3.700000 = 5.200000
Sumo f 5. 600000 and 8. 900000:14– 500000 sumof5.200000and 14.500000:19.70000
We have defined sum1, sum2 and sum3 as float variables.
We are callingfunction add three times with the following assignment statements:
sum1 =add (a, b);
sum2 = add (c, d);
sum3 = add (sum1, surr2);
Thus the programgoesbackand forth betweenmain &, add as given below:
Main () add (a, b) main () add(c, d) main ()
Add (sum1, sum2)
Main ()
Had we not used the function odd, we would have to write statement spertaining to add 3
times in the main program such a program would be large and difficult toread. In this method
we have to code for add only once, and hence the program size is small. This is one of the
reasons for the usage of functions.

9
In Example, we could add another function call by add (10.005, 3.1125); this statement will
also work perfectly. After the function is executed, the sum will be returned to the main
function. Therefore, both variables and constants can be passed to a function by making use of
the same function declaration.
Categories of Functions
When a function is called, control of the program gets transferred to the function.
Function Name (argument1, argument2...);
In the example above, the statement multiply (i, j); inside the main () function is function call.
Calling of function can be done in several ways
Here are different types of function calling. Depending on the number of parameters it can
accept, function can be classified into following 4 types –

Function Type Parameter Return Value

Type 1 Accepting Parameter Returning Value

Type 2 Accepting Parameter Not Returning Value

Type 3 Not Accepting Parameter Returning Value

Type 4 Not Accepting Parameter Not Returning Value

Let us consider all types of functions one by one –


Type 1: Accepting Parameter and Returning Value
Above type of method is written like this –
Int add (int i, int j)
{
Return i + j;
}

10
And Called like this –
Int answer = sum (2, 3);
We need to assign the function call to any of the variable since we need to capture returned
value.
Type 2: Accepting Parameter and Not Returning Value
Above type of method is written like this –
Void add (int i, int j)
{
Printf ("%d",i+j);
}
Above method can be called using following syntax –
Sum (2, 3);

Type 3: Not Accepting Parameter but Returning Value


Above type of method is written like this –
Int add ()
{
Int i, int j;
i = 10;
j = 20;
Return i + j;
}
Called using following syntax –
Result = add ();
Type 4: Not Accepting Parameter and Not Returning Value

11
Above type of method is written like this –
Void add ()
{
Int i, int j;
i = 10;
j = 20;
Printf ("Result: %d", i+j);;
}
And called like this –
Add ();
Function returning multiple values
Programmers are usually in the search of ways to return multiple values from a function.
Unfortunately, C and C++ do not allow this directly. But fortunately, with a little bit of clever
programming, we can easily achieve this.
Below are the methods to return multiple values from a function in C:
1. By using pointers.
2. By using structures.
3. By using Arrays.
Example: Consider an example where the task is to find the greater and smaller of two distinct
numbers. We could write multiple functions. The main problem is the trouble of calling more
than one function since we need to return multiple values and of course having more number
of lines of code to be typed.
Returning multiple values using pointers:
Pass the argument with their address and make changes in their value using pointer. So that
the values get changed into the original argument.
// modified program using pointers
#include <stdio.h>

12
// add is the short name for address
Void compare (int a, int b, int* add_great, int* add_small)
{
If (a > b) {
// a is stored in the address pointed
// by the pointer variable *add_great
*add_great = a;
*add_small = b;
}
Else {
*add_great = b;
*add_small = a;
}
}
// Driver code
Int main ()
{
Int great, small, x, y;
Printf ("Enter two numbers: \n");
Scanf ("%d%d", &x, &y);
// the last two arguments are passed
// by giving addresses of memory locations
Compare (x, y, &great, &small);
Printf ("\nThe greater number is %d and the"

13
"Smaller number is %d",
Great, small);
Return 0;
}
Output:
Enter two numbers:
58
The greater number is 8 and the smaller number is 5
Returning multiple values using structures:
As the structure is a user-defined datatype. The idea is to define a structure with two integer
variables and store the greater and smaller values into those variables, and then use the values
of that structure.
// modified program using structures
#include <stdio.h>
Struct greater Smaller {
Intgreater, smaller;
};
Type def struct greater Smaller Struct;
Struct find Greater Smaller (inta, intb)
{
Struct s;
If (a > b) {
s.greater = a;
s.smaller = b;
}

14
Else {
s.greater = b;
s.smaller = a;
}
Returns;
}
// Driver code
Intmain ()
{
Intx, y;
Struct result;

Printf ("Enter two numbers: \n");


Scanf ("%d%d", &x, &y);

// the last two arguments are passed


// by giving addresses of memory locations
Result = findGreaterSmaller(x, y);
Printf ("\nThe greater number is %d and the"
"Smaller number is %d",
result.greater, result.smaller);
return0;
}
Output:

15
Enter two numbers:
58
The greater number is 8 and the smaller number is 5
Returning multiple values using an array (Works only when returned items are
of same types):
When an array is passed as an argument then its base address is passed to the function so
whatever changes made to the copy of the array, it is changed in the original array.
Below is the program to return multiple values using array i.e. store greater value at arr [0]
and smaller at arr [1].
// modified program using array
#include <stdio.h>
// Store the greater element at 0th index
Void find Greater Smaller (int a, int b, int arr [])
{
// Store the greater element at
// 0th index of the array
If (a > b) {
Arr [0] = a;
Arr [1] = b;
}
Else {
Arr [0] = b;
Arr [1] = a;
}
}
// Driver code
16
Int main()
{
Int x, y;
Int arr [2];

Printf ("Enter two numbers: \n");


Scanf ("%d%d", &x, &y);
Find Greater Smaller (x, y, arr);
Printf ("\nThe greater number is %d and the"
"Smaller number is %d",
Arr [0], arr [1]);
Return 0;
}
Output:
Enter two numbers:
58
The greater number is 8 and the smaller number is 5
Arraysin Functions
Arrays can be passed down to functions like other single variables. We use them by their name
as arguments when we call the function. The parameter list of the function must indicate the
fact that a parameter is an array by augmenting the [] at the end of the one dimensional arrays.
In one-dimensional arrays the actual size does not have to be given. In case of two-
dimensional arrays were commend that you give the size of the array in both dimensions.
The following example show the concept of array of function
#include<stdio.h>
#include<conio.h>void read (int*, int); void dis (int*, int); void main () {
17
Inta [5] b [5], c 5], i;
Printf (“Enter the elements of first list\n”);
Read (a, 5);
Printf (“The elements of first list are\n”);
Dis (a, 5);
}
Void read(intc[],inti)
{
Intj; for (j=0;j<i;j++) scanf(“%d”,&c[j]); fflush(stdin);
}
Void dis (intd [], inti)
{
Intj; for (j=0;j<i;j++) printf(“%d“,d[j]); printf(“\n”);
}
Passing arrays and individual array elements to functions
#include<stdio.h>
#define SIZE 5
Void modify Array (intb [], intsize);
Void modifies Element (inte);
Int main ()
{
Inta [SIZE] = {0, 1, 2, 3, 4};
Int i;
Printf (“Effectsofpassingentirearraybyreference: \n\nThe Valuesoftheoriginalarrayare: \n”);

18
For (i= 0;i< SIZE; i++){
Printf (“%3d”, a[i]);
}
Printf (“\n”);
Modify Array (a, SIZE);
Printf (“The values of themodified arrayare: \n”);
For (i= 0;i< SIZE; i++)
{
Printf (“%3d”, a[i]);
}
Printf (“\n\n\nEffects ofpassingarray element““by value:\n\nThe value ofa[3]is%d\n”,a[3]);
Modify Element (a [3]);
Printf (“The value of a[3] is%d\n”,a[3]);
return0;
}
Void modify Array (intb [], int size)
{
Intj;
For (j= 0;j<size;j++){
B [j]*= 2;
}
}
Void modify Element (inte)
{

19
Printf (“Value in modifyElement is%d\n”, e *=2 );
}
Nesting of Functions
Inside a function you can define and use other functions. Here is an example that show Sahel
perfunction to simplifya complicated calculation.
Varcomplicated =function(x) {
Varf=function (y) {
Return y* 3 + 1;
};
Returnf (f(x));
};
Vary= complicated (2);
//Nowyis 22
In the definition of a function you can refer to the arguments of the function. You can also
refer to variables outside the function in the enclosing function. Here is the same example but
with a constant 1 factored outasa variable.
Varcomplicated =function(x){
Varc, f;
c = 1; //constant
f=function (y) {
//We canrefer toc inhere!
Return y* 3 + c;
};
Returnf (f(x));
};

20
Vary= complicated (2);
//y is still 22 here
That was actually his first example of a closure! The outer function closes over the inner
functions, and the inner functions can use variables from the outer function.
An important case is when the inner function refers to arguments from the enclosing outer
function. Arguments are like variables, you can refer to them from inside in the same way.
Here is an example of a function create that takes anargument x and returns a new function.
The returned function takes no arguments and returns x.
Varcreate= function(x) {
Varf=function (){
Return x; //we can refer to xhere!
};
Return f;
};
//createtakesone argument, createsa function varg= create (42);
//gisa functionthattakesno arguments now vary= g();
//yis 42 here
In the example, even after the create function finishes the function it returns keeps working.
Recursion
Recursion is a process by which a function calls itself repeatedly, until some specified
condition has been satisfied. The process is used for repetitive computation in which each
action is stated in terms of previous result.
In order to solve a problem recursively, two conditions must be satisfied:
1. The problem must be written in recursive form.
2. The problem statement must include a stopping condition.
Example: /*to calculate the factorial of an integer recursively * /

21
# include <stdio.h>
Main ( )
{
Int n;
Long int fact (int);
Printf (“\n n = “);
Scanf (“%d”, &n);
Printf (“\n n! = % LD” fact (n));
}
Long int fact (int n)
{
If (n < = 1)
Return 1;
Else
Return (n * factorial (n-1));
}
Linear arrays
Declaration of one dimensional:
Data type nameof array [size];
e.g
Int n [10];
Here n is an array of size 10. There are 10 positions in this array which are represented by a
[0], a[1], a[2]……………….a[9].
There are two methods of storing values in an array.

22
Initialization of array
Int a[]={1,2,3,4,5};
To get values from user
For (i=0;i<5;i++)
Scanf (“%d”,a[i]);
Some of the application of one dimensional array is searching, sorting.
Example: program to search a particular element in an array
#include<stdio.h>
#include<conio.h>
Void main ()
{
Int a [10], s, i;
Printf (“enter the elements of the array”);
For (i=0;i<10;i++)
Scanf (“%d”, &a[i]);
Printf (“enter the element to be searched”);
Scanf (“%d”, &s);
For (i=0; i<10;i++)
{
If (a[i] ==s)
{
Printf (“the element is found at %d”, i+1);
Break;
}

23
}
If (i==10)
Printf (“element not found”);
}
Example: program to perform Bubble sorting
#include<stdio.h>
#include<conio.h>
Void main ()
{
Int a[10],i,j;
Printf (“enter the elements of the array”);
For (i=0;i<10;i++)
Scanf (“%d”, &a[i]);
For (i=0; i<10; i++)
{
For (j=0; j<9; j++)
{
If (a[j]> a[j+1])
{
Temp = array [j+1];
A [j+1] = array[j];
A[j] = temp;
}
}

24
}
}
More examples of arrays:
C program to reverse an array
C program to reverse an array: - This program reverses the array elements. For example if a is
an array of integers with three elements
such that
a [0] = 1
a [1] = 2
a [2] = 3
then on reversing the array will be
a [0] = 3
a [1] = 2
a [0] = 1
In the program swapping is done to reverse the array elements.
Given below is the c code to reverse an array.
#include<stdio.h>
#include<conio.h>
Int main ()
{
Int n, i, j, temp, a[100];
Printf ("Enter the number of elements in array ");
Scanf ("%d", &n);
Printf ("Enter the array elements");
For (i = 0; i < n; i++)
Scanf ("%d", &a[i]);
If (n%2 == 0)
i = n/2 - 1;
25
Else
i = n/2;
For (j = 0; j < i; j++)
{
Temp = a [j];
A [j] = a [n -j - 1];
A [n-j-1] = temp;
}
Printf ("Reverse array is\n");
For (i = 0; i < n; i++)
Printf ("%d\n", a[i]);
Getch ();
Return 0;
}
Print the largest and second largest element in an array

#include <stdio.h>
#define MAXELT 1000
Void main ()
{
Int i=-1, n=0, largest, slargest;
Char t [10];
Void largest_and_second_largest (int [], int, int &, int &);
Int list [MAXELT];
Do {//read the list of numbers

26
If (i! =-1)
List [i++] =n;
Else
I++;
Printf ("\nEnter the numbers <End by #>");
Gets (t);
If (sscanf (t,"%d", &n)<1)
Break;
} while (1);
largest_and_second_largest (list, i, largest, slargest);
Printf ("The largest of the list is %d and the second largest is %d.", largest, slargest);
}
//pre: there must be atleast two numbers in the list
Void largest_and_second_largest (int list [], int n, int & largest, int & slargest)
{
Int largeindex=0, i;
Largest=list [0];
For (i=1;i<n;i++) //find the largest loop
If (list[i]>largest) {
Largest=list[i];
Largeindex=i; //to eliminate the largest later
}
//we have found the largest, stored in largest and its
//index stored in largeindex. Now find the second largest

27
//ignoring the largest.
If (largeindex==0)
Slargest=list [1];
Else
Slargest=list [0];
For (i=0; i<n;i++)
If (list[i]>slargest && i! =largeindex)
Slargest=list[i];
//we have found the second largest
}
/* Program to count the no of positive and negative numbers*/
#include<stdio.h>
void main()
{
int a[50],n,count_neg=0,count_pos=0,I;
printf(“Enter the size of the arrayn”);
scanf(“%d”,&n);
printf(“Enter the elements of the arrayn”);
for I=0;I < n;I++)
scanf(“%d”,&a[I]);
for(I=0;I < n;I++)
{
if(a[I] < 0)
count_neg++;
else
count_pos++;
}
printf(“There are %d negative numbers in the arrayn”,count_neg);
printf(“There are %d positive numbers in the arrayn”,count_pos);
}

28
Bubble sort in c:

#include <stdio.h>

Void bubble_sort (int a[], int size);

Int main (void) {

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

Int i = 0;

Printf ("before: \n");

For (i = 0; i < 10; i++) printf ("%d ", arr [i]);

Printf ("\n");

bubble_sort (arr, 10);

Printf ("after:\n");

For (i = 0; i < 10; i++) printf ("%d ", arr[i]);

Printf ("\n");

Return 0;

Void bubble_sort (int a [], int size) {

Int switched = 1;

Int hold = 0;

Int i = 0;

Int j = 0;

29
Size -= 1;

For (i = 0; i < size && switched; i++) {

Switched = 0;

For (j = 0; j < size - i; j++)

If (a [j] > a [j+1]) {

Switched = 1;

Hold = a[j];

A [j] = a[j + 1];

A [j + 1] = hold;

Multidimensional arrays
Two dimensional arrays is an array of M x N where M is the total number of rows and N is the
total numbers of coloums.
Declaration of 2D array:
Data type array-name[m][n];
E.g int n[3][3];
Here n is a 2D array of 3 rows and 3 columns and can store 9 elements.
The position are represented as follows
N [0][0] n [0][1] n [0][2]
N [1][0] n [1][1] n [1][2]

30
N [2][0] n [2][1] n [2][2]
Initialization of 2D array
int a[][]={{1,2,3},{4,5,6},{7,8,9}};
To input data from user in 2D array , we use nesting of loops.
Printf (“enter the data in 2D array”);
For (i=0;i<3;i++)
{
For (j=0;j<3;j++)
{
Scanf (“%d”, &a[i][j]);
}
}
2D array is mainly used to solve the problems related to matrices like addition of matrix,
multiplication of matrix, transpose of matrix etc.
Example:
Addition of matrix
#include<stdio.h>
Int main () {
int a[3][3],b[3][3],c[3][3],i,j;
Printf ("Enter the First matrix->");
For (i=0;i<3;i++)
For (j=0;j<3;j++)
Scanf ("%d", &a[i][j]);
Printf ("\nEnter the Second matrix->");
For (i=0;i<3;i++)
31
For (j=0;j<3;j++)
Scanf ("%d", &b[i][j]);
Printf ("\nThe First matrix is\n");
For (i=0;i<3;i++){
Printf ("\n");
For (j=0;j<3;j++)
Printf ("%d\t", a[i][j]);
}
Printf ("\nThe Second matrix is\n");
For (i=0;i<3;i++){
Printf ("\n");
For (j=0;j<3;j++)
Printf ("%d\t", b[i][j]);
}
For (i=0;i<3;i++)
For (j=0;j<3;j++)
C [i][j]=a[i][j]+b[i][j];
Printf ("\nThe Addition of two matrix is\n");
For (i=0;i<3;i++){
Printf ("\n");
For (j=0;j<3;j++)
Printf ("%d\t", c[i][j]);
}
Return 0;

32
}
Example:
Transpose of a matrix
#include<stdio.h>

#include<conio.h>

Void main ()
{
int a[3][3], t[3][3],i,j;

for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf(“Enter the values FOR %d row & %d column: “, i+1,j+1);
scanf(“%d”,&a[i][j]);
}
}
printf(“\n\nEntered Matrix \n”);
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf(“\t%d”,a[i][j]);
}
printf(“\n”);
}

for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
t[i][j]=a[j][i];
}

33
printf(“\n\nTransposed Matrix \n”);
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf(“\t%d”,t[i][j]);
}
printf(“\n”);
}}

Programming examples of two dimensional arrays:


/* Program to check upper triangular matrix or not.
#include <stdio.h>
#include <conio.h>
Void main ()
{
Int a[3][3],i,j,flg=0;
Clrscr ();
Printf ("\n\t Enter 3*3 Matrix: ");
For (i=0;i<3;i++)
{
For (j=0;j<3;j++)
{
Scanf ("%d", &a[i][j]);
}
}
For (i=0;i<3;i++)
{

34
For (j=0;j<3;j++)
{
If (a[i]>a[j] && a[i][j]==0)
{
Flg=flg+1;
}
}
}
If (flg==3)
Printf ("\n\n Upper triangular matrix !");
Else
printf ("\n\n Not Upper triangular matrix !");
Getch ();}
Output:
Enter 3*3 Matrixes:
123
011
003
Upper triangular matrix! _
Strings: Arrays and strings, string manipulation using library functions

String
C char as basic data type, but no string type. String such as word or a sentence is defined as a
character array that is a set of character. A group of character is also known as string.
Defining string:

35
To declare a text string, specify a type of char and place the number of character in the array
in square brackets after the string name
Char STR [10];
This generates an array of 10 characters and gets a continuous memory location. Some of the
operations on strings are:
 Reading Strings
 Finding length of a string
 Copying one string to another.
 comparing of strings
 concatenation of string
I/O of string data
Reading strings: String can be entered using input function like gets () and scanf ()
E.g
Char STR [20];
Printf (“enter the string”);
Scanf (“%s”, str);
Or
Char STR [20];
Puts (“enter string”);
Gets (string);
There is a small difference between gets () and scanf () while entering string. Gets () allows us
to enter space in data.
String can be displayed on the screen using output function like puts ()
Puts (“Gurgaon”);
Puts (address”);

36
Programs to show some of the functions of strings.
Copying one string to another
#include<stdio.h>
#include<conio.h>
#include<string.h>
Void main ()
{
Char STR 1 [20], str 2 [20];
Int i, l;
Printf (“enter the string”);
Gets (str1);
l=strlen (str1);
For (i=0;i<=l;i++)
str2 [i] =str1 [i];
Puts (“the copied string is”);
Puts (str2)
}
Built-in library functions to manipulate strings
Some of the inbuilt function which is available in C language is:
The strlen function computes the length of the string
Example
#include <stdio.h>
#include <string.h>
Int main()
{
37
Char s [20] = "abcde1010101";
Printf ("The length of \"%s\" is %d characters.\n", s, strlen(s));
Return 0;
}
Output:
The length of "abcde1010101" is 12 characters.
Return Values
The strlen function returns the number of characters that precede the terminating NULL
character.
Strcpy () function.
Here are some C programs which implement the strcpy () function.
Method1
char *mystrcpy(char *dst, const char *src)
{
char *ptr;
ptr = dst;
while(*dst++=*src++);
return(ptr);
}
The strcpy function copies src, including the terminating null character, to the location
specified by dst. No overflow checking is performed when strings are copied or appended.
The behavior of strcpy is undefined if the source and destination strings overlap. It returns the
destination string. No return value is reserved to indicate an error.
Note that the prototype of strcpy as per the C standards is char *strcpy (char *DST, const char
*src); Notice the const for the source, which signifies that the function must not change the
source string in anyway! Method 2 char *my_strcpy(char dest[], const char source[])
{
int i = 0;
while (source[i] != '\0')
{
dest[i] = source[i];
38
i++;
}
dest[i] = '\0';
return(dest);
}
Strcmp() - compare two strings

#include <string.h>
int strcmp (const char *s1, const char *s2);

The strcmp () function shall compare the string pointed to by s1 to the string pointed to by s2.

The sign of a non-zero return value shall be determined by the sign of the difference between
the values of the first pair of bytes (both interpreted as type unsigned char) that differ in the
strings being compared.

RETURN VALUE

Upon completion, strcmp() shall return an integer greater than, equal to, or less than 0, if the
string pointed to by s1 is greater than, equal to, or less than the string pointed to by s2,
respectively.

EXAMPLES

Checking a Password Entry

The following example compares the information read from standard input to the value of the
name of the user entry. If the strcmp () function returns 0 (indicating a match), a further check
will be made to see if the user entered the proper old password. The crypt () function shall
encrypt the old password entered by the user, using the value of the encrypted password in the
passwd structure as the salt. If this value matches the value of the encrypted passwd in the
structure, the entered password oldpasswd is the correct user's password. Finally, the program
encrypts the new password so that it can store the information in the passwd structure.

#include <string.h>

#include <unistd.h>

#include <stdio.h>
39
...

Int valid_change;

Struct passwd *p;

Char user [100];

Char oldpasswd [100];

Char newpasswd [100];

Char savepasswd [100];

...

If (strcmp (p->pw_name, user) == 0) {

If (strcmp (p->pw_passwd, crypt (oldpasswd, p->pw_passwd)) == 0) {

Strcpy (savepasswd, crypt (newpasswd, user));

p->pw_passwd = savepasswd;

valid_change = 1;

Else {

Fprintf (stderr, "Old password is not valid\n");

Strcat() function

#include <stdio.h>

40
char *strcat(char *dest, const char *src);

Description:

The strcat function concatenates or appends src to dest. All characters from src are copied
including the terminating null character.

Return Value

The strcat function returns dest.

Example

 #include <stdio.h>
 int main() {
 char string1[20];
 char string2[20];
 strcpy(string1, "Hello");
 strcpy(string2, "Hellooo");
 printf("Returned String : %s\n", strcat( string1, string2 ));
 printf("Concatenated String : %s\n", string1 );
 return 0;
 }

It will produce following result:

Returned String : HelloHellooo

Concatenated String : HelloHellooo

Programming exercises:
C program to reverse a string
#include<string.h>

Int main (){

41
Char STR [20], rev [20];

Int I, j;

Printf ("\nEnter a string :");

Scanf ("%s", str);

For (i=strlen (str)-1,j=0;i>=0;i--,j++)

Rev [j] = STR [i];

Rev [j] ='\0';

If (strcmp (rev, STR))

Printf ("\nThe string is not a palindrome");

Else

Printf ("\nThe string is a palindrome");

Return 0;

Program to find substring of a string:


#include<stdio.h>
#include<conio.h>
Int main ()
{
Int i=0, j=0, k=0, count=0, l=0, k1=0;
Char a [80], b [80];
Clrscr ();
Printf ("\nEnter main string:-\n");

42
Gets (a);
Printf ("\nEnter sub-string:-\n");
Gets (b);
l= strlen (b);
While (a[i]! =EOF)
{
If (a[i] ==b[j])
{
i++;
j++;
k1=1;
If (j==l)
{
j=0;
k=1;
Count=count+1;
}
}
Else
{
If (k1==1)
{
j=0;
k1=0;

43
}
Else
I++;
}
}
If (k==1)
{
Printf ("\n\nThe given sub-string is present in the main string.");
Printf ("\nIt is present %d times.", count);
}
Else
{
If (k==0)
Printf ("\n\nThe given sub-string is not present in the main string.");
}
}
Program to find total vowel, consonants, digits and special character in C
#include<stdio.h>
#include<conio.h>
#include<string.h>
Void main ()
{
Char s [100];
Int b, c, d, e, i, l, p;

44
b=c=d=e=0;
Clrscr ();
Printf ("\n\t Enter the string :=>");
Gets (s);
l=strlen(s);
For (i=0;s[i]!='\0';i++)
{
If ((s[i]>=65&&s[i] <=90||s[i]>=97&&s[i] <=122))
B++;
If (s[i]>=48&&s[i]<=57)
C++;

if(s[i]=='a'||s[i]=='e'||s[i]=='i'||s[i]=='o'||s[i]=='u'||s[i]=='A'||s[i]=='E'||s[i]=='I'||s[i]=='O'||s[i]=='U
')
D++;
if (s[i]==' ')
E++;
}
p=b-d;
Printf ("\n\t No of vowels=%d \n", d);
Printf ("\n\t No of consonants=%d \n ", p);
Printf ("\n\t No of digits=%d \n", c);
Printf ("\n\t no of words=%d \n ", e+1);
Printf ("\n\t No of specal character=%d \n", l-b-c-e);
Getch ();

45
}
List of String library function
Functions Use
Strlen Finds length of a string
Strlwr Converts a string to lowercase
Strupr Converts a string to uppercase
Strcat Appends one string to uppercase
Strncat Appends fi rst n characters of a string at the end
of another
Strcpy Copies a string into another
Strncpy Copies first n characters o one string into another
Strcmp Compares two strings
Strncmp Compares fi rst n characters of two strings
Strcmpi Compares two strings without regard to case (“I”
denotes that this function ignores case)

Stricmp Compares two strings without regards to case


(identical to strcmpi)
Strnicmp Compares first n characters if two strings without
regard to case
Strdup Duplicates a string
Strchr Finds first occurrence of a given character in a
string
Strchr Finds last occurrence of a given character in a
string

46
Strrchr Finds last occurrence of a given character in a
string
Strstr Finds first occurrence of a given striung in
another string
Strset Sets all characers of string to a given character
Strnset Sets first n characters of a string to a given
character
Strrev Reverses string

Array of strings
How to declare array of strings?
Char variable_name [ROWS][COLS];

Here,
ROW - Total number of maximum strings
COLS - Total number of characters in a string

Program to create, read and print an array of strings in C


#include <stdio.h>
#define MAX_STRINGS 10
#define STRING_LENGTH 50
Int main ()
{
//declaration
Char strings [MAX_STRINGS][STRING_LENGTH];
Int loop, n;

Printf ("Enter total number of strings: ");

47
Scanf ("%d", &n);
Printf ("Enter strings...\n");
For (loop=0; loop<n; loop++)
{
Printf ("String [%d]? ", loop+1);
Getchar (); //read & ignore extra character (NULL)
//read string with spaces
Scanf ("% [^\n] s",strings [loop]);
}
Printf ("\nStrings is...\n");
For (loop=0; loop<n; loop++)
{
Printf ("[%2d]: %s\n", loop+1, strings [loop]);
}
Return 0;
}
Output

Enter total number of strings: 5


Enter strings...
String [1]? Hello friends, how are you?
String [2]? I hope, you all are fine!
String [3]? By the way, what are you doing?
String [4]? I hope you're doing good.
String [5]? Bye Bye!!!

48
Strings are...
[1]: Hello friends, how are you?
[2]: I hope, you all are fine!
[3]: By the way, what are you doing?
[4]: I hope you're doing well.
[5]: Bye Bye!!!
Here, MAX_STRINGS is a Macro that define total number of maximum strings
and STRING_LENGTH to define total number of characters in a string.

Summary
This unit has the detail of array declaration both types of arrays like one dimensional and two
dimensional. Also it has programs related to the different application of the array like sorting
and searching. Some of programs related to two dimensional array has also been done like
matrix addition, matrix multiplication etc. A special type of array, which is known as string is
also explained in this unit. The different operations on strings and string functions have also
be explained
Keywords
Array: An array is the collection of elements with contiguous memorial location.
Binary Search: It is a digital scheme for locating a specific object in a large set. Each objectin
the set is given a key which help us to searching special objects from a collection.
Bubble sort: It is asimple sort ingal gorithm that works by repeatedly stepping through the list
to be sorted, comparing each pair of adjacent items and swapping them if they are in the
wrong order. Insertion sort: It is one of the basical gorithms that exist among hundreds of
sort ingal gorithms. It only performs n–1 passes; wheren is the number of elements to sort.
Linear Search: It is the most basic of search algorithm you can have. A linear search
sequentially moves through a collection (or data structure) looking for a matching value.
Multi-Dimensional Arrays: Multi dimensional arrays operate on the same principle as single-
dimensional arrays. It shows the different dimensions of an array.

49
Null-terminated String: Stringis terminated by a special character which is called as null
terminator or null parameter (/0).
Strcat (): It is used to concatenate a null-terminated string to end of another string
variable.This is equivalent to pastingone stringon tot he end of another, over writing the null
terminator.
String: Cstring is defined as an array of characters or a pointer to characters.
Strlen () It returns the length of a string, excluding the null
Strncmp (): It is used to compare the first n characters of two strings. The strings are
compared character by character starting at the characters pointed at by the two pointers.
Formal parameters: The arguments declared as part of the proto type are also known as
formal parameters.
Function declaration: The function declarationis a replica of the function declaration.
Register variables: Register variable area special case of automatic variables. Automatic
variables are allocated storage in the memory of the computer.
Static variables: Static variables are local to the functions and exist till the termination of the
program.
Self assessement
1. Which of the followingis validstatementto declarea string?
(a) Char_name [20]; (b) charname [20];
(c) char-name [20]; (d) char Name [20]
2. Whilepassingarrayelements to afunction bycallby value we pass valuesofarrayelementsto
the function.
(a) True (b) False
3. Whatwillbe the output?main(){ charname[10]=“String”,n[10];puts(strcpy(n,name));
Printf (“%d”, strcmp (n, name));}
(a) String, 0 (b) String, 5
(c) String, 2 (d) None of these.

50
4. Thesefunctionsare appropriatewhen strings are tobe receivedfromthe screenorsenttothe
screen withouterrors.
(a) True (b) False
5. Strcmp ()is used to compare strings.
(a) Three (b) two
(c) Many (d) four
6 What are the two dimensional array?
(a) Chars1 [25]= “pat”; (b) char D[25];
(c)chararray[0]=“Hello”;(d)charnames[2][8]= {“Frans”,“Coenen”};
7. The compilercan compute itforus based on the size of the initialize
Charstring [] = “Hello,world!”;
(a) 13 (b) 15
(c) 14 (d) 12
8. The lastcharacteris thenullcharacterhavingASCII value zero
(a) True (b) False
9. Scanfto getonlyone variableata time, in a singlestatement.
(a) True (b) False
10. The outputwillbe: charS [25] =“world!”; charD[25]=“Hello,“; strncat(D, S, 5);strncat(D, S,
strlen(S)–1);
(a) Hello world (b) Helloworld
(c) “Hello,world” (d) ”word,Hello”
Review questions
1. Howdowestore astringin the array?
2. Differentiate betweenstring andcharacters.
3. Write aprogramwhichwould print the alphabetsetatozand A toZ indecimaland character
form.

51
4. Write a program, which will arrange the words in the ascending order of word length.
5. What is the string handling functions in C?
6. Whatare the differences between strcpy () and strncpy ()?
7. Whatare the string input/output functions?
8. Differentiate between strcat () and strncat ()?
9. Define the concept of string and string variable.
10. How do we create the arrays of strings?
11. What do you mean by function? Explain the various advantages of making functions
12. Make a function in c to find length of a string
13. Make a recursive function to print fibbonacci series upto n terms
Answers for Self Assessment Questions
1. C 2. C. 3. B 4. D 5. A
6. A 7. D 8. D 9. A 10. D

****

52

You might also like