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

UNIT-4 Programming in C

The document discusses different types of arrays in C language including one dimensional, two dimensional, and multidimensional arrays. It provides the syntax for declaring each type of array and examples of initializing and accessing array elements. Dynamic arrays are also covered as arrays that can be resized at runtime using functions like malloc() and calloc().

Uploaded by

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

UNIT-4 Programming in C

The document discusses different types of arrays in C language including one dimensional, two dimensional, and multidimensional arrays. It provides the syntax for declaring each type of array and examples of initializing and accessing array elements. Dynamic arrays are also covered as arrays that can be resized at runtime using functions like malloc() and calloc().

Uploaded by

Manda Vaishnavi
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 17

UNIT-4: ARRAYS

Definition: An array is a collection of elements of same type that share a common name.

The elements of an array are stored in contiguous memory locations.


In ‘C language, arrays are classified into two types. They are

1. One Dimensional Arrays


2. Multi Dimensional Arrays

ONE DIMENSIONAL ARRAY


When an array is declared with only one dimension (subscript) then it is called “One
dimensional array” or “single dimensional array”.

Declaring one dimensional Array:

The general format of declaring a one dimensional array is as follows:

Syntax:

datatype arrayname[size] ;

In the above syntax,


 The datatype is any valid data type of C language. An array can hold all the values
based on the specified data type.
 The ‘arrayname’ is an identifier that specifies name of the array variable. All the
elements will share this variable name.
 The ‘size’ indicates maximum number of elements that an array can hold. It must be a
positive integer constant.

Example-1: int a[5];


The above declaration reserves 5 contiguous memory locations of integer data type
for the array ‘a’. The conceptual view for the above declaration is as shown below:

0 1 2 3 4

a[0] a[1] a[2] a[3] a[4]

Storing values into the Array


To store the array elements, we follow the following two methods. They are:

- Initialisation of the array


- Reading the array elements

Initialisation of the Array:

While declaring an array, we can initialise it with some values. The general format to
initialise one dimensional array is as follows:

Syntax:

datatype arrayname[size] = {V0, V1, …, Vsize-1} ;

Here, V0, V1, …, Vsize-1 are the initial values of the specified array. If we omit the
values then an array contains garbage values. The number of values must be less than or
equal to the size of the array. When there are few values then the remaining elements are
assigned with zeros.

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


int a[5] = {78, 34, 98, 90, 124};  78 34 98 90 124

Reading the arrays elements: To read the array elements thru keyboard, we write and
execute the following example

for(i=0;i<=n-1;i++)
scanf(“%d”,&num[i]);
Accessing elements of the Array:
Once we store the elements of an array, we may access the elements of the array. To
access the array elements, we use the index numbers of the array. The index numbers helps us
to identify a particular location of the array. The following example is used to accessing the
elements of an array and prints them on the screen.
main()
{
int a[]={ 5, 6, 9, 7, 3};
int i;
clrscr();
printf(“The Elements are \n”);
for(i=0 ; i<5; i++)
printf(“ %d \n”, a[i]);
getch();
}
Two-Dimensional Arrays
When an array uses only two subscripts then it is called “two-dimensional array”. A
two-dimensional array is useful for matrix operations.

Declaring Two-Dimensional Array:

The general format of declaring a two dimensional array is as follows:

Syntax:

datatype arrayname[rowsize][columnsize] ;

In the above syntax,


 The datatype is any valid data type of C language. An array can hold all the values
based on the specified data type.
 The ‘arrayname’ is an identifier that specifies name of the array variable. All the
elements will share this variable name.
 The ‘rowsize’ indicates maximum number of rows and ‘columnsize’ indicates number
of columns in a row.
Example: int a[4][3];
Here, it reserves 12 (4 rows x 3 columns) integer type memory locations for the array
‘a’. The conceptual view for the above declaration is as shown below:
a[4][3]

0 1 2

Initialisation of Two Dimensional Array:

While declaring an array, we can initialise it with some values. The general format to
initialise two dimensional array is as follows:
Syntax:

datatype arrayname[rowsize][columnsize] = {{row1 values}, {row2 values}, …, } ;

