0% found this document useful (0 votes)
27 views9 pages

04 CS3001

The document discusses arrays in C programming language. It defines what an array is, properties of arrays, declaration and initialization of arrays, memory organization of arrays, C strings and traversing strings. It provides examples of declaring, initializing and printing arrays and strings.
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)
27 views9 pages

04 CS3001

The document discusses arrays in C programming language. It defines what an array is, properties of arrays, declaration and initialization of arrays, memory organization of arrays, C strings and traversing strings. It provides examples of declaring, initializing and printing arrays and strings.
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/ 9

Awadhesh Kumar Singh

9414774988
ARRAYS [email protected]

An array is defined as the collection of similar type of data items stored at contiguous memory
locations. Arrays are the derived data type in C programming language which can store the
primitive type of data such as int, char, double, float, etc. It also has the capability to store the
collection of derived data types, such as pointers, structure, etc. The array is the simplest data
structure where each data element can be randomly accessed by using its index number.

C array is beneficial if you have to store similar elements. For example, if we want to store the
marks of a student in 6 subjects, then we don't need to define different variables for the marks
in the different subject. Instead of that, we can define an array which can store the marks in
each subject at the contiguous memory locations.

By using the array, we can access the elements easily. Only a few lines of code are required to
access the elements of the array.

Properties of Array
The array contains the following properties.

o Each element of an array is of same data type and carries the same size, i.e., int = 4
bytes.
o Elements of the array are stored at contiguous memory locations where the first element
is stored at the smallest memory location.
o Elements of the array can be randomly accessed since we can calculate the address of
each element of the array with the given base address and the size of the data element.

Advantage of C Array
1) Code Optimization: Less code to the access the data.

2) Ease of traversing: By using the for loop, we can retrieve the elements of an array easily.

3) Ease of sorting: To sort the elements of the array, we need a few lines of code only.

4) Random Access: We can access any element randomly using the array.

Disadvantage of C Array
1) Fixed Size: Whatever size, we define at the time of declaration of the array, we can't
exceed the limit. So, it doesn't grow the size dynamically like LinkedList which we will
learn later.

Declaration of C Array
Awadhesh Kumar Singh
9414774988
ARRAYS [email protected]

We can declare an array in the c language in the following way.

data_type array_name[array_size];

Now, let us see the example to declare the array.

int marks[5];

Here, int is the data_type, marks are the array_name, and 5 is the array_size.

Initialization of C Array
The simplest way to initialize an array is by using the index of each element. We can initialize
each element of the array by using the index. Consider the following example.

marks[0]=80;//initialization of array
marks[1]=60;
marks[2]=70;
marks[3]=85;
marks[4]=75;

C Array: Declaration with Initialization


We can initialize the c array at the time of declaration. Let's see the code.

int marks[5]={20,30,40,50,60};

In such case, there is no requirement to define the size. So it may also be written as the
following code.

int marks[]={20,30,40,50,60};

Let's see the C program to declare and initialize the array in C.


Awadhesh Kumar Singh
9414774988
ARRAYS [email protected]

Memory organization of array


whenever an array is declared in the program, contiguous memory to it elements are allocated.
Initial address of the array – address of the first element of the array is called base address of
the array. Each element will occupy the memory space required to accommodate the values for
its type, i.e.; depending on elements datatype, 1, 4 or 8 bytes of memory is allocated for each
element. Next successive memory address is allocated to the next element in the array. This
process of allocating memory goes on till the number of elements in the array gets over.

Below diagram shows how memory is allocated to an integer array of N elements. Its base
address – address of its first element is 10000. Since it is an integer array, each of its element
will occupy 4 bytes of space. Hence first element occupies memory from 10000 to 10003.
Second element of the array occupies immediate next memory address in the memory, i.e.;
10004 which requires another 4 bytes of space. Hence it occupies from 10004 to 10007. In this
way all the N elements of the array occupies the memory space.

If the array is a character array, then its elements will occupy 1 byte of memory each. If it is a
float array then its elements will occupy 8 bytes of memory each. But this is not the total size
or memory allocated for the array. They are the sizes of individual elements in the array. If we
need to know the total size of the array, then we need to multiply the number of elements with
the size of individual element.

i.e.; Total memory allocated to an Array = Number of elements * size of one element
Total memory allocated to an Integer Array of N elements = Number of elements * size of
one element
= N * 4 bytes
= 10 * 4 bytes = 40 Bytes, where N = 10
= 500 * 4 bytes = 2000 Bytes, where N = 500
Total memory allocated to an character Array of N elements= Number of elements * size of
one element
= N * 1 Byte
= 10 * 1 Byte = 10 Bytes, where N = 10
Awadhesh Kumar Singh
9414774988
ARRAYS [email protected]

= 500 * 1 Byte = 500 Bytes, where N=500


This is how memory is allocated for the single dimensional array.

C program to declare and initialize the array in C.


1. #include<stdio.h>
2. int main(){
3. int i=0;
4. int marks[5]={20,30,40,50,60};//declaration and initialization of array
5. //traversal of array
6. for(i=0;i<5;i++){
7. printf("%d \n",marks[i]);
8. }
9. return 0;
10. }

C Strings
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.

There are two ways to declare a string in c language.

1. By char array
2. By string literal

Let's see the example of declaring string by char array in C language.

