SlideShare una empresa de Scribd logo
1 de 5
Descargar para leer sin conexión
For more Https://www.ThesisScientist.com
Unit 6
Arrays
Introduction to Arrays
An array is a group of data items of same data type that share a common name. Ordinary variables are
capable of holding only one value at a time. If we want to store more than one value at a time in a single
variable, we use arrays.
An array is a collective name given to a group of similar variables. Each member in the group is referred to
by its position in the group.
Arrays are alloted the memory in a strictly contiguous fashion. The simplest array is one dimensional array
which is a list of variables of same data type. An array of one dimensional arrays is called a two
dimensional array.
One Dimensional Array
A list of items can be given one variable name using only one subscript and such a variable is called a one
dimensional array.
e.g.: If we want to store a set of five numbers by an array variable number. Then it will be
accomplished in the following way:
int number [5];
This declaration will reserve five contiguous memory locations as shown below:
Number [0] Number [1] Number [2] Number [3] Number [4]
As C performs no bounds checking, care should be taken to ensure that the array indices are within the
declared limits. Also, indexing in C begins from 0 and not from 1.
Array Declaration
Arrays are defined in the same manner as ordinary variables, except that each array name must be
accompanied by the size specification.
The general form of array declaration is:
data-type array-name [size];
data-type specifies the type of array, size is a positive integer number or symbolic constant that indicates
the maximum number of elements that can be stored in the array.
e.g.: float height [50];
This declaration declares an array named height containing 50 elements of type float.
NOTE The compiler will interpret first element as height [0]. As in C, the array elements are
induced for 0 to [size-1].
Array Initialization
The elements of an array can be initialized in the same way as the ordinary variables, when they are
declared. Given below are some examples which show how the arrays are initialized.
static int num [6] = {2, 4, 5, 45, 12};
static int n [ ] = {2, 4, 5, 45, 12};
static float press [ ] = {12.5, 32.4, -23.7, -11.3};
In these examples note the following points:
(a) Till the array elements are not given any specific values, they contain garbage value.
(b) If the array is initialized where it is declared, its storage class must be either static or extern. If the
storage class is static, all the elements are initialized by 0.
(c) If the array is initialized where it is declared, mentioning the dimension of the array is optional.
Accessing Elements of an Array
Once an array is declared, individual elements of the array are referred using subscript or index number.
This number specifies the element's position in the array. All the elements of the array are numbered
starting from 0. Thus number [5] is actually the sixth element of an array.
Entering Data into an Array
It can be explained by the following examples:
main( )
{
int num [6];
int count;
for (count = 0; count < 6; count ++)
{
printf ("n Enter %d element:" count+1);
scanf ("%d", &num [count]);
}
}
In this example, using the for loop, the process of asking and receiving the marks is accomplished. When
count has the value zero, the scanf( ) statement will cause the value to be stored at num [0]. This process
continues until count has the value greater than 5.
Reading Data from an Array
Consider the program given above. It has entered 6 values in the array num. Now to read values from this
array, we will again use for Loop to access each cell. The given program segment explains the retrieval of
the values from the array.
for (count = 0; count < 6; count ++)
{
printf ("n %d value =", num [count]);
}
Memory Representation of Array
Consider the following array declaration:
int arr[8];
16 bytes get immediately reserved in memory because each of the 8 integers would be 2 bytes long and
since the array is not being initialized, all eight values present in it would be garbage values.
Whatever be the initial values, all the array elements would always be present in contiguous memory
location. This arrangement of array elements in memory is shown below.
12 34 66 -45 23 346 77 98
4002 4004 4006 4008 4010 4012 4014 4016
Value
Address
1212 34 66 -45 23 346 77 98
4002 4004 4006 4008 4010 4012 4014 4016
Value
Address
In C, there is no check to see if the subscript used for an array exceeds the size of the array. Data entered
with a subscript exceeding the array size will simply be placed in memory outside the array. This will
lead to unpredictable results and there will be no error message to warn you that you are going beyond
the array size. So to see to it that you do not reach beyond the array size is entirely the programmer's
botheration and not the compiler's.
Strings
Just as a group of integers can be stored in an integer array, group of characters can be stored in a character
array or "strings". The string constant is a one dimensional array of characters terminated by null character
('0'). This null character '0' (ASCII value 0) is different from 'O' (ASCII value 48).
The terminating null character is important because it is the only way the function that works with string
can know where the string ends.
e.g.: Static char name [ ] = {'K', 'R', 'I', 'S', 'H', '0'};
This example shows the declaration and initialization of a character array. The array elements of a character
array are stored in contiguous locations with each element occupying one byte of memory.
K R I S H N A ‘0’
4001 4002 4003 4004 4005 4006 4007 4009
NOTEOTE1. Contrary to the numeric array where a 5 digit number can be stored in one array cell, in
the character arrays only a single character can be stored in one cell. So in order to
store an array of strings, a 2-dimensional array is required.
2. As scanf( ) function is not capable of receiving multi word string, such strings should be
Two Dimensional Array
This is a table of four rows and three columns. Such a table of items can be defined using two dimensional
arrays.
General form of declaring a 2-D array is
data_type array_name [row_size] [colum_size];
Initialization of a 2-Dimensional Array
Two dimensional arrays may be initialized by a list of initial values enclosed in braces following their
declaration.
e.g.: static int table [2] [3] = {0, 0, 0, 1, 1, 1};
initializes the elements of the first row to 0 and the second row to one. The initialization is done by row.
The aforesaid statement can be equivalently written as
static int table [2] [3] = {{0, 0, 0}, {1, 1, 1}};
by surrounding the elements of each row by braces.
We can also initialize a two dimensional array in the form of a matrix as shown below:
static int table [2] [3] = {{0, 0, 0},
{1, 1, 1}};
The syntax of the above statement. Commas are required after each brace that closes off a row,
except in the case of the last row.
If the values are missing in an initializer, they are automatically set to 0. For instance, the statement
static int table [2] [3] = {{1, 1},
{2}};
will initialize the first two elements of the first row to one, the first element of the second row to two, and
all the other elements to 0.
When all the elements are to be initialized to 0, the following short cut method may be used.
static int m [3] [5] = {{0}, {0}, {0}};
The first element of each row is explicitly initialized to 0 while other elements are automatically initialized
to 0.
While initializing an array, it is necessary to mention the second (column) dimension, whereas the first
dimension (row) is optional. Thus, the following declarations are acceptable.
static int arr [2] [3] = {12, 34, 23, 45, 56, 45};
static int arr [ ] [3] = {12, 34, 23, 45, 56, 45 };
Memory Representation of Two Dimensional Array
In memory, whether it is a one dimensional or a two dimensional array, the array elements are stored in one
continuous chain.
The arrangement of array elements of a two dimensional array of students, which contains roll numbers in
one column and the marks in the other (in memory) is shown below:
1234
5002 5004 5006 5008 5010 5012 5014 5016
Value
Address
1234 1234 1234 1234 1234 1234 1234
S[0][0] S[0][1] S[1][0] S[1][1] S[2][0] S[2][1] S[3][0] S[3][0]Notation
1234
5002 5004 5006 5008 5010 5012 5014 5016
Value
Address
1234 1234 1234 1234 1234 1234 1234
S[0][0] S[0][1] S[1][0] S[1][1] S[2][0] S[2][1] S[3][0] S[3][0]Notation
e.g.: 1. Program that stores roll number and marks obtained by a student side by
side in a matrix
main( )
{
int stud [4] [2];
int i, j;
for (i = 0; i < = 3; i++)
{
printf ("n Enter roll no. and marks");
scanf ("%d%d", &stud [i] [0], &stud[i] [1]);
}
for (i = 0; i < = 3; i++)
printf ("%d%dn", stud [i] [0], stud [i] [0];
}
There are two parts to the program, in the first part through a for Loop
we read in the values of roll number and marks, whereas in second part
through another for Loop we print out these values.
Multi-dimensional Array
C allows arrays of three or more dimensions. Multi-dimensional arrays are defined in much the same
manner as one-dimensional arrays, except that a separate pair of square brackets is required for each
subscript.
The general form of a multi-dimensional array is
data_type array_name [s1] [s2] [s3] . . . [sm];
e.g.: int survey [3] [5] [12];
float table [5] [4] [5] [3];
Here, survey is a 3-dimensional array declared to contain 180 integer_type elements. Similarly, table is a 4-
dimensional array containing 300 elements of floating point type.
An example of initializing a 4-dimensional array:
static int arr [3] [4] [2] = {{{2, 4}, {7, 8}, {3, 4}, {5, 6},},
{{7, 6}, {3, 4}, {5, 3}, {2, 3}, },
{{8, 9}, {7, 2}, {3, 4}, {6, 1}, }
};
In this example, the outer array has three elements, each of which is a two dimensional array of four rows,
each of which is a one dimensional array of two elements.

Más contenido relacionado

La actualidad más candente

La actualidad más candente (20)

C++ programming (Array)
C++ programming (Array)C++ programming (Array)
C++ programming (Array)
 
One dimensional 2
One dimensional 2One dimensional 2
One dimensional 2
 
Array in c++
Array in c++Array in c++
Array in c++
 
C programming , array 2020
C programming , array 2020C programming , array 2020
C programming , array 2020
 
Arrays in c
Arrays in cArrays in c
Arrays in c
 
Arrays in c
Arrays in cArrays in c
Arrays in c
 
Arrays-Computer programming
Arrays-Computer programmingArrays-Computer programming
Arrays-Computer programming
 
Array
ArrayArray
Array
 
Multi-Dimensional Lists
Multi-Dimensional ListsMulti-Dimensional Lists
Multi-Dimensional Lists
 
Arrays and Strings
Arrays and Strings Arrays and Strings
Arrays and Strings
 
Array and string
Array and stringArray and string
Array and string
 
ARRAY
ARRAYARRAY
ARRAY
 
Array
ArrayArray
Array
 
Array Introduction One-dimensional array Multidimensional array
Array Introduction One-dimensional array Multidimensional arrayArray Introduction One-dimensional array Multidimensional array
Array Introduction One-dimensional array Multidimensional array
 
Data structure array
Data structure  arrayData structure  array
Data structure array
 
Introduction to Array ppt
Introduction to Array pptIntroduction to Array ppt
Introduction to Array ppt
 
Array
ArrayArray
Array
 
Programming in c Arrays
Programming in c ArraysProgramming in c Arrays
Programming in c Arrays
 
C++ Arrays
C++ ArraysC++ Arrays
C++ Arrays
 
Data Structure and Algorithms Arrays
Data Structure and Algorithms ArraysData Structure and Algorithms Arrays
Data Structure and Algorithms Arrays
 

Similar a Introduction to Arrays in C

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
aroraopticals15
 

Similar a Introduction to Arrays in C (20)

ARRAYS
ARRAYSARRAYS
ARRAYS
 
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 library functions
Arrays and library functionsArrays and library functions
Arrays and library functions
 
Unit ii data structure-converted
Unit  ii data structure-convertedUnit  ii data structure-converted
Unit ii data structure-converted
 
Arrays
ArraysArrays
Arrays
 
Unit4 Slides
Unit4 SlidesUnit4 Slides
Unit4 Slides
 
Arrays
ArraysArrays
Arrays
 
Module 4- Arrays and Strings
Module 4- Arrays and StringsModule 4- Arrays and Strings
Module 4- Arrays and Strings
 
C (PPS)Programming for problem solving.pptx
C (PPS)Programming for problem solving.pptxC (PPS)Programming for problem solving.pptx
C (PPS)Programming for problem solving.pptx
 
Array
ArrayArray
Array
 
Array&amp;string
Array&amp;stringArray&amp;string
Array&amp;string
 
02 arrays
02 arrays02 arrays
02 arrays
 
3.ArraysandPointers.pptx
3.ArraysandPointers.pptx3.ArraysandPointers.pptx
3.ArraysandPointers.pptx
 
Arrays
ArraysArrays
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
 
Arrays
ArraysArrays
Arrays
 
Arrays
ArraysArrays
Arrays
 
C Programming Unit-3
C Programming Unit-3C Programming Unit-3
C Programming Unit-3
 
2 arrays
2   arrays2   arrays
2 arrays
 
Array in C
Array in CArray in C
Array in C
 

Más de Thesis Scientist Private Limited

Latest Thesis Topics for Fog computing
Latest Thesis Topics for Fog computingLatest Thesis Topics for Fog computing
Latest Thesis Topics for Fog computing
Thesis Scientist Private Limited
 

Más de Thesis Scientist Private Limited (20)

HTML guide for beginners
HTML guide for beginnersHTML guide for beginners
HTML guide for beginners
 
Ransomware attacks 2017
Ransomware attacks 2017Ransomware attacks 2017
Ransomware attacks 2017
 
How to write a Great Research Paper?
How to write a Great Research Paper?How to write a Great Research Paper?
How to write a Great Research Paper?
 
Research Process design
Research Process designResearch Process design
Research Process design
 
How to write a good Dissertation/ Thesis
How to write a good Dissertation/ ThesisHow to write a good Dissertation/ Thesis
How to write a good Dissertation/ Thesis
 
How to write a Research Paper
How to write a Research PaperHow to write a Research Paper
How to write a Research Paper
 
Internet security tips for Businesses
Internet security tips for BusinessesInternet security tips for Businesses
Internet security tips for Businesses
 
How to deal with a Compulsive liar
How to deal with a Compulsive liarHow to deal with a Compulsive liar
How to deal with a Compulsive liar
 
Driverless car Google
Driverless car GoogleDriverless car Google
Driverless car Google
 
Podcast tips beginners
Podcast tips beginnersPodcast tips beginners
Podcast tips beginners
 
Vastu for Career Success
Vastu for Career SuccessVastu for Career Success
Vastu for Career Success
 
Reliance jio broadband
Reliance jio broadbandReliance jio broadband
Reliance jio broadband
 
Job Satisfaction definition
Job Satisfaction definitionJob Satisfaction definition
Job Satisfaction definition
 
Mistakes in Advertising
Mistakes in AdvertisingMistakes in Advertising
Mistakes in Advertising
 
Contributor in a sentence
Contributor in a sentenceContributor in a sentence
Contributor in a sentence
 
Different Routing protocols
Different Routing protocolsDifferent Routing protocols
Different Routing protocols
 
Ad hoc network routing protocols
Ad hoc network routing protocolsAd hoc network routing protocols
Ad hoc network routing protocols
 
IPTV Thesis
IPTV ThesisIPTV Thesis
IPTV Thesis
 
Latest Thesis Topics for Fog computing
Latest Thesis Topics for Fog computingLatest Thesis Topics for Fog computing
Latest Thesis Topics for Fog computing
 
Latest Research Topics On Flying Ad-Hoc Networks (FANETs):
Latest Research Topics On Flying Ad-Hoc Networks (FANETs):Latest Research Topics On Flying Ad-Hoc Networks (FANETs):
Latest Research Topics On Flying Ad-Hoc Networks (FANETs):
 

Último

Call Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort ServiceCall Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
notes on Evolution Of Analytic Scalability.ppt
notes on Evolution Of Analytic Scalability.pptnotes on Evolution Of Analytic Scalability.ppt
notes on Evolution Of Analytic Scalability.ppt
MsecMca
 
Integrated Test Rig For HTFE-25 - Neometrix
Integrated Test Rig For HTFE-25 - NeometrixIntegrated Test Rig For HTFE-25 - Neometrix
Integrated Test Rig For HTFE-25 - Neometrix
Neometrix_Engineering_Pvt_Ltd
 
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar ≼🔝 Delhi door step de...
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar  ≼🔝 Delhi door step de...Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar  ≼🔝 Delhi door step de...
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar ≼🔝 Delhi door step de...
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
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
Cara Menggugurkan Kandungan 087776558899
 

Último (20)

Call Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort ServiceCall Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
 
(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
 
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
 
Unit 1 - Soil Classification and Compaction.pdf
Unit 1 - Soil Classification and Compaction.pdfUnit 1 - Soil Classification and Compaction.pdf
Unit 1 - Soil Classification and Compaction.pdf
 
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
 
(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7
(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7
(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7
 
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
 
University management System project report..pdf
University management System project report..pdfUniversity management System project report..pdf
University management System project report..pdf
 
notes on Evolution Of Analytic Scalability.ppt
notes on Evolution Of Analytic Scalability.pptnotes on Evolution Of Analytic Scalability.ppt
notes on Evolution Of Analytic Scalability.ppt
 
Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024
 
Integrated Test Rig For HTFE-25 - Neometrix
Integrated Test Rig For HTFE-25 - NeometrixIntegrated Test Rig For HTFE-25 - Neometrix
Integrated Test Rig For HTFE-25 - Neometrix
 
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar ≼🔝 Delhi door step de...
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar  ≼🔝 Delhi door step de...Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar  ≼🔝 Delhi door step de...
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar ≼🔝 Delhi door step de...
 
2016EF22_0 solar project report rooftop projects
2016EF22_0 solar project report rooftop projects2016EF22_0 solar project report rooftop projects
2016EF22_0 solar project report rooftop projects
 
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
 
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced LoadsFEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
 
Unit 2- Effective stress & Permeability.pdf
Unit 2- Effective stress & Permeability.pdfUnit 2- Effective stress & Permeability.pdf
Unit 2- Effective stress & Permeability.pdf
 
UNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its PerformanceUNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its Performance
 
Hostel management system project report..pdf
Hostel management system project report..pdfHostel management system project report..pdf
Hostel management system project report..pdf
 
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
 
Bhosari ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready For ...
Bhosari ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready For ...Bhosari ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready For ...
Bhosari ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready For ...
 

Introduction to Arrays in C

  • 1. For more Https://www.ThesisScientist.com Unit 6 Arrays Introduction to Arrays An array is a group of data items of same data type that share a common name. Ordinary variables are capable of holding only one value at a time. If we want to store more than one value at a time in a single variable, we use arrays. An array is a collective name given to a group of similar variables. Each member in the group is referred to by its position in the group. Arrays are alloted the memory in a strictly contiguous fashion. The simplest array is one dimensional array which is a list of variables of same data type. An array of one dimensional arrays is called a two dimensional array. One Dimensional Array A list of items can be given one variable name using only one subscript and such a variable is called a one dimensional array. e.g.: If we want to store a set of five numbers by an array variable number. Then it will be accomplished in the following way: int number [5]; This declaration will reserve five contiguous memory locations as shown below: Number [0] Number [1] Number [2] Number [3] Number [4] As C performs no bounds checking, care should be taken to ensure that the array indices are within the declared limits. Also, indexing in C begins from 0 and not from 1. Array Declaration Arrays are defined in the same manner as ordinary variables, except that each array name must be accompanied by the size specification. The general form of array declaration is: data-type array-name [size];
  • 2. data-type specifies the type of array, size is a positive integer number or symbolic constant that indicates the maximum number of elements that can be stored in the array. e.g.: float height [50]; This declaration declares an array named height containing 50 elements of type float. NOTE The compiler will interpret first element as height [0]. As in C, the array elements are induced for 0 to [size-1]. Array Initialization The elements of an array can be initialized in the same way as the ordinary variables, when they are declared. Given below are some examples which show how the arrays are initialized. static int num [6] = {2, 4, 5, 45, 12}; static int n [ ] = {2, 4, 5, 45, 12}; static float press [ ] = {12.5, 32.4, -23.7, -11.3}; In these examples note the following points: (a) Till the array elements are not given any specific values, they contain garbage value. (b) If the array is initialized where it is declared, its storage class must be either static or extern. If the storage class is static, all the elements are initialized by 0. (c) If the array is initialized where it is declared, mentioning the dimension of the array is optional. Accessing Elements of an Array Once an array is declared, individual elements of the array are referred using subscript or index number. This number specifies the element's position in the array. All the elements of the array are numbered starting from 0. Thus number [5] is actually the sixth element of an array. Entering Data into an Array It can be explained by the following examples: main( ) { int num [6]; int count; for (count = 0; count < 6; count ++) { printf ("n Enter %d element:" count+1); scanf ("%d", &num [count]); } } In this example, using the for loop, the process of asking and receiving the marks is accomplished. When count has the value zero, the scanf( ) statement will cause the value to be stored at num [0]. This process continues until count has the value greater than 5. Reading Data from an Array Consider the program given above. It has entered 6 values in the array num. Now to read values from this array, we will again use for Loop to access each cell. The given program segment explains the retrieval of the values from the array.
  • 3. for (count = 0; count < 6; count ++) { printf ("n %d value =", num [count]); } Memory Representation of Array Consider the following array declaration: int arr[8]; 16 bytes get immediately reserved in memory because each of the 8 integers would be 2 bytes long and since the array is not being initialized, all eight values present in it would be garbage values. Whatever be the initial values, all the array elements would always be present in contiguous memory location. This arrangement of array elements in memory is shown below. 12 34 66 -45 23 346 77 98 4002 4004 4006 4008 4010 4012 4014 4016 Value Address 1212 34 66 -45 23 346 77 98 4002 4004 4006 4008 4010 4012 4014 4016 Value Address In C, there is no check to see if the subscript used for an array exceeds the size of the array. Data entered with a subscript exceeding the array size will simply be placed in memory outside the array. This will lead to unpredictable results and there will be no error message to warn you that you are going beyond the array size. So to see to it that you do not reach beyond the array size is entirely the programmer's botheration and not the compiler's. Strings Just as a group of integers can be stored in an integer array, group of characters can be stored in a character array or "strings". The string constant is a one dimensional array of characters terminated by null character ('0'). This null character '0' (ASCII value 0) is different from 'O' (ASCII value 48). The terminating null character is important because it is the only way the function that works with string can know where the string ends. e.g.: Static char name [ ] = {'K', 'R', 'I', 'S', 'H', '0'}; This example shows the declaration and initialization of a character array. The array elements of a character array are stored in contiguous locations with each element occupying one byte of memory. K R I S H N A ‘0’ 4001 4002 4003 4004 4005 4006 4007 4009 NOTEOTE1. Contrary to the numeric array where a 5 digit number can be stored in one array cell, in the character arrays only a single character can be stored in one cell. So in order to store an array of strings, a 2-dimensional array is required. 2. As scanf( ) function is not capable of receiving multi word string, such strings should be Two Dimensional Array This is a table of four rows and three columns. Such a table of items can be defined using two dimensional arrays.
  • 4. General form of declaring a 2-D array is data_type array_name [row_size] [colum_size]; Initialization of a 2-Dimensional Array Two dimensional arrays may be initialized by a list of initial values enclosed in braces following their declaration. e.g.: static int table [2] [3] = {0, 0, 0, 1, 1, 1}; initializes the elements of the first row to 0 and the second row to one. The initialization is done by row. The aforesaid statement can be equivalently written as static int table [2] [3] = {{0, 0, 0}, {1, 1, 1}}; by surrounding the elements of each row by braces. We can also initialize a two dimensional array in the form of a matrix as shown below: static int table [2] [3] = {{0, 0, 0}, {1, 1, 1}}; The syntax of the above statement. Commas are required after each brace that closes off a row, except in the case of the last row. If the values are missing in an initializer, they are automatically set to 0. For instance, the statement static int table [2] [3] = {{1, 1}, {2}}; will initialize the first two elements of the first row to one, the first element of the second row to two, and all the other elements to 0. When all the elements are to be initialized to 0, the following short cut method may be used. static int m [3] [5] = {{0}, {0}, {0}}; The first element of each row is explicitly initialized to 0 while other elements are automatically initialized to 0. While initializing an array, it is necessary to mention the second (column) dimension, whereas the first dimension (row) is optional. Thus, the following declarations are acceptable. static int arr [2] [3] = {12, 34, 23, 45, 56, 45}; static int arr [ ] [3] = {12, 34, 23, 45, 56, 45 }; Memory Representation of Two Dimensional Array In memory, whether it is a one dimensional or a two dimensional array, the array elements are stored in one continuous chain. The arrangement of array elements of a two dimensional array of students, which contains roll numbers in one column and the marks in the other (in memory) is shown below:
  • 5. 1234 5002 5004 5006 5008 5010 5012 5014 5016 Value Address 1234 1234 1234 1234 1234 1234 1234 S[0][0] S[0][1] S[1][0] S[1][1] S[2][0] S[2][1] S[3][0] S[3][0]Notation 1234 5002 5004 5006 5008 5010 5012 5014 5016 Value Address 1234 1234 1234 1234 1234 1234 1234 S[0][0] S[0][1] S[1][0] S[1][1] S[2][0] S[2][1] S[3][0] S[3][0]Notation e.g.: 1. Program that stores roll number and marks obtained by a student side by side in a matrix main( ) { int stud [4] [2]; int i, j; for (i = 0; i < = 3; i++) { printf ("n Enter roll no. and marks"); scanf ("%d%d", &stud [i] [0], &stud[i] [1]); } for (i = 0; i < = 3; i++) printf ("%d%dn", stud [i] [0], stud [i] [0]; } There are two parts to the program, in the first part through a for Loop we read in the values of roll number and marks, whereas in second part through another for Loop we print out these values. Multi-dimensional Array C allows arrays of three or more dimensions. Multi-dimensional arrays are defined in much the same manner as one-dimensional arrays, except that a separate pair of square brackets is required for each subscript. The general form of a multi-dimensional array is data_type array_name [s1] [s2] [s3] . . . [sm]; e.g.: int survey [3] [5] [12]; float table [5] [4] [5] [3]; Here, survey is a 3-dimensional array declared to contain 180 integer_type elements. Similarly, table is a 4- dimensional array containing 300 elements of floating point type. An example of initializing a 4-dimensional array: static int arr [3] [4] [2] = {{{2, 4}, {7, 8}, {3, 4}, {5, 6},}, {{7, 6}, {3, 4}, {5, 3}, {2, 3}, }, {{8, 9}, {7, 2}, {3, 4}, {6, 1}, } }; In this example, the outer array has three elements, each of which is a two dimensional array of four rows, each of which is a one dimensional array of two elements.