SlideShare une entreprise Scribd logo
1  sur  39
COM1407
Computer Programming
Lecture 08
Arrays
K.A.S.H. Kulathilake
B.Sc. (Hons) IT, MCS , M.Phil., SEDA(UK)
Rajarata University of Sri Lanka
Department of Physical Sciences
1
Objectives
• At the end of this lecture students should be able
to;
▫ Describe the C arrays.
▫ Practice the declaration, initialization and access
linear arrays.
▫ Practice the declaration, initialization and access
two dimensional arrays.
▫ Apply taught concepts for writing programs.
2
Introduction
• The C language provides a capability that enables you to
define a set of ordered data items known as an array.
• Arrays a kind of data structure that can store a fixed-size
sequential collection of elements of the same type.
• An array is used to store a collection of data, but it is
often more useful to think of an array as a collection of
variables of the same type.
• Instead of declaring individual variables, such as
number0, number1, ..., and number99, you declare one
array variable such as numbers and use numbers[0],
numbers[1], and ..., numbers[99] to represent individual
variables.
• A specific element in an array is accessed by an index.
3
Introduction (Cont…)
• All arrays consist of contiguous memory
locations.
• The lowest address corresponds to the first
element and the highest address to the last
element.
4
One Dimension Array
• A list of items can be given one variable name
using only one subscript and such a variable is
called a single subscripted variable or a one-
dimensional array.
• In C, single-subscripted variable xi can be
expressed as:
x[l] , x[2] , x[3], ……………, x[n]
5
Declaring Array
• 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 arraySize must be an integer constant greater
than zero and type can be any valid C data type.
• For example, to declare a 5-element array
called balance of type double, use this statement;
double balance[5];
• Here balance is a variable array which is sufficient
to hold up to 5 double numbers.
6
Array Initialization
• Following is an example to assign a single element
of the array;
balance[0] = 1000.0;
balance[1] = 2.0;
balance[2] = 3.4;
balance[3] = 7.0;
balance[4] = 50.0;
• All arrays have 0 as the index of their first element
which is also called the base index and the last index
of an array will be total size of the array minus 1.
7
Array Initialization (Cont…)
• 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[] = {1000.0, 2.0, 3.4, 7.0, 50.0};
• You will create exactly the same array as you did in
the previous example.
8
Array Initialization (Cont…)
• You can declare and initialize an array in C using
a single statement as follows:
double balance[5] = {1000.0, 2.0, 3.4, 7.0, 50.0};
• The number of values between braces { } cannot
be larger than the number of elements that we
declare for the array between square brackets [ ].
9
Accessing Array 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[3];
• The above statement will take the 4th element
from the array and assign the value to salary
variable.
10
Demonstration
#include <stdio.h>
int main ()
{
int index;
double balance[5];
balance[0] = 1000.0;
balance[1] = 2.0;
balance[2] = 3.4;
balance[3] = 7.0;
balance[4] = 50.0;
printf ("Direct Accessn");
printf ("%6.2fn ", balance[3]);
printf ("Loop through Accessn");
for (index = 0; index < 5; index++)
printf ("%6.2fn ", balance[index]);
return 0;
}
11
Demonstration
#include <stdio.h>
int main ()
{
int index;
double balance[] = {1000.0, 2.0, 3.4, 7.0, 50.0};
for (index = 0; index < 5; index++)
printf ("%6.2fn ", balance[index]);
return 0;
}
12
Demonstration
#include <stdio.h>
int main ()
{
int index;
double balance[5] = {1000.0, 2.0, 3.4, 7.0, 50.0};
for (index = 0; index < 5; index++)
printf ("%6.2fn ", balance[index]);
return 0;
}
13
Demonstration
#include <stdio.h>
int main ()
{
int balance[5];
int index;
printf ("Before Initializationn");
for (index = 0; index < 5; index++)
printf ("%in", balance[index]);
printf ("nAfter Initializationn");
for (index = 0; index < 5; index++){
balance[index] = index*10;
printf ("%in ", balance[index]);
}
return 0;
}
14
What happen if you
access an array just
after the
declaration:
Replace the following statement for array
declaration in line 4 and see the results?
int balance[5] = {0,0,0,0,0};
Demonstration
• Following statements may be used in
programs just like any other C variable.
aNumber = number[0] + 10;
number [4] = number [0] + number[2];
number [2] = x[5] + y[10];
value[6] = number [i] * 3;
• The subscript of an array can be integer
constants, integer variables like i, or
expressions that yield integers.
15
Demonstration
#include <stdio.h>
int main ()
{
int index;
double cost;
double us_balance[4];
double balance[] = {1000.0, 2.0, 3.4, 7.0, 50.0};
cost = balance[2]+100;
printf ("Cost ---> %6.2fn ", cost);
for (index = 0; index < 4; index++){
us_balance[index] = balance [index] +
balance [index+1];
printf ("%6.2fn ", us_balance[index]);
}
return 0;
}
16
Demonstration
#include <stdio.h>
int main ()
{
int index;
double ot[] = {10.0, 30.0, 35.5, 21.5,20};
int rate[] = {10,20,30,20,10};
double gross[5];
for (index = 0; index < 5; index++){
gross[index] = ot[index] * rate[index];
printf ("%6.2fn", gross[index]);
}
return 0;
}
17
Demonstration
#include <stdio.h>
int main ()
{
const int OT_RATE = 10;
int index;
double ot[] = {10.0, 30.0, 35.5, 21.5,20};
double gross[5];
for (index = 0; index < 5; index++){
gross[index] = ot[index] * OT_RATE;
printf ("%6.2fn", gross[index]);
}
return 0;
}
18
Bound Checking?
• Declares grades to be an array containing 100
integer elements:
double grades[100];
• Valid references to this array can be made by using
subscripts from 0 through 99.
• But be careful to use valid subscripts because C does
not do any checking of array bounds for you.
• So a reference to element number 150 of array
grades, as previously declared, does not necessarily
cause an error but does most likely cause unwanted,
if not unpredictable, program results.
19
Demonstration
• Array of Counters
#include <stdio.h>
int main (void)
{
int ratingCounters[11], i, response;
for ( i = 1; i <= 10; ++i )
ratingCounters[i] = 0;
printf ("Enter your responsesn");
for ( i = 1; i <= 20; ++i ) {
scanf ("%i", &response);
if ( response < 1 || response > 10 )
printf ("Bad response: %in", response);
else
++ratingCounters[response];
}
printf ("nnRating Number of Responsesn");
printf ("------ -------------------n");
for ( i = 1; i <= 10; ++i )
printf ("%4i%14in", i, ratingCounters[i]);
return 0;
}
20
Demonstration
• Generating Fibonacci Numbers
#include <stdio.h>
int main (void)
{
int Fibonacci[15], i;
Fibonacci[0] = 0;
Fibonacci[1] = 1;
for ( i = 2; i < 15; ++i )
Fibonacci[i] = Fibonacci[i-2] +
Fibonacci[i-1];
for ( i = 0; i < 15; ++i )
printf ("%in", Fibonacci[i]);
return 0;
}
21
Character Array
#include <stdio.h>
int main (void)
{
char word[] = { 'H', 'e', 'l', 'l', 'o', '!' };
int i;
for ( i = 0; i < 6; i++ )
printf ("%c", word[i]);
printf ("n");
return 0;
}
22
Character Array (Cont…)
• The most notable point in the preceding program is
the declaration of the character array word.
• There is no mention of the number of elements in
the array.
• The C language allows you to define an array
without specifying the number of elements.
• If this is done, the size of the array is determined
automatically based on the number of initialization
elements.
• Because preceding program has six initial values
listed for the array word, the C language implicitly
dimensions the array to six elements
23
Demonstration
• Base Converter (up to 16)
#include <stdio.h>
int main (void)
{
const char baseDigits[16] = {
'0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
int convertedNumber[64];
long int numberToConvert;
int nextDigit, base, index = 0;
printf ("Number to be converted? ");
scanf ("%ld", &numberToConvert);
printf ("Base? ");
scanf ("%i", &base);
24
Demonstration
do {
convertedNumber[index] = numberToConvert % base;
++index;
numberToConvert = numberToConvert / base;
}
while ( numberToConvert != 0 );
printf ("Converted number = ");
for (--index; index >= 0; --index ) {
nextDigit = convertedNumber[index];
printf ("%c", baseDigits[nextDigit]);
}
printf ("n");
return 0;
}
25
Multidimensional Arrays
• The types of arrays that you have been exposed
to so far are all linear arrays / single dimension
arrays.
• That is, they all dealt with a single dimension.
• The C language allows arrays of any dimension
to be defined.
• In this section, you take a look at two-
dimensional arrays.
26
Multidimensional Arrays (Cont…)
• One of the most natural applications for a two-dimensional
array arises in the case of a matrix.
• In mathematics, it is quite common to refer to an element of a
matrix by use of a double subscript.
• So if you call the preceding matrix M, the notation Mi,j refers
to the element in the ith row, jth column, where i ranges from 1
to 4, and j ranges from 1 to 5.
• The notation M3,2 refers to the value 20, which is found in the
3rd row, 2nd column of the matrix
27
Multidimensional Arrays (Cont…)
• In C, you can use an analogous notation when referring to elements
of a twodimensional array.
• However, because C likes to start numbering things at zero, the 1st
row of the matrix is actually row 0, and the 1st column of the matrix
is column 0.
• The preceding matrix would then have row and column
designations, as shown below;
28
Multidimensional Arrays (Cont…)
• Whereas in mathematics the notation Mi,j is used, in C the
equivalent notation is M[i][j].
• Remember, the first index number refers to the row number,
whereas the second index number references the column.
• So the statement
int sum = M[0][2] + M[2][4];
• adds the value contained in row 0, column 2—which is –3—to the
value contained in row 2, column 4—which is 14—and assigns the
result of 11 to the variable sum.
• Two-dimensional arrays are declared the same way that one-
dimensional arrays are; thus;
int M[4][5];
• declares the array M to be a two-dimensional array consisting of 4
rows and 5 columns, for a total of 20 elements.
• Each position in the array is defined to contain an integer value.
29
Multidimensional Arrays (Cont…)
• Two-dimensional arrays can be initialized in a manner analogous to
their one-dimensional counterparts.
• When listing elements for initialization, the values are listed by row.
• Brace pairs are used to separate the list of initializers for one row
from the next.
• So to define and initialize the array M to the elements listed in
preceding table, a statement such as the following can be used:
30
Multidimensional Arrays (Cont…)
#include <stdio.h>
int main (void)
{
int M[4][5] = {
{ 10, 5, -3, 17, 82 },
{ 9, 0, 0, 8, -7 },
{ 32, 20, 1, 0, 14 },
{ 0, 0, 8, 7, 6 }
};
int x, y;
for ( x = 0; x < 4; x++){
for (y = 0; y < 5; y++)
printf( "%2i. ", M[x][y]);
printf ("n");
}
return 0;
}
31
Multidimensional Arrays (Cont…)
• As with one-dimensional arrays, it is not required
that the entire array be initialized.
• A statement such as
int M[4][5] = {
{ 10, 5, -3 },
{ 9, 0, 0 },
{ 32, 20, 1 },
{ 0, 0, 8 }
};
• Only initializes the first three elements of each row
of the matrix to the indicated values.
• The remaining values are set to 0.
32
Multidimensional Arrays (Cont…)
#include <stdio.h>
int main (void)
{
int M[4][5] = {
{ 10, 5, -3 },
{ 9, 0, 0 },
{ 32, 20, 1 },
{ 0, 0, 8 }
};
int x, y;
for ( x = 0; x < 4; x++){
for (y = 0; y < 5; y++)
printf( "%2i. ", M[x][y]);
printf ("n");
}
return 0;
}
33
Multidimensional Arrays (Cont…)
• Note that commas are required after each brace
that closes off a row, except in the case of the
final row.
• The use of the inner pairs of braces is actually
optional.
• If not supplied, initialization proceeds by row.
• Thus, the preceding statement could also have
been written as follows:
int M[4][5] = { 10, 5, -3, 17, 82, 9, 0, 0, 8, -7,
32, 20, 1, 0, 14, 0, 0, 8, 7, 6 };
34
Multidimensional Arrays (Cont…)
#include <stdio.h>
int main (void)
{
int M[4][5] = { 10, 5, -3, 17, 82, 9, 0,
0, 8, -7, 32, 20, 1, 0, 14, 0, 0, 8, 7, 6 };
int x, y;
for ( x = 0; x < 4; x++){
for (y = 0; y < 5; y++)
printf( "%2i. ", M[x][y]);
printf ("n");
}
return 0;
}
35
Variable Length Arrays
• In the examples we discussed up to now, you
have seen how the size of an array is declared to
be of a specific size.
• The C language allows you to declare arrays of a
variable size.
• Note that, full support for variable-length arrays
was not offered by all C compilers.
• You might want to check your compiler’s
documentation before you use this feature.
36
Objective Re-cap
• Now you should be able to:
▫ Describe the C arrays.
▫ Practice the declaration, initialization and access
linear arrays.
▫ Practice the declaration, initialization and access
two dimensional arrays.
▫ Apply taught concepts for writing programs.
37
References
• Chapter 07, - Programming in C, 3rd Edition,
Stephen G. Kochan
38
Next: Working with Functions
39

Contenu connexe

Tendances (20)

Arrays in c
Arrays in cArrays in c
Arrays in c
 
Unit 6. Arrays
Unit 6. ArraysUnit 6. Arrays
Unit 6. Arrays
 
Two dimensional arrays
Two dimensional arraysTwo dimensional arrays
Two dimensional arrays
 
Arrays in C language
Arrays in C languageArrays in C language
Arrays in C language
 
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
 
Array assignment
Array assignmentArray assignment
Array assignment
 
Array
ArrayArray
Array
 
ARRAYS
ARRAYSARRAYS
ARRAYS
 
Python programming workshop
Python programming workshopPython programming workshop
Python programming workshop
 
Arrays
ArraysArrays
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)
 
