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

lecture4 (1)

Arrays are a data structure in C that store a fixed-size collection of elements of the same type, allowing for efficient data management and access. They can store primitive and derived data types, and their elements are stored in contiguous memory locations, enabling random access. The document covers array declaration, initialization, advantages, disadvantages, and examples of sorting and passing arrays to functions.
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)
2 views9 pages

lecture4 (1)

Arrays are a data structure in C that store a fixed-size collection of elements of the same type, allowing for efficient data management and access. They can store primitive and derived data types, and their elements are stored in contiguous memory locations, enabling random access. The document covers array declaration, initialization, advantages, disadvantages, and examples of sorting and passing arrays to functions.
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/ 9

ARRAYS

Arrays a kind of data structure that can store a fixed-size sequential collection of
elements of the same type. An array is used to store a collection of data, but it is
often more useful to think of an array as a collection of variables of the same type.
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 subjects. 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.
All arrays consist of contiguous memory locations. The lowest address corresponds to
the first element and the highest address to the last element.
Declaring Arrays

To declare an array in C, a programmer specifies the type of the elements and the
number of elements required by an array as follows −
We can declare an array in the c language in the following way.
1. data_type array_name[array_size];
Now, let us see the example to declare the array.
1. int marks[5];
Here, int is the data_type, marks are the array_name, and 5 is the array_size.
This is called a single-dimensional array. The arraySize must be an integer constant
greater than zero and type can be any valid C data type. For example, to declare a
10-element array called balance of type double, use this statement −
double balance[10];
Here balance is a variable array which is sufficient to hold up to 10 double numbers.

Initializing Arrays

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.

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

You can initialize an array in C either one by one or using a single statement as
follows
double balance[5] = {1000.0, 2.0, 3.4, 7.0, 50.0};
The number of values between braces { } cannot be larger than the number of
elements that we declare for the array between square brackets [ ].
If you omit the size of the array, an array just big enough to hold the initialization is
created. Therefore, if you write −
double balance[] = {1000.0, 2.0, 3.4, 7.0, 50.0};
You will create exactly the same array as you did in the previous example. Following
is an example to assign a single element of the array −
balance[4] = 50.0;
The above statement assigns the 5 th element in the array with a value of 50.0. All
arrays have 0 as the index of their first element which is also called the base index
and the last index of an array will be total size of the array minus 1. Shown below is
the pictorial representation of the array we discussed above −
Accessing Array Elements

An element is accessed by indexing the array name. This is done by placing the index
of the element within square brackets after the name of the array. For example −
salary = balance[9];
The above statement will take the 10 th element from the array and assign the value
to salary variable. The following example Shows how to use all the three above
mentioned concepts viz. declaration, assignment, and accessing arrays −
#include <stdio.h>

int main () {

int n[10]; /* n is an array of 10 integers */


int i,j;

/* initialize elements of array n to 0 */


for ( i = 0; i < 10; i++ ) {
n[ i ] = i + 100; /* set element at location i to i + 100 */
}

/* output each array element's value */


for (j = 0; j < 10; j++ ) {
printf("Element[%d] = %d\n", j, n[j] );
}

return 0;
}
When the above code is compiled and executed, it produces the following result −
Element[0] = 100
Element[1] = 101
Element[2] = 102
Element[3] = 103
Element[4] = 104
Element[5] = 105
Element[6] = 106
Element[7] = 107
Element[8] = 108
Element[9] = 109
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

C Array: Declaration with Initialization


We can initialize the c array at the time of declaration. Let's see the code.
1. 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.
1. int marks[]={20,30,40,50,60};
Let's see the 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. }
Output
20
30
40
50
60
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. }
Program to print the largest and second largest element of the array.
1. #include<stdio.h>
2. void main ()
3. {
4. int arr[100],i,n,largest,sec_largest;
5. printf("Enter the size of the array?");
6. scanf("%d",&n);
7. printf("Enter the elements of the array?");
8. for(i = 0; i<n; i++)
9. {
10. scanf("%d",&arr[i]);
11. }
12. largest = arr[0];
13. sec_largest = arr[1];
14. for(i=0;i<n;i++)
15. {
16. if(arr[i]>largest)
17. {
18. sec_largest = largest;
19. largest = arr[i];
20. }
21. else if (arr[i]>sec_largest && arr[i]!=largest)
22. {
23. sec_largest=arr[i];
24. }
25. }
26. printf("largest = %d, second largest = %d",largest,sec_largest);
27. }
Return an Array in C
What is an 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.
Let's first see how to pass a single-dimensional array to a function.
Passing array to a function
1. #include <stdio.h>
2. int getarray(int arr[]) ;
3. int main()
4. {
5. int arr[5]={45,67,34,78,90};
6. getarray(arr);
7. return 0;
8. }
9.
10. getarray(int arr[])
11. {
12. printf("Elements of array are : ");
13. for(int i=0;i<5;i++)
14. {
15. printf("%d ", arr[i]);
16. }
17. }
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[].
Output

