0% found this document useful (0 votes)
15 views15 pages

Array Unit 1

Uploaded by

Manish Dhanuk
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
15 views15 pages

Array Unit 1

Uploaded by

Manish Dhanuk
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 15

ARRAY

An array is a type of data structure that stores a fixed-size of a homogeneous


collection of data. In short, we can say that array is a collection of variables
of the same type.

For example, if we want to declare 'n' number of variables, n1, n2...n., if we


create all these variables individually, then it becomes a very tedious task. In
such a case, we create an array of variables having the same type. Each
element of an array can be accessed using an index of the element.

Properties of Array

o Each element of an array is of same data type and carries the


same size, i.e., char = 1 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 .

Advantage of C Array
o 1) Code Optimization: Less code to the access the data.
o 2) Ease of traversing: By using the for loop, we can retrieve
the elements of an array easily.
o 3) Ease of sorting: To sort the elements of the array, we
need a few lines of code only.
o 4) Random Access: We can access any element randomly
using the array.

Disadvantage of C Array
o 1) Fixed Size: Whatever size, we define at the time of
declaration of the array, we can't exceed the limit.

Array Type: 1. Single Dimension Array (1-D Array)

2. Multi Dimension Array (2-D Array, 3-D Array………)


Declaration of C Array
We can declare an array in the c language in the following way.

data_type array_name[array_size];
EX. 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.

1. At the Time of Declaration

int marks[5]={80,60,70,85,75};

or

int marks[]={80,60,70,85,75};

After Declaration

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

1. #include<stdio.h>
2. int main(){
3. int i=0;
4. int marks[5];//declaration of array
5. marks[0]=80;//initialization of array
6. marks[1]=60;
7. marks[2]=70;
8. marks[3]=85;
9. marks[4]=75;
10. //traversal of array
11. for(i=0;i<5;i++){
12. printf("%d \n",marks[i]);
13. }//end of for loop
14. return 0;
15. }

Output

80
60
70
85
75

OR
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 Array Example: Sorting an array
In the following program, we are using bubble sort method to sort
the array in ascending order.

1. #include<stdio.h>
2. void main ()
3. {
4. int i, j,temp;
5. int a[10] = { 10, 9, 7, 101, 23, 44, 12, 78, 34, 23};
6. for(i = 0; i<10; i++)
7. {
8. for(j = i+1; j<10; j++)
9. {
10. if(a[j] > a[i])
11. {
12. temp = a[i];
13. a[i] = a[j];
14. a[j] = temp;
15. }
16. }
17. }
18. printf("Printing Sorted Element List ...\n");
19. for(i = 0; i<10; i++)
20. {
21. printf("%d\n",a[i]);
22. }
23. }
Two 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.

Declaration of two dimensional Array in C


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

1. data_type array_name[rows][columns];
Ex- 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. At the time of declaration


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

Arr[2][0]=3
Arr[2][1]=4
Arr[2][2]=5

Arr[3][0]=4
Arr[3][1]=5
Arr[3][2]=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. }

Output

13. arr[0][0] = 1
14. arr[0][1] = 2
15. arr[0][2] = 3
16. arr[1][0] = 2
17. arr[1][1] = 3
18. arr[1][2] = 4
19. arr[2][0] = 3
20. arr[2][1] = 4
21. arr[2][2] = 5
22. arr[3][0] = 4
23. arr[3][1] = 5
24. arr[3][2] = 6
C 2D array example: Storing elements in a matrix and
printing it.

1. #include <stdio.h>
2. void main ()
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. }

Output
Enter a[0][0]: 56
Enter a[0][1]: 10
Enter a[0][2]: 30
Enter a[1][0]: 34
Enter a[1][1]: 21
Enter a[1][2]: 34

Enter a[2][0]: 45
Enter a[2][1]: 56
Enter a[2][2]: 78

printing the elements ....

56 10 30
34 21 34
45 56 78

How to pass a single-dimensional array


to a function.
Passing array to a function:-
1. #include <stdio.h>
2. void getarray(int arr[])
3. {
4. printf("Elements of array are : ");
5. for(int i=0;i<5;i++)
6. {
7. printf("%d ", arr[i]);
8. }
9. }
10. int main()
11. {
12. int arr[5]={45,67,34,78,90};
13. getarray(arr);
14. return 0;
15. }
In the above program, we have first created the array arr[] and
then we pass this array to the function getarray().
The getarray() function prints all the elements of the array arr[].
Passing array to a function as a pointer