Here, If we omit the values then an array contains garbage values. The number of
values must be less than or equal to the size of the array. When there are few values then the
remaining elements are assigned with zeros.

Example-1:

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

This example initialises the array ‘a’ with the given values as shown below:

a 0 1 2

0 4 6 8

1 1 3 5

Example-1:

int a[2][3] = { {4, 8}, {5}};

This example initialises the array ‘a’ with the given values as shown below:

a 0 1 2

0 4 8 0

1 5 0 0

Accessing of two dimensional arrays:

Each two dimensional array element is referred or accessed by specifying the array
name followed by two subscripts. The subscripts must be enclosed within square brackets.

For example,

a[0][0] refers to the first element in the two dimensional array.

a[rowsize-1][colsize-1] refers to the last element of the array.

The remaining elements can be accessed as a[0][1], a[2][3], a[1][2] and so on.

The two dimensional array that contains ‘m’ rows and ‘n’ columns can be read using
loops as follows:

for(i=0;i<=m-1;i++)
for(j=0;j<=n-1;j++)

scanf(“%d”,&a[i][j]);
Multidimensional Arrays
A multi-dimensional array can be termed as an array of arrays that stores
homogeneous data in tabular form. Data in multidimensional arrays is generally
stored in row-major order in the memory.

The general form of declaring N-dimensional arrays is shown below.

Syntax:
data_type array_name[size1][size2]....[sizeN];
 data_type: Type of data to be stored in the array.
 array_name: Name of the array.
 size1, size2,…, sizeN: Size of each dimension.

Examples:
Two dimensional array: int two_d[10][20];
Three dimensional array: int three_d[10][20][30];

 Size of Multidimensional Arrays:


 The total number of elements that can be stored in a multidimensional
array can be calculated by multiplying the size of all the dimensions.

For example:
 The array int x[10][20] can store total (10*20) = 200 elements.
 Similarly array int x[5][10][20] can store total (5*10*20) = 1000
elements.
To get the size of the array in bytes, we multiply the size of a single element with
the total number of elements in the array.

For example:
 Size of array int x[10][20] = 10 * 20 * 4 = 800 bytes. (where int = 4
bytes)
 Similarly, size of int x[5][10][20] = 5 * 10 * 20 * 4 = 4000 bytes.
(where int = 4 bytes)
The most commonly used forms of the multidimensional array are:
1. Two Dimensional Array
2. Three Dimensional Array
Dynamic Array
we can’t change the size of the array after its declaration. Due to this, we may
encounter situations where our array doesn’t have enough space left for required
elements or we allotted more than the required memory leading to memory
wastage. To solve this problem, dynamic arrays come into the picture.
A Dynamic Array is allocated memory at runtime and its size can be changed
later in the program.
We can create a dynamic array in C by using the following methods:
1. Using malloc() Function
2. Using calloc() Function

1. Dynamic Array Using malloc() Function


The “malloc” or “memory allocation” method in C is used to dynamically
allocate a single large block of memory with the specified size. It returns a
pointer of type void which can be cast into a pointer of any form. It is defined
inside <stdlib.h> header file.

Syntax:
ptr = (cast-type*) malloc(byte-size);
We can use this function to create a dynamic array of any type by simply
allocating a memory block of some size and then typecasting the returned void
pointer to the pointer of the required type.
Example:
ptr = (int*) malloc(100 * sizeof(int));
In the above example, we have created a dynamic array of type int and size 100
elements.

Example:
 C

// C program to create dynamic array using malloc() function

#include <stdio.h>
#include <stdlib.h>
int main()
{

// address of the block created hold by this pointer


int* ptr;
int size;

// Size of the array


printf("Enter size of elements:");
scanf("%d", &size);

// Memory allocates dynamically using malloc()


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

// Checking for memory allocation


if (ptr == NULL) {
printf("Memory not allocated.\n");
}
else {

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

// Get the elements of the array


for (int j = 0; j < size; ++j) {
ptr[j] = j + 1;
}

// Print the elements of the array


printf("The elements of the array are: ");
for (int k = 0; k < size; ++k) {
printf("%d, ", ptr[k]);
}
}

return 0;
}

