Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 18

Array in C

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.

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.

Types of Array

 Single Dimensional Array / One Dimensional Array


 Two Dimensional Array / Multi Dimensional Array

Single Dimensional Array


Single dimensional arrays are used to store list of values of same data type. In other words, single
dimensional arrays are used to store a row of values. In single dimensional array, data is stored in linear
form. Single dimensional arrays are also called as one-dimensional arrays, Linear Arrays or simply 1-
D Arrays.
Syntax
data_type array_name[array_size];  

Now, let us see the example to declare the array.


int marks[5];  

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

Declaration with Initialization


We can initialize the c array at the time of declaration. Let's see the code.
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.

int marks[]={20,30,40,50,60};  

Example Program
#include<stdio.h>
int main()
{
int i=0;
int marks[5]={20,30,40,50,60}; //declaration and initialization of array
for(i=0;i<5;i++)
{
printf("%d \t",marks[i]);
}
return 0;
}
Output
20 30 40 50 60

Example 2:
#include <stdio.h>
int main()
{
int number[5];

printf("Enter 5 number: ");

for(int i = 0; i < 5; ++i)


{
scanf("%d", &number[i]);
}

printf("Displaying the number: ");

for(int i = 0; i < 5; ++i) {


printf("%d\n", number[i]);
}
return 0;
}
Output
Enter 5 number: 1 2 3 4 5                                                                           

Displaying the number: 1        2       3       4       5 

Program to find the average of n numbers using arrays

#include <stdio.h>
int main()
{
int marks[10], i, n, sum = 0, average;
printf("Enter number of elements: ");
scanf("%d", &n);
for(i=0; i<n; ++i)
{
printf("Enter number %d: ",i++);
scanf("%d", &marks[i]);
sum += marks[i];
}
average = sum/n;
printf("Average = %d", average);
return 0;
}
Output
Enter number of elements: 3                                                                         
Enter number 1: 2                                                                                   
Enter number 2: 3                                                                                   
Enter number 3: 4                                                                                   
Average = 3 

Example: Sorting an array in ascending order.

#include<stdio.h>
int main ()
{
int i, j,temp;
int a[10] = { 10, 9, 7, 101, 23};
for(i = 0; i<5; i++)
{
for(j = i+1; j<5; 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<5; i++)

{
printf("%d\n",a[i]);
}
return 0;
}
Output
Printing Sorted Element List ...                                                                      
101                                                                                                   
23                                                                                                    
10                                                                                                    
9                                                                                                     

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.

The syntax to declare the 2D array

data_type  array_name[rows][columns];  

Example
#include<stdio.h>
int main()
{
int i=0,j=0;
int arr[3][3]={{1,2,3},{4,5,6},{7,8,9}};
for(i=0;i<3;i++)
{
printf("\n");
for(j=0;j<3;j++)
{
printf(" %d \t",arr[i][j]);
}
}
return 0;
}
Output
1       2       3                                                                                    
 4       5       6                                                                                    
 7       8       9 

Example
#include<stdio.h>
int main()
{
int disp[10][10];
int i, j,n;
printf("Enter the row and colum: ");
scanf("%d",&n);
for(i=0; i<n; i++)
{
for(j=0;j<n;j++)
{
printf("Enter value for disp[%d][%d]:", i, j);
scanf("%d", &disp[i][j]);
}
}
printf("Two Dimensional array elements:\n");
for(i=0; i<n; i++)
{
printf("\n");
for(j=0;j<n;j++)
{
printf("%d \t", disp[i][j]);

}
}
return 0;
}
Output
Enter the row and colum: 3                                                                            
Enter value for disp[0][0]:1                                                                          
Enter value for disp[0][1]:2                                                                          
Enter value for disp[0][2]:3                                                                          
Enter value for disp[1][0]:4                                                                          
Enter value for disp[1][1]:5                                                                          
Enter value for disp[1][2]:6                                                                          
Enter value for disp[2][0]:7                                                                          
Enter value for disp[2][1]:8                                                                          
Enter value for disp[2][2]:9                                                                          
Two Dimensional array elements:                                                                       
                                                                                                      
1       2       3                                                                                     
4       5       6                                                                                     
7       8       9 

#include <stdio.h>
int main()
{
int a[2][2],b[2][2],c[2][2],i,j;

printf("\nENTER VALUES FOR FIRST MATRIX :\n");


for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
scanf("%d",&a[i][j]);
}
}

printf("\nENTER VALUES FOR SECOND MATRIX :\n");


for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
scanf("%d",&b[i][j]);
}
}
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
c[i][j]=a[i][j]+b[i][j];
}
}

printf("\n THE ADDITION OF MATRIX IS :\n");


for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
printf("%5d",c[i][j]);
}
printf("\n");
}
return 0;
}

