SlideShare a Scribd company logo
1 of 5
Download to read offline
1
r
":j~" ~ C - Arrays v
~
C programming language provides a data structure called the array, which can store a fixed-size
sequential collection of elements of the same type. An array is lLsed to store a collection of data,
but it is often more useful to think ofan anay as a collection of variables of the same type.
Instead of declaring individual variables, such as numberO, numberl, .... and number99, you
declare one array variable such as numbers and lLse numbers[O], numbers[l], and ...,
numbers[99] to represent individual variables. A specific element in an anay is accessed by an
index.
All arrays consist of contiguous memory locations. The lowest address corresponds to the first
element and the highest address to the last element.
First Element last Eleme.nt
Numbers[OI Numbers{11 Numbers[21 Numbers(3)
Declaring Arrays
To declare an array in C, a programmer specifies the type of the elements and the number of
elements required by an array as follows:
type arrayName [ arraySize ];
This is called a single-dimensional array. The :lrraySize must be an integer constant greater than
./.crv and type can be any valid C data type. ror example, to declare a 10-element array called
balance oftype double, use this statement:
double balance[IO];
Now balance is avariable array which is sufficient to hold upto 10 double numbers.
Initializing Arrays
You em! initialize array in C either one by one or using a single statement as follows:
double balm!ce[5] = {I 000.0, 2.0, 3.4, 17.0, 50.0};
The number of values between braces { } can not be larger than the number of elements that we
declm'c for the anay between square brackets [ ]. Following is an example to assign a single
element ofthe array:
If you omit the size of the array. an array just big enough to hold the initialization is created.
Therefore, if you write:
double balance[] = {l000.0, 2.0, 3.4,17.0,50.0);
You will create exactly the same array as you did in the previolls example.
I I
Multi-dimensional Arrays in C
C programming language allows multidimensional arrays. Here is the general foml of a
multidimensional array declaration:
type name[size1] [size2] . .. [sizeN] ;
For example, the following declaration creates a three dimensional 5. 10.4 integer array:
int threedim[5] [10] [4];
Two-Dimensional Arrays:
The simplest form ofthe multidimensional array is the two-dimensional array. A two-
dimensional array is, in essence. a list of one-dimensional alTays. To declare a two-dimensional
integer array of size x.y you would write something as follows:
type arrayName [ x ] [ y ] ;
Where type can be any valid C data type and arrayName will be a valid C identitier. A two-
dimensional array can be think as a table which will have x number of rows and y number of
columns. A 2-dimensional array a, which contains three rows and four colwnns can be shown as
below:
Column 0 Column 1 Column 2 Column 3
Row 0 a[ 0 ][ 0 ) a[ 0 )[ 1 ) a[ 0 )[ 2] a( 0 ][ 3]
Row 1 a[ 1 ]( 0 ] a[ 1 ]( 1 ) a[ 1 ]( 2 J a[ 1 ]( 3]
Row 2 a[2](O) a[ 2 ][ 1 1 a[ 2 ][ 2 ) a[ 2 )[ 3 1
Thus, every element in array a is identified by an element name of the fonn at i )[ j ), where a is
the nanle of the array. and i and j are the subscripts that uniquely identify each element in a.
Initializing Two-Dimensional Arrays:
Multidimensional arrays may be initialized by specifying bracketed values for each row.
Following is an array with 3 rows and each row has 4 columns.
int a[3] [4] ~ {
to , 1, 2 , 3} ,
{4 , 5 , 6 , 7},
{S , 9 , 10 , ll}
} ;
/* initializers for row indexed by 0 */
/* initializers for row indexed by 1 ./
1* initializers for row indexed by 2 */
The nested braces, which indicate the intended row, are optional. The following initialization is
equivalent to previous example:
int a[3][ 4] ~ {O ,1, 2 , 3 ,4, 5 , 6 , 7 , 8 , 9 , 10 , 1l} ;
balance[4] = 50.0;
The above statement assigns element number 5th in the array a value of 50.0. Array with 4th
index will be 5th ie. last element because all arrays have 0 as the index of their first element
which is also called base index. Following is the pictorial representation of the same array we
discussed above:
o 1 2 3 4
balance 1000.0 2.0 3.4 7.0 50.0
Accessing AlTay Elements
An element is accessed by indexing the array name. This is done by placing the index of the
element within square brackets after the name of the array. For example:
double salary = balance[9];
The above statement will take 10th element from the array and assign the value to salary
variable. Following is an example which will use all the above mentioned three concepts viz.
declaration, assignment and accessing arrays:
#include <stdio.h>
int main 0
{
int n[ 10 ]; /* n is an array of 10 integers */
illt i.j:
/* initialize elements of array n to 0 */
for ( i =0; i < 10; i++ )
{
n[ i ] =i + 100; /* set element at location i to i + 100 */
}
/* output each array element's value */
for (j =0; j < 10; j++ )
{
printf("Element[%d] = %dn", j, n[j] );
}
return 0:
,
...,,
, J
When the above code is compiled and executed, it produces the following result:
Elemcnt[O] = 100
Element[l] = 101
Element[2] =102
Element[3] = 103
Element[4] = 104
Element[5] = 105
Element[6] = 106
Element[7] =107
Element[8] = 108
Element[9] = 109
C Arrays in Detail
Arrays are important to C and should need lots of more details. There are following few
important concepts related to array which should be clear to a C programmer:
Concept
Multi-dimensional arrays
Passing arrays to functions
Return array from a
function
Pointer to an array
Description
C supports multidimensional !Ill'ays. The simplest form of the
multidimensional array is the two-dimensional array.
You can pass to the fUllction a pointer to an alTay by specifying the
array's n!lllle without !Ill index.
C allows a function to return !Ill array.
YOll C!lll generate a pointer to the first element of an array by
simply specifying the array name, without any index.
1
....
, Accessing Two-Dimensional Array Elements:
An element in 2-dimensional an'ay is accessed by using the subscripts. i.e., row index and
column index ofthe array. For example:
int val - a[21 [31 ;
The above statement will take 4th element from the 3rd row of the array. You can verify it in the
above diagram. Let us check below program where we have used nested loop to handle a two
dimensional array:
#include <stdio . h>
int main ( )
/* an array with 5 rows and 2 columns*/
int a[5][21 - ( (0 , 0) , (1,2), (2 , 4), (3 , 6) , (4 , 8)) ;
int i , j ;
/ * output each array element ' s value */
for ( i - 0 ; i < 5 ; i++ )
(
for ( j - 0; j < 2 ; j ++ )
(
printf( " a[ %d] [ %d] - %dn ", i , j , ali] [j] ) ;
return 0 ;
When the above code is compiled and executed. it produces the following result:
a [01 [01 :
°a [01 [1] : 0
a[l] [0] : 1
a [1] [1] : 2
a[2] [0] : 2
a[2][1] : 4
a [3] [0] : 3
a [3] [1] : 6
a [4] [0] : 4
a[4] [ 1] : 8
As explained above, you can have arrays with any number of dimensions. although it is likely
that most ofthe arrays you create will be ofone or two dimensions.

More Related Content

What's hot

What's hot (20)

Programming in c Arrays
Programming in c ArraysProgramming in c Arrays
Programming in c Arrays
 
Java: Introduction to Arrays
Java: Introduction to ArraysJava: Introduction to Arrays
Java: Introduction to Arrays
 
2- Dimensional Arrays
2- Dimensional Arrays2- Dimensional Arrays
2- Dimensional Arrays
 
2D Array
2D Array 2D Array
2D Array
 
Arrays in C language
Arrays in C languageArrays in C language
Arrays in C language
 
Arrays in c language
Arrays in c languageArrays in c language
Arrays in c language
 
Lecture 15 - Array
Lecture 15 - ArrayLecture 15 - Array
Lecture 15 - Array
 
1 D Arrays in C++
1 D Arrays in C++1 D Arrays in C++
1 D Arrays in C++
 
One dimensional arrays
One dimensional arraysOne dimensional arrays
One dimensional arrays
 
Arrays in c
Arrays in cArrays in c
Arrays in c
 
Two dimensional array
Two dimensional arrayTwo dimensional array
Two dimensional array
 
Arrays 1D and 2D , and multi dimensional
Arrays 1D and 2D , and multi dimensional Arrays 1D and 2D , and multi dimensional
Arrays 1D and 2D , and multi dimensional
 
Multi dimensional array
Multi dimensional arrayMulti dimensional array
Multi dimensional array
 
Programming in c arrays
Programming in c   arraysProgramming in c   arrays
Programming in c arrays
 
Multi-Dimensional Lists
Multi-Dimensional ListsMulti-Dimensional Lists
Multi-Dimensional Lists
 
Arrays in c
Arrays in cArrays in c
Arrays in c
 
Arrays in c
Arrays in cArrays in c
Arrays in c
 
Lecture 16 - Multi dimensional Array
Lecture 16 - Multi dimensional ArrayLecture 16 - Multi dimensional Array
Lecture 16 - Multi dimensional Array
 
C Programming : Arrays
C Programming : ArraysC Programming : Arrays
C Programming : Arrays
 
Two dimensional arrays
Two dimensional arraysTwo dimensional arrays
Two dimensional arrays
 

Viewers also liked

Orlando felisberto t1 903096 e fólio-a
Orlando felisberto t1 903096 e fólio-aOrlando felisberto t1 903096 e fólio-a
Orlando felisberto t1 903096 e fólio-aorlandoduarte
 
полногеномный скрининг эмбрионов методом A cgh
полногеномный скрининг эмбрионов методом A cghполногеномный скрининг эмбрионов методом A cgh
полногеномный скрининг эмбрионов методом A cghDmytro Mykytenko
 
Control presupuestario
Control presupuestarioControl presupuestario
Control presupuestariokari_96
 
Williams v. Mai II -- Published Opinion
Williams v. Mai II -- Published OpinionWilliams v. Mai II -- Published Opinion
Williams v. Mai II -- Published OpinionEric Little
 
Presentation for MEED - Copy
Presentation for MEED - CopyPresentation for MEED - Copy
Presentation for MEED - CopySenthil Kumar, S
 
Green Office Garden Services Pres4Dec16
Green Office Garden Services Pres4Dec16Green Office Garden Services Pres4Dec16
Green Office Garden Services Pres4Dec16Kevin Moriarty
 
SnapComms for Security Awareness
SnapComms for Security AwarenessSnapComms for Security Awareness
SnapComms for Security AwarenessSnapComms
 
CCTEG Drill equipment and technology
CCTEG Drill equipment and technologyCCTEG Drill equipment and technology
CCTEG Drill equipment and technologyOwen Ji
 

Viewers also liked (14)

Sesión 3
Sesión 3Sesión 3
Sesión 3
 
Orlando felisberto t1 903096 e fólio-a
Orlando felisberto t1 903096 e fólio-aOrlando felisberto t1 903096 e fólio-a
Orlando felisberto t1 903096 e fólio-a
 
полногеномный скрининг эмбрионов методом A cgh
полногеномный скрининг эмбрионов методом A cghполногеномный скрининг эмбрионов методом A cgh
полногеномный скрининг эмбрионов методом A cgh
 
Control presupuestario
Control presupuestarioControl presupuestario
Control presupuestario
 
Noorul CV
Noorul CVNoorul CV
Noorul CV
 
Williams v. Mai II -- Published Opinion
Williams v. Mai II -- Published OpinionWilliams v. Mai II -- Published Opinion
Williams v. Mai II -- Published Opinion
 
Presentation for MEED - Copy
Presentation for MEED - CopyPresentation for MEED - Copy
Presentation for MEED - Copy
 
Reina porto lopez
Reina porto lopezReina porto lopez
Reina porto lopez
 
Netradi tehnika risovaniya_-_kopiya1
Netradi tehnika risovaniya_-_kopiya1Netradi tehnika risovaniya_-_kopiya1
Netradi tehnika risovaniya_-_kopiya1
 
Verduras
VerdurasVerduras
Verduras
 
Green Office Garden Services Pres4Dec16
Green Office Garden Services Pres4Dec16Green Office Garden Services Pres4Dec16
Green Office Garden Services Pres4Dec16
 
Ecorregiones.de panama
Ecorregiones.de panamaEcorregiones.de panama
Ecorregiones.de panama
 
SnapComms for Security Awareness
SnapComms for Security AwarenessSnapComms for Security Awareness
SnapComms for Security Awareness
 
CCTEG Drill equipment and technology
CCTEG Drill equipment and technologyCCTEG Drill equipment and technology
CCTEG Drill equipment and technology
 

Similar to C Arrays in 40 (20)

Arrays and library functions
Arrays and library functionsArrays and library functions
Arrays and library functions
 
Arrays
ArraysArrays
Arrays
 
Introduction to Arrays in C
Introduction to Arrays in CIntroduction to Arrays in C
Introduction to Arrays in C
 
19-Lec - Multidimensional Arrays.ppt
19-Lec - Multidimensional Arrays.ppt19-Lec - Multidimensional Arrays.ppt
19-Lec - Multidimensional Arrays.ppt
 
Array
ArrayArray
Array
 
02 arrays
02 arrays02 arrays
02 arrays
 
Unit 6. Arrays
Unit 6. ArraysUnit 6. Arrays
Unit 6. Arrays
 
Arrays-Computer programming
Arrays-Computer programmingArrays-Computer programming
Arrays-Computer programming
 
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
 
Arrays and Strings
Arrays and Strings Arrays and Strings
Arrays and Strings
 
Chapter 13.pptx
Chapter 13.pptxChapter 13.pptx
Chapter 13.pptx
 
Unit ii data structure-converted
Unit  ii data structure-convertedUnit  ii data structure-converted
Unit ii data structure-converted
 
Arrays
ArraysArrays
Arrays
 
Arrays In C
Arrays In CArrays In C
Arrays In C
 
Data Structure Midterm Lesson Arrays
Data Structure Midterm Lesson ArraysData Structure Midterm Lesson Arrays
Data Structure Midterm Lesson 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
 
Lecture 9
Lecture 9Lecture 9
Lecture 9
 
Arrays
ArraysArrays
Arrays
 
Algo>Arrays
Algo>ArraysAlgo>Arrays
Algo>Arrays
 
Data structure array
Data structure  arrayData structure  array
Data structure array
 

Recently uploaded

Artificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxArtificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxbritheesh05
 
Application of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptxApplication of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptx959SahilShah
 
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdfCCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdfAsst.prof M.Gokilavani
 
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfAsst.prof M.Gokilavani
 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidNikhilNagaraju
 
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfCCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfAsst.prof M.Gokilavani
 
DATA ANALYTICS PPT definition usage example
DATA ANALYTICS PPT definition usage exampleDATA ANALYTICS PPT definition usage example
DATA ANALYTICS PPT definition usage examplePragyanshuParadkar1
 
complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...asadnawaz62
 
Biology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxBiology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxDeepakSakkari2
 
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)dollysharma2066
 
EduAI - E learning Platform integrated with AI
EduAI - E learning Platform integrated with AIEduAI - E learning Platform integrated with AI
EduAI - E learning Platform integrated with AIkoyaldeepu123
 
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...srsj9000
 
Risk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdfRisk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdfROCENODodongVILLACER
 
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionSachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionDr.Costas Sachpazis
 
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerStudy on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerAnamika Sarkar
 

Recently uploaded (20)

Artificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxArtificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptx
 
Application of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptxApplication of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptx
 
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdfCCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
 
POWER SYSTEMS-1 Complete notes examples
POWER SYSTEMS-1 Complete notes  examplesPOWER SYSTEMS-1 Complete notes  examples
POWER SYSTEMS-1 Complete notes examples
 
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfid
 
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfCCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
 
DATA ANALYTICS PPT definition usage example
DATA ANALYTICS PPT definition usage exampleDATA ANALYTICS PPT definition usage example
DATA ANALYTICS PPT definition usage example
 
complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...
 
Biology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxBiology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptx
 
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
 
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
 
EduAI - E learning Platform integrated with AI
EduAI - E learning Platform integrated with AIEduAI - E learning Platform integrated with AI
EduAI - E learning Platform integrated with AI
 
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCRCall Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
 
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
 
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptxExploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
 
Risk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdfRisk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdf
 
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionSachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
 
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerStudy on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
 
Design and analysis of solar grass cutter.pdf
Design and analysis of solar grass cutter.pdfDesign and analysis of solar grass cutter.pdf
Design and analysis of solar grass cutter.pdf
 

C Arrays in 40

  • 1. 1 r ":j~" ~ C - Arrays v ~ C programming language provides a data structure called the array, which can store a fixed-size sequential collection of elements of the same type. An array is lLsed to store a collection of data, but it is often more useful to think ofan anay as a collection of variables of the same type. Instead of declaring individual variables, such as numberO, numberl, .... and number99, you declare one array variable such as numbers and lLse numbers[O], numbers[l], and ..., numbers[99] to represent individual variables. A specific element in an anay is accessed by an index. All arrays consist of contiguous memory locations. The lowest address corresponds to the first element and the highest address to the last element. First Element last Eleme.nt Numbers[OI Numbers{11 Numbers[21 Numbers(3) Declaring Arrays To declare an array in C, a programmer specifies the type of the elements and the number of elements required by an array as follows: type arrayName [ arraySize ]; This is called a single-dimensional array. The :lrraySize must be an integer constant greater than ./.crv and type can be any valid C data type. ror example, to declare a 10-element array called balance oftype double, use this statement: double balance[IO]; Now balance is avariable array which is sufficient to hold upto 10 double numbers. Initializing Arrays You em! initialize array in C either one by one or using a single statement as follows: double balm!ce[5] = {I 000.0, 2.0, 3.4, 17.0, 50.0}; The number of values between braces { } can not be larger than the number of elements that we declm'c for the anay between square brackets [ ]. Following is an example to assign a single element ofthe array: If you omit the size of the array. an array just big enough to hold the initialization is created. Therefore, if you write: double balance[] = {l000.0, 2.0, 3.4,17.0,50.0); You will create exactly the same array as you did in the previolls example.
  • 2. I I Multi-dimensional Arrays in C C programming language allows multidimensional arrays. Here is the general foml of a multidimensional array declaration: type name[size1] [size2] . .. [sizeN] ; For example, the following declaration creates a three dimensional 5. 10.4 integer array: int threedim[5] [10] [4]; Two-Dimensional Arrays: The simplest form ofthe multidimensional array is the two-dimensional array. A two- dimensional array is, in essence. a list of one-dimensional alTays. To declare a two-dimensional integer array of size x.y you would write something as follows: type arrayName [ x ] [ y ] ; Where type can be any valid C data type and arrayName will be a valid C identitier. A two- dimensional array can be think as a table which will have x number of rows and y number of columns. A 2-dimensional array a, which contains three rows and four colwnns can be shown as below: Column 0 Column 1 Column 2 Column 3 Row 0 a[ 0 ][ 0 ) a[ 0 )[ 1 ) a[ 0 )[ 2] a( 0 ][ 3] Row 1 a[ 1 ]( 0 ] a[ 1 ]( 1 ) a[ 1 ]( 2 J a[ 1 ]( 3] Row 2 a[2](O) a[ 2 ][ 1 1 a[ 2 ][ 2 ) a[ 2 )[ 3 1 Thus, every element in array a is identified by an element name of the fonn at i )[ j ), where a is the nanle of the array. and i and j are the subscripts that uniquely identify each element in a. Initializing Two-Dimensional Arrays: Multidimensional arrays may be initialized by specifying bracketed values for each row. Following is an array with 3 rows and each row has 4 columns. int a[3] [4] ~ { to , 1, 2 , 3} , {4 , 5 , 6 , 7}, {S , 9 , 10 , ll} } ; /* initializers for row indexed by 0 */ /* initializers for row indexed by 1 ./ 1* initializers for row indexed by 2 */ The nested braces, which indicate the intended row, are optional. The following initialization is equivalent to previous example: int a[3][ 4] ~ {O ,1, 2 , 3 ,4, 5 , 6 , 7 , 8 , 9 , 10 , 1l} ;
  • 3. balance[4] = 50.0; The above statement assigns element number 5th in the array a value of 50.0. Array with 4th index will be 5th ie. last element because all arrays have 0 as the index of their first element which is also called base index. Following is the pictorial representation of the same array we discussed above: o 1 2 3 4 balance 1000.0 2.0 3.4 7.0 50.0 Accessing AlTay Elements An element is accessed by indexing the array name. This is done by placing the index of the element within square brackets after the name of the array. For example: double salary = balance[9]; The above statement will take 10th element from the array and assign the value to salary variable. Following is an example which will use all the above mentioned three concepts viz. declaration, assignment and accessing arrays: #include <stdio.h> int main 0 { int n[ 10 ]; /* n is an array of 10 integers */ illt i.j: /* initialize elements of array n to 0 */ for ( i =0; i < 10; i++ ) { n[ i ] =i + 100; /* set element at location i to i + 100 */ } /* output each array element's value */ for (j =0; j < 10; j++ ) { printf("Element[%d] = %dn", j, n[j] ); } return 0:
  • 4. , ...,, , J When the above code is compiled and executed, it produces the following result: Elemcnt[O] = 100 Element[l] = 101 Element[2] =102 Element[3] = 103 Element[4] = 104 Element[5] = 105 Element[6] = 106 Element[7] =107 Element[8] = 108 Element[9] = 109 C Arrays in Detail Arrays are important to C and should need lots of more details. There are following few important concepts related to array which should be clear to a C programmer: Concept Multi-dimensional arrays Passing arrays to functions Return array from a function Pointer to an array Description C supports multidimensional !Ill'ays. The simplest form of the multidimensional array is the two-dimensional array. You can pass to the fUllction a pointer to an alTay by specifying the array's n!lllle without !Ill index. C allows a function to return !Ill array. YOll C!lll generate a pointer to the first element of an array by simply specifying the array name, without any index. 1
  • 5. .... , Accessing Two-Dimensional Array Elements: An element in 2-dimensional an'ay is accessed by using the subscripts. i.e., row index and column index ofthe array. For example: int val - a[21 [31 ; The above statement will take 4th element from the 3rd row of the array. You can verify it in the above diagram. Let us check below program where we have used nested loop to handle a two dimensional array: #include <stdio . h> int main ( ) /* an array with 5 rows and 2 columns*/ int a[5][21 - ( (0 , 0) , (1,2), (2 , 4), (3 , 6) , (4 , 8)) ; int i , j ; / * output each array element ' s value */ for ( i - 0 ; i < 5 ; i++ ) ( for ( j - 0; j < 2 ; j ++ ) ( printf( " a[ %d] [ %d] - %dn ", i , j , ali] [j] ) ; return 0 ; When the above code is compiled and executed. it produces the following result: a [01 [01 : °a [01 [1] : 0 a[l] [0] : 1 a [1] [1] : 2 a[2] [0] : 2 a[2][1] : 4 a [3] [0] : 3 a [3] [1] : 6 a [4] [0] : 4 a[4] [ 1] : 8 As explained above, you can have arrays with any number of dimensions. although it is likely that most ofthe arrays you create will be ofone or two dimensions.