SlideShare uma empresa Scribd logo
1 de 14
Baixar para ler offline
Page 1
ARRAYS
Need of an Array:
The variables of fundamental data types namely char,int,float,double can store only one value at
any given time. Therefore they can be used only to handle limited amounts of data. To process large
amount of data , we need a powerful data type that would facilitate efficient storing, accessing and
manipulation of data items. C supports a derived data type known as array that can be used for such
applications.
Array:
An array in C language is a collection of similar data-type, means an array can hold value of a
particular data type for which it has been declared.
Arrays can be created from any of the C data-types int, float, and char. So an integer array can
only hold integer values and cannot hold values other than integer. When we declare array, it allocates
contiguous memory location for storing values whereas 2 or 3 variables of same data-type can have
random locations. So this is the most important difference between a variable and an array.
Array Definition:
Array is a collection of variables, that can be stored in a continuous memory locations and shared a
common name.
(or)
Array by definition is a variable that hold multiple elements which has the same data type.
Arrays are of following types:
• Single dimensional arrays
• Double dimensional arrays
• Multi-dimension arrays.
Each of this array type can be of either static array or dynamic array. Static arrays have their
sizes declared from the start and the size cannot be changed after declaration. Dynamic arrays that allow
you to dynamically change their size at runtime, but they require more advanced techniques such as
pointers and memory allocation.
Single Dimension Arrays:
Declaring Single Dimension Arrays
Arrays can be declared using any of the data types available in C. Array size must be declared
using constant value before initialization. A single dimensional array will be useful for simple grouping of
data that is relatively small in size.
Page 2
We can declare an array by specifying its data type, name and the fixed number of elements the array
holds between square brackets immediately following the array name.
The following illustrates how to declare an array:
data_type array_name[size];
For example, to declare an array that contains 100 integer numbers you can do as follows:
int a[100];
You must follow the rules below when you declare an array in C:
• The data type can be any valid C data types including C structure and union.
• The name of an array has to follow the rule of C variables.
• The size of array has to be a positive constant integer.
So far, we've been declaring simple variables: the declaration
int i;
Declares a single variable, named i, of type int. It is also possible to declare an array of several elements.
The declaration :
int a[10];
Declares an array, named a, consisting of ten elements, each of type int. Simply speaking, an array is a
variable that can hold more than one value. You specify which of the several values you're referring to at
any given time by using a numeric subscript OR index. (Arrays in programming are similar to vectors or
matrices in mathematics.) We can represent the array a above with a picture
Like this:
Initializing Single dimensional Arrays:
An array can be initialized at either of the flowing stages:’
• At compile time
• At run time
Page 3
Compile time initialization:
It is like a variable, an array can be initialized. To initialize an array, you provide initializing values
which are enclosed within curly braces in the declaration and placed following an equals sign after the
array name.
Here is an examples of initializing an array of integers.
int a[5] = {2,1,3,7,8}; this declaration initialize the given 5 elements to an array a.
int arr[]={12,32,53,14,95}; this approach works fine as long as we initialize every element in the array
arr.
int a[5]={20,30,40}; this compile time initialization is partial. In such cases, the remaining elements are
initialized to zero.
char list[10]={‘a’,’e’,’i’}; this initialize first 3 position with a,e,i. and remaining all 7 positions to NULL.
int num[3]=(30,40,50,60}; we have more initializers than the declared size, the compiler will produce an
error. It is illegal in C.
The array initialization is done is given below
int a[5] = {12, 14, 16, 17, 18};
Here 5 elements are stored in an array ‘a’. The array elements are stored sequentially in separate
locations. Reading of array elements begins from ‘0’. Array elements are called by array names followed
by the element numbers. The 5 elements are referred as
Subscripted variable a[0] refers to the first element of array a, 12 i.e. a[0]=12
Subscripted variable a[1] refers to the first element of array a, 14 i.e. a[1]=14
Subscripted variable a[2] refers to the first element of array a, 16 i.e. a[2]=16
Subscripted variable a[3] refers to the first element of array a, 17 i.e. a[3]=17
Subscripted variable a[4] refers to the first element of array a ,18 i.e. a[4]=18
If the array size is declared as 5. The elements are stored from index 0 to 4. i.e. If a[5] has been declared,
then values are stored from a[0] to a[4].
The integer enclosed in brackets is the array subscript, and its value must be in the range from
zero to one less than the number of memory cells in the array.
Page 4
1) A simple ‘C’ program on Array Initialization Example
void main()
{
int arr[5],i;
clrscr();
arr[0]=10;
arr[1]=20;
arr[2]=30;
arr[3]=40;
arr[4]=50;
printf("Value in array arr[0] : %dn",arr[0]);
printf("Value in array arr[1] : %dn",arr[1]);
printf("Value in array arr[2] : %dn",arr[2]);
printf("Value in array arr[3] : %dn",arr[3]);
printf("Value in array arr[4] : %dn",arr[4]);
printf("n");
for(i=0;i<5;i++)
{
printf("Value in array arr[%d] : %dn",i,arr[i]);
}
}
Run time initialization:
An array can be explicitly initialized at run time. This approach is usually applied for initializing large
arrays. For example, consider the following segment of a C program.
-----------------
-----------------
for(i=0 ; i<10 ; i++)
a[i]=0;
The above runtime for loop statement initializes 0 to all 0-9 subscripts values of an array a[] , when the
program execution takes place.
Accessing Array Element from one-dimensional array:
Page 5
You can access array elements via indexes like array_name[index].
Indexes of array starts from 0 not 1 so the highest elements of an array is array_name[size-1]
In C, arrays are zero-based: the ten elements of a 10-element array are numbered from 0 to 9.
The subscript which specifies a single element of an array is simply an integer expression in square
brackets. The first element of the array is a[0], the second element is a[1], etc. You can use these ``array
subscript expressions'' anywhere you can use the name of a simple variable, for example:
a[0] = 10;
a[1] = 20;
a[2] = a[0] + a[1];
We can access all the elements of an array with the following statements:
when we wanted to do something with a (such as print it out), the loop would run from 0 to n, where n is
not greater than the array size. (or whatever a's size was):
for(i = 0; i < n; i = i + 1)
printf("%dn", a[i]);
Sample Programs
/*A simple ‘C’ program to demonstrate the Runtime initialization and use of an array. */
main()
{
int i[10],j;
for ( j=0 ; j<10 ; j++)
i[j] = j ;
for ( j=0 ; j<10 ; j++)
printf("%d" , i[j]) ;
}
The above programs prints the output as 0 1 2 3 4 5 6 7 8 9.
1. /*Program to read an array of 10 numbers and print them */
void main()
{
int a[10],i;
clrscr();
Page 6
printf("Enter 10 values :");
for(i=0; i<10; i++)
scanf("%d",&a[i]);
printf("Given Values :");
for(i=0; i<10; i++)
printf("%3d",a[i]);
}
Output
Enter 10 values ; 21 22 23 24 25 26 27 28 29 30
Given Values : 21 22 23 24 25 26 27 28 29 30
2./* Program to calculate the sum and average of six subject marks using arrays */
void main()
{
int a[10],i,sum=0;
float avg;
clrscr();
printf("Enter 6 subject marks :");
for(i=0; i<6; i++)
{
scanf("%d",&a[i]);
sum = sum + a[i];
}
printf("Sum = %d",sum);
avg= sum/6;
printf("nAvg = %f",avg);
}
Output
Enter 6 subject marks : 50 55 60 65 70 75
Sum = 375
Avg = 62.000000
3./* Program to calculate maximum and minimum of given numbers */
void main()
{
int a[100],n,max=0,min,i;
clrscr();
printf("Enter total numbers :");
scanf("%d",&n);
printf("Enter %d numbers :",n);
for(i=0; i<n; i++)
{
scanf("%d",&a[i]);
}
for(i=0; i<n; i++)
{
if(max<a[i])
max = a[i];
}
printf("Maximum Number = %d",max);
min=a[0];
for(i=0; i<n; i++)
Page 7
{
if(min>a[i])
min = a[i];
}
printf("nMinimum Number = %d",min);
}
Output
Enter total numbers : 5
Enter 5 numbers : 16 32 03 15 12
Maximum Number = 32
Minimum Number = 36
Two Dimensional Arrays :
The array which is used to represent and store data in a tabular form is called as 'two
dimensional array.' Such type of array specially used to represent data in a matrix form.
The following syntax is used to represent two dimensional array.
Syntax:
<data-type> <array_name> [row_subscript][column-subscript];
Example:
int a[3][3];
In above example, a is an array of type integer which has storage size of 3 * 3 matrix. The total size
would be 3 * 3 * 2 = 18 bytes.
It is also called as 'multidimensional array.'
* Memory Allocation :
Fig : Memory allocation for two dimensional array
Initializing the Two-Dimensional arrays:
Compile time initializing of two-dimensional array:
Page 8
We can initialize this 2D-array by writing:
int theArray[5][3] = { 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15 };
we can group the initializations with braces, as in the following example:
int theArray[5][3] = { {1,2,3},{4,5,6},{7,8,9},{10,11,12},{13,14,15} };
The compiler ignores the inner braces, which make it easier to understand how the numbers
are distributed. Each value must be separated by a comma, without regard to the braces. The entire
initialization set must be within braces, and it must end with a semicolon.
Int table[2][3]={ {1,1},(2}}; in this initialization the missing values are automatically set to 0.
All the elements can be initialized to zero by the following declaration:
Int m[3][5]={ {0},{0},{0}};
Runtime initialization of Two-Dimensional Arrays:
An two-dimensional array can be explicitly initialized at run time. This approach is usually applied for
initializing large arrays. For example, consider the following segment of a C program.
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
{
scanf("%d",&a[i][j]); //read 3*3 array
}
}
In this initialization the scanf functions reads the array elements in in a[][] by using two for loop
statements, and i,j are two subscripts of array a.
/*Program to demonstrate two dimensional array.*/
#include <stdio.h>
#include <conio.h>
void main()
{
int a[3][3], i, j;
clrscr();
printf("nt Enter matrix of 3*3 : ");
for(i=0; i<3; i++)
{
Page 9
for(j=0; j<3; j++)
{
scanf("%d",&a[i][j]); //read 3*3 array
}
}
printf("nt Matrix is : n");
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
{
printf("t %d",a[i][j]); //print 3*3 array
}
printf("n");
}
getch();
}
Output :
Enter matrix of 3*3 : 3 4 5 6 7 2 1 2 3
Matrix is :
3 4 5
6 7 2
1 2 3
/* Program to read elements of two-dimensional array and print them in matrix format*/
void main()
{
int a[3][2],i,j;
clrscr();
printf("Enter elements of 3x2 matrix :");
for(i=0; i<3; i++)
{
for(j=0; j<2; j++)
{
scanf("%d",&a[i][j]);
}
}
printf("Given Elements are :n");
for(i=0; i<3; i++)
{
for(j=0; j<2; j++)
{
printf("%3d",a[i][j]);
}
printf("n");
Page 10
}
}
Output
Enter elements of 3x2 matrix : 1 5 2 6 3 7
Given elements
1 5
2 6
3 7
/* Program to perform addition and subtraction of two matrices*/
void main()
{
int a[3][2],b[3][2],c[3][2],d[3][2],i,j;
clrscr();
printf("Enter elements of 3x2 matrix A:");
for(i=0; i<3; i++)
{
for(j=0; j<2; j++)
{
scanf("%d",&a[i][j]);
}
}
printf("Enter elements of 3x2 matrix B:");
for(i=0; i<3; i++)
{
for(j=0; j<2; j++)
{
scanf("%d",&b[i][j]);
}
}
for(i=0; i<3; i++)
{
for(j=0; j<2; j++)
{
c[i][j] = a[i][j] + b[i][j];
d[i][j] = a[i][j] - b[i][j];
}
}
printf("Resultant Sum Matrix :n");
for(i=0; i<3; i++)
{
for(j=0; j<2; j++)
{
printf("%3d",c[i][j]);
}
printf("n");
}
printf("Resultant Diff. Matrix :n");
for(i=0; i<3; i++)
{
for(j=0; j<2; j++)
Page 11
{
printf("%3d",d[i][j]);
}
printf("n");
}
}
Output
Enter elements of 3x2 matrix A : 1 2 3 4 5 6
Enter elements of 3x2 matrix B : 7 8 9 0 1 2
Resultant Sum Matrix :
8 10
12 4
6 7
Resultant Diff. Matrix ;
-6 -6
-6 4
4 4
/* Program to perform multiplication of two matrices*/
void main()
{
int a[3][2],b[2][3],c[3][3],i,j,k;
clrscr();
printf("Enter elements of 3x2 matrix A:");
for(i=0; i<3; i++)
{
for(j=0; j<2; j++)
{
scanf("%d",&a[i][j]);
}
}
printf("Enter elements of 2x3 matrix B:");
for(i=0; i<2; i++)
{
for(j=0; j<3; j++)
{
scanf("%d",&b[i][j]);
}
}
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
{
c[i][j]=0;
for(k=0; k<2; k++)
{
c[i][j] =c[i][j] + (a[i][k] * b[k][j]);
}
Page 12
}
}
printf("Resultant Product Matrix :n");
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
{
printf("%3d",c[i][j]);
}
printf("n");
}
}
Output
Enter elements of 3x2 matrix A : 1 2 3 4 5 6
Enter elements of 2x3 matrix B : 1 2 3 4 5 6
Resultant Product Matrix :
9 12 15
19 26 33
29 40 51
/* Program to check whether given matrix is symmetric or not*/
void main()
{
int a[3][3],b[3][3],i,j,count=0;
clrscr();
printf("Enter elements of 3x3 matrix :");
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
{
scanf("%d",&a[i][j]);
}
}
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
{
b[i][j]=a[j][i];
}
}
printf("Transpose of matrix :n");
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
{
printf("%3d",b[i][j]);
}
Page 13
printf("n");
}
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
{
if(a[i][j] == b[i][j])
count++;
}
}
if(count == 9)
printf("Symmetric Matrix");
else
printf("Non Symmetric Matrix");
}
Output
Enter elements of 3x3 matrix : 1 2 3 2 3 4 3 4 5
Transpose of matrix :
1 2 3
2 3 4
3 4 5
Symmetric Matrix
Page 14
Multidimensional Arrays
Multidimensional arrays have three, four or more dimensions. The first dimension is called plane,
which consists of rows and columns. Arrays of four or more dimensions can be created and used, but
difficult to draw.
Three-dimensional array can be defined as array of two-dimensional arrays. In other words, it is
an array of arrays of array.
Declaration:
int a[2][3][4];
Here2 indicates a plane consisting of 3 rows and 4 columns
Initialization
int a[2][3][4] = {
{
{0,1,2,3},
{4,5,6,7},
{8,9,10,11}
},
{
{12,13,14,15},
{16,17,18,19},
{20,22,23,24}
}
};

