C-prgm Unit-i8

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 21

BE SEM - I

C- Programming
Unit 8: Arrays and string

Syllabus Unit: - 8

Introduction

An array is defined as the collection of elements of the same data type stored at contiguous
memory locations. The elements of the array share the same variable name but each element
has its own unique index number (also known as a subscript). An array is the derived data type
in C programming language which can store the primitive type of data such as int, char, double,
float, etc. And it can also store the collection of derived data types, such as pointers, structure,
etc. Elements of the array can be randomly accessed by using its index number.

Declaration of C Array
Like any other variable, arrays must be declared before they are used. General form of array
declaration is,

data-type variable-name[size];

Example
int arr[10];

Here, int is the data type, arr is the name of the array and 10 is the size of array. It means
array arr can only contain 10 elements of int type.

Index of an array starts from 0 to size-1 i.e first element of arr array will be stored
at arr[0] address and the last element will occupy arr[9].

There are various ways in which we can declare an array. It can be done by
specifying its type and size, by initializing it or both.

Teksan Gharti
BE SEM - I
C- Programming
// Array declaration by specifying size

int arr1[10];

// Array declaration by initializing elements

int arr[] = { 10, 20, 30, 40 }

// Array declaration by specifying size and initializing elements

int arr[6] = { 10, 20, 30, 40 }


Initialization of an Array

After an array is declared it must be initialized. Arrays may be initialized when they are
declared, just as any other variables.

For example:-
int mark[5] = {19, 10, 8, 17, 9};

You can also initialize an array like this.


int mark[] = {19, 10, 8, 17, 9};

We can also initialize each element of the array by using the index. Consider the following
example.

marks[0]=80;
marks[1]=60;
marks[2]=70;
marks[3]=85;
marks[4]=75;

Access element of an array in C

Element of array can be accessed by using array subscript (or index) . Subscript starts
with 0, which means arr[0] represents the first element in the array arr.the general form of
accessing the array element is as follows…..

Syntax:
arr_name[index];

In general arr[n-1] can be used to access nth element of an array. where n is any integer number.
For example:

Teksan Gharti
BE SEM - I
C- Programming
int mydata[20];
mydata[0] /* first element of array mydata*/
mydata[19] /* last (20th) element of array mydata*/

Advantages of an Array in C:-


• Random access of elements using array index.
• Use of less line of code as it creates a single array of multiple elements.
• Easy access to all the elements.
• Traversal through the array becomes easy using a single loop.
• Sorting becomes easy as it can be accomplished by writing less line of code.
Disadvantages of an Array in C:-
• Allows a fixed number of elements to be entered which is decided at the time of
declaration. Unlike a linked list, an array in C is not dynamic.
• Insertion and deletion of elements can be costly since the elements are needed to be
managed in accordance with the new memory allocation.

Single And Multi -dimensional arrays

Single Dimensional Array


An array which has only one subscript is known as one dimensional array i.e. int arr[5].
A one-dimensional array is a group of elements having the same datatype and same name. In
this type of array, the Individual elements are referred to using common name and unique index
of the elements.

In c programming language, single dimensional arrays are used to store list of values of same
datatype. In other words, single dimensional arrays are used to store a row of values. In single
dimensional array, data is stored in linear form. Single dimensional arrays are also called
as one-dimensional arrays, Linear Arrays or simply 1-D Arrays.

Declaration of Single Dimensional Array

the following syntax shows the general syntax for declaring a single dimensional array...

datatype arrayName [ size ] ;

Example :-

int rollNumbers [60] ;

The above declaration of single dimensional array reserves 60 continuous memory locations of
2 bytes each with the name rollNumbers and tells the compiler to allow only integer values into
those memory locations.

Teksan Gharti
BE SEM - I
C- Programming
Initialization of Single Dimensional Array

The general form for declaring a single dimensional array...

datatype arrayName [ size ] = {value1, value2, ...} ;

Example:-

int marks [6] = { 89, 90, 76, 78, 98, 86 } ;

