View
242
Download
1
Category
Preview:
Citation preview
CS101: Fundamentals of Computer Programming Dr. Tejada stejada@usc.edu www-bcf.usc.edu/~stejada Week 4: Arrays,Strings, File I/O
Problem: Write a program to calculate the average test score for 10 students on 3 tests and printouts their letter grade based on the average. Use an array to hold the average test score of the 10 students.
1. Create a function to calculate the average test score 1. The function should ask the user enter 3 test scores to
average 2. Then calculate the average test score 3. Return the average test score
2. Create a function that printouts the student’s grade based on this average.
1. The function should based on the average score determine the student’s grade:
score >=90 is A, score>=80 is B, score >=70 is C, score >=60 is D, else F
2
double calculateAvg(int studentNum) {
double sum = 0; //sum of all test scores
double testScore; //individual student test score
cout << “Student: ” << studentNum << endl;
for (int i=0; i< 3; i++)
{
cout << “Enter test score “ << i+1 << “: “;
cin >> testscore; sum = sum + testscore;
}
return sum/3;
}
3
4
void printGrade(double score)
{
if (score >= 90)
cout << “A” << endl;
else if (score >= 80)
cout << “B” << endl;
else if (score >= 70)
cout << “C” << endl;
else if (score >= 60)
cout << “D” << endl;
else
cout << “F” << endl;
}
int main()
{
const int NUM_OF_STUDENTS = 10;
double averages[NUM_OF_STUDENTS]= {0};
//calculates and stores 10 students averages
for (int i=0; i<NUM_OF_STUDENTS; i++)
averages[i] = calculateAvg(i);
//prints out the grade for 10 students for (int i=0; i<NUM_OF_STUDENTS; i++)
{
cout << “Student: “ << i << endl;
printGrade(averages[i]);
} }
5
Two-‐ and Mul,dimensional Arrays � Two-dimensional array: collection of a fixed number
of components arranged in two dimensions � Sometimes called matrices or tables
� Declaration syntax:
� intExp1 and intExp2 are expressions with positive
integer values specifying the number of rows and columns in the array
� To access a component:
6
Mul,dimensional Arrays � n-‐dimensional array: collec,on of a fixed number of elements arranged in n dimensions (n >= 1)
� Declara,on syntax:
� To access a component:
C++ Programming: Program Design Including Data Structures, Sixth Edition
7
Accessing 2D Array Components
C++ Programming: Program Design Including Data Structures, Sixth Edition
8
Example: sales[5][3] = 25.75;
Two-‐Dimensional Array Ini,aliza,on During Declara,on
� Two-‐dimensional arrays can be ini,alized when they are declared: � Elements of each row are enclosed within braces and separated by commas
� All rows are enclosed within braces � For number arrays, unspecified elements are set to 0 � Example: int board[4][3]= {{2, 3, 1}
{15, 25, 13}
{20, 4, 7} {11, 18, 14}};
9
Processing Two-‐Dimensional Arrays � Ways to process a two-‐dimensional array:
� Process en,re array � Row processing: process a single row at a ,me � Column processing: process a single column at a ,me
� Each row and each column of a two-‐dimensional array is a one-‐dimensional array � To process, use algorithms similar to processing one-‐dimensional arrays
C++ Programming: Program Design Including Data Structures, Sixth Edition
10
Ini,aliza,on � Examples:
� To ini,alize row number 4 (fiPh row) to 0:
� To ini,alize the en,re matrix to 0:
C++ Programming: Program Design Including Data Structures, Sixth Edition
11
Input � Examples:
� To input into row number 4 (fiPh row):
� To input data into each component of matrix:
C++ Programming: Program Design Including Data Structures, Sixth Edition
12
Sum by Row � Example:
� To find the sum of row number 4:
C++ Programming: Program Design Including Data Structures, Sixth Edition
13
Sum by Column � Example:
� To find the sum of each individual column:
14
Find the Largest Element
15
• Example: – To find the largest element in each row:
Passing Two-‐Dimensional Arrays as Parameters to Func,ons
� Two-‐dimensional arrays are passed by reference as parameters to a func,on � Base address is passed to formal parameter
� Two-‐dimensional arrays are stored in row order � When declaring a two-‐dimensional array as a formal parameter, can omit size of first dimension, but not the second
C++ Programming: Program Design Including Data Structures, Sixth Edition
16
Arrays of Strings and the string Type � To declare an array of 100 components of type string:
string list[100];
� Basic opera,ons, such as assignment, comparison, and input/output, can be performed on values of the string type
� The data in list can be processed just like any one-‐dimensional array
C++ Programming: Program Design Including Data Structures, Sixth Edition
17
Arrays of Strings and Character Arrays
18
Character Arrays and C-‐Strings
� Character array: an array whose components are of type char
� C-‐strings are null-‐terminated ('\0‘) character arrays
� Example: � 'A' is the character A � "A" is the C-‐string A
� "A" represents two characters, 'A' and '\0‘
19
C++ Programming: Program Design Including Data Structures, Sixth Edition
� Example: char name[16]; � Since C-strings are null terminated and name has
16 components, the largest string it can store has 15 characters
� If you store a string whose length is less than the array size, the last components are unused
20
C++ Programming: Program Design Including Data Structures, Sixth Edition
Character Arrays and C-‐Strings
� Size of an array can be omitted if the array is initialized during declaration
� Example: char name[] = "John";
� Declares an array of length 5 and stores the C-string "John" in it
� Useful string manipulation functions � strcpy, strcmp, and strlen � #include <cstring>
21
C++ Programming: Program Design Including Data Structures, Sixth Edition
Character Arrays and C-‐Strings
String Comparison � C-‐strings are compared character by character using the colla,ng sequence of the system � Use the func,on strcmp
� If using the ASCII character set: � "Air" < "Boat" � "Air" < "An" � "Bill" < "Billy" � "Hello" < "hello"
22
C++ Programming: Program Design Including Data Structures, Sixth Edition
Reading and Wri,ng Strings � Most rules for arrays also apply to C-‐strings (which are character arrays)
� Aggregate opera,ons, such as assignment and comparison, are not allowed on arrays
� C++ does allow aggregate opera,ons for the input and output of C-‐strings
23
C++ Programming: Program Design Including Data Structures, Sixth Edition
String Input � Example: cin >> name;
� Stores the next input C-string into name
� To read strings with blanks, use get function: cin.get(name, m+1);
� Stores the next m characters into name but the newline character is not stored in name
� If input string has fewer than m characters, reading stops at the newline character
24
C++ Programming: Program Design Including Data Structures, Sixth Edition
String Output � Example: cout << name;
� Outputs the content of name on the screen � << continues to write the contents of name
until it finds the null character � If name does not contain the null character,
then strange output may occur � << continues to output data from memory
adjacent to name until a '\0' is found
25
C++ Programming: Program Design Including Data Structures, Sixth Edition
� manipulator is used to format the output � Two types of manipulators:
� With parameters
� Without parameters � Parameterized: require iomanip header
� setprecision, setw, and setfill � Nonparameterized: require iostream header
� endl, showpoint, left, and right C++ Programming: Program Design Including
Data Structures, Sixth Edition
26
Forma`ng Output
� setw manipulator � Outputs the value of an expression in a specified number of
columns � cout << setw(5) << name << endl; � If number of columns exceeds the number of columns required by
the expression � Output of the expression is right-‐jus,fied � Unused columns to the leP are filled with spaces
� setfill manipulator � Output stream variables can use setfill to fill unused columns
with a character � cout << setfill('#');
� left and right manipulators leP-‐jus,fies or right-‐jus,fies the output
� unsetf manipulator to disable other manipulator
27
Addi,onal Output Forma`ng Tools
File Input/Output � File: area in secondary storage to hold info � File I/O is a five-‐step process
1. Include fstream header 2. Declare file stream variables 3. Associate the file stream variables with the input/
output sources 4. Use the file stream variables with >>, <<, or other
input/output func,ons 5. Close the files
C++ Programming: Program Design Including Data Structures, Sixth Edition
28
Text File I/O #include <iostream> #include <fstream> using namespace std;
int main ()
{
int x; double y;
ifstream ifile (“input.txt“);
ofstream ofile;
ofile.open(“output.txt");
if( ifile.good() ){ // make sure not at end ifile >> x >> y; } else { return 1; }
ofile << “Int from file is “ << x << endl; ofile << “Double from file is “ << y << endl; ifile.close(); ofile.close();
return 0; }
5 -3.5
input.txt
Int from file is 5 Double from file is -3.5
output.txt
File Access � Though the data is on disk we can
imagine a “file pointer” (abbreviated “fp”) to the current position in the file � Similar analogy to a “play head” in
a tape recorder / VHS player � Your ifstream object (ifile) implicitly
keeps track of where you are in the file via this “pointer” � Any access to the file implicitly moves/updates
the location of the pointer
� EOF (end-of-file) or other error means no more data can be read. Use the good() function to ensure file pointer is okay or read/write operation succeeded
I t w a s t h e b e s t o f
...
fp
char c; ifile >> c;
a t f e r . T h e E n d ! EOF
fp
I t w a s t h e b e s t o f
fp
...
...
...
char c; ifile >> c; // get first char while( ifile.good() ) { // process c ifile >> c; // get next char
}
File text
>> Operator � Recall that with cin the >> operator
stops getting a value when it encounters whitespace and also skips whitespace to get to the next value
� In the example on this slide, the spaces will NOT be read in � They will be skipped by the >> operator
� To get raw data from the file (including whitespaces) use the get() function
I t w a s t h e b e s t o f
...
fp
char c; ifile >> c; // skips space and returns ‘w’
I t w a s t h e b e s t o f
...
char ch; ifile.get(ch); // get next char while( ifile.good() ) { // process ch ifile.get(ch); // get next char
}
File text
fp
Getting Lines of Text � Using the >> operator to get an
input string of text implicitly stops at the first whitespace
� How can we get a whole line of text (including spaces) � cin.getline(char buf[], int bufsize); � ifstream.getline(char buf[], int
bufsize); � Reads max of bufsize-1 characters
(including newline)
#include <iostream> #include <fstream> using namespace std;
int main ()
{
char myline[100]; int i = 1;
ifstream ifile (“input.txt“);
if( ifile.fail() ){ // exit if bad return 1; }
ifile.getline(myline, 100); while (ifile.good()) { cout << i++ << “: “ << myline << endl; ifile.getline(myline, 100); }
ifile.close(); return 0; }
The fox jumped over the log.
The bear ate some honey.
The CS student solved a hard problem.
1: The fox jumped over the log.
2: The bear ate some honey.
3: The CS student solved a hard problem.
input.txt
output
stdin, stdout, stderr � Most OS’es map console I/O
(keyboard and monitor I/O) to 3 predefined FILE pointers: � stdin (input from keyboard) = cin � stdout (output to monitor) = cout
� Normal output
� stderr (output to monitor) = cerr � Exception / error information
� Unix/Linux can allow you to redirect stdout vs. stderr separately � ./prog > log_of_stdout.txt � ./prog >& log_of_stderr.txt
int main() { char first_char; char first_line[80];
// read char from keyboard cin << first_char;
// read entire line of text from // keyboard cin.getline(first_line, 80);
// echo line back to stdout cout << first_line;
// output to stderr cerr << “I had an error.” << endl;
return 0; }
Problem: Write a program to calculate the average test score for each student in 3 classes of 10 students on 3 tests and printouts all the students’ letter grades based on their average. � Use a 2D array to hold the average test scores of
the 10 students for the 3 classes. � Create a function to calculate the average test
scores for 1 class of 10 students � Reuse these functions: 1. double calculateAvg(int studentNum)
2. void printGrade(double score)
34
double calculateAvg(int studentNum) {
double sum = 0; //sum of all test scores
double testScore; //individual student test score
cout << “Student: ” << studentNum << endl;
for (int i=0; i< 3; i++)
{
cout << “Enter test score “ << i+1 << “: “;
cin >> testscore; sum = sum + testscore;
}
return sum/3;
}
35
36
void printGrade(double score)
{
if (score >= 90)
cout << “A” << endl;
else if (score >= 80)
cout << “B” << endl;
else if (score >= 70)
cout << “C” << endl;
else if (score >= 60)
cout << “D” << endl;
else
cout << “F” << endl;
}
Take Home Problem: Write a program to calculate the average test score for each student in 3 classes of 10 students on 3 tests and printouts all the students’ letter grades based on their average. � Use a 2D array to hold the average test scores of the
10 students for the 3 classes. � Create a function to calculate the average test scores
for 1 class of 10 students. Use this function header: 1. void calculateClassAvgs(double studentAvgs[], int classNum,
int numOfStudents)
� Reuse these functions: 1. double calculateAvg(int studentNum) 2. void printGrade(double score)
37
Recommended