0% found this document useful (0 votes)
2 views25 pages

C++ Lec13 IIT

Chapter 14 of 'An Introduction to Programming through C++' focuses on arrays, which are collections of variables of the same type that simplify data handling. It covers array creation, initialization, operations, and examples such as student marks display and histogram computation. Key concepts include array indexing, out-of-range errors, and the importance of using expressions for dynamic indexing.

Uploaded by

Abhishek Goutam
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views25 pages

C++ Lec13 IIT

Chapter 14 of 'An Introduction to Programming through C++' focuses on arrays, which are collections of variables of the same type that simplify data handling. It covers array creation, initialization, operations, and examples such as student marks display and histogram computation. Key concepts include array indexing, out-of-range errors, and the importance of using expressions for dynamic indexing.

Uploaded by

Abhishek Goutam
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

An Introduction to Programming

though C++
Abhiram G. Ranade

Ch. 14: Arrays


Computers must deal with large amounts of data

• Simulate what happens when many balls are


moving in a box. (Gas molecules?)
• Given altitudes of various points in a lake, find
how much water is there given the water level.
• Given the road map of India, find the shortest
route from Kirloskarwadi to Tatanagar.
How to handle lot of data?
• Fundamental problem: Writing out variable names to store
information would be tiring

double pressure1, pressure2, …, pressure1000;

• This is the problem solved using Arrays.


• More elaborate, modern, and flexible solution involving
“vector”s will be discussed later.
• Arrays are simple to understand. Ideas useful in vectors too.
Outline
• How to create arrays, access elements
• Using arrays
– Storing sequences
– Storing sets
– Storing “queues”
– Storing multiple graphics objects
• Example programs
Arrays
double pressure[1000];
• Essentially defines 1000 variables (“array elements”).
• Variables are named pressure[0], pressure[1], pressure[2],
…, pressure[999]
• General form:
data-type array-name[size];
• size also called length.
• array-name[index] gives indexth variable.
• Necessary: 0 <= index < size.
• Not just a collection of variables: Index may be given as an
expression.
Array element operations
double pressure[1000];
cin >> pressure[0] >> pressure[2];
pressure[1] = (pressure[0] + pressure[2])/2;
for(int i=0; i<1000; i++) cin >> pressure[i];
cout << pressure[439]*3.33 << endl;

for(int i=1; i<999; i++)


pressure[i] = (pressure[i-1] + pressure[i+1])/2;

• Array index can be an expression which will be evaluated during execution


and then the corresponding element will be used.
• Not possible with 1000 names.
Index out of range
double pressure[1000];
pressure[1000] = 1.2;
double d = pressure[-5];
• In the assignments above, the array index is outside the
allowed range: 0 through size-1.
• If the array indes is out of range, the program may run and
produce wrong results, may halt with a message. Nothing is
guaranteed.

• The programmer must ensure index stays in range.


Initialization while defining
int squares[4] = {0, 1, 4, 9};
int cubes[] = {0, 1, 8, 27, 64};
// size = 5 inferred.

int x, pqr[200], y[]={1,2,3,4};


Exercises
• Define an array to store 10 telephone numbers
– Assume telephone numbers are 9 digit long
– Assume telephone numbers are 12 digit long
• Define an array to store the first 5 primes, and
initialize it to be the 5 primes.
What we discussed
An array is a collection of variables of the same type.
A[0], A[1], ..., A[n-1]
Where A is the array name, [i] is the index.
Key point: the index can be specified by an expression which is
evaluated and the result used to determine which variable is
meant.
• How to declare arrays, with and without initialization.
• How to get values into and out of array elements.
• Next: Examples of use
🚲
Marks display problem
• Read in marks of the 100 students in a class,
given in roll number order, 0 to 99.
• After that:
– Students may arrive in any order, and give their roll
number.
– The program must respond by printing out their marks.

– If any illegal number is given as roll number, the


program must terminate.
Program
double marks[100];

for(int i=0; i<100; i++)


cin >> marks[i];

while(true){
int rollno;
cout << “Roll no:”;
cin >> rollno;
if(rollno < 0 || rollno > 99) break;
cout << marks[rollno] << endl;
}
Display who got highest
// marks defined and read into as before.
double maxsofar = marks[0];
for(int i=1; i < 100; i++){
// Plan: at the beginning of the ith iteration,
// maxsofar should hold the maximum of marks[0..i-1].
maxsofar = max(maxsofar, marks[i]);
}
// maxsofar now holds max value in marks[0..99].

for(int i=0; i < 100; i++)


if(marks[i] == maxsofar) cout << i << endl;

• Accumulating the maximum into the variable maxsofar: Very standard idiom.
• Going over the array to filter elements that match a certain condition: also standard.
Demo
• highest.cpp
Uses input redirection: data taken from highest.dat
Exercise
Usually we will have roll numbers starting at 1
rather than at 0.
To handle this, a simple strategy is to store the
marks of roll number i in marks[i-1].
Modify both the programs discussed in this segment
to follow this convention.
What we discussed
• Some simple programs involving arrays.
• Point to note: we did not store the roll numbers, because
the index played the role of the roll numbers.
• Programs involved idioms such as
– Going through all elements of the array and filtering out
elements to print.
– Accumulating the maximum in a variable. Other kinds of
accumulation is also possible, e.g. sum.
• Next: more examples
🚲
Histogram
Read in marks as before, print how many scored between 0-9, 10-19,20-
29, …, 90-99, and exactly 100.

int hist[11];
// Plan: hist[i] will store number of
// students getting marks between
// 10*i and 10*(i+1)-1

• On reading a certain mark v, add 1 to suitable element of hist.


• Which element?
– v/10, assuming v is integer, and truncation in division.
Histogram
for(int i=0; i<11; i++)
hist[i]=0;
for(int i=0; i<100; i++){
double marks; cin >> marks;
hist[ int(marks)/10 ]++;
// int(..) converts to int.
}
Demo
• hist.cpp
What we discussed
• Histogram computation
• Key ideas:
– Index is calculated in an unusual manner
– Integer division plays an important role
Next: Marks display variation

🚲
Mark display variation
• Roll numbers are not in range 1 .. 100, but a larger range, e.g. 170010022.
• Marklist = 100 pairs of numbers: (rollno, marks), … .
• Teacher must enter roll number, marks into the computer.
• Later:
– Students arrive and each student types in roll number r.
– Program must print out marks if r is valid roll number.
– If r is -1, then stop.
Program idea:
• Use an additional array for storing roll numbers.
• Store ith roll number in rollno[i] and ith mark into marks[i].
• When students arrive: Examine each element of the roll number array and
see if it equals r. If so print corresponding marks.
The program
int rollno[100]; double marks[100];
for(int i=0; i<100; i++) cin >> rollno[i] >> marks[i];

while(true){
int r; cin >> r; // read in query roll number
if(r == -1) break;
bool found = false;
for(int i=0; i<100; i++){
if(rollno[i] == r){
cout << marks[i] << endl;
found = true;
break;
}
}
if(!found) cout << “Roll number not found.\n”;
}
Demo
• generalRollNos.cpp
Exercise
• Modify the program so that there are marks for
two subjects.
What we discussed
• If the roll numbers are not in the range 0..N-1
where N is the number of students, then we need
to store the roll numbers also.
• Searching through the array to find data
corresponding to a “key” is a common idiom.
– Use of a “found” variable is a natural strategy
Next: Polynomial multiplication
🚲

You might also like