The above declaration of single dimensional array reserves 6 contiguous memory locations of
2 bytes each with the name marks and initializes with value 89 in first memory location, 90 in
second memory location, 76 in third memory location, 78 in fourth memory location, 98 in
fifth memory location and 86 in sixth memory location.

We can also use the following general syntax to intialize a single dimensional array without
specifying size and with initial values...

datatype arrayName [ ] = {value1, value2, ...} ;

The array must be initialized if it is created without specifying any size. In this case, the size
of the array is decided based on the number of values initialized.

Example :-
int marks [] = { 89, 90, 76, 78, 98, 86 } ;

char studentName [] = "btechsmartclass" ;

In the above example declaration, size of the array 'marks' is 6 and the size of the
array 'studentName' is 16. This is because in case of character array, compiler stores one exttra
character called \0 (NULL) at the end.

Accessing Elements of Single Dimensional Array

In c programming language, to access the elements of single dimensional array we use array
name followed by index value of the element that to be accessed.

The index value must be enclosed in square braces. The index value of single dimensional
array starts with zero (0) for first element and incremented by one for each element.

We use the following general syntax to access individual elements of single dimensional
array...

arrayName [ indexValue ]

Example :-
marks [2] = 99 ;

In the above statement, the third element of 'marks' array is assinged with value '99'.

Teksan Gharti
BE SEM - I
C- Programming

Program:- Accept n number of values in an array and display it in reverse


order.
#include <stdio.h>
void main()
{
int i,n,a[100];

printf("\n\n Accept n number of values in an array and display it in reverse order:\n");


printf("------------------------------------------------------------------------\n");

printf("Accept the number of elements to store in the array :");


scanf("%d",&n);

printf("Input %d number of elements in the array :\n",n);


for(i=0;i<n;i++)
{
printf("index position - %d : ",i);
scanf("%d",&a[i]);
}

printf("\nThe values store into the array are : \n");


for(i=0;i<n;i++)
{
printf("% 5d",a[i]);
}

printf("\n\nThe values store into the array in reverse are :\n");


for(i=n-1;i>=0;i--)
{
printf("% 5d",a[i]);
}

printf("\n\n");

Output: -

Teksan Gharti
BE SEM - I
C- Programming

Multi Dimensional Array

An array of arrays is called as multi-dimensional array. In simple words, an array


created with more than one dimension (size) is called as multi-dimensional array. Multi-
dimensional array can be of two-dimensional array or three-dimensional array or four-
dimensional array or more...

Most popular and commonly used multi-dimensional array is two dimensional array. The 2-D
arrays are used to store data in the form of table. We also use 2-D arrays to create
mathematical matrices.

Declaration of Two-Dimensional Array

We use the following general syntax for declaring a two-dimensional array...

datatype arrayName [ rowSize ] [ columnSize ] ;

Example :-

int matrix_A [2][3] ;

The above declaration of two-dimensional array reserves 6 continuous memory locations of 2


bytes each in the form of 2 rows and 3 columns.

Initialization of Two-Dimensional Array

We use the following general syntax for declaring and initializing a two-dimensional array with
specific number of rows and columns with initial values.

datatype arrayName [rows][colmns] = {{r1c1value, r1c2value, ...},{r2c1, r2c2,...}...} ;

Example: -

int matrix_A [2][3] = { {1, 2, 3},{4, 5, 6} } ;

Teksan Gharti
BE SEM - I
C- Programming
The above declaration of two-dimensional array reserves 6 contiguous memory
locations of 2 bytes each in the form of 2 rows and 3 columns. And the first row is initialized
with values 1, 2 & 3 and second row is initialized with values 4, 5 & 6.

We can also initialize as follows...


Example :-

int matrix_A [2][3] = {


{1, 2, 3},
{4, 5, 6}
};

Accessing Individual Elements of Two Dimensional Array

In a c programming language, to access elements of a two-dimensional array we use


array name followed by row index value and column index value of the element that to be
accessed.

We use the following general syntax to access the individual elements of a two-dimensional
array...

arrayName [ rowIndex ] [ columnIndex ]

Example: -

matrix_A [0][1] = 10 ;

Here, the element with row index 0 and column index 1 of matrix_A array is assigned with
value 10.

Program No: -Accept the value of array and print in matrix form

#include <stdio.h>
void main()
{
int arr1[3][2],i,j;
printf("\n\n Accept the value of array and print the in matrix form of 3x2 :\n");
printf("------------------------------------------------------\n");

printf("Accept the value of array :\n");

for(i=0;i<3;i++)
{
for(j=0;j<2;j++)
{
printf("index position - [%d],[%d] : ",i,j);
scanf("%d",&arr1[i][j]);

Teksan Gharti
BE SEM - I
C- Programming
}
}

printf("\nPrint the value of array : \n");

for(i=0;i<3;i++)
{
printf("\n");
for(j=0;j<2;j++)
printf("%d\t",arr1[i][j]);
}
printf("\n\n");
}
Output: -

Processing an array
(declaring, initialling, assigning all task come in the processing of array)

Passing arrays to function: -


Just like variables, array can also be passed to a function as an argument. Passing more
than one variable of the same type to a function is required by various general problems in the
C language. It is seen as an important task to Pass arrays to a function in C as to be passed as
the actual parameters from the main function some amount of numbers is required. For
instance, a function in C that sorts the 10 elements in the ascending order. In order to be passed
as the actual parameters from the main function, these types of function will require 10
numbers. In this case, instead of declaring those 10 numbers that are different from each other
and then passing into the function, Users can declare and initialize an array and pass that into
the function, instead of declaring 10 different numbers and then passing into the function.
Doing this will automatically resolve all the complexity as the function will now work for any
number of provided values.

Teksan Gharti
BE SEM - I
C- Programming
The syntax to pass an array to the function: -

functionName(arrayName);//passing array

The function that receives an array as an argument in three ways by declaring the formal
parameter: -

1) Formal parameters as a pointer –