Mais conteúdo relacionado

Mais procurados (20)

arrays and pointers
arrays and pointersarrays and pointers
arrays and pointers
 
Java: Introduction to Arrays
Java: Introduction to ArraysJava: Introduction to Arrays
Java: Introduction to Arrays
 
Passing an Array to a Function (ICT Programming)
Passing an Array to a Function (ICT Programming)Passing an Array to a Function (ICT Programming)
Passing an Array to a Function (ICT Programming)
 
Array and string
Array and stringArray and string
Array and string
 
1 D Arrays in C++
1 D Arrays in C++1 D Arrays in C++
1 D Arrays in C++
 
Arrays
ArraysArrays
Arrays
 
One dimensional arrays
One dimensional arraysOne dimensional arrays
One dimensional arrays
 
02 c++ Array Pointer
02 c++ Array Pointer02 c++ Array Pointer
02 c++ Array Pointer
 
Array in c
Array in cArray in c
Array in c
 
Arrays
ArraysArrays
Arrays
 
Array Of Pointers
Array Of PointersArray Of Pointers
Array Of Pointers
 
arrays in c
arrays in carrays in c
arrays in c
 
Arrays in c
Arrays in cArrays in c
Arrays in c
 
Arrays and Strings
Arrays and Strings Arrays and Strings
Arrays and Strings
 
