unit2-programming-in-c (1)
unit2-programming-in-c (1)
lOMoARcPSD|22072273
1. Introduction to Arrays
• An Array is a collection of similar data elements. These data elements have same data
types stored in contiguous memory location.
• Array is a collection of elements of same data type stored under common name.
• An array is a data structure that is used for storage of homogeneous data.
• It is classified into three types
i) One dimensional Array
ii) Two dimensional Array
iii) Multi-dimensional Array
1.1 Characteristics of an Array
• The elements of the array are stored in continuous memory location.
• Individual elements of an array can be accessed with the integer value known as index.
• Array index starts from 0.
Example
int a[4]={20,45,67,89};
UNIT 2 - ARRAYS
program:
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
int a[4]={20,45,67,89};
printf(“%d \t%d\t%d\t%d”,a[0],a[1],a[2],a[3]);
getch();
}
Output:
20 45 67 89
program:
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
int a[4]={20,45,67,89};
int i;
for(i=0;i<4;i++)
{
printf(“%d\t”,a[i]);
}
getch();
}
Output:
20 45 67 89
2.3 Run time initialization:
int a[4];
for(i=0;i<4;i++)
{
scanf(“%d”,&a[i]);
}
UNIT 2 - ARRAYS
Output:
Col 0 Col 1
Row 0 10 20
Row 1 30 40
Row 2 50 60
UNIT 2 - ARRAYS
program :
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
int a[3][2]={{10,20},{30,40},{50,60}};
printf(“%d\t”,a[0][0]);
printf(“%d\n”,a[0][1]);
printf(“%d\t”,a[1][0]);
printf(“%d\n”,a[1][1]);
printf(“%d\t”,a[2][0]);
printf(“%d\n”,a[2][1]);
}
Output:
10 20
30 40
50 60
program to read the array elements and print the same
#include<stdio.h>
#include<conio.h>
void main()
{
int a[3][2]={{10,20},{30,40},{50,60}};
int i,j;
printf("\nThe Matrix");
for(i=0;i<2;i++)
{
printf("\n");
for(j=0;j<2;j+
+)
{
printf("\t%d",a[i][j]);
}
}
getch();
}
Output:
10 20
30 40
50 60
UNIT 2 - ARRAYS
int a[2][3];
for(i=0;i<2;i++)
{
for(j=0;j<3;j++)
{
scanf(“%d”, &a[i][j]);
}
}
program :
#include<stdio.h>
#include<conio.h>
void main()
{
int a[2][3];
int i,j;
printf(“Enter the elements\
n”);
for(i=0;i<2;i++)
{
for(j=0;j<3;j++)
{
scanf(“%d”, &a[i][j]);
}
}
Output:
Enter the elements
1
2
3
4
The elements are
1 2
UNIT 2 - ARRAYS
2 4
Output:
Enter Matrix A
12
34
Enter Matrix B
12
34
The result
24
68
getch();
}
Output:
Enter matrix A
1 2
3 4
Transpose
1 3
2 4
UNIT 2 - ARRAYS
Output:
Enter Matrix A
12
34
Enter Matrix B
12
34
The result
7 10
15 22
Initialization of a 3d array int arr[2][3][2] = { { {0, 1}, {2, 3}, {4, 5} },{ {6, 7}, {8, 9}, {10, 11} }};
#include <stdio.h>
int main()
{
int arr[2][3][2] = { { {0, 1}, {2, 3}, {4, 5} }, { {6, 7}, {8, 9}, {10, 11} }};
// Printing the array
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 3; j++)
{
for (int k = 0; k < 2; k++)
{
printf("%d ", arr[i][j][k]);
}
printf("\n");
}
printf("\n");
}
return 0;
}
OUTPUT
0 1
2 3
4 5
6 7
8 9
10 11