void myFunction(int *param)


{
………..
}

As shown in above syntax, a pointer can be passed with a help of a pointer variable carrying
the address of the first location of the array. This type of array passing mechanism is
called call by reference. In this case, we pass the address of the array elements while calling
the function. A detailed example is given below:

Program: -

#include <stdio.h>
void disp(int *num)
{
printf(" %d", *num);
printf("\n");
}

int main()
{
int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
int i;
for ( i=0; i<10; i++)
{

/* Passing addresses of array elements*/

disp(&arr[i]);
}

return 0;
}

Teksan Gharti
BE SEM - I
C- Programming
Output: -

2) Formal parameters as a sized array −

void myFunction(int param[5])


{
…………….
}

Program: - Formal parameters as sized array

#include<stdio.h>
void giveMeArray(int a[]);
int main()
{
int myArray[] = { 2, 3, 4 };
giveMeArray(myArray);
return 0;
}

void giveMeArray(int a[3])


{

int index = 0;
for(index= 0; index <3; ++index)
{
printf("%d\n",a[index]);
}
}

Teksan Gharti
BE SEM - I
C- Programming
Output:-

Program: -(2) Formal parameters as sized array

#include <stdio.h>

#define ARRAY_SIZE 8
void ReadArray(int acData[ARRAY_SIZE])
{
int index = 0;
for(index= 0; index < ARRAY_SIZE; ++index)
{
printf("%d\n",acData[index]);
}
}
int main(int argc, char *argv[])
{
//Create an array
int aiData[ARRAY_SIZE] = {1,2,3,4,5,6,7,8};
//Pass array as a parameter
ReadArray(aiData);
return 0;
}

Output:-

Teksan Gharti
BE SEM - I
C- Programming
3) Formal parameters as an unsized array –

void myFunction(int param[])


{
………….
}

Program:- Formal parameters as an unsized array –

#include <stdio.h>
//Size of the created array
#define ARRAY_SIZE 8
void ReadArray(int acData[])
{
int index = 0;
for(index= 0; index < ARRAY_SIZE; ++index)
{
printf("%d\n",acData[index]);
}
}
int main()
{

int aiData[ARRAY_SIZE] = {1,2,3,4,5,6,7,8};

ReadArray(aiData);
return 0;
}