function, storage class and array and strings
 function, storage class and array and strings function, storage class and array and strings
function, storage class and array and strings
 
C++ lecture 04
C++ lecture 04C++ lecture 04
C++ lecture 04
 
Array
ArrayArray
Array
 
C Programming Unit-3
C Programming Unit-3C Programming Unit-3
C Programming Unit-3
 
Array
ArrayArray
Array
 
Array data structure
Array data structureArray data structure
Array data structure
 

Semelhante a Arrays-Computer programming

Semelhante a Arrays-Computer programming (20)

Introduction to Arrays in C
Introduction to Arrays in CIntroduction to Arrays in C
Introduction to Arrays in C
 
02 arrays
02 arrays02 arrays
02 arrays
 
Array and its types and it's implemented programming Final.pdf
Array and its types and it's implemented programming Final.pdfArray and its types and it's implemented programming Final.pdf
Array and its types and it's implemented programming Final.pdf
 
Programming in c Arrays
Programming in c ArraysProgramming in c Arrays
Programming in c Arrays
 
Arrays
ArraysArrays
Arrays
 
Arrays In C
Arrays In CArrays In C
Arrays In C
 
CP Handout#7
CP Handout#7CP Handout#7
CP Handout#7
 
Arrays & Strings
Arrays & StringsArrays & Strings
Arrays & Strings
 
