Arrays 1D and 2D , and multi dimensional
-
Upload
appili-vamsi-krishna -
Category
Education
-
view
17 -
download
2
Transcript of Arrays 1D and 2D , and multi dimensional
ARRAYSDeclaration, Initialisation , Reading &
Writing of Arrays
• We have used the fundamental data types, char, int, float, double.
• These types are constrained by the fact that a variable of these types can store only one value at any given time
• In many applications, we need to handle large volumes of data
• To process such large amounts of data, we need a powerful data types that would facilitate efficient storing, accessing and manipulation of data items
INTRODUCTION
• C supports a derived data type known as array.• An array is a fixed-sized sequenced collection of
elements of the same data type thats shares a common name.
• The common name a is the array name and each individual data item is known as an element of the array.
• The elements of the array are stored in the subsequent memory locations starting from the memory location given by the array name.
INTRODUCTION
Array can be classified as two types are,
1. One-Dimensional Array2. Two-Dimensional or
multidimensional Array
Types of Array
One-Dimensional Array
◦ A one-dimensional array can be used to represent a list of data items. It is also known as a vector.
Two-Dimensional Array
◦ A two dimensional array can be used to represent a table of data items consisting of rows and columns. It is also known as a matrix
Cont.,
Declaration of Arrays Every array must be declared before use like
other variables. The declarations of one-dimensional and
multidimensional arrays differ slightly. Declaration of One-dimensional array:
where data_type refers to the data type of elements in the array.
It can be a primitive or derived data type. name is an identifier which represents the array name.size is an integer expression representing the total number of elements in the array.
data_type name1[size1], name2[size2],…, namen[sizen];
Declaratiaon of One-dimensional Arrays
The base address of an array is the address of the zeroth element (starting element) of that array.
When an array is declared, the compiler allocates a base address and reserves enough space in memory for all the elements of the array.
In C, the array name represents this base address. For example, float x[5]; is the declaration of a one-
dimensional array. It defines a float array x of size 5 that represents a
block of 5 consecutive storage regions.
Each element in the array is referred to by the array variables x[0], x[1], x[2] ,x[3] and x[4] where 0,1,2,3 and 4 represent subscripts or indices of the array.
In general, x[i] refers to the ith element of the array. The array subscripts always start at zero in C and they
are integer expressions. Hence, x[0] refers to the starting element, x[1] refers
to the next element and x[4] refers to the last element. The declaration double list[10], array[15]; declares
two arrays, named list and array having 10 and 15 elements respectively of double precision data type.
Declaration of One-dimensional Arrays…
The elements of an array may be assigned with the values using initialisation instead of reading them by the I/O functions.
An array can be initialised in its declaration only. The list of initialisers (values) are enclosed in braces. The initialisers are separated by commas and they must be
constants or constant expressions. One-dimensional array can be initialised as given below.
int a[4]={3,5, -8, 10}; The values within the braces are scanned from left end and
assigned to a[0], a[1] and so on. A semicolon should be placed after the closing brace.
Initialisation of Arrays
“For “ loops used extensively for array processing
Example 1: write a program to read an array and print.
#include<stdio.h>void main()
{ int i,a[10]; for(i=0;i<10;i++)
scanf(“%d”,&a[i]); for(i=0;i<10;i++)Printf(“\n %d”,a[i]);
}
Example2: write a program to read integer number and copy it another array.
Example3: write a program to read 10 values and sum these 10 values and print.
Example4: write a program to read 10 values and store it in another array in reverse order.
Example5: Write a c program for swapping of two arrays.
#include<stdio.h>void main(){ int x[2],i; printf("\nEnter the inputs:"); for(i=0;i<2;i++)
scanf("%d",&x[i]); for(i=0;i<2;i++)
printf("\nThe value in x[%d] is %d",i,x[i]);}
OUTPUT:Enter the inputs:36
The value in x[0] is 3The value in x[1] is 6
EXAMPLE
/*Determines the length of a message */#include<stdio.h>main(){char ch;int len=0;printf(“Enter a message : ”);ch=getchar();while (ch!=‘\n’) {len++;ch=getchar();}printf(“Your message was %d character(s) long. \n”, len);return 0;}
CHARACTER ARRAY The c languages treats strings as arrays of characters The compiler terminates the character strings with an
additional null (‘\0’) character. String is a one dimensional array of characters in c. The element name[10] holds the null character ‘\0’ at
the end When declaring character arrays, we must always
allow one extra elements space for the null terminator
#include<stdio.h>
void main(){ int i=0;
char a[]="abcd";
while(a[i]!='\0') {
printf("\t%c",a[i]);i++;}
}
OUTPUT:a b c d
There are different way to initialize a character array variable.
char name[10]=“StudingTonight”; //valid initialization
char name[10]={‘L’,’E’,’S’,’S’,’O’,’N’,’S’,’\0’}; // valid Init
Some example for illegal Initialization of character array are,
char ch[3]=“hello”; // Illegal char str[4];
str=“hello”; //illegal
Declaring and Initialization of character array
Format:
data_type array_name[row_size1][column_size1]; The first subscript represents the row size and the second subscript
represents the column size. The value in the ith row and jth column is referred to by name[i][j]. The total number of elements in a two dimensional array is
calculated by multiplying the number of rows by the number of columns.
In two-dimensional arrays, the values are stored row by row.
Declaration of Two-dimensional Arrays
int x[3][2];
Example
For example, the declaration int a[3][2] ,b[7][4]; defines the two-dimensional integer arrays a and b.
These arrays are arrays of integer arrays. Six (rows * columns) elements of a are stored row by row in
the consecutive memory locations. This method of storing the elements in the memory is
known as row major order storage representation The zeroth element of array a is denoted by a[0][0] and the
last element in that array is denoted by a[2][1]. Similarly, for the array b, the zeroth element and the last
element are represented by b[0][0] and b[6][3] respectively.
Declaration of Two-dimensional Arrays…
Declaration of Two-dimensional Arrays…
Starting element a[0][0] a[0][1] a[1][0] a[1][1] a[2][0] Last element a[2][1]
Row 0
Row 1Row 1
Row 2
Storage representation of matrix a
Syntax:data_type array_name[row_size][col_size]={variables};
A two-dimensional array can be initialised as given below.int a[3][2] = {20, 25, -3, 8, -5, 7};
Here, the initialised values are assigned to the array elements according to the order of the storage in the memory.
But if the initialisers are enclosed within the inner braces as given below
int a[3][2] = {{20,25}, {-3, 8}, {-5,7}}; The initialised values within the inner braces are assigned to each row. To enforce the assignment of each row, it is essential to use the inner
braces.
Initialisation of Arrays
If the number of values initialised for an array is less than the size mentioned, the missing elements are assigned zero. In the initialisation
int a[3][4] = { {1,2},{4,8,15} };
the elements a[0][0] and a[0][1] of the zeroth row and a[1][0], a[1][1] and a[1][2] of the first row are initialised with the values 1,2,4,8 and 15 respectively.
All the other elements are initialised to zero.
If it is given as int a[3][4] = {1,2,3,8,15};
the values are assigned from the left end to a[0][0], a[0][1], a[0][2], a[0][3], and a[[1][0] according to the order of the storage representation.
If the number of initialisers exceeds the size of the array, it is an error.
Initialisation of Arrays…
The size of a one-dimensional array need not be mentioned in its
initialisation.
In this case, the compiler will count the values assigned and take it as
the size of that array.
In multidimensional arrays the leftmost subscript may be omitted and
all the others must be specified. The initialisation
int x[ ] = {2,4,6,8,10};
makes the array x having 5 elements
float a[ ][2] = {{3.2,4.8}, {5.3,3.7}};
makes the array a having 2 rows and 2 columns.
Initialisation of Arrays…
EXAMPLE#include<stdio.h>void main(){ int i,j; int x[2][2]={ {1,50},
{2,75}};
for(i=0;i<2;i++)for(j=0;j<2;j++)
printf("\nThe value in x[%d][%d] is %d",i,j,x[i][j]);
}
OUTPUT:The value in x[0][0] is 1
The value in x[0][1] is 50The value in x[1][0] is 2The value in x[1][1] is 75
EXAMPLE#include<stdio.h>void main(){ int i,j; int x[][2]={ {1,50},{2,75},{3,65}};
for(i=0;i<=2;i++)for(j=0;j<2;j++)
printf("\nThe value in x[%d][%d] is %d",i,j,x[i][j]);
}
OUTPUT:The value in x[0][0] is 1The value in x[0][1] is 50The value in x[1][0] is 2The value in x[1][1] is 75The value in x[2][0] is 3The value in x[2][1] is 65
/* PROGRAM TO FIND THE MINIMUM VALUE AND ITS POSITION */ #include<stdio.h> #define MAX 5 main( ) { int a[MAX],i,min; int pos = 0; /* Fixing position if the first number is the minimum value */ printf("Enter the array elements\n"); for(i=0;i<MAX;i++) scanf("%d",&a[i]); min=a[0]; for(i=1;i<MAX;i++) if(a[i] < min) { min=a[i]; pos=i; /* Fixing the minimum value position*/ } printf(“ MINIMUM VALUE = %d\n”,min); printf(“ POSITION = %d\n”,pos); }
SAMPLE INPUT AND OUTPUT Enter the array elements14 29 37 25 45 MINIMUM VALUE = 14POSITION = 0
#define MAXROW 2#define MAXCOL 4main( ) { int s[MAXROW][MAXCOL],t[MAXCOL][MAXROW]; int i,j; printf("Enter the values of the matrix\n"); for(i=0;i<MAXROW;i++) for(j=0;j<MAXCOL;j++) scanf("%d",&s[i][j]); printf("\nGiven Matrix\n\n"); for(i=0;i<MAXROW;i++) { for(j=0;j<MAXCOL;j++) printf("%d\t",s[i][j]); printf("\n"); }
/* PROGRAM TO FIND THE TRANSPOSE OF A MATRIX */
for(i=0;i<MAXCOL;i++) for(j=0;j<MAXROW;j++) t[i][j] = s[j][i]; printf("\nTranspose of the matrix\n\n"); for(i=0;i<MAXCOL;i++) { for(j=0;j<MAXROW;j++) printf("%d\t",t[i][j]); printf("\n"); }}
SAMPLE INPUT AND OUTPUT Enter the values of the matrix10 20 30 40 50 60 70 80
Given Matrix 10 20 30 4050 60 70 80 Transpose of the matrix 10 5020 6030 7040 80
#include<stdio.h>#include<conio.h>void main(){ int i,j,k,r1,r2,c1,c2; int a[5][5],b[5][5],c[5][5]; clrscr(); //step1: printf("\n Enter the size of
matrix A:"); scanf("%d%d",&r1,&c1); printf("\n Enter the size of
matrix B: "); scanf("%d%d",&r2,&c2); if((c1==c2)&&(r1==r2))
goto step2; else
goto step1;
//step2: printf("\n Enter the elements of matrix A \n"); for(i=0;i<r1;i++) {
for(j=0;j<c1;j++){
scanf("%d",&a[i][j]);}
} printf("\n Enter the elements of matrix B \n"); for(i=0;i<r2;i++) {
for(j=0;j<c2;j++){
scanf("\t%d",&b[i][j]);}
}
for(i=0;i<r1;i++) {
for(j=0;j<c1;j++){c[i][j]=0; c[i][j]=c[i][j]+a[i][j]+b[i][j];}
} printf("\n The resultant
matrix after addition of A & B is\n");
for(i=0;i<r1;i++) {
for(j=0;j<c1;j++)printf("%d\t",c[i][j]);printf("\n");
} getch();}
OUTPUT:Enter the size of matrix A: 22 Enter the size of matrix B: 22 Enter the elements of matrix
A2222 Enter the elements of matrix
B3333 The resultant matrix after
addition of A&B is5 55 5
/* PROGRAM TO REMOVE THE DUPLICATE ELEMENTS IN AN ARRAY */ #define MAX 5main( ) { int a[MAX]; int i,j,k,n=MAX,p; for(i=0;i<n;i++) { printf("Enter the value of a[%d]:\n",i); scanf("%d",&a[i]); } printf("Array before deleting duplicate elements\n"); for(i=0;i<n;i++) printf("%d\t",a[i]); for(i=0;i<n;i++) { for(j=i+1;j<n;j++)
{ if(a[i] == a[j]) { p = i ; for(k=j;k<n;k++) a[k] =a[++j]; j = p; n--; } } } putchar('\n'); printf("Array after deleting duplicate elements\n"); for(i=0;i<n;i++) printf("%d\t",a[i]); putchar('\n'); }
SAMPLE INPUT AND OUTPUT Enter the value of a[0]:5Enter the value of a[1]:8Enter the value of a[2]:5Enter the value of a[3]:12Enter the value of a[4]:8Array before deleting duplicate elements5 8 5 12
8Array after deleting duplicate elements5 8 12
Example Programs
Example program 2/* PROGRAM TO SORT AN ARRAY */ #define MAX 5main( ) { int a[MAX],i,j,temp; printf("Enter the array elements\n"); for(i=0;i<MAX;i++) scanf("%d",&a[i]); for(i=0;i<MAX;i++) for(j=i+1;j<MAX;j++) { if(a[i] >a[j])
Example Programs
Example program 2… { temp = a[i]; a[i] = a[j]; a[j] = temp; } } printf("\nAscending order\n"); for(i=0;i<MAX;i++) printf("%d\t",a[i]); printf("\nDescending order\n"); for(i=MAX-1;i>=0;i--) printf("%d\t",a[i]); }
SAMPLE INPUT AND OUTPUT Enter the array elements11 15 20 45 15Ascending order11 15 15 20 45Descending order45 20 15 15 11
Example Programs
Example program 3 /*PROGRAM TO CONVERT A 2-D ARRAY TO 1-D ARRAY */ #define MAXROW 3#define MAXCOL 2main( ) { int a[MAXROW][MAXCOL],b[MAXROW*MAXCOL]; int i,j,k=0; printf("Enter the matrix elements in row order\n"); for(i=0;i<MAXROW;i++) for(j=0;j<MAXCOL;j++) { scanf("%d",&a[i][j]);
Example Programs
Example program 3… b[k++] = a[i][j]; } printf("Given two-dimensional array\n"); for(i=0;i<MAXROW;i++) { for(j=0;j<MAXCOL;j++) printf("%d\t",a[i][j]); printf("\n"); } printf("Equivalent one-dimensional array\n"); for(i=0;i<MAXROW*MAXCOL;i++) printf("%d\t",b[i]); }
SAMPLE INPUT AND OUTPUT Enter the matrix elements in row order10 15 20 25 30 35Given two-dimensional array10 1520 2530 35Equivalent one-dimensional array10 15 20 25 30 35