Output:-

Teksan Gharti
BE SEM - I
C- Programming
Program:-(2) Formal parameters as an unsized array –

#include <stdio.h>

/* function declaration */
double getAverage(int arr[], int size);

int main ()
{

int balance[5] = {1, 2, 3, 4, 5};


double avg;
int s;
s = sizeof balance/ sizeof balance[0];
avg = getAverage(balance, s ) ;

printf( "Average value is: %f ", avg );

return 0;
}

double getAverage(int arr[], int size)


{

int i;
double avg;
double sum = 0;

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


{
sum += arr[i];
}

avg = sum / size;

return avg;
}

Output:-

Teksan Gharti
BE SEM - I
C- Programming

Note: -
To determine the number of elements in the array, we can divide the total size of the array by
the size of the array element. You could do this with the type, like this:
int a [10];
size n = sizeof(a) / sizeof(int);

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

Example:

char label[] = "Single";


This array looks like in memory as following:
--------------------------
| S | i | n | g | l | e | \0 |
--------------------------

So, the string is a 1-D array of characters and array of strings is a 2-D array of characters.
Just like we can create a 2-D array of int, float etc; we can also create a 2-D array of character
or array of strings. Here is how we can declare a 2-D array of characters.

Char ch_arr[3][10] = {
{'s', 'p', 'i', 'k', 'e', '\0'},
{'t', 'o', 'm','\0'},
{'j', 'e', 'r', 'r', 'y','\0'}
};

It is important to end each 1-D array by the null character. We can’t use them as
strings. Declaring an array of strings in this way is rather tedious, that’s why C provides an
alternative syntax to achieve the same thing. This above initialization is equivalent to:

char ch_arr[3][10] = {
"spike",
"tom",
"jerry"
};

The first subscript of the array i.e 3 denotes the number of strings in the array and the second
subscript denotes the maximum length of the string.

Teksan Gharti
BE SEM - I
C- Programming
Program:-
#include <stdio.h>
#include <string.h>

#define NUM_OF_STR 4
#define MAX_STR_SZ 40
#define DEST_SIZE 100

int main()
{

char arr[NUM_OF_STR][MAX_STR_SZ] ={ "array of c string",


"is fun to use",
"make sure to properly",
"tell the array size"
};

char dest[DEST_SIZE] = "";


int i ;

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


{
strcat(dest, arr[i]);
if (i < NUM_OF_STR - 1)
{
strcat(dest, " ");
}
}

printf(dest);

return 0;
}

Output:-

Teksan Gharti
BE SEM - I
C- Programming
String Handling Function: -

C programming language provides a set of pre-defined functions called string handling


functions to work with string values. The string handling functions are defined in a header
file called string.h. Whenever we want to use any string handling function, we must include
the header file called string.h.

There are lots of string handling functions available in string.h header file. Here are some of
the important string manipulation functions.

Function Syntax Description

strcpy() strcpy(string1, string2) Copies string2 value into string1

strncpy() strncpy(string1, string2, 5) Copies first 5 characters string2 into string1

strlen() strlen(string1) returns total number of characters in string1

strcat() strcat(string1,string2) Appends string2 to string1

strncat() strncpy(string1, string2, 4) Appends first 4 characters of string2 to


string1

strcmp() strcmp(string1, string2) Returns 0 if string1 and string2 are the


same;
less than 0 if string1<string2; greater than 0
if string1>string2
(it starts comparison character by character
starting from the first character until the
characters in both strings are equal or a
NULL character is encountered.)

strncmp() strncmp(string1, string2, 4) Compares first 4 characters of both string1


and string2

strcmpi() strcmpi(string1,string2) Compares two strings, string1 and string2


by ignoring case (upper or lower)

Teksan Gharti
BE SEM - I
C- Programming
Function Syntax Description

stricmp() stricmp(string1, string2) Compares two strings, string1 and string2


by ignoring case (similar to strcmpi())

strlwr() strlwr(string1) Converts all the characters of string1 to


lower case.

strupr() strupr(string1) Converts all the characters of string1 to


upper case.