ARRAYS
ARRAYSARRAYS
ARRAYS
 
Arrays
ArraysArrays
Arrays
 
Arrays and library functions
Arrays and library functionsArrays and library functions
Arrays and library functions
 
Array&amp;string
Array&amp;stringArray&amp;string
Array&amp;string
 
Arrays in C language
Arrays in C languageArrays in C language
Arrays in C language
 
Module 4- Arrays and Strings
Module 4- Arrays and StringsModule 4- Arrays and Strings
Module 4- Arrays and Strings
 
Array.pptx
Array.pptxArray.pptx
Array.pptx
 
Homework Assignment – Array Technical DocumentWrite a technical .pdf
Homework Assignment – Array Technical DocumentWrite a technical .pdfHomework Assignment – Array Technical DocumentWrite a technical .pdf
Homework Assignment – Array Technical DocumentWrite a technical .pdf
 
Unit4 Slides
Unit4 SlidesUnit4 Slides
Unit4 Slides
 
2 arrays
2   arrays2   arrays
2 arrays
 
Arrays_in_c++.pptx
Arrays_in_c++.pptxArrays_in_c++.pptx
Arrays_in_c++.pptx
 
Array
ArrayArray
Array
 

Mais de nmahi96

Matlab lab manual
Matlab lab manualMatlab lab manual
Matlab lab manualnmahi96
 
Heat transfer(HT) lab manual
Heat transfer(HT) lab manualHeat transfer(HT) lab manual
Heat transfer(HT) lab manualnmahi96
 
Personal Survival Techniques(PST)
Personal Survival Techniques(PST)Personal Survival Techniques(PST)
Personal Survival Techniques(PST)nmahi96
 
Personal Survival and Social Responsibilities(PSSR)
Personal Survival and Social Responsibilities(PSSR)Personal Survival and Social Responsibilities(PSSR)
Personal Survival and Social Responsibilities(PSSR)nmahi96
 
Fire prevention and Fire Fighting(FPFF)
Fire prevention and Fire Fighting(FPFF)Fire prevention and Fire Fighting(FPFF)
Fire prevention and Fire Fighting(FPFF)nmahi96
 
Elementary First Aid(EFA)
Elementary First Aid(EFA)Elementary First Aid(EFA)
Elementary First Aid(EFA)nmahi96
 
INERT GAS SYSTEM(IG)
INERT GAS SYSTEM(IG)INERT GAS SYSTEM(IG)
INERT GAS SYSTEM(IG)nmahi96
 
Practical Marine Electrical Knowledge 2ed 1999
Practical Marine Electrical Knowledge 2ed 1999Practical Marine Electrical Knowledge 2ed 1999
Practical Marine Electrical Knowledge 2ed 1999nmahi96
 
Graduate marine engineering(GME)important questions
Graduate marine engineering(GME)important questionsGraduate marine engineering(GME)important questions
Graduate marine engineering(GME)important questionsnmahi96
 
FEA intro patran_nastran
FEA intro patran_nastranFEA intro patran_nastran
FEA intro patran_nastrannmahi96
 
Ansys beam problem
Ansys beam problemAnsys beam problem
Ansys beam problemnmahi96
 
Screw thread measurement
Screw thread measurementScrew thread measurement
Screw thread measurementnmahi96
 
Optical measuring instruments
Optical measuring instrumentsOptical measuring instruments
Optical measuring instrumentsnmahi96
 
Tolerance and Fits
Tolerance and FitsTolerance and Fits
Tolerance and Fitsnmahi96
 
Ignition system
Ignition systemIgnition system
Ignition systemnmahi96
 
Clutch system
Clutch systemClutch system
Clutch systemnmahi96
 
Braking system
Braking systemBraking system
Braking systemnmahi96
 

Mais de nmahi96 (20)

Matlab lab manual
Matlab lab manualMatlab lab manual
Matlab lab manual
 
Heat transfer(HT) lab manual
Heat transfer(HT) lab manualHeat transfer(HT) lab manual
Heat transfer(HT) lab manual
 
STSDSD
STSDSDSTSDSD
STSDSD
 
Personal Survival Techniques(PST)
Personal Survival Techniques(PST)Personal Survival Techniques(PST)
Personal Survival Techniques(PST)
 
Personal Survival and Social Responsibilities(PSSR)
Personal Survival and Social Responsibilities(PSSR)Personal Survival and Social Responsibilities(PSSR)
Personal Survival and Social Responsibilities(PSSR)
 
Fire prevention and Fire Fighting(FPFF)
Fire prevention and Fire Fighting(FPFF)Fire prevention and Fire Fighting(FPFF)
Fire prevention and Fire Fighting(FPFF)
 
Elementary First Aid(EFA)
Elementary First Aid(EFA)Elementary First Aid(EFA)
Elementary First Aid(EFA)
 