Arrays in C
Arrays in CArrays in C
Arrays in C
 
Arrays and library functions
Arrays and library functionsArrays and library functions
Arrays and library functions
 
Multidimensional array in C
Multidimensional array in CMultidimensional array in C
Multidimensional array in C
 
Arrays in c
Arrays in cArrays in c
Arrays in c
 
C arrays
C arraysC arrays
C arrays
 
Lecture 15 - Array
Lecture 15 - ArrayLecture 15 - Array
Lecture 15 - Array
 
2D Array
2D Array 2D Array
2D Array
 
Arrays
ArraysArrays
Arrays
 
Arrays in C++
Arrays in C++Arrays in C++
Arrays in C++
 

Similaire à COM1407: Arrays

Programming Fundamentals Arrays and Strings
Programming Fundamentals   Arrays and Strings Programming Fundamentals   Arrays and Strings
Programming Fundamentals Arrays and Strings imtiazalijoono
 
VIT351 Software Development VI Unit2
VIT351 Software Development VI Unit2VIT351 Software Development VI Unit2
VIT351 Software Development VI Unit2YOGESH SINGH
 
Arrays-Computer programming
Arrays-Computer programmingArrays-Computer programming
Arrays-Computer programmingnmahi96
 
presentation_arrays_1443553113_140676.ppt
presentation_arrays_1443553113_140676.pptpresentation_arrays_1443553113_140676.ppt
presentation_arrays_1443553113_140676.pptNamakkalPasanga
 
