Unit - 3
Unit - 3
Arrays
Q1) What is one dimensional array?
A1)
A one-dimensional array is a group of elements having the same datatype and same name. Individual elements are referred to using common name and unique index of the elements.
The simplest form of an array is one-dimensional-array. The array itself is given name and its elements are referred to by their subscripts. In , an array is denoted as follows:
Array_name[array_size]
Where size specifies the number of elements in the array and the subscript (also called index) value ranges from 0 through size-1.
Declare One Dimensional Array
Here is the general form to declare one dimensional array in
Data_type array_name[array_size];
Here, data_type is any valid data type, array_name is the name of the array, and array_size is the size of array. Here is an example, declaring an array named arr of int type, having maximum element size of 10 elements
Int arr[10];
Initialize One Dimensional Array
Here is the general form to initialize values to one dimensional array
Data_type array_name[array_size] = {comma_separated_element_list};
Here is an example, declaring and initializing values to the array name arr of type int, containing 10 elements
Int arr[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
Q2) Give some of the examples of one dimensional array
A2)
Here are some example program, demonstrating one dimensional array
/*One Dimensional Array */
#include<iostream.h>
#include<conio.h>
Void main()
{
Clrscr();
Int arr[5] = {1, 2, 3, 4, 5};
Int i;
For(i=0; i<5; i++)
{
Cout<<"arr["<<i<<"] = "<<arr[i]<<"\n";
}
Getch();
}
Here
Is the sample output of this program:
Here is another example, also demonstrating one dimension array in
/* One Dimensional Array */
#include<iostream.h>
#include<conio.h>
Void main()
{
Clrscr();
Int arr[10];
Int i;
Int sum=0, avg=0;
Cout<<"Enter 10 array elements: ";
For(i=0; i<10; i++)
{
Cin>>arr[i];
Sum = sum + arr[i];
}
Cout<<"\nThe array elements are: \n";
For(i=0; i<10; i++)
{
Cout<<arr[i]<<" ";
}
Cout<<"\n\nSum of all elements is: "<<sum;
Avg = sum/10;
Cout<<"\nAnd average is: "<<avg;
Getch();
}
Here is the sample run of the above program:
Q3) What is multi-dimensional array?
A3)
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. 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.
- 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.
- Int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
Q4) Give some of the example of two dimensional array
A4)
Two-dimensional array example in C
- #include<stdio.h>
- Int main(){
- Int i=0,j=0;
- Int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
- //traversing 2D array
- For(i=0;i<4;i++){
- For(j=0;j<3;j++){
- Printf("arr[%d] [%d] = %d \n",i,j,arr[i][j]);
- }//end of j
- }//end of i
- Return 0;
- }
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.
- #include <stdio.h>
- Void main ()
- {
- Int arr[3][3],i,j;
- For (i=0;i<3;i++)
- {
- For (j=0;j<3;j++)
- {
- Printf("Enter a[%d][%d]: ",i,j);
- Scanf("%d",&arr[i][j]);
- }
- }
- Printf("\n printing the elements ....\n");
- For(i=0;i<3;i++)
- {
- Printf("\n");
- For (j=0;j<3;j++)
- {
- Printf("%d\t",arr[i][j]);
- }
- }
- }
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
Q5) Explain in detail string manipulation
A5)
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 −
Sr.No. | Function & Purpose |
1 | Strcpy(s1, s2); Copies string s2 into string s1. |
2 | Strcat(s1, s2); Concatenates string s2 onto the end of string s1. |
3 | Strlen(s1); Returns the length of string s1. |
4 | Strcmp(s1, s2); Returns 0 if s1 and s2 are the same; less than 0 if s1<s2; greater than 0 if s1>s2. |
5 | Strchr(s1, ch); Returns a pointer to the first occurrence of character ch in string s1. |
6 | Strstr(s1, s2); Returns a pointer to the first occurrence of string s2 in string s1. |
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
Q6) What is an Array explain its properties advantages and disadvantages?
A6)
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.
- Each element of an array is of same data type and carries the same size, i.e., int = 4 bytes.
- Elements of the array are stored at contiguous memory locations where the first element is stored at the smallest memory location.
- 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 Linked List.
Q7) Explain declaration and initialization of array in C with example
A7)
Declaration of C Array
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 example
- #include<stdio.h>
- Int main(){
- Int i=0;
- Int marks[5];//declaration of array
- Marks[0]=80;//initialization of array
- Marks[1]=60;
- Marks[2]=70;
- Marks[3]=85;
- Marks[4]=75;
- //traversal of array
- For(i=0;i<5;i++){
- Printf("%d \n",marks[i]);
- }//end of for loop
- Return 0;
- }
Output
80
60
70
85
75
Write a Program to print the largest and second largest element of the array
- #include<stdio.h>
- Void main ()
- {
- Int arr[100],i,n,largest,sec_largest;
- Printf("Enter the size of the array?");
- Scanf("%d",&n);
- Printf("Enter the elements of the array?");
- For(i = 0; i<n; i++)
- {
- Scanf("%d",&arr[i]);
- }
- Largest = arr[0];
- Sec_largest = arr[1];
- For(i=0;i<n;i++)
- {
- If(arr[i]>largest)
- {
- Sec_largest = largest;
- Largest = arr[i];
- }
- Else if (arr[i]>sec_largest && arr[i]!=largest)
- {
- Sec_largest=arr[i];
- }
- }
- Printf("largest = %d, second largest = %d",largest,sec_largest);
- }
Q8) Write a program for Passing array to a function and Passing array to a function as a pointer
A8)
Passing array to a function
- #include <stdio.h>
- Void getarray(int arr[])
- {
- Printf("Elements of array are : ");
- For(int i=0;i<5;i++)
- {
- Printf("%d ", arr[i]);
- }
- }
- Int main()
- {
- Int arr[5]={45,67,34,78,90};
- Getarray(arr);
- Return 0;
- }
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.
- #include <stdio.h>
- Void printarray(char *arr)
- {
- Printf("Elements of array are : ");
- For(int i=0;i<5;i++)
- {
- Printf("%c ", arr[i]);
- }
- }
- Int main()
- {
- Char arr[5]={'A','B','C','D','E'};
- Printarray(arr);
- Return 0;
- }
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
Q9) How to return an array from a function?
A9)
Returning pointer pointing to the array
- #include <stdio.h>
- Int *getarray()
- {
- Int arr[5];
- Printf("Enter the elements in an array : ");
- For(int i=0;i<5;i++)
- {
- Scanf("%d", &arr[i]);
- }
- Return arr;
- }
- Int main()
- {
- Int *n;
- n=getarray();
- Printf("\nElements of array are :");
- For(int i=0;i<5;i++)
- {
- Printf("%d", n[i]);
- }
- Return 0;
- }
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