INERT GAS SYSTEM(IG)
INERT GAS SYSTEM(IG)INERT GAS SYSTEM(IG)
INERT GAS SYSTEM(IG)
 
Practical Marine Electrical Knowledge 2ed 1999
Practical Marine Electrical Knowledge 2ed 1999Practical Marine Electrical Knowledge 2ed 1999
Practical Marine Electrical Knowledge 2ed 1999
 
Sensors
SensorsSensors
Sensors
 
Graduate marine engineering(GME)important questions
Graduate marine engineering(GME)important questionsGraduate marine engineering(GME)important questions
Graduate marine engineering(GME)important questions
 
FEA intro patran_nastran
FEA intro patran_nastranFEA intro patran_nastran
FEA intro patran_nastran
 
Ansys beam problem
Ansys beam problemAnsys beam problem
Ansys beam problem
 
Ansys
Ansys Ansys
Ansys
 
Screw thread measurement
Screw thread measurementScrew thread measurement
Screw thread measurement
 
Optical measuring instruments
Optical measuring instrumentsOptical measuring instruments
Optical measuring instruments
 
Tolerance and Fits
Tolerance and FitsTolerance and Fits
Tolerance and Fits
 
Ignition system
Ignition systemIgnition system
Ignition system
 
Clutch system
Clutch systemClutch system
Clutch system
 
Braking system
Braking systemBraking system
Braking system
 

Último

Thermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VThermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VDineshKumar4165
 
Unleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leapUnleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leapRishantSharmaFr
 
Thermal Engineering Unit - I & II . ppt
Thermal Engineering  Unit - I & II . pptThermal Engineering  Unit - I & II . ppt
Thermal Engineering Unit - I & II . pptDineshKumar4165
 
"Lesotho Leaps Forward: A Chronicle of Transformative Developments"
"Lesotho Leaps Forward: A Chronicle of Transformative Developments""Lesotho Leaps Forward: A Chronicle of Transformative Developments"
"Lesotho Leaps Forward: A Chronicle of Transformative Developments"mphochane1998
 
Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...
Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...
Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...Call Girls Mumbai
 
A Study of Urban Area Plan for Pabna Municipality
A Study of Urban Area Plan for Pabna MunicipalityA Study of Urban Area Plan for Pabna Municipality
A Study of Urban Area Plan for Pabna MunicipalityMorshed Ahmed Rahath
 
Standard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power PlayStandard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power PlayEpec Engineered Technologies
 
Block diagram reduction techniques in control systems.ppt
Block diagram reduction techniques in control systems.pptBlock diagram reduction techniques in control systems.ppt
Block diagram reduction techniques in control systems.pptNANDHAKUMARA10
 
A CASE STUDY ON CERAMIC INDUSTRY OF BANGLADESH.pptx
A CASE STUDY ON CERAMIC INDUSTRY OF BANGLADESH.pptxA CASE STUDY ON CERAMIC INDUSTRY OF BANGLADESH.pptx
A CASE STUDY ON CERAMIC INDUSTRY OF BANGLADESH.pptxmaisarahman1
 
NO1 Top No1 Amil Baba In Azad Kashmir, Kashmir Black Magic Specialist Expert ...
NO1 Top No1 Amil Baba In Azad Kashmir, Kashmir Black Magic Specialist Expert ...NO1 Top No1 Amil Baba In Azad Kashmir, Kashmir Black Magic Specialist Expert ...
NO1 Top No1 Amil Baba In Azad Kashmir, Kashmir Black Magic Specialist Expert ...Amil baba
 
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXssuser89054b
 
Online food ordering system project report.pdf
Online food ordering system project report.pdfOnline food ordering system project report.pdf
Online food ordering system project report.pdfKamal Acharya
 
HAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKAR
HAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKARHAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKAR
HAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKARKOUSTAV SARKAR
 
Moment Distribution Method For Btech Civil
Moment Distribution Method For Btech CivilMoment Distribution Method For Btech Civil
Moment Distribution Method For Btech CivilVinayVitekari
 
Work-Permit-Receiver-in-Saudi-Aramco.pptx
Work-Permit-Receiver-in-Saudi-Aramco.pptxWork-Permit-Receiver-in-Saudi-Aramco.pptx
Work-Permit-Receiver-in-Saudi-Aramco.pptxJuliansyahHarahap1
 
Employee leave management system project.
Employee leave management system project.Employee leave management system project.
Employee leave management system project.Kamal Acharya
 
Engineering Drawing focus on projection of planes
Engineering Drawing focus on projection of planesEngineering Drawing focus on projection of planes
Engineering Drawing focus on projection of planesRAJNEESHKUMAR341697
 
data_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfdata_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfJiananWang21
 

Último (20)

Thermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VThermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - V
 
Unleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leapUnleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leap
 
Thermal Engineering Unit - I & II . ppt
Thermal Engineering  Unit - I & II . pptThermal Engineering  Unit - I & II . ppt
Thermal Engineering Unit - I & II . ppt
 
"Lesotho Leaps Forward: A Chronicle of Transformative Developments"
"Lesotho Leaps Forward: A Chronicle of Transformative Developments""Lesotho Leaps Forward: A Chronicle of Transformative Developments"
"Lesotho Leaps Forward: A Chronicle of Transformative Developments"
 
Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7
Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7
Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7
 
Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...
Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...
Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...
 
A Study of Urban Area Plan for Pabna Municipality
A Study of Urban Area Plan for Pabna MunicipalityA Study of Urban Area Plan for Pabna Municipality
A Study of Urban Area Plan for Pabna Municipality
 
Standard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power PlayStandard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power Play
 