Output
ENTER VALUES FOR FIRST MATRIX :                                                                       
1                                                                                                     
2                                                                                                     
3                                                                                                     
4                                                                                                     
                                                                                                      
ENTER VALUES FOR SECOND MATRIX :                                                                      
1                                                                                                     
2                                                                                                     
3                                                                                                     
4                                                                                                     
                                                                                                      
 THE ADDITION OF MATRIX IS :                                                                          
    2    4                                                                                            
    6    8 

Matrix Multiplication

#include <stdio.h>
int main()
{
int a[2][2],b[2][2],c[2][2],i,j,mul[10][10];

printf("\nENTER VALUES FOR FIRST MATRIX :\n");


for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("\nENTER VALUES FOR SECOND MATRIX :\n");
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
scanf("%d",&b[i][j]);
}
}
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
mul[i][j]=0;
for(int k=0;k<2;k++)
{
mul[i][j]=mul[i][j]+a[i][k]*b[k][j];
}
// c[i][j]=a[i][j]+b[i][j];
}
}
printf("\n THE ADDITION OF MATRIX IS :\n");
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
printf("%5d",mul[i][j]);
}
printf("\n");
}
return 0;
}
Output
ENTER VALUES FOR FIRST MATRIX :                                                                       
1  2                                                                                                   
1  2                                                                                                   
                                                                                                      
ENTER VALUES FOR SECOND MATRIX :                                                                      
1  2                                                                                                   
1  2                                                                                                   
                                                                                                      
 THE ADDITION OF MATRIX IS :                                                                          
    3    6                                                                                            
    3    6 

Mean Value:
#include <stdio.h>
void main()
{
int m[5],i,sum=0,n;
float mean;
printf(“enter number of students \n”);
scanf(“%d”,&n);
printf(“enter marks of students \n”);
for(i=0;i<n;i++)
{
scanf(“%d”,&m[i]);
}
for(i=0;i<n;i++)
sum=sum+m[i];
mean=(float)sum/n;
printf(“Mean=%f”,mean);
}

Median:

#include<stdio.h>
#include<conio.h>
main()
{
int i,j,temp,n,a[20],sum=0;
float median;
printf("enter n:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\n enter %d number:",i+1);
scanf("%d",&a[i]);
}
for(i=0;i<n-1;i++)
{
for(j=i+1;j<n;j++)
{
if(a[j]<a[i])
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
if(n%2==0)
{
median=((a[n/2]+a[n/2 -1])/2.0);
}
else
{
median=a[n/2];
}
printf("\n the median value is %f",median);
getch();
}

Output:
Enter N:5
Enter 1 number:11
Enter 2 number:12
Enter 3 number:13
Enter 4 number:14
Enter 5 number:15
The median value is 13.000000

Computing Mode:
#include<stdio.h>
#include<conio.h>
void main()
{
int maxvalue = 0, maxCount = 0, i, j,a[20],n,count=0;
clrscr();
printf("enter the N value:");
scanf("%d",&n);
for(i = 0; i < n;i++)
{
printf("\n Enter %d number:",i+1);
scanf("%d",&a[i]);
}
for(i=0;i<n;i++)
{
for (j = i+1; j < n;j++)
{
if(a[j] == a[i])
count++;
}
if (count > maxCount)
{
maxCount = count;
maxvalue = a[i];
printf("\nThe mode value is %d",maxvalue);
}
}
getch();
}
Output:
Enter the N value:5
Enter 1 Number:0
Enter 2 Number:6
Enter 3 Number:7
Enter 4 Number:2
Enter 5 Number:7
The mode value is 7

Example: Matrix Addition


#include<stdio.h>
#include<conio.h>
main()
{
int a[25][25],b[25][25], c[25][25], i, j m, n;
clrscr();
printf(“\n Enter the rows and columns of two matrices… “);
scanf(“%d %d “, &m, &n)
printf{“\n Enter the elements of A matrix…”);
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf(“%d”,&a[i][j]);
printf{“\n Enter the elements of B matrix…”);
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf(“%d”, &b[i][j]);
for(i=0;i<m;i++)
for(j=0;j<n;j++)
c[i][j]=a[i][j] + b[i][j];
printf(“\n The addition of two matrices”);
for(i=0;i<m;i++)
{
printf(“\n”);
for(j=0;j<n;j++)
{
printf(“\t %d”,c[i][j]);
}
}
getch();
}
Output:
Enter the rows and columns of two matrices…. 3 3
Enter the elements of A matrix… 1 2 3 4 5 6 7 8 9
Enter the elements of B matrix… 1 2 3 4 5 6 7 8 9
The addition of two matrixes
246
8 10 12
14 16 18

Example: Matrix Multiplication


#include <stdio.h>
#include <conio.h>
main()
{
int a[10][10], b[10][10], c[10][10];
int r1, c1, r2, c2;
int i, j, k;
clrscr();
printf("Enter order of matrix A : ");
scanf("%d%d", &r1, &c1);
printf("Enter order of matrix B : ");
scanf("%d%d", &r2, &c2);
if (c1 != r2)
{
printf("Matrix multiplication not possible");
getch();
exit(0);
}
printf("Enter matrix A elements\n");
for(i=0; i<r1; i++)
for(j=0; j<c1; j++)
scanf("%d", &a[i][j]);
printf("Enter matrix B elements\n");
for(i=0; i<r2; i++)
for(j=0; j<c2; j++)
scanf("%d", &b[i][j]);
for(i=0; i<r1; i++)
{
for(j=0; j<c2; j++)
{
c[i][j] = 0;
for(k=0; k<c1; k++)
{
c[i][j] =c[i][j]+ a[i][k] * b[k][j];
}
}
}
printf("Product matrix C\n");
for(i=0; i<r1; i++)
{
for(j=0; j<c2; j++)
{
printf("%d\t",c[i][j]);
}
printf("\n");
}
getch();
}
Output
Enter order of matrix A : 2 3
Enter order of matrix B : 3 2
Enter matrix A elements
111
111
Enter matrix B elements
22
22
22
Product matrix C
66
66

Example: Matrix Scaling


#include<graphics.h>
#include<stdlib.h>
#include<stdio.h>
#include<math.h>
void main()
{
int graphdriver=DETECT,graphmode,errorcode;
int i;
int x2,y2,x1,y1,x,y;
printf("Enter the 2 line end points:");
printf("x1,y1,x2,y2");
scanf("%d%d%d%d",&x1,&y1,&x2,&y2);
initgraph(&graphdriver,&graphmode,"c:\\tc\\bgi");
line(x1,y1,x2,y2);
printf("Enter scaling co-ordinates ");
printf("x,y");
scanf("%d%d",&x,&y);
x1=(x1*x);
y1=(y1*y);
x2=(x2*x);
y2=(y2*y);
printf("Line after scaling");
line(x1,y1,x2,y2);
getch();
closegraph();
}

Example: Matrix Transpose


#include<stdio.h>
#include<conio.h>
void main()
{
int a[5][5],i,j,m,n;
clrscr();
printf("How many rows");
scanf("%d",&n);
printf("How many columns");
scanf("%d",&m);
printf("\nEnter the matrix:\n");
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf("%d",&a[i][j]);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
printf("%d",a[i][j]);
printf("\n");
}
printf("\nTranspose of given matrix:\n");
for(i=0;i<m;++i)
{
for(j=0;j<n;++j)
printf("%d ",a[j][i]);
printf("\n");
}
getch();
}
Output:
How many rows 2
How many columns 2
Enter the matrix: 1 2 3 4
12
34
Transpose of given matrix:
13
24
C String Length: strlen() function

The strlen() function returns the length of the given string. It doesn't count null character
'\0'.

#include<stdio.h>  
#include <string.h>    
int main(){    
char ch[20]={'p', 'y', 't', 'h' , 'o', 'n'};    
int a= strlen(ch);    
   printf("Length of string is: %d",a);    
 return 0;    
}    
Output:
Length of string is: 6

C Copy String: strcpy( )


The strcpy(destination, source) function copies the source string in destination.
#include<stdio.h>  
#include <string.h>    
int main(){    
 char ch[20]={'p', 'y', 't', 'h' , 'o', 'n'};
   char ch2[20];    
   strcpy(ch2,ch);    
   printf("Value of second string is: %s",ch2);    
 return 0;    
}    
Output:
Value of second string is: python

C String Concatenation: strcat( )


The strcat(first_string, second_string) function concatenates two strings and result is
returned to first_string.
#include<stdio.h>  
#include <string.h>    
int main(){    
char ch[10]={'h', 'e', 'l', 'l', 'o'};
char ch2[10]={'C','J','A','V','A'};  
 strcat(ch,ch2);    
   printf("Value of first string is: %s",ch);    
 return 0;    
}    
Output:
Value of first string is: hellocCJAVA

C Compare String: strcmp()


The strcmp(first_string, second_string) function compares two string and returns 0 if both
strings are equal.
Here, we are using gets() function which reads string from the console.
#include<stdio.h>  
#include <string.h>    
int main(){    
  char str1[20],str2[20];    
  printf("Enter 1st string: ");    
  gets(str1);
  printf("Enter 2nd string: ");    
  gets(str2);    
  if(strcmp(str1,str2)==0)    
      printf("Strings are equal");    
  else    
      printf("Strings are not equal");    
 return 0;    
}    
Output:

Enter 1st string: hello


Enter 2nd string: hello
Strings are equal

C Reverse String: strrev()