Passing array to a function as a pointer


Now, we will see 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.
Output
Note: From the above examples, we observe that array is passed to a function as a
reference which means that array also persist outside the function.
How to return an array from a function
Returning pointer pointing to the array
1. #include <stdio.h>
2. int *getarray();
3. {
4. int arr[5];
5. printf("Enter the elements in an array : ");
6. for(int i=0;i<5;i++)
7. {
8. scanf("%d", &arr[i]);
9. }
10. return arr;
11. }
12. int main()
13. {
14. int *n;
15. n=getarray();
16. printf("\nElements of array are :");
17. for(int i=0;i<5;i++)
18. {
19. printf("%d", n[i]);
20. }
21. return 0;
22. }
In the above program, getarray() function returns a variable 'arr'. It returns a local
variable, but it is an illegal memory location to be returned, which is allocated within a
function in the stack. Since the program control comes back to the main() function,
and all the variables in a stack are freed. Therefore, we can say that this program is
returning memory location, which is already de-allocated, so the output of the
program is a segmentation fault.
Output

There are three right ways of returning an array to a function:


o Using dynamically allocated array
o Using static array
o Using structure

Returning array by passing an array which is to be returned as a parameter


to the function.
1. #include <stdio.h>
2. int *getarray(int *a)
3. {
4.
5. printf("Enter the elements in an array : ");
6. for(int i=0;i<5;i++)
7. {
8. scanf("%d", &a[i]);
9. }
10. return a;
11. }
12. int main()
13. {
14. int *n;
15. int a[5];
16. n=getarray(a);
17. printf("\nElements of array are :");
18. for(int i=0;i<5;i++)
19. {
20. printf("%d", n[i]);
21. }
22. return 0;
23. }
Output

Returning array using malloc() function.


1. #include <stdio.h>
2. #include<malloc.h>
3. int *getarray()
4. {
5. int size;
6. printf("Enter the size of the array : ");
7. scanf("%d",&size);
8. int *p= malloc(sizeof(size));
9. printf("\nEnter the elements in an array");
10. for(int i=0;i<size;i++)
11. {
12. scanf("%d",&p[i]);
13. }
14. return p;
15. }
16. int main()
17. {
18. int *ptr;
19. ptr=getarray();
20. int length=sizeof(*ptr);
21. printf("Elements that you have entered are : ");
22. for(int i=0;ptr[i]!='\0';i++)
23. {
24. printf("%d ", ptr[i]);
25. }
26. return 0;
27. }
Output

Using Static Variable


1. #include <stdio.h>
2. int *getarray()
3. {
4. static int arr[7];
5. printf("Enter the elements in an array : ");
6. for(int i=0;i<7;i++)
7. {
8. scanf("%d",&arr[i]);
9. }
10. return arr;
11.
12. }
13. int main()
14. {
15. int *ptr;
16. ptr=getarray();
17. printf("\nElements that you have entered are :");
18. for(int i=0;i<7;i++)
19. {
20. printf("%d ", ptr[i]);
21. }
22. }
In the above code, we have created the variable arr[] as static
in getarray() function, which is available throughout the program. Therefore, the
function getarray() returns the actual memory location of the variable 'arr'.
Output

Using Structure
The structure is a user-defined data type that can contain a collection of items of
different types. Now, we will create a program that returns an array by using
structure.
1. #include <stdio.h>
2. #include<malloc.h>
3. struct array
4. {
5. int arr[8];
6. };
7. struct array getarray()
8. {
9. struct array y;
10. printf("Enter the elements in an array : ");
11. for(int i=0;i<8;i++)
12. {
13. scanf("%d",&y.arr[i]);
14. }
15. return y;
16. }
17. int main()
18. {
19. struct array x=getarray();
20. printf("Elements that you have entered are :");
21. for(int i=0;x.arr[i]!='\0';i++)
22. {
23. printf("%d ", x.arr[i]);
24. }
25. return 0;
26. }
Output

You might also like