Block diagram reduction techniques in control systems.ppt
Block diagram reduction techniques in control systems.pptBlock diagram reduction techniques in control systems.ppt
Block diagram reduction techniques in control systems.ppt
 
A CASE STUDY ON CERAMIC INDUSTRY OF BANGLADESH.pptx
A CASE STUDY ON CERAMIC INDUSTRY OF BANGLADESH.pptxA CASE STUDY ON CERAMIC INDUSTRY OF BANGLADESH.pptx
A CASE STUDY ON CERAMIC INDUSTRY OF BANGLADESH.pptx
 
NO1 Top No1 Amil Baba In Azad Kashmir, Kashmir Black Magic Specialist Expert ...
NO1 Top No1 Amil Baba In Azad Kashmir, Kashmir Black Magic Specialist Expert ...NO1 Top No1 Amil Baba In Azad Kashmir, Kashmir Black Magic Specialist Expert ...
NO1 Top No1 Amil Baba In Azad Kashmir, Kashmir Black Magic Specialist Expert ...
 
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
 
Online food ordering system project report.pdf
Online food ordering system project report.pdfOnline food ordering system project report.pdf
Online food ordering system project report.pdf
 
HAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKAR
HAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKARHAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKAR
HAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKAR
 
Moment Distribution Method For Btech Civil
Moment Distribution Method For Btech CivilMoment Distribution Method For Btech Civil
Moment Distribution Method For Btech Civil
 
Work-Permit-Receiver-in-Saudi-Aramco.pptx
Work-Permit-Receiver-in-Saudi-Aramco.pptxWork-Permit-Receiver-in-Saudi-Aramco.pptx
Work-Permit-Receiver-in-Saudi-Aramco.pptx
 
Employee leave management system project.
Employee leave management system project.Employee leave management system project.
Employee leave management system project.
 
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak HamilCara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
 
Engineering Drawing focus on projection of planes
Engineering Drawing focus on projection of planesEngineering Drawing focus on projection of planes
Engineering Drawing focus on projection of planes
 
data_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfdata_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdf
 