Array,MULTI ARRAY, IN C
Array,MULTI ARRAY, IN CArray,MULTI ARRAY, IN C
Array,MULTI ARRAY, IN Cnaveed jamali
 
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.pdfajajkhan16
 
Programming in C (part 2)
Programming in C (part 2)Programming in C (part 2)
Programming in C (part 2)SURBHI SAROHA
 
Lecture 5Arrays on c++ for Beginner.pptx
Lecture 5Arrays on c++ for Beginner.pptxLecture 5Arrays on c++ for Beginner.pptx
Lecture 5Arrays on c++ for Beginner.pptxarjurakibulhasanrrr7
 

Similaire à COM1407: Arrays (20)

Session 4
Session 4Session 4
Session 4
 
Programming Fundamentals Arrays and Strings
Programming Fundamentals   Arrays and Strings Programming Fundamentals   Arrays and Strings
Programming Fundamentals Arrays and Strings
 
Array
ArrayArray
Array
 
CP Handout#7
CP Handout#7CP Handout#7
CP Handout#7
 
CHAPTER 5
CHAPTER 5CHAPTER 5
CHAPTER 5
 
VIT351 Software Development VI Unit2
VIT351 Software Development VI Unit2VIT351 Software Development VI Unit2
VIT351 Software Development VI Unit2
 
