Lecture-8_array - Computer Science I - Martin Hardwick...

Info iconThis preview shows pages 1–4. Sign up to view the full content.

View Full Document Right Arrow Icon

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: Computer Science I - Martin Hardwick Lecture 1 -- 1 One-Dimensional Array A one-dimensional array is a list of variables, all of the same type. it can be any of the C++ data types or object types a has a declared length each variable is identified by a subscript starting with 0 and ending with length -1 each variable in the list is called an element of the array Example: int counters[128]; An array element can be used in a program anywhere a variable can be used. e.g., 23 -45 2345 0 . . . 123 [0] [1] [2] [3] [127] counters counters[0] = 0; counters[i] = counters[i] + 1; cin >> counters[j]; if (counters[i-2] > 0) { . . .}; Computer Science I - Martin Hardwick Lecture 1 -- 2 For loops and arrays // Initialize counters to 0 for (int k=0; k<128; k++) { counters[k] = 0; } As always, counter variables should be initialized to 0 before you start counting. In this case, all 128 elements of the array must be initialized to 0 The easiest way to do this is with a for loop In general, you will find for loops very useful when working with arrays. Note again that the subscript of an array element can be an int variable or an arbitrary expression (as long as it evaluations to an int). Computer Science I - Martin Hardwick Lecture 1 -- 3 Program to initialize an array #include <iostream> using namespace std; int main() { int grades[100]; int i, count; for (i=0; i<100; i++) { cout << "> "; // display a prompt cin >> grades[i]; if (grades[i] < 0) break; } count = i; cout << count << " grades were entered" << endl; for (i=0; i<count; i++) { cout << "Grade " << i << " is " << grades[i] << endl; } return 0; } Goal: Get a list of grades and print them. Algorithm: Read until < 0 entered Print all the values read break is a statement that we can use to stop a loop early Works with both FOR and WHILE loops Useful for the other conditions that would otherwise make the condition of the loop unnecessarily complex Computer Science I - Martin Hardwick...
View Full Document

This note was uploaded on 04/04/2011 for the course CS 2400 taught by Professor Richie during the Spring '11 term at Rensselaer Polytechnic Institute.

Page1 / 12

Lecture-8_array - Computer Science I - Martin Hardwick...

This preview shows document pages 1 - 4. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online