Array 1
Array 1
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
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.
Advantages of C Array
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.
Disadvantages 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
data_type array_name[array_size];
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;
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]);
return 0;
Output
80
60
70
85
75
There are various ways in which we can declare an array. It can be done by specifying its type and
size, by initializing it or both.
Example:
#include <stdio.h>
int main()
{
int arr[5];
arr[0] = 5;
arr[1] = -10;
arr[2] = 2;
arr[3] = arr[0];
return 0;
}
Output:
5 -10 2 5
Example:
#include <stdio.h>
int main()
{
// an array of 10 integers. If arr[0] is stored at
// address x, then arr[1] is stored at x + sizeof(int)
// arr[2] is stored at x + sizeof(int) + sizeof(int)
// and so on.
int arr[5], i;
return 0;
}
Output:
Size of integer in this compiler is 4
Address arr[0] is 0x7ffd636b4260
Address arr[1] is 0x7ffd636b4264
Address arr[2] is 0x7ffd636b4268
Address arr[3] is 0x7ffd636b426c
Address arr[4] is 0x7ffd636b4270
#include<stdio.h>
int main(){
int i=0;
int marks[5]={20,30,40,50,60};//declaration and initialization of array
//traversal of array
for(i=0;i<5;i++){
printf("%d \n",marks[i]);
}
return 0;
}
Output
20
30
40
50
60
#include<stdio.h>
void main ()
{
int i, j,temp;
int a[10] = { 10, 9, 7, 101, 23, 44, 12, 78, 34, 23};
for(i = 0; i<10; i++)
{
for(j = i+1; j<10; j++)
{
if(a[j] > a[i])
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
printf("Printing Sorted Element List ...\n");
for(i = 0; i<10; i++)
{
printf("%d\n",a[i]);
}
}
C 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);
Program to take 5 values from the user and store them in an array
// Print the elements stored in the array
#include <stdio.h>
int main() {
int values[5];
Output
Enter 5 integers: 1
-3
34
0
3
Displaying integers: 1
-3
34
0
3
#include <stdio.h>
int main()
{
int marks[10], i, n, sum = 0, average;
average = sum/n;
printf("Average = %d", average);
return 0;
}
Output
Enter n: 5
Enter number1: 45
Enter number2: 35
Enter number3: 38
Enter number4: 31
Enter number5: 49
Average = 39
There are seven numbers stored in an array. The following program prints all the numbers of that
array as well as prints the numbers in backward.
#include<stdio.h>
int main()
int M[10];
int j;
M[0] = 2;
M[1] = 4;
M[2] = 6;
M[3] = 8;
M[4] = 10;
M[5] = 12;
M[6] = 14;
/* print numbers in M */
printf("M[%d] = %d\n",j,M[j]);
printf("M[%d] = %d\n",j,M[j]);
Output:
Copying arrays:
int list2[6];
and we want to copy the contents of list1 to list2. For general variables (e.g. int x=3, y=5) we use
simple assignment statement (x=y or y=x). But for arrays the following statement is wrong.
list2 = list1;
We must copy between arrays element by element and the two arrays must have the same size. In
the following example, we use a for loop which makes this easy.
#include <stdio.h>
main()
int list2[6];
list2[ctr] = list1[ctr];
printf("%d ",list2[ctr]);
Copy
Output:
Elements of list2 :
2 4 6 8 10 12
C Multidimensional Arrays
In C programming, you can create an array of arrays. These arrays are known as multidimensional
arrays. For example,
float x[3][4];
Here, x is a two-dimensional (2d) array. The array can hold 12 elements. You can think the array
as a table with 3 rows and each row has 4 columns.
float y[2][4][3];
Initialization of a 2d array
Initialization of a 3d array
You can initialize a three-dimensional array in a similar way like a two-dimensional array. Here's
an example,
int test[2][3][4] = {
{{3, 4, 2, 3}, {0, -3, 9, 11}, {23, 12, 23, 2}},
{{13, 4, 56, 3}, {5, 9, 3, 5}, {3, 1, 4, 9}}};
Output
City 1, Day 1: 33
City 1, Day 2: 34
City 1, Day 3: 35
City 1, Day 4: 33
City 1, Day 5: 32
City 1, Day 6: 31
City 1, Day 7: 30
City 2, Day 1: 23
City 2, Day 2: 22
City 2, Day 3: 21
City 2, Day 4: 24
City 2, Day 5: 22
City 2, Day 6: 25
City 2, Day 7: 26
Displaying values:
City 1, Day 1 = 33
City 1, Day 2 = 34
City 1, Day 3 = 35
City 1, Day 4 = 33
City 1, Day 5 = 32
City 1, Day 6 = 31
City 1, Day 7 = 30
City 2, Day 1 = 23
City 2, Day 2 = 22
City 2, Day 3 = 21
City 2, Day 4 = 24
City 2, Day 5 = 22
City 2, Day 6 = 25
City 2, Day 7 = 26
Example 2: Sum of two matrices
#include <stdio.h>
int main()
{
float a[2][2], b[2][2], result[2][2];
if (j == 1)
printf("\n");
}
return 0;
}
Output
Sum Of Matrix:
2.2 0.5
-0.9 25.0
#include <stdio.h>
int main()
{
int test[2][3][2];
printf("\nDisplaying values:\n");
for (int i = 0; i < 2; ++i)
{
for (int j = 0; j < 3; ++j)
{
for (int k = 0; k < 2; ++k)
{
printf("test[%d][%d][%d] = %d\n", i, j, k, test[i][j][k]);
}
}
}
return 0;
}
Output
Enter 12 values:
1
2
3
4
5
6
7
8
9
10
11
12
Displaying Values:
test[0][0][0] = 1
test[0][0][1] = 2
test[0][1][0] = 3
test[0][1][1] = 4
test[0][2][0] = 5
test[0][2][1] = 6
test[1][0][0] = 7
test[1][0][1] = 8
test[1][1][0] = 9
test[1][1][1] = 10
test[1][2][0] = 11
test[1][2][1] = 12
C program demonstrates how to store the elements entered by user in a 2d array and how to display
the elements of a two dimensional array.
#include<stdio.h>
int main(){
/* 2D array declaration*/
int disp[2][3];
/*Counter variables for the loop*/
int i, j;
for(i=0; i<2; i++) {
for(j=0;j<3;j++) {
printf("Enter value for disp[%d][%d]:", i, j);
scanf("%d", &disp[i][j]);
}
}
//Displaying array elements
printf("Two Dimensional array elements:\n");
for(i=0; i<2; i++) {
for(j=0;j<3;j++) {
printf("%d ", disp[i][j]);
if(j==2){
printf("\n");
}
}
}
return 0;
}
Output:
We already know, when we initialize a normal array (or you can say one dimensional array) during
declaration, we need not to specify the size of it. However that’s not the case with 2D array, you
must always specify the second dimension even if you are specifying elements during the
declaration. Let’s understand this with the help of few examples –
/* Valid declaration*/
int abc[2][2] = {1, 2, 3 ,4 }
/* Valid declaration*/
int abc[][2] = {1, 2, 3 ,4 }
/* Invalid declaration – you must specify second dimension*/
int abc[][] = {1, 2, 3 ,4 }
/* Invalid because of the same reason mentioned above*/
int abc[2][] = {1, 2, 3 ,4 }
How to store user input data into 2D array
We can calculate how many elements a two dimensional array can have by using this formula:
The array arr[n1][n2] can have n1*n2 elements. The array that we have in the example below is
having the dimensions 5 and 4. These dimensions are known as subscripts. So this array has first
subscript value as 5 and second subscript value as 4.
So the array abc[5][4] can have 5*4 = 20 elements.
To store the elements entered by user we are using two for loops, one of them is a nested loop. The
outer loop runs from 0 to the (first subscript -1) and the inner for loops runs from 0 to the (second
subscript -1). This way the the order in which user enters the elements would be abc[0][0],
abc[0][1], abc[0][2]…so on.
#include<stdio.h>
int main(){
/* 2D array declaration*/
int abc[5][4];
/*Counter variables for the loop*/
int i, j;
for(i=0; i<5; i++) {
for(j=0;j<4;j++) {
printf("Enter value for abc[%d][%d]:", i, j);
scanf("%d", &abc[i][j]);
}
}
return 0;
}
In above example, We have a 2D array abc of integer type. Conceptually we can visualize the
above array like this:
However the actual representation of this array in memory would be something like this:
If We follow the rule of array initialization then we can write the above statement as follows:
String Declaration
Method 1:
char address[]="TEXAS";
In the above declaration NULL character (\0) will automatically be inserted at the end of the
string.
#include <stdio.h>
#include <string.h>
int main()
{
/* String Declaration*/
char nickname[20];
/*Displaying String*/
printf("%s",nickname);
return 0;
}
Output:
#include <stdio.h>
#include <string.h>
int main()
{
/* String Declaration*/
char nickname[20];
puts(nickname);
return 0;
}
C – String functions
C String function – strlen
Syntax:
Example of strlen:
#include <stdio.h>
#include <string.h>
int main()
{
char str1[20] = "BeginnersBook";
printf("Length of string str1: %d", strlen(str1));
return 0;
}
Output:
Syntax:
Example of strnlen:
#include <stdio.h>
#include <string.h>
int main()
{
char str1[20] = "BeginnersBook";
printf("Length of string str1 when maxlen is 30: %d", strnlen(str1, 30));
printf("Length of string str1 when maxlen is 10: %d", strnlen(str1, 10));
return 0;
}
Output:
Length of string str1 when maxlen is 30: 13
Length of string str1 when maxlen is 10: 10
Have you noticed the output of second printf statement, even though the string length was 13 it
returned only 10 because the maxlen was 10.
If string1 < string2 OR string1 is a substring of string2 then it would result in a negative
value. If string1 > string2 then it would return positive value.
If string1 == string2 then you would get 0(zero) when you use this function for compare strings.
Example of strcmp:
#include <stdio.h>
#include <string.h>
int main()
{
char s1[20] = "BeginnersBook";
char s2[20] = "BeginnersBook.COM";
if (strcmp(s1, s2) ==0)
{
printf("string 1 and string 2 are equal");
}else
{
printf("string 1 and 2 are different");
}
return 0;
}
Output:
Example of strncmp:
#include <stdio.h>
#include <string.h>
int main()
{
char s1[20] = "BeginnersBook";
char s2[20] = "BeginnersBook.COM";
/* below it is comparing first 8 characters of s1 and s2*/
if (strncmp(s1, s2, 8) ==0)
{
printf("string 1 and string 2 are equal");
}else
{
printf("string 1 and 2 are different");
}
return 0;
}
Output:
Example of strcat:
#include <stdio.h>
#include <string.h>
int main()
{
char s1[10] = "Hello";
char s2[10] = "World";
strcat(s1,s2);
printf("Output string after concatenation: %s", s1);
return 0;
}
Output:
Example of strncat:
#include <stdio.h>
#include <string.h>
int main()
{
char s1[10] = "Hello";
char s2[10] = "World";
strncat(s1,s2, 3);
printf("Concatenation using strncat: %s", s1);
return 0;
}
Output:
Example of strcpy:
#include <stdio.h>
#include <string.h>
int main()
{
char s1[30] = "string 1";
char s2[30] = "string 2 : I’m gonna copied into s1";
/* this function has copied s2 into s1*/
strcpy(s1,s2);
printf("String s1 is: %s", s1);
return 0;
}
Output:
Example of strncpy:
#include <stdio.h>
#include <string.h>
int main()
{
char first[30] = "string 1";
char second[30] = "string 2: I’m using strncpy now";
/* this function has copied first 10 chars of s2 into s1*/
strncpy(s1,s2, 12);
printf("String s1 is: %s", s1);
return 0;
}
Output:
Example of strchr:
#include <stdio.h>
#include <string.h>
int main()
{
char mystr[30] = "I’m an example of function strchr";
printf ("%s", strchr(mystr, 'f'));
return 0;
}
Output:
f function strchr
#include <stdio.h>
#include <string.h>
int main()
{
char mystr[30] = "I’m an example of function strchr";
printf ("%s", strrchr(mystr, 'f'));
return 0;
}
Output:
function strchr
Why output is different than strchr? It is because it started searching from the end of the
string and found the first ‘f’ in function instead of ‘of’.
Example of strstr:
#include <stdio.h>
#include <string.h>
int main()
{
char inputstr[70] = "String Function in C at BeginnersBook.COM";
printf ("Output string is: %s", strstr(inputstr, 'Begi'));
return 0;
}
Output:
void main()
{
char str[100]; /* Declares a string of size 100 */
int l= 0;
Output:
void main()
{
char str[100]; /* Declares a string of size 100 */
int l= 0;
Sample Output:
void main()
{
char str[100]; /* Declares a string of size 100 */
int l,i;
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void main()
{
char str[100]; /* Declares a string of size 100 */
int l=0;
Sample Output:
m o c . e c r u o s e r 3 w
void main()
{
char str[str_size];
int i, wrd;
printf("\n\nCount the total number of words in a string :\n");
printf("------------------------------------------------------\n");
printf("Input the string : ");
fgets(str, sizeof str, stdin);
i = 0;
wrd = 1;
i++;
}
Sample Output:
int main()
{
int ctr=0;
char str_char;
char str[100];