char ch[10]={'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', '\0'};

As we know, array index starts from 0, so it will be represented as in the figure given
below.
Awadhesh Kumar Singh
9414774988
ARRAYS [email protected]

While declaring string, size is not mandatory. So, we can write the above code as given
below:

1. char ch[]={'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', '\0'};

We can also define the string by the string literal in C language. For example:

1. char ch[]="abcdefghij";

In such case, '\0' will be appended at the end of the string by the compiler.

Difference between char array and string literal


There are two main differences between char array and literal.

o We need to add the null character '\0' at the end of the array by ourself whereas, it is
appended internally by the compiler in the case of the character array.
o The string literal cannot be reassigned to another set of characters whereas, we can
reassign the characters of the array.

String Example in C
Let's see a simple example where a string is declared and being printed. The '%s' is
used as a format specifier for the string in c language.

1. #include<stdio.h>
2. #include <string.h>
3. int main(){
4. char ch[11]= {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', '\0'};
5. char ch2[11]="abcdefghij";
6.
7. printf("Char Array Value is: %s\n", ch);
8. printf("String Literal Value is: %s\n", ch2);
9. return 0;
10. }

Traversing String
Traversing the string is one of the most important aspects in any of the programming
languages. We may need to manipulate a very large text which can be done by
Awadhesh Kumar Singh
9414774988
ARRAYS [email protected]

traversing the text. Traversing string is somewhat different from the traversing an
integer array. We need to know the length of the array to traverse an integer array,
whereas we may use the null character in the case of string to identify the end the
string and terminate the loop.

Hence, there are two ways to traverse a string.

o By using the length of string


o By using the null character.

Using the length of string


Let's see an example of counting the number of vowels in a string.

1. #include<stdio.h>
2. void main ()
3. {
4. char s[11] = "abcdefghij";
5. int i = 0;
6. int count = 0;
7. while(i<11)
8. {
9. if(s[i]=='a' || s[i] == 'e' || s[i] == 'i' || s[i] == 'u' || s[i] == 'o')
10. {
11. count ++;
12. }
13. i++;
14. }
15. printf("The number of vowels %d",count);
16. }

Accepting string as the input


Till now, we have used scanf to accept the input from the user. However, it can also be
used in the case of strings but with a different scenario. Consider the below code which
stores the string while space is encountered.
1. #include<stdio.h>
2. void main ()
3. {
Awadhesh Kumar Singh
9414774988
ARRAYS [email protected]

4. char s[20];
5. printf("Enter the string?");
6. scanf("%s",s);
7. printf("You entered %s",s);
8. }

It is clear from the output that, the above code will not work for space separated
strings. To make this code working for the space separated strings, the minor changed
required in the scanf function, i.e., instead of writing scanf("%s",s), we must write:
scanf("%[^\n]s",s) which instructs the compiler to store the string s while the new line
(\n) is encountered.

Here we must also notice that we do not need to use address of (&) operator in scanf
to store a string since string s is an array of characters and the name of the array, i.e.,
s indicates the base address of the string (character array) therefore we need not use
& with it.

Some important points


However, there are the following points which must be noticed while entering the
strings by using scanf.

o The compiler doesn't perform bounds checking on the character array. Hence, there
can be a case where the length of the string can exceed the dimension of the character
array which may always overwrite some important data.
o Instead of using scanf, we may use gets() which is an inbuilt function defined in a
header file string.h. The gets() is capable of receiving only one string at a time.

Two(multi) Dimensional Array in C


The two-dimensional array can be defined as an array of arrays. The 2D array is
organized as matrices which can be represented as the collection of rows and columns.
However, 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.
Awadhesh Kumar Singh
9414774988
ARRAYS [email protected]

Declaration of two-dimensional Array in C


The syntax to declare the 2D array is given below.

data_type array_name[rows][columns];

Consider the following example.

int twodimen[4][3];

Here, 4 is the number of rows, and 3 is the number of columns.

Initialization of 2D Array in C
In the 1D array, we don't need to specify the size of the array if the declaration and
initialization are being done simultaneously. However, this will not work with 2D arrays.
We will have to define at least the second dimension of the array. The two-dimensional
array can be declared and defined in the following way.

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

Two-dimensional array example in C

1. #include<stdio.h>
2. int main(){
3. int i=0,j=0;
4. int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
5. //traversing 2D array
6. for(i=0;i<4;i++){
7. for(j=0;j<3;j++){
8. printf("arr[%d] [%d] = %d \n",i,j,arr[i][j]);
9. }//end of j
10. }//end of i
11. return 0;
12. }

C 2D array example: Storing elements in a matrix and printing it.

1. #include <stdio.h>
2. void main ()
Awadhesh Kumar Singh
9414774988
ARRAYS [email protected]

3. {
4. int arr[3][3],i,j;
5. for (i=0;i<3;i++)
6. {
7. for (j=0;j<3;j++)
8. {
9. printf("Enter a[%d][%d]: ",i,j);
10. scanf("%d",&arr[i][j]);
11. }
12. }
13. printf("\n printing the elements ....\n");
14. for(i=0;i<3;i++)
15. {
16. printf("\n");
17. for (j=0;j<3;j++)
18. {
19. printf("%d\t",arr[i][j]);
20. }
21. }
22. }

You might also like