The strrev(string) function returns reverse of the given string. Let's see a simple example
of strrev() function.
#include<stdio.h>  
#include <string.h>    
int main(){    
  char str[20];    
  printf("Enter string: ");    
  gets(str);
  printf("String is: %s",str);    
  printf("\nReverse String is: %s",strrev(str));    
 return 0;    
}    
Output:
Enter string: python
String is: python
Reverse String is: nohtyp

C String Lowercase: strlwr()


The strlwr(string) function returns string characters in lowercase. Let's see a simple
example of strlwr() function.
#include<stdio.h>  
#include <string.h>    
int main(){    
  char str[20];    
  printf("Enter string: ");    
  gets(str);//reads string from console    
  printf("String is: %s",str);    
  printf("\nLower String is: %s",strlwr(str));    
 return 0;    
}    
Output:
Enter string: PYTHON
String is: PYTHON
Lower String is: python

C String Uppercase: strupr()


The strupr(string) function returns string characters in uppercase. Let's see a simple
example of strupr() function.
#include<stdio.h>  
#include <string.h>    
int main(){    
  char str[20];    
  printf("Enter string: ");    
  gets(str);//reads string from console    
  printf("String is: %s",str);    
  printf("\nUpper String is: %s",strupr(str));    
 return 0;    
}    
Output:
Enter string: java
String is: java
Upper String is: JAVA

#include <stdio.h>
int main() {
int a[10][10], transpose[10][10], r, c;
printf("Enter rows and columns: ");
scanf("%d %d", &r, &c);

// asssigning elements to the matrix


printf("\nEnter matrix elements:\n");
for (int i = 0; i < r; ++i)
for (int j = 0; j < c; ++j) {
printf("Enter element a%d%d: ", i + 1, j + 1);
scanf("%d", &a[i][j]);
}

// printing the matrix a[][]


printf("\nEntered matrix: \n");
for (int i = 0; i < r; ++i)
for (int j = 0; j < c; ++j) {
printf("%d ", a[i][j]);
if (j == c - 1)
printf("\n");
}

// computing the transpose


for (int i = 0; i < r; ++i)
for (int j = 0; j < c; ++j) {
transpose[j][i] = a[i][j];
}

// printing the transpose


printf("\nTranspose of the matrix:\n");
for (int i = 0; i < c; ++i)
for (int j = 0; j < r; ++j) {
printf("%d ", transpose[i][j]);
if (j == r - 1)
printf("\n");
}
return 0;
}

Linear Search:

Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int a[10],i,n,m,c=0;
clrscr();
printf("Enter the size of an array: ");
scanf("%d",&n);
printf("Enter the elements of the array: ");
for(i=0;i<=n-1;i++)
scanf("%d",&a[i]);
printf("Enter the number to be searched: ");
scanf("%d",&m);
for(i=0;i<=n-1;i++)
{
if(a[i]==m)
{
printf("Element is in the position %d\n",i+1);
c=1;
break;
}
}
if(c==0)
printf("The number is not in the list");
getch();
}
Output:
Enter the size of an array: 4
Enter the elements of the array: 4 3 5 1
Enter the number to be search: 5
Element is in the position 3
Binary search:

#include<stdio.h>
void main()
{
int a[10],i,n,m,c=0,l,u,mid;
printf("Enter the size of an array: ");
scanf("%d",&n);
printf("Enter the elements in ascending order: ");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("Enter the number to be searched: ");
scanf("%d",&m);
l=0,u=n-1;
while(l<=u)
{
mid=(l+u)/2;
if(m==a[mid])
{
c=1;
break;
}
else if(m<a[mid])
{
u=mid-1;
}
else
l=mid+1;
}
if(c==0)
printf("The number is not found.");
else
printf("The number is found.");
}
Sample output:
Enter the size of an array: 5
Enter the elements in ascending order: 4 7 8 11 21
Enter the number to be search: 11
The number is found.
Example:
3 5 7 9 11
Search key=7
middle element=7
Searching element=middle element. So the element is found.
Search key=11
Middle element=7
Searching element>middle
So go to right half: 9 11.
Repeat steps until 11 is found or list ends.

Selection Sort:

#include <stdio.h>
int main()
{
int a[100], n, i, j, position, swap;
printf("Enter number of elementsn");
scanf("%d", &n);
printf("Enter %d Numbers n", n);
for (i = 0; i < n; i++)
scanf("%d", &a[i]);
for(i = 0; i < n - 1; i++)
{
position=i;
for(j = i + 1; j < n; j++)
{
if(a[position] > a[j])
position=j;
}
if(position != i)
{
swap=a[i];
a[i]=a[position];
a[position=swap;
}
}
printf("Sorted Array:n");
for(i = 0; i < n; i++)
printf("%dn", a[i]);
return 0;
}

You might also like