Output:
Enter size of elements:5
Memory successfully allocated using malloc.
The elements of the array are: 1, 2, 3, 4, 5,
2. Dynamic Array Using calloc() Function
The “calloc” or “contiguous allocation” method in C is used to dynamically
allocate the specified number of blocks of memory of the specified type and
initialized each block with a default value of 0.
The process of creating a dynamic array using calloc() is similar to the malloc()
method. The difference is that calloc() takes arguments instead of one as
compared to malloc(). Here, we provide the size of each element and the number
of elements required in the dynamic array. Also, each element in the array is
initialized to zero.
Syntax:
ptr = (cast-type*)calloc(n, element-size);
Example:
ptr = (int*) calloc(5, sizeof(float));
In the above example, we have created a dynamic array of type float having five
elements.
Let’s take another example to create a dynamic array using the calloc() method.
Example:
 C

// C program to create dynamic array using calloc() function

#include <stdio.h>
#include <stdlib.h>

int main()
{

// address of the block created hold by this pointer


int* ptr;
int size;

// Size of the array


printf("Enter size of elements:");
scanf("%d", &size);

// Memory allocates dynamically using calloc()


ptr = (int*)calloc(size, sizeof(int));

// Checking for memory allocation


if (ptr == NULL) {
printf("Memory not allocated.\n");
}
else {

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

// Get the elements of the array


for (int j = 0; j < size; ++j) {
ptr[j] = j + 1;
}

// Print the elements of the array


printf("The elements of the array are: ");
for (int k = 0; k < size; ++k) {
printf("%d, ", ptr[k]);
}
}

return 0;
}
Output:
Enter size of elements:6
Memory successfully allocated using malloc.
The elements of the array are: 1, 2, 3, 4, 5, 6,
A string is a sequence of one or more characters. Any group of characters enclosed within
double quotes is a string constant. In ‘C’ language, strings are manipulated using arrays and
pointers.

Ex: “Hello” “Computer Science” etc.

A string is a one dimensional array of characters terminated by a null (\0) character.


The null character is stored at the end of array of characters to mark the end of the string. If
an array is used to store the strings then that array is often called “string variable”. A string
that is not terminated by ‘\0’ is not really a string, but it is only a collection of characters.

Operations on strings:

The common operations performed on strings are:

i. Reading and writing strings


ii. Combining strings together (concatenation)
iii. Copying one string to another
iv. Comparing strings for equality
v. Finding the number of characters in a string (length)

Declaring a String Variable:

To manipulate strings, an array must be declared with character data type. A string can be
declared as follows:

Syntax: char arrayname[size];

The ‘size’ is the number of characters in the array.

Example: char name[40]; char city[15]; etc.


Initialising a String Variable:

1. A string of characters can be stored in an array as follows:

Ex: 1. char city[6] = {‘D’,’E’,’L’,’H’,’I’};

2. char city[6] = “DELHI”;

(OR)

char city[] = “DELHI”;

In the above examples, the C compiler automatically inserts ‘\0’ character at the end. So,
the conceptual view for the above examples is as shown below:

D E L H I \0

2. A string can be initialised using pointers as follows:

Ex: char *city = “DELHI”;

Here, it stores the string “DELHI” into memory and assigns the starting location
address to the pointer variable ‘city’. The conceptual view for the above example is as shown
below:

city 4650 4651 4652 4653 4654 4655

4650 D E L H I \0

Array of Strings (or) Two-dimensional character type array:

To store more than one string in the array, then the array can be declared as follows

char arrayname[size1][size2];

Here, ‘size1’ specifies the number of strings and ‘size2’ refers the number of
characters in each string.

Example: char city[3][10] = {“DELHI”,”BANGALORE”,”CHENNAI”};

This example reserves 3 memory locations to store 3 strings. Each string may contain
10 characters (10 bytes). The conceptual view for the above declaration is
City[0 D E L H I \0
]

City[1 B A N G A L O R E \0
]

City[2 C H E N N A I \
] 0

Scanf( ) and Printf( ) functions:

Strings can be read and write using formatted I/O functions by the format character
“%s”. While using “%s” character, the address operator and subscript should not be specified
for the array.