Arrays
ArraysArrays
Arrays
 
Chapter 13.pptx
Chapter 13.pptxChapter 13.pptx
Chapter 13.pptx
 
Array-part1
Array-part1Array-part1
Array-part1
 
Arrays-Computer programming
Arrays-Computer programmingArrays-Computer programming
Arrays-Computer programming
 
Arrays
ArraysArrays
Arrays
 
02 arrays
02 arrays02 arrays
02 arrays
 
presentation_arrays_1443553113_140676.ppt
presentation_arrays_1443553113_140676.pptpresentation_arrays_1443553113_140676.ppt
presentation_arrays_1443553113_140676.ppt
 
Array,MULTI ARRAY, IN C
Array,MULTI ARRAY, IN CArray,MULTI ARRAY, IN C
Array,MULTI ARRAY, IN C
 
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
 
Unit4 Slides
Unit4 SlidesUnit4 Slides
Unit4 Slides
 
Array
ArrayArray
Array
 
Array
ArrayArray
Array
 
Programming in C (part 2)
Programming in C (part 2)Programming in C (part 2)
Programming in C (part 2)
 
Lecture 5Arrays on c++ for Beginner.pptx
Lecture 5Arrays on c++ for Beginner.pptxLecture 5Arrays on c++ for Beginner.pptx
Lecture 5Arrays on c++ for Beginner.pptx
 

Plus de Hemantha Kulathilake

NLP_KASHK:Parsing with Context-Free Grammar
NLP_KASHK:Parsing with Context-Free Grammar NLP_KASHK:Parsing with Context-Free Grammar
NLP_KASHK:Parsing with Context-Free Grammar Hemantha Kulathilake
 
