C++ Lec13 IIT
C++ Lec13 IIT
though C++
Abhiram G. Ranade
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].
• 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
🚲
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
🚲