When %s character is used with scanf( ) function, it terminates its input at the first
white space character (white space characters are blanks, tabs and carriage return i.e.‘\n’). For
example, if we input “NEW DELHI”, then it takes only “NEW”.

Example:

#include<stdio.h>

Main( )

char name[30];

printf(“Enter a string “);

scanf(“%s”,name);
printf(“%s”,name);

gets( ) and puts( ) Functions:

These functions are also used to read and write strings. The gets( ) function reads a
string upto carriage return i.e. ‘\n’ pressed. The puts( ) functions writes the specified string on
the monitor. These functions will not require any format character to read and write strings.

Example:

#include<stdio.h>

main( )

{
char name[30];

printf(“Enter a string “);

gets(name);

puts(name);

Built-In String Functions:

In ‘C’ language, there are several function are used to manipulate strings. These
functions are included in “string.h” file. The following are some of the most commonly used
string functions:

1. Strlen( ) Function:

This function finds the length of the given string. It means it counts and returns the
number of characters present in the string. The output of this function is an integer.

Syntax: strlen(string); Where ‘string’ is constant or array variable.

Example:

#include<stdio.h>

#include<string.h>

main( )
{

int n;

char name[10] = “ABCDE”;

n = strlen(name);

printf(“length = %d”, n);

Output  5

2. Strrev( ) Function:

This function is used to reverse all the characters in the given string except null
character.
Syntax: strrev(string); Where ‘string’ is constant or array variable.

Example:

#include<stdio.h>

#include<string.h>

main( )

char name[10] = “ABCDE”;

strrev(name);

puts(name);

Output  EDCBA

3. Strlwr( ) Function:

This function converts all the uppercase letters in the given string into lowercase.

Syntax: strlwr(string); Where ‘string’ is constant or array variable.

Example:

#include<stdio.h>

#include<string.h>

main( )
{

char name[10] = “aBcDe”;

strlwr(name);

puts(name);

Output  abcde

4. Strupr( ) Function:

This function converts all the lowercase letters in the given string into uppercase.

Syntax: strupr(string); Where ‘string’ is constant or array variable.

Example:
#include<stdio.h>

#include<string.h>

main( )

char name[10] = “aBcDe”;

strlwr(name);

puts(name);

} Output  ABCDE

5. Strcpy( ) Function:

This function copies the contents of one string (source) to another string (destination).
The contents of the source string are unchanged.

Syntax: strcpy(string1, string2); Where ‘string1’ is destination string and


‘string2’ is source string. The contents of string2 are copied to string1.

Example:

#include<stdio.h>

#include<string.h>

main( )

char a[10] = “ABCDE”;


char b[10];

strcpy(b, a);

puts(b);

The above example copies the contents of ‘a’ to ‘b’. Hence the output is ABCDE.

6. Strcat( ) Function:

This function appends the contents of one string (source) to another string
(destination). This is called concatenation of two strings. The contents of the source string are
unchanged.

Syntax: strcat(string1, string2); Where ‘string1’ is destination string and


‘string2’ is source string. The contents of string2 are appended to string1.
Example:

#include<stdio.h>

#include<string.h>

main( )

char a[30] = “ABC”;

char b[30] = “DEF”;

strcat(b, a);

puts(b);

The above example append the contents of ‘a’ to ‘b’. Hence the output is DEFABC

7. Strcmp( ) Function:

This function is used to compare two strings.

Syntax: strcmp(string1, string2)

Here,

1. If string1 is equal to string2 then it returns value 0


2. If string1 is less than string2 then it returns a negative (less than 0) value.
3. If string1 is greater than string2 then it returns positive (greater than 0) value.

Example:

#include<stdio.h>

#include<string.h>

main( )

char a[30], b[30];

int c;

printf(“Enter First String”);

gets(a);

printf(“Enter Second String”);


gets(b);

c = strcmp(a, b);

if (c = = 0)

printf(“String1 and string2 are equal”);

else

if (c < 0)

printf(“String1 is less than string2”);

else

if (c > 0)

printf(“String1 is greater than string2”);

You might also like