How to pass an array to a function as a pointer.

1. #include <stdio.h>
2. void printarray(char *arr)
3. {
4. printf("Elements of array are : ");
5. for(int i=0;i<5;i++)
6. {
7. printf("%c ", arr[i]);
8. }
9. }
10. int main()
11. {
12. char arr[5]={'A','B','C','D','E'};
13. printarray(arr);
14. return 0;
15. }

In the above code, we have passed the array to the function as a


pointer. The function printarray() prints the elements of an array.

C Strings
The string can be defined as the one-dimensional array of
characters terminated by a null ('\0'). Each character in the array
occupies one byte of memory.
The termination character ('\0') is important in a string since it is the
only way to identify where the string ends.

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


1. By char array
2. By string literal

Declaring string by char array in C language.

char ch[10]={'j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't', '\0'};

Declare string by the string literal in C language. For example:

1. char ch[]="javatpoint";

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

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

Output

Char Array Value is: javatpoint


String Literal Value is: javatpoint

 A Character array is a derived data type in C that is used to store a collection of characters or
strings.
 A char data type takes 1 byte of memory, so a character array has the memory of the number of
elements in the array. (1* number_of_elements_in_array).
 Each character in a character array has an index that shows the position of the character in the
string.
 The first character will be indexed 0 and the successive characters are indexed 1,2,3 etc...
 The null character \0 is used to find the end of characters in the array and is always stored in the
index after the last character or in the last index.

Initialization of Character Array in C

There are different ways to initialize a character array in c. Let us understand them with
examples.

Using {} Curly Braces

 We can use {} brackets to initialize a character array by specifying the characters in the
array.
 The advantage of using this method is we don't have to specify the length of the array as
the compiler can find it for us.

Let us see a example where we initialize an array using {} and print it.

#include <stdio.h>
#include<string.h>
int main(){
//initialization
char char_array[] = {'c', 'h', 'a', 'r', '$','*'};
int a=puts(char_array); //print array
if(a>0){
printf("printed successfully\n");
}
printf("length of character array = %d",strlen(char_array));
//prints length of the character array.
return 0;
}

Output

char$*
printed successfully
length of character array = 6

The puts() function is used to print a character array or string to the output. It has the
following syntax

int puts(const char* array);


The const char* is a character pointer that points to the character array. The puts
function returns a positive integer on success and the EOF(End of file) error on failure.

The strlen() function is present in the string.h header and is used to find the length of a
string. It has the following syntax,

int strlen(const char *str);

This function returns the length of the string.

Using String Assignment

 A easy way to initialize a character array is using string assignment.


 We don't need to specify the length of the array in this method too.

Consider the following example,

#include <string.h>
#include <stdio.h>

int main(){
char char_array[] = "string of characters";
puts(char_array);
printf("length of character array = %d",strlen(char_array));
return 0;
}

Output

string of characters
length of character array = 20

Using {{ }} Double Curly Braces(2D Char Array)

 This method is used to store two or more strings together in a single


array.
 As a character array can only store characters, to store different strings
we use a 2-dimensional array with syntax arr[i][j].
 The i denotes the string and j denote the position of the character in the
string at position i.
 The i can be left empty as it is automatically computed by the compiler
but the value of j must be provided.
#include <stdlib.h>
#include <stdio.h>

int main(){
char arr[][5] = { {"code"}, {"break"}};
for (int i = 0; i < 2; ++i) {
for (int j = 0; j < 5; j++) {
printf("%c ", arr[i][j]);
}
printf("\n");
}
printf("\n");

return 0;
}

Output

c o d e
b r e a k

What is the Use of Char Array in C?

 A string is stored and represented using a character array.


 Every string operation such as copying two strings or concatenating two strings is done only
using the character array.
 We can individually access every character in an array using the character array.
 Writing and reading from files also use character arrays.

Importance of Char Array

 Character array is used to store and manipulate characters.

Row-Major order or Column-Major order


For example, consider the two-dimensional array declarations as shown in the
image below.

Row-Major Order
If the compiler is implemented using row-major order, then the values will get
stored in the memory, as shown in the image below.
Row Major Order in C

In the above image, the values 1, 2, 3, 4, 5, and 6 are stored at starting


memory locations 50, 54, 58, 62, 66, and 70 (Assume int takes 4 bytes of
space).

For example, if we want to access value two from memory, we must declare
a[0][1].
Column Major Order
If the compiler is implemented by column-major order, the array elements will
be stored in the memory, as shown in the image below.

You might also like