Arrays-Computer programming

  • 1. Page 1 ARRAYS Need of an Array: The variables of fundamental data types namely char,int,float,double can store only one value at any given time. Therefore they can be used only to handle limited amounts of data. To process large amount of data , we need a powerful data type that would facilitate efficient storing, accessing and manipulation of data items. C supports a derived data type known as array that can be used for such applications. Array: An array in C language is a collection of similar data-type, means an array can hold value of a particular data type for which it has been declared. Arrays can be created from any of the C data-types int, float, and char. So an integer array can only hold integer values and cannot hold values other than integer. When we declare array, it allocates contiguous memory location for storing values whereas 2 or 3 variables of same data-type can have random locations. So this is the most important difference between a variable and an array. Array Definition: Array is a collection of variables, that can be stored in a continuous memory locations and shared a common name. (or) Array by definition is a variable that hold multiple elements which has the same data type. Arrays are of following types: • Single dimensional arrays • Double dimensional arrays • Multi-dimension arrays. Each of this array type can be of either static array or dynamic array. Static arrays have their sizes declared from the start and the size cannot be changed after declaration. Dynamic arrays that allow you to dynamically change their size at runtime, but they require more advanced techniques such as pointers and memory allocation. Single Dimension Arrays: Declaring Single Dimension Arrays Arrays can be declared using any of the data types available in C. Array size must be declared using constant value before initialization. A single dimensional array will be useful for simple grouping of data that is relatively small in size.
  • 2. Page 2 We can declare an array by specifying its data type, name and the fixed number of elements the array holds between square brackets immediately following the array name. The following illustrates how to declare an array: data_type array_name[size]; For example, to declare an array that contains 100 integer numbers you can do as follows: int a[100]; You must follow the rules below when you declare an array in C: • The data type can be any valid C data types including C structure and union. • The name of an array has to follow the rule of C variables. • The size of array has to be a positive constant integer. So far, we've been declaring simple variables: the declaration int i; Declares a single variable, named i, of type int. It is also possible to declare an array of several elements. The declaration : int a[10]; Declares an array, named a, consisting of ten elements, each of type int. Simply speaking, an array is a variable that can hold more than one value. You specify which of the several values you're referring to at any given time by using a numeric subscript OR index. (Arrays in programming are similar to vectors or matrices in mathematics.) We can represent the array a above with a picture Like this: Initializing Single dimensional Arrays: An array can be initialized at either of the flowing stages:’ • At compile time • At run time
  • 3. Page 3 Compile time initialization: It is like a variable, an array can be initialized. To initialize an array, you provide initializing values which are enclosed within curly braces in the declaration and placed following an equals sign after the array name. Here is an examples of initializing an array of integers. int a[5] = {2,1,3,7,8}; this declaration initialize the given 5 elements to an array a. int arr[]={12,32,53,14,95}; this approach works fine as long as we initialize every element in the array arr. int a[5]={20,30,40}; this compile time initialization is partial. In such cases, the remaining elements are initialized to zero. char list[10]={‘a’,’e’,’i’}; this initialize first 3 position with a,e,i. and remaining all 7 positions to NULL. int num[3]=(30,40,50,60}; we have more initializers than the declared size, the compiler will produce an error. It is illegal in C. The array initialization is done is given below int a[5] = {12, 14, 16, 17, 18}; Here 5 elements are stored in an array ‘a’. The array elements are stored sequentially in separate locations. Reading of array elements begins from ‘0’. Array elements are called by array names followed by the element numbers. The 5 elements are referred as Subscripted variable a[0] refers to the first element of array a, 12 i.e. a[0]=12 Subscripted variable a[1] refers to the first element of array a, 14 i.e. a[1]=14 Subscripted variable a[2] refers to the first element of array a, 16 i.e. a[2]=16 Subscripted variable a[3] refers to the first element of array a, 17 i.e. a[3]=17 Subscripted variable a[4] refers to the first element of array a ,18 i.e. a[4]=18 If the array size is declared as 5. The elements are stored from index 0 to 4. i.e. If a[5] has been declared, then values are stored from a[0] to a[4]. The integer enclosed in brackets is the array subscript, and its value must be in the range from zero to one less than the number of memory cells in the array.
  • 4. Page 4 1) A simple ‘C’ program on Array Initialization Example void main() { int arr[5],i; clrscr(); arr[0]=10; arr[1]=20; arr[2]=30; arr[3]=40; arr[4]=50; printf("Value in array arr[0] : %dn",arr[0]); printf("Value in array arr[1] : %dn",arr[1]); printf("Value in array arr[2] : %dn",arr[2]); printf("Value in array arr[3] : %dn",arr[3]); printf("Value in array arr[4] : %dn",arr[4]); printf("n"); for(i=0;i<5;i++) { printf("Value in array arr[%d] : %dn",i,arr[i]); } } Run time initialization: An array can be explicitly initialized at run time. This approach is usually applied for initializing large arrays. For example, consider the following segment of a C program. ----------------- ----------------- for(i=0 ; i<10 ; i++) a[i]=0; The above runtime for loop statement initializes 0 to all 0-9 subscripts values of an array a[] , when the program execution takes place. Accessing Array Element from one-dimensional array:
  • 5. Page 5 You can access array elements via indexes like array_name[index]. Indexes of array starts from 0 not 1 so the highest elements of an array is array_name[size-1] In C, arrays are zero-based: the ten elements of a 10-element array are numbered from 0 to 9. The subscript which specifies a single element of an array is simply an integer expression in square brackets. The first element of the array is a[0], the second element is a[1], etc. You can use these ``array subscript expressions'' anywhere you can use the name of a simple variable, for example: a[0] = 10; a[1] = 20; a[2] = a[0] + a[1]; We can access all the elements of an array with the following statements: when we wanted to do something with a (such as print it out), the loop would run from 0 to n, where n is not greater than the array size. (or whatever a's size was): for(i = 0; i < n; i = i + 1) printf("%dn", a[i]); Sample Programs /*A simple ‘C’ program to demonstrate the Runtime initialization and use of an array. */ main() { int i[10],j; for ( j=0 ; j<10 ; j++) i[j] = j ; for ( j=0 ; j<10 ; j++) printf("%d" , i[j]) ; } The above programs prints the output as 0 1 2 3 4 5 6 7 8 9. 1. /*Program to read an array of 10 numbers and print them */ void main() { int a[10],i; clrscr();
  • 6. Page 6 printf("Enter 10 values :"); for(i=0; i<10; i++) scanf("%d",&a[i]); printf("Given Values :"); for(i=0; i<10; i++) printf("%3d",a[i]); } Output Enter 10 values ; 21 22 23 24 25 26 27 28 29 30 Given Values : 21 22 23 24 25 26 27 28 29 30 2./* Program to calculate the sum and average of six subject marks using arrays */ void main() { int a[10],i,sum=0; float avg; clrscr(); printf("Enter 6 subject marks :"); for(i=0; i<6; i++) { scanf("%d",&a[i]); sum = sum + a[i]; } printf("Sum = %d",sum); avg= sum/6; printf("nAvg = %f",avg); } Output Enter 6 subject marks : 50 55 60 65 70 75 Sum = 375 Avg = 62.000000 3./* Program to calculate maximum and minimum of given numbers */ void main() { int a[100],n,max=0,min,i; clrscr(); printf("Enter total numbers :"); scanf("%d",&n); printf("Enter %d numbers :",n); for(i=0; i<n; i++) { scanf("%d",&a[i]); } for(i=0; i<n; i++) { if(max<a[i]) max = a[i]; } printf("Maximum Number = %d",max); min=a[0]; for(i=0; i<n; i++)
  • 7. Page 7 { if(min>a[i]) min = a[i]; } printf("nMinimum Number = %d",min); } Output Enter total numbers : 5 Enter 5 numbers : 16 32 03 15 12 Maximum Number = 32 Minimum Number = 36 Two Dimensional Arrays : The array which is used to represent and store data in a tabular form is called as 'two dimensional array.' Such type of array specially used to represent data in a matrix form. The following syntax is used to represent two dimensional array. Syntax: <data-type> <array_name> [row_subscript][column-subscript]; Example: int a[3][3]; In above example, a is an array of type integer which has storage size of 3 * 3 matrix. The total size would be 3 * 3 * 2 = 18 bytes. It is also called as 'multidimensional array.' * Memory Allocation : Fig : Memory allocation for two dimensional array Initializing the Two-Dimensional arrays: Compile time initializing of two-dimensional array:
  • 8. Page 8 We can initialize this 2D-array by writing: int theArray[5][3] = { 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15 }; we can group the initializations with braces, as in the following example: int theArray[5][3] = { {1,2,3},{4,5,6},{7,8,9},{10,11,12},{13,14,15} }; The compiler ignores the inner braces, which make it easier to understand how the numbers are distributed. Each value must be separated by a comma, without regard to the braces. The entire initialization set must be within braces, and it must end with a semicolon. Int table[2][3]={ {1,1},(2}}; in this initialization the missing values are automatically set to 0. All the elements can be initialized to zero by the following declaration: Int m[3][5]={ {0},{0},{0}}; Runtime initialization of Two-Dimensional Arrays: An two-dimensional array can be explicitly initialized at run time. This approach is usually applied for initializing large arrays. For example, consider the following segment of a C program. for(i=0; i<3; i++) { for(j=0; j<3; j++) { scanf("%d",&a[i][j]); //read 3*3 array } } In this initialization the scanf functions reads the array elements in in a[][] by using two for loop statements, and i,j are two subscripts of array a. /*Program to demonstrate two dimensional array.*/ #include <stdio.h> #include <conio.h> void main() { int a[3][3], i, j; clrscr(); printf("nt Enter matrix of 3*3 : "); for(i=0; i<3; i++) {
  • 9. Page 9 for(j=0; j<3; j++) { scanf("%d",&a[i][j]); //read 3*3 array } } printf("nt Matrix is : n"); for(i=0; i<3; i++) { for(j=0; j<3; j++) { printf("t %d",a[i][j]); //print 3*3 array } printf("n"); } getch(); } Output : Enter matrix of 3*3 : 3 4 5 6 7 2 1 2 3 Matrix is : 3 4 5 6 7 2 1 2 3 /* Program to read elements of two-dimensional array and print them in matrix format*/ void main() { int a[3][2],i,j; clrscr(); printf("Enter elements of 3x2 matrix :"); for(i=0; i<3; i++) { for(j=0; j<2; j++) { scanf("%d",&a[i][j]); } } printf("Given Elements are :n"); for(i=0; i<3; i++) { for(j=0; j<2; j++) { printf("%3d",a[i][j]); } printf("n");
  • 10. Page 10 } } Output Enter elements of 3x2 matrix : 1 5 2 6 3 7 Given elements 1 5 2 6 3 7 /* Program to perform addition and subtraction of two matrices*/ void main() { int a[3][2],b[3][2],c[3][2],d[3][2],i,j; clrscr(); printf("Enter elements of 3x2 matrix A:"); for(i=0; i<3; i++) { for(j=0; j<2; j++) { scanf("%d",&a[i][j]); } } printf("Enter elements of 3x2 matrix B:"); for(i=0; i<3; i++) { for(j=0; j<2; j++) { scanf("%d",&b[i][j]); } } for(i=0; i<3; i++) { for(j=0; j<2; j++) { c[i][j] = a[i][j] + b[i][j]; d[i][j] = a[i][j] - b[i][j]; } } printf("Resultant Sum Matrix :n"); for(i=0; i<3; i++) { for(j=0; j<2; j++) { printf("%3d",c[i][j]); } printf("n"); } printf("Resultant Diff. Matrix :n"); for(i=0; i<3; i++) { for(j=0; j<2; j++)
  • 11. Page 11 { printf("%3d",d[i][j]); } printf("n"); } } Output Enter elements of 3x2 matrix A : 1 2 3 4 5 6 Enter elements of 3x2 matrix B : 7 8 9 0 1 2 Resultant Sum Matrix : 8 10 12 4 6 7 Resultant Diff. Matrix ; -6 -6 -6 4 4 4 /* Program to perform multiplication of two matrices*/ void main() { int a[3][2],b[2][3],c[3][3],i,j,k; clrscr(); printf("Enter elements of 3x2 matrix A:"); for(i=0; i<3; i++) { for(j=0; j<2; j++) { scanf("%d",&a[i][j]); } } printf("Enter elements of 2x3 matrix B:"); for(i=0; i<2; i++) { for(j=0; j<3; j++) { scanf("%d",&b[i][j]); } } for(i=0; i<3; i++) { for(j=0; j<3; j++) { c[i][j]=0; for(k=0; k<2; k++) { c[i][j] =c[i][j] + (a[i][k] * b[k][j]); }
  • 12. Page 12 } } printf("Resultant Product Matrix :n"); for(i=0; i<3; i++) { for(j=0; j<3; j++) { printf("%3d",c[i][j]); } printf("n"); } } Output Enter elements of 3x2 matrix A : 1 2 3 4 5 6 Enter elements of 2x3 matrix B : 1 2 3 4 5 6 Resultant Product Matrix : 9 12 15 19 26 33 29 40 51 /* Program to check whether given matrix is symmetric or not*/ void main() { int a[3][3],b[3][3],i,j,count=0; clrscr(); printf("Enter elements of 3x3 matrix :"); for(i=0; i<3; i++) { for(j=0; j<3; j++) { scanf("%d",&a[i][j]); } } for(i=0; i<3; i++) { for(j=0; j<3; j++) { b[i][j]=a[j][i]; } } printf("Transpose of matrix :n"); for(i=0; i<3; i++) { for(j=0; j<3; j++) { printf("%3d",b[i][j]); }
  • 13. Page 13 printf("n"); } for(i=0; i<3; i++) { for(j=0; j<3; j++) { if(a[i][j] == b[i][j]) count++; } } if(count == 9) printf("Symmetric Matrix"); else printf("Non Symmetric Matrix"); } Output Enter elements of 3x3 matrix : 1 2 3 2 3 4 3 4 5 Transpose of matrix : 1 2 3 2 3 4 3 4 5 Symmetric Matrix
  • 14. Page 14 Multidimensional Arrays Multidimensional arrays have three, four or more dimensions. The first dimension is called plane, which consists of rows and columns. Arrays of four or more dimensions can be created and used, but difficult to draw. Three-dimensional array can be defined as array of two-dimensional arrays. In other words, it is an array of arrays of array. Declaration: int a[2][3][4]; Here2 indicates a plane consisting of 3 rows and 4 columns Initialization int a[2][3][4] = { { {0,1,2,3}, {4,5,6,7}, {8,9,10,11} }, { {12,13,14,15}, {16,17,18,19}, {20,22,23,24} } };