strdup() string1 = strdup(string2) Duplicated value of string2 is assigned to


string1

strchr() strchr(string1, 'b') Returns a pointer to the first occurrence of


character 'b' in string1

strrchr() 'strrchr(string1, 'b') Returns a pointer to the last occurrence of


character 'b' in string1

strstr() strstr(string1, string2) Returns a pointer to the first occurrence of


string2 in string1

strset() strset(string1, 'B') Sets all the characters of string1 to given


character 'B'.

strnset() strnset(string1, 'B', 5) Sets first 5 characters of string1 to given


character 'B'.

strrev() strrev(string1) It reverses the value of string1

1) function – strlen

Program:-
#include <stdio.h>
#include <string.h>
int main()
{
char str1[20] = "hello";
printf("Length of string str1: %d", strlen(str1));
return 0;
}

Teksan Gharti
BE SEM - I
C- Programming
Output:

Length of string str1: 5

2) function – strcmp
Program:-

#include <stdio.h>
#include <string.h>
int main()
{
char s1[20] = "hello";
char s2[20] = "helloworld";
if (strcmp(s1, s2) ==0)
{
printf("string 1 and string 2 are equal");
}
else
{
printf("string 1 and 2 are different");
}
return 0;
}

Output:

string 1 and 2 are different

3) function – strncmp

Program: -
#include <stdio.h>
#include <string.h>
int main()
{
char s1[20] = "Engineering";
char s2[20] = "EngineeringFirstSem";
/* below it is comparing first 8 characters of s1 and s2*/
if (strncmp(s1, s2, 8) ==0)
{
printf("string 1 and string 2 are equal");
}
else
{
printf("string 1 and 2 are different");
}
return 0;
}

Teksan Gharti
BE SEM - I
C- Programming
Output:
string1 and string 2 are equal

4) function – strcat
Program:-

#include <stdio.h>
#include <string.h>
int main()
{
char s1[10] = "Hello";
char s2[10] = "World";
strcat(s1,s2);
printf("Output string after concatenation: %s", s1);
return 0;
}

Output:

Output string after concatenation: HelloWorld

5) function – strncat

Program

#include <stdio.h>
#include <string.h>
int main()
{
char s1[10] = "Hello";
char s2[10] = "World";
strncat(s1,s2, 3);
printf("Concatenation using strncat: %s", s1);
return 0;
}

Output:

Concatenation using strncat: HelloWor

6) function – strcpy
Program: -

#include <stdio.h>
#include <string.h>
int main()
{
char s1[30] = "string 1";
char s2[30] = "string 2 : I’m going to copied into s1";

Teksan Gharti
BE SEM - I
C- Programming
/* this function has copied s2 into s1*/
strcpy(s1,s2);
printf("String s1 is: %s", s1);
return 0;
}

Output:

String s1 is: string 2: I’m going to copied into s1

7) function – strncpy
Program
#include <stdio.h>
#include <string.h>
int main()
{
char s1[30] = "string 1";
char s2[30] = "string 2: I’m using strncpy now";
/* this function has copied first 12 chars of s2 into s1*/
strncpy(s1,s2, 12);
printf("String s1 is: %s", s1);
return 0;
}

Output:

8) function – strchr
Program
#include <stdio.h>
#include <string.h>
int main()
{
char mystr[30] = "I’m an example of function strchr";
printf ("%s", strchr(mystr, 'f'));
return 0;
}

Output:

f function strchr

Teksan Gharti
BE SEM - I
C- Programming
9) function – Strrchr
Program

#include <stdio.h>
#include <string.h>
int main()
{
char mystr[40] = "I’m an example of function fstrchr";
printf ("%s", strrchr(mystr, 'f'));
return 0;
}

Output:

fstrchr

10) function – strstr


Program
#include <stdio.h>
#include <string.h>
int main()
{
char inputstr[70] = "this is Himalayan engineering collage";
printf ("Output string is: %s", strstr(inputstr, 'engi'));
return 0;
}

Output:

Output string is: engineering collage

=================== End Unit 8 ==========================

Teksan Gharti

You might also like