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.
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 We can declare an array in the c language in the following way.
Now, let us see the example to declare the array.
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.
|
|
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. Declaration of two dimensional Array in C The syntax to declare the 2D array is given below.
Consider the following example.
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.
Two-dimensional array example in C
Output 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 C 2D array example: Storing elements in a matrix and printing it.
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 |
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.
Output
|
Strings are actually one-dimensional array of characters terminated by a null character '\0'. Thus a null-terminated string contains the characters that comprise the string followed by a null. The following declaration and initialization create a string consisting of the word "Hello". To hold the null character at the end of the array, the size of the character array containing the string is one more than the number of characters in the word "Hello." char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'}; If you follow the rule of array initialization then you can write the above statement as follows − char greeting[] = "Hello"; Following is the memory presentation of the above defined string in C/C++ − Actually, you do not place the null character at the end of a string constant. The C compiler automatically places the '\0' at the end of the string when it initializes the array. Let us try to print the above mentioned string − #include <stdio.h>
int main () {
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'}; printf("Greeting message: %s\n", greeting ); return 0; } When the above code is compiled and executed, it produces the following result − Greeting message: Hello C supports a wide range of functions that manipulate null-terminated strings −
The following example uses some of the above-mentioned functions − #include <stdio.h> #include <string.h>
int main () {
char str1[12] = "Hello"; char str2[12] = "World"; char str3[12]; int len ;
/* copy str1 into str3 */ strcpy(str3, str1); printf("strcpy( str3, str1) : %s\n", str3 );
/* concatenates str1 and str2 */ strcat( str1, str2); printf("strcat( str1, str2): %s\n", str1 );
/* total lenghth of str1 after concatenation */ len = strlen(str1); printf("strlen(str1) : %d\n", len );
return 0; } When the above code is compiled and executed, it produces the following result − strcpy( str3, str1) : Hello strcat( str1, str2): HelloWorld strlen(str1) : 10 |
In C, there are cases where we need to store multiple attributes of an entity. It is not necessary that an entity has all the information of one type only. It can have different attributes of different data types. For example, an entity Student may have its name (string), roll number (int), marks (float). To store such type of information regarding an entity student, we have the following approaches:
Let's look at the first approach in detail.
Output Enter the name, roll number, and marks of the student 1Arun 90 91 Enter the name, roll number, and marks of the student 2Varun 91 56 Enter the name, roll number, and marks of the student 3Sham 89 69
Printing the Student details... Arun 90 91.000000 Varun 91 56.000000 Sham 89 69.000000 The above program may fulfill our requirement of storing the information of an entity student. However, the program is very complex, and the complexity increase with the amount of the input. The elements of each of the array are stored contiguously, but all the arrays may not be stored contiguously in the memory. C provides you with an additional and simpler approach where you can use a special data structure, i.e., structure, in which, you can group all the information of different data type regarding an entity. |
Structure in c is a user-defined data type that enables us to store the collection of different data types. Each element of a structure is called a member. Structures ca; simulate the use of classes and templates as it can store various information The ,struct keyword is used to define the structure. Let's see the syntax to define the structure in c.
Let's see the example to define a structure for an entity employee in c.
The following image shows the memory allocation of the structure employee that is defined in the above example. Here, struct is the keyword; employee is the name of the structure; id, name, and salary are the members or fields of the structure. Let's understand it by the diagram given below: Declaring structure variable We can declare a variable for the structure so that we can access the member of the structure easily. There are two ways to declare structure variable:
1st way: Let's see the example to declare the structure variable by struct keyword. It should be declared within the main function.
Now write given code inside the main() function.
The variables e1 and e2 can be used to access the values stored in the structure. Here, e1 and e2 can be treated in the same way as the objects in C++ and Java. 2nd way: Let's see another way to declare variable at the time of defining the structure.
|
In Bubble sort, Each element of the array is compared with its adjacent element. The algorithm processes the list in passes. A list with n elements requires n-1 passes for sorting. Consider an array A of n elements whose elements are to be sorted by using Bubble sort. The algorithm processes like following.
Algorithm:
Complexity
C Program
Output: Printing Sorted Element List . . . 7 9 10 12 23 34 34 44 78 101 |
This is an in-place comparison-based sorting algorithm. Here, a sub-list is maintained which is always sorted. For example, the lower part of an array is maintained to be sorted. An element which is to be 'insert'ed in this sorted sub-list, has to find its appropriate place and then it is to be inserted there. Hence the name insertion sort. Implementation in C #include <stdio.h> #include <stdbool.h>
#define MAX 7
int intArray[MAX] = {4,6,3,2,1,9,7};
void printline(int count) { int i;
for(i = 0;i < count-1;i++) { printf("="); }
printf("=\n"); }
void display() { int i; printf("[");
// navigate through all items for(i = 0;i < MAX;i++) { printf("%d ",intArray[i]); }
printf("]\n"); }
void insertionSort() {
int valueToInsert; int holePosition; int i;
// loop through all numbers for(i = 1; i < MAX; i++) {
// select a value to be inserted. valueToInsert = intArray[i];
// select the hole position where number is to be inserted holePosition = i;
// check if previous no. is larger than value to be inserted while (holePosition > 0 && intArray[holePosition-1] > valueToInsert) { intArray[holePosition] = intArray[holePosition-1]; holePosition--; printf(" item moved : %d\n" , intArray[holePosition]); }
if(holePosition != i) { printf(" item inserted : %d, at position : %d\n" , valueToInsert,holePosition); // insert the number at hole position intArray[holePosition] = valueToInsert; }
printf("Iteration %d#:",i); display();
} }
void main() { printf("Input Array: "); display(); printline(50); insertionSort(); printf("Output Array: "); display(); printline(50); } If we compile and run the above program, it will produce the following result − Output Input Array: [4 6 3 2 1 9 7 ] ================================================== Iteration 1#:[4 6 3 2 1 9 7 ] item moved : 6 item moved : 4 item inserted : 3, at position : 0 Iteration 2#:[3 4 6 2 1 9 7 ] item moved : 6 item moved : 4 item moved : 3 item inserted : 2, at position : 0 Iteration 3#:[2 3 4 6 1 9 7 ] item moved : 6 item moved : 4 item moved : 3 item moved : 2 item inserted : 1, at position : 0 Iteration 4#:[1 2 3 4 6 9 7 ] Iteration 5#:[1 2 3 4 6 9 7 ] item moved : 9 item inserted : 7, at position : 5 Iteration 6#:[1 2 3 4 6 7 9 ] Output Array: [1 2 3 4 6 7 9 ] Explain Selection Sort in detail with examples In selection sort, the smallest value among the unsorted elements of the array is selected in every pass and inserted to its appropriate position into the array. First, find the smallest element of the array and place it on the first position. Then, find the second smallest element of the array and place it on the second position. The process continues until we get the sorted array. The array with n elements is sorted by using n-1 pass of selection sort algorithm.
Therefore, by following the above explained process, the elements A[0], A[1], A[2],...., A[n-1] are sorted. Example Consider the following array with 6 elements. Sort the elements of the array by using selection sort. A = {10, 2, 3, 90, 43, 56}.
Sorted A = {2, 3, 10, 43, 56, 90} Complexity
Algorithm SELECTION SORT(ARR, N)
SMALLEST (ARR, K, N, POS)
C Program
Output: printing sorted elements... 7 9 10 12 23 23 34 44 78 101 |