NLP_KASHK:Context-Free Grammar for English
NLP_KASHK:Context-Free Grammar for EnglishNLP_KASHK:Context-Free Grammar for English
NLP_KASHK:Context-Free Grammar for EnglishHemantha Kulathilake
 
NLP_KASHK:Evaluating Language Model
NLP_KASHK:Evaluating Language ModelNLP_KASHK:Evaluating Language Model
NLP_KASHK:Evaluating Language ModelHemantha Kulathilake
 
NLP_KASHK:Finite-State Morphological Parsing
NLP_KASHK:Finite-State Morphological ParsingNLP_KASHK:Finite-State Morphological Parsing
NLP_KASHK:Finite-State Morphological ParsingHemantha Kulathilake
 
COM1407: Structures, Unions & Dynamic Memory Allocation
COM1407: Structures, Unions & Dynamic Memory Allocation COM1407: Structures, Unions & Dynamic Memory Allocation
COM1407: Structures, Unions & Dynamic Memory Allocation Hemantha Kulathilake
 
COM1407: Program Control Structures – Repetition and Loops
COM1407: Program Control Structures – Repetition and Loops COM1407: Program Control Structures – Repetition and Loops
COM1407: Program Control Structures – Repetition and Loops Hemantha Kulathilake
 

Plus de Hemantha Kulathilake (20)

NLP_KASHK:Parsing with Context-Free Grammar
NLP_KASHK:Parsing with Context-Free Grammar NLP_KASHK:Parsing with Context-Free Grammar
NLP_KASHK:Parsing with Context-Free Grammar
 
NLP_KASHK:Context-Free Grammar for English
NLP_KASHK:Context-Free Grammar for EnglishNLP_KASHK:Context-Free Grammar for English
NLP_KASHK:Context-Free Grammar for English
 
NLP_KASHK:POS Tagging
NLP_KASHK:POS TaggingNLP_KASHK:POS Tagging
NLP_KASHK:POS Tagging
 
NLP_KASHK:Markov Models
NLP_KASHK:Markov ModelsNLP_KASHK:Markov Models
NLP_KASHK:Markov Models
 
NLP_KASHK:Smoothing N-gram Models
NLP_KASHK:Smoothing N-gram ModelsNLP_KASHK:Smoothing N-gram Models
NLP_KASHK:Smoothing N-gram Models
 
NLP_KASHK:Evaluating Language Model
NLP_KASHK:Evaluating Language ModelNLP_KASHK:Evaluating Language Model
NLP_KASHK:Evaluating Language Model
 
NLP_KASHK:N-Grams
NLP_KASHK:N-GramsNLP_KASHK:N-Grams
NLP_KASHK:N-Grams
 
NLP_KASHK:Minimum Edit Distance
NLP_KASHK:Minimum Edit DistanceNLP_KASHK:Minimum Edit Distance
NLP_KASHK:Minimum Edit Distance
 
NLP_KASHK:Finite-State Morphological Parsing
NLP_KASHK:Finite-State Morphological ParsingNLP_KASHK:Finite-State Morphological Parsing
NLP_KASHK:Finite-State Morphological Parsing
 
NLP_KASHK:Morphology
NLP_KASHK:MorphologyNLP_KASHK:Morphology
NLP_KASHK:Morphology
 
NLP_KASHK:Text Normalization
NLP_KASHK:Text NormalizationNLP_KASHK:Text Normalization
NLP_KASHK:Text Normalization
 
NLP_KASHK:Finite-State Automata
NLP_KASHK:Finite-State AutomataNLP_KASHK:Finite-State Automata
NLP_KASHK:Finite-State Automata
 
NLP_KASHK:Regular Expressions
NLP_KASHK:Regular Expressions NLP_KASHK:Regular Expressions
NLP_KASHK:Regular Expressions
 
NLP_KASHK: Introduction
NLP_KASHK: Introduction NLP_KASHK: Introduction
NLP_KASHK: Introduction
 
COM1407: File Processing
COM1407: File Processing COM1407: File Processing
COM1407: File Processing
 
COm1407: Character & Strings
COm1407: Character & StringsCOm1407: Character & Strings
COm1407: Character & Strings
 
COM1407: Structures, Unions & Dynamic Memory Allocation
COM1407: Structures, Unions & Dynamic Memory Allocation COM1407: Structures, Unions & Dynamic Memory Allocation
COM1407: Structures, Unions & Dynamic Memory Allocation
 
COM1407: Input/ Output Functions
COM1407: Input/ Output FunctionsCOM1407: Input/ Output Functions
COM1407: Input/ Output Functions
 
COM1407: Working with Pointers
COM1407: Working with PointersCOM1407: Working with Pointers
COM1407: Working with Pointers
 
COM1407: Program Control Structures – Repetition and Loops
COM1407: Program Control Structures – Repetition and Loops COM1407: Program Control Structures – Repetition and Loops
COM1407: Program Control Structures – Repetition and Loops
 

Dernier

ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.MaryamAhmad92
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...pradhanghanshyam7136
 
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Pooja Bhuva
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfDr Vijay Vishwakarma
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentationcamerronhm
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.pptRamjanShidvankar
 
How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17Celine George
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17Celine George
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the ClassroomPooky Knightsmith
 
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxmarlenawright1
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17Celine George
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structuredhanjurrannsibayan2
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxCeline George
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...Poonam Aher Patil
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfNirmal Dwivedi
 
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptxCOMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptxannathomasp01
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptxMaritesTamaniVerdade
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibitjbellavia9
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxDr. Ravikiran H M Gowda
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxAreebaZafar22
 

Dernier (20)

ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
 
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentation
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the Classroom
 
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structure
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptx
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
 
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptxCOMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptx
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 

COM1407: Arrays

  • 1. COM1407 Computer Programming Lecture 08 Arrays K.A.S.H. Kulathilake B.Sc. (Hons) IT, MCS , M.Phil., SEDA(UK) Rajarata University of Sri Lanka Department of Physical Sciences 1
  • 2. Objectives • At the end of this lecture students should be able to; ▫ Describe the C arrays. ▫ Practice the declaration, initialization and access linear arrays. ▫ Practice the declaration, initialization and access two dimensional arrays. ▫ Apply taught concepts for writing programs. 2
  • 3. Introduction • The C language provides a capability that enables you to define a set of ordered data items known as an array. • Arrays a kind of data structure that can store a fixed-size sequential collection of elements of the same type. • An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type. • Instead of declaring individual variables, such as number0, number1, ..., and number99, you declare one array variable such as numbers and use numbers[0], numbers[1], and ..., numbers[99] to represent individual variables. • A specific element in an array is accessed by an index. 3
  • 4. Introduction (Cont…) • All arrays consist of contiguous memory locations. • The lowest address corresponds to the first element and the highest address to the last element. 4
  • 5. One Dimension Array • A list of items can be given one variable name using only one subscript and such a variable is called a single subscripted variable or a one- dimensional array. • In C, single-subscripted variable xi can be expressed as: x[l] , x[2] , x[3], ……………, x[n] 5
  • 6. Declaring Array • 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 arraySize must be an integer constant greater than zero and type can be any valid C data type. • For example, to declare a 5-element array called balance of type double, use this statement; double balance[5]; • Here balance is a variable array which is sufficient to hold up to 5 double numbers. 6
  • 7. Array Initialization • Following is an example to assign a single element of the array; balance[0] = 1000.0; balance[1] = 2.0; balance[2] = 3.4; balance[3] = 7.0; balance[4] = 50.0; • All arrays have 0 as the index of their first element which is also called the base index and the last index of an array will be total size of the array minus 1. 7
  • 8. Array Initialization (Cont…) • 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[] = {1000.0, 2.0, 3.4, 7.0, 50.0}; • You will create exactly the same array as you did in the previous example. 8
  • 9. Array Initialization (Cont…) • You can declare and initialize an array in C using a single statement as follows: double balance[5] = {1000.0, 2.0, 3.4, 7.0, 50.0}; • The number of values between braces { } cannot be larger than the number of elements that we declare for the array between square brackets [ ]. 9
  • 10. Accessing Array 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[3]; • The above statement will take the 4th element from the array and assign the value to salary variable. 10
  • 11. Demonstration #include <stdio.h> int main () { int index; double balance[5]; balance[0] = 1000.0; balance[1] = 2.0; balance[2] = 3.4; balance[3] = 7.0; balance[4] = 50.0; printf ("Direct Accessn"); printf ("%6.2fn ", balance[3]); printf ("Loop through Accessn"); for (index = 0; index < 5; index++) printf ("%6.2fn ", balance[index]); return 0; } 11
  • 12. Demonstration #include <stdio.h> int main () { int index; double balance[] = {1000.0, 2.0, 3.4, 7.0, 50.0}; for (index = 0; index < 5; index++) printf ("%6.2fn ", balance[index]); return 0; } 12
  • 13. Demonstration #include <stdio.h> int main () { int index; double balance[5] = {1000.0, 2.0, 3.4, 7.0, 50.0}; for (index = 0; index < 5; index++) printf ("%6.2fn ", balance[index]); return 0; } 13
  • 14. Demonstration #include <stdio.h> int main () { int balance[5]; int index; printf ("Before Initializationn"); for (index = 0; index < 5; index++) printf ("%in", balance[index]); printf ("nAfter Initializationn"); for (index = 0; index < 5; index++){ balance[index] = index*10; printf ("%in ", balance[index]); } return 0; } 14 What happen if you access an array just after the declaration: Replace the following statement for array declaration in line 4 and see the results? int balance[5] = {0,0,0,0,0};
  • 15. Demonstration • Following statements may be used in programs just like any other C variable. aNumber = number[0] + 10; number [4] = number [0] + number[2]; number [2] = x[5] + y[10]; value[6] = number [i] * 3; • The subscript of an array can be integer constants, integer variables like i, or expressions that yield integers. 15
  • 16. Demonstration #include <stdio.h> int main () { int index; double cost; double us_balance[4]; double balance[] = {1000.0, 2.0, 3.4, 7.0, 50.0}; cost = balance[2]+100; printf ("Cost ---> %6.2fn ", cost); for (index = 0; index < 4; index++){ us_balance[index] = balance [index] + balance [index+1]; printf ("%6.2fn ", us_balance[index]); } return 0; } 16
  • 17. Demonstration #include <stdio.h> int main () { int index; double ot[] = {10.0, 30.0, 35.5, 21.5,20}; int rate[] = {10,20,30,20,10}; double gross[5]; for (index = 0; index < 5; index++){ gross[index] = ot[index] * rate[index]; printf ("%6.2fn", gross[index]); } return 0; } 17
  • 18. Demonstration #include <stdio.h> int main () { const int OT_RATE = 10; int index; double ot[] = {10.0, 30.0, 35.5, 21.5,20}; double gross[5]; for (index = 0; index < 5; index++){ gross[index] = ot[index] * OT_RATE; printf ("%6.2fn", gross[index]); } return 0; } 18
  • 19. Bound Checking? • Declares grades to be an array containing 100 integer elements: double grades[100]; • Valid references to this array can be made by using subscripts from 0 through 99. • But be careful to use valid subscripts because C does not do any checking of array bounds for you. • So a reference to element number 150 of array grades, as previously declared, does not necessarily cause an error but does most likely cause unwanted, if not unpredictable, program results. 19
  • 20. Demonstration • Array of Counters #include <stdio.h> int main (void) { int ratingCounters[11], i, response; for ( i = 1; i <= 10; ++i ) ratingCounters[i] = 0; printf ("Enter your responsesn"); for ( i = 1; i <= 20; ++i ) { scanf ("%i", &response); if ( response < 1 || response > 10 ) printf ("Bad response: %in", response); else ++ratingCounters[response]; } printf ("nnRating Number of Responsesn"); printf ("------ -------------------n"); for ( i = 1; i <= 10; ++i ) printf ("%4i%14in", i, ratingCounters[i]); return 0; } 20
  • 21. Demonstration • Generating Fibonacci Numbers #include <stdio.h> int main (void) { int Fibonacci[15], i; Fibonacci[0] = 0; Fibonacci[1] = 1; for ( i = 2; i < 15; ++i ) Fibonacci[i] = Fibonacci[i-2] + Fibonacci[i-1]; for ( i = 0; i < 15; ++i ) printf ("%in", Fibonacci[i]); return 0; } 21
  • 22. Character Array #include <stdio.h> int main (void) { char word[] = { 'H', 'e', 'l', 'l', 'o', '!' }; int i; for ( i = 0; i < 6; i++ ) printf ("%c", word[i]); printf ("n"); return 0; } 22
  • 23. Character Array (Cont…) • The most notable point in the preceding program is the declaration of the character array word. • There is no mention of the number of elements in the array. • The C language allows you to define an array without specifying the number of elements. • If this is done, the size of the array is determined automatically based on the number of initialization elements. • Because preceding program has six initial values listed for the array word, the C language implicitly dimensions the array to six elements 23
  • 24. Demonstration • Base Converter (up to 16) #include <stdio.h> int main (void) { const char baseDigits[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; int convertedNumber[64]; long int numberToConvert; int nextDigit, base, index = 0; printf ("Number to be converted? "); scanf ("%ld", &numberToConvert); printf ("Base? "); scanf ("%i", &base); 24
  • 25. Demonstration do { convertedNumber[index] = numberToConvert % base; ++index; numberToConvert = numberToConvert / base; } while ( numberToConvert != 0 ); printf ("Converted number = "); for (--index; index >= 0; --index ) { nextDigit = convertedNumber[index]; printf ("%c", baseDigits[nextDigit]); } printf ("n"); return 0; } 25
  • 26. Multidimensional Arrays • The types of arrays that you have been exposed to so far are all linear arrays / single dimension arrays. • That is, they all dealt with a single dimension. • The C language allows arrays of any dimension to be defined. • In this section, you take a look at two- dimensional arrays. 26
  • 27. Multidimensional Arrays (Cont…) • One of the most natural applications for a two-dimensional array arises in the case of a matrix. • In mathematics, it is quite common to refer to an element of a matrix by use of a double subscript. • So if you call the preceding matrix M, the notation Mi,j refers to the element in the ith row, jth column, where i ranges from 1 to 4, and j ranges from 1 to 5. • The notation M3,2 refers to the value 20, which is found in the 3rd row, 2nd column of the matrix 27
  • 28. Multidimensional Arrays (Cont…) • In C, you can use an analogous notation when referring to elements of a twodimensional array. • However, because C likes to start numbering things at zero, the 1st row of the matrix is actually row 0, and the 1st column of the matrix is column 0. • The preceding matrix would then have row and column designations, as shown below; 28
  • 29. Multidimensional Arrays (Cont…) • Whereas in mathematics the notation Mi,j is used, in C the equivalent notation is M[i][j]. • Remember, the first index number refers to the row number, whereas the second index number references the column. • So the statement int sum = M[0][2] + M[2][4]; • adds the value contained in row 0, column 2—which is –3—to the value contained in row 2, column 4—which is 14—and assigns the result of 11 to the variable sum. • Two-dimensional arrays are declared the same way that one- dimensional arrays are; thus; int M[4][5]; • declares the array M to be a two-dimensional array consisting of 4 rows and 5 columns, for a total of 20 elements. • Each position in the array is defined to contain an integer value. 29
  • 30. Multidimensional Arrays (Cont…) • Two-dimensional arrays can be initialized in a manner analogous to their one-dimensional counterparts. • When listing elements for initialization, the values are listed by row. • Brace pairs are used to separate the list of initializers for one row from the next. • So to define and initialize the array M to the elements listed in preceding table, a statement such as the following can be used: 30
  • 31. Multidimensional Arrays (Cont…) #include <stdio.h> int main (void) { int M[4][5] = { { 10, 5, -3, 17, 82 }, { 9, 0, 0, 8, -7 }, { 32, 20, 1, 0, 14 }, { 0, 0, 8, 7, 6 } }; int x, y; for ( x = 0; x < 4; x++){ for (y = 0; y < 5; y++) printf( "%2i. ", M[x][y]); printf ("n"); } return 0; } 31
  • 32. Multidimensional Arrays (Cont…) • As with one-dimensional arrays, it is not required that the entire array be initialized. • A statement such as int M[4][5] = { { 10, 5, -3 }, { 9, 0, 0 }, { 32, 20, 1 }, { 0, 0, 8 } }; • Only initializes the first three elements of each row of the matrix to the indicated values. • The remaining values are set to 0. 32
  • 33. Multidimensional Arrays (Cont…) #include <stdio.h> int main (void) { int M[4][5] = { { 10, 5, -3 }, { 9, 0, 0 }, { 32, 20, 1 }, { 0, 0, 8 } }; int x, y; for ( x = 0; x < 4; x++){ for (y = 0; y < 5; y++) printf( "%2i. ", M[x][y]); printf ("n"); } return 0; } 33
  • 34. Multidimensional Arrays (Cont…) • Note that commas are required after each brace that closes off a row, except in the case of the final row. • The use of the inner pairs of braces is actually optional. • If not supplied, initialization proceeds by row. • Thus, the preceding statement could also have been written as follows: int M[4][5] = { 10, 5, -3, 17, 82, 9, 0, 0, 8, -7, 32, 20, 1, 0, 14, 0, 0, 8, 7, 6 }; 34
  • 35. Multidimensional Arrays (Cont…) #include <stdio.h> int main (void) { int M[4][5] = { 10, 5, -3, 17, 82, 9, 0, 0, 8, -7, 32, 20, 1, 0, 14, 0, 0, 8, 7, 6 }; int x, y; for ( x = 0; x < 4; x++){ for (y = 0; y < 5; y++) printf( "%2i. ", M[x][y]); printf ("n"); } return 0; } 35
  • 36. Variable Length Arrays • In the examples we discussed up to now, you have seen how the size of an array is declared to be of a specific size. • The C language allows you to declare arrays of a variable size. • Note that, full support for variable-length arrays was not offered by all C compilers. • You might want to check your compiler’s documentation before you use this feature. 36
  • 37. Objective Re-cap • Now you should be able to: ▫ Describe the C arrays. ▫ Practice the declaration, initialization and access linear arrays. ▫ Practice the declaration, initialization and access two dimensional arrays. ▫ Apply taught concepts for writing programs. 37
  • 38. References • Chapter 07, - Programming in C, 3rd Edition, Stephen G. Kochan 38
  • 39. Next: Working with Functions 39