37
CS101: Fundamentals of Computer Programming Dr. Tejada [email protected] www-bcf.usc.edu/~stejada Week 4: Arrays,Strings, File I/O

CS101 Fundamentals of Computer Programmingstejada/csci101/slides/wk4b-arrays2.pdfCS101: Fundamentals of Computer Programming! Dr. Tejada [email protected] stejada Week 4: Arrays,Strings,

  • Upload
    buidat

  • View
    241

  • Download
    1

Embed Size (px)

Citation preview

Page 1: CS101 Fundamentals of Computer Programmingstejada/csci101/slides/wk4b-arrays2.pdfCS101: Fundamentals of Computer Programming! Dr. Tejada stejada@usc.edu stejada Week 4: Arrays,Strings,

CS101: Fundamentals of Computer Programming  Dr. Tejada [email protected] www-bcf.usc.edu/~stejada Week 4: Arrays,Strings, File I/O

Page 2: CS101 Fundamentals of Computer Programmingstejada/csci101/slides/wk4b-arrays2.pdfCS101: Fundamentals of Computer Programming! Dr. Tejada stejada@usc.edu stejada Week 4: Arrays,Strings,

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

Page 3: CS101 Fundamentals of Computer Programmingstejada/csci101/slides/wk4b-arrays2.pdfCS101: Fundamentals of Computer Programming! Dr. Tejada stejada@usc.edu stejada Week 4: Arrays,Strings,

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

Page 4: CS101 Fundamentals of Computer Programmingstejada/csci101/slides/wk4b-arrays2.pdfCS101: Fundamentals of Computer Programming! Dr. Tejada stejada@usc.edu stejada Week 4: Arrays,Strings,

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;

}

Page 5: CS101 Fundamentals of Computer Programmingstejada/csci101/slides/wk4b-arrays2.pdfCS101: Fundamentals of Computer Programming! Dr. Tejada stejada@usc.edu stejada Week 4: Arrays,Strings,

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

Page 6: CS101 Fundamentals of Computer Programmingstejada/csci101/slides/wk4b-arrays2.pdfCS101: Fundamentals of Computer Programming! Dr. Tejada stejada@usc.edu stejada Week 4: Arrays,Strings,

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

Page 7: CS101 Fundamentals of Computer Programmingstejada/csci101/slides/wk4b-arrays2.pdfCS101: Fundamentals of Computer Programming! Dr. Tejada stejada@usc.edu stejada Week 4: Arrays,Strings,

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

Page 8: CS101 Fundamentals of Computer Programmingstejada/csci101/slides/wk4b-arrays2.pdfCS101: Fundamentals of Computer Programming! Dr. Tejada stejada@usc.edu stejada Week 4: Arrays,Strings,

Accessing  2D  Array  Components  

C++ Programming: Program Design Including Data Structures, Sixth Edition

8

Example: sales[5][3] = 25.75;

Page 9: CS101 Fundamentals of Computer Programmingstejada/csci101/slides/wk4b-arrays2.pdfCS101: Fundamentals of Computer Programming! Dr. Tejada stejada@usc.edu stejada Week 4: Arrays,Strings,

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

Page 10: CS101 Fundamentals of Computer Programmingstejada/csci101/slides/wk4b-arrays2.pdfCS101: Fundamentals of Computer Programming! Dr. Tejada stejada@usc.edu stejada Week 4: Arrays,Strings,

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

Page 11: CS101 Fundamentals of Computer Programmingstejada/csci101/slides/wk4b-arrays2.pdfCS101: Fundamentals of Computer Programming! Dr. Tejada stejada@usc.edu stejada Week 4: Arrays,Strings,

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

Page 12: CS101 Fundamentals of Computer Programmingstejada/csci101/slides/wk4b-arrays2.pdfCS101: Fundamentals of Computer Programming! Dr. Tejada stejada@usc.edu stejada Week 4: Arrays,Strings,

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

Page 13: CS101 Fundamentals of Computer Programmingstejada/csci101/slides/wk4b-arrays2.pdfCS101: Fundamentals of Computer Programming! Dr. Tejada stejada@usc.edu stejada Week 4: Arrays,Strings,

Sum  by  Row  � Example:  

�  To  find  the  sum  of  row  number  4:  

C++ Programming: Program Design Including Data Structures, Sixth Edition

13

Page 14: CS101 Fundamentals of Computer Programmingstejada/csci101/slides/wk4b-arrays2.pdfCS101: Fundamentals of Computer Programming! Dr. Tejada stejada@usc.edu stejada Week 4: Arrays,Strings,

Sum  by  Column  � Example:  

�  To  find  the  sum  of  each  individual  column:  

14

Page 15: CS101 Fundamentals of Computer Programmingstejada/csci101/slides/wk4b-arrays2.pdfCS101: Fundamentals of Computer Programming! Dr. Tejada stejada@usc.edu stejada Week 4: Arrays,Strings,

Find  the  Largest  Element  

15

•  Example:  – To  find  the  largest  element  in  each  row:  

Page 16: CS101 Fundamentals of Computer Programmingstejada/csci101/slides/wk4b-arrays2.pdfCS101: Fundamentals of Computer Programming! Dr. Tejada stejada@usc.edu stejada Week 4: Arrays,Strings,

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

Page 17: CS101 Fundamentals of Computer Programmingstejada/csci101/slides/wk4b-arrays2.pdfCS101: Fundamentals of Computer Programming! Dr. Tejada stejada@usc.edu stejada Week 4: Arrays,Strings,

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

Page 18: CS101 Fundamentals of Computer Programmingstejada/csci101/slides/wk4b-arrays2.pdfCS101: Fundamentals of Computer Programming! Dr. Tejada stejada@usc.edu stejada Week 4: Arrays,Strings,

Arrays  of  Strings  and  Character  Arrays  

18

Page 19: CS101 Fundamentals of Computer Programmingstejada/csci101/slides/wk4b-arrays2.pdfCS101: Fundamentals of Computer Programming! Dr. Tejada stejada@usc.edu stejada Week 4: Arrays,Strings,

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

Page 20: CS101 Fundamentals of Computer Programmingstejada/csci101/slides/wk4b-arrays2.pdfCS101: Fundamentals of Computer Programming! Dr. Tejada stejada@usc.edu stejada Week 4: Arrays,Strings,

� 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    

Page 21: CS101 Fundamentals of Computer Programmingstejada/csci101/slides/wk4b-arrays2.pdfCS101: Fundamentals of Computer Programming! Dr. Tejada stejada@usc.edu stejada Week 4: Arrays,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    

Page 22: CS101 Fundamentals of Computer Programmingstejada/csci101/slides/wk4b-arrays2.pdfCS101: Fundamentals of Computer Programming! Dr. Tejada stejada@usc.edu stejada Week 4: Arrays,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

Page 23: CS101 Fundamentals of Computer Programmingstejada/csci101/slides/wk4b-arrays2.pdfCS101: Fundamentals of Computer Programming! Dr. Tejada stejada@usc.edu stejada Week 4: Arrays,Strings,

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

Page 24: CS101 Fundamentals of Computer Programmingstejada/csci101/slides/wk4b-arrays2.pdfCS101: Fundamentals of Computer Programming! Dr. Tejada stejada@usc.edu stejada Week 4: Arrays,Strings,

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

Page 25: CS101 Fundamentals of Computer Programmingstejada/csci101/slides/wk4b-arrays2.pdfCS101: Fundamentals of Computer Programming! Dr. Tejada stejada@usc.edu stejada Week 4: Arrays,Strings,

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

Page 26: CS101 Fundamentals of Computer Programmingstejada/csci101/slides/wk4b-arrays2.pdfCS101: Fundamentals of Computer Programming! Dr. Tejada stejada@usc.edu stejada Week 4: Arrays,Strings,

� 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  

Page 27: CS101 Fundamentals of Computer Programmingstejada/csci101/slides/wk4b-arrays2.pdfCS101: Fundamentals of Computer Programming! Dr. Tejada stejada@usc.edu stejada Week 4: Arrays,Strings,

�  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  

Page 28: CS101 Fundamentals of Computer Programmingstejada/csci101/slides/wk4b-arrays2.pdfCS101: Fundamentals of Computer Programming! Dr. Tejada stejada@usc.edu stejada Week 4: Arrays,Strings,

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

Page 29: CS101 Fundamentals of Computer Programmingstejada/csci101/slides/wk4b-arrays2.pdfCS101: Fundamentals of Computer Programming! Dr. Tejada stejada@usc.edu stejada Week 4: Arrays,Strings,

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

Page 30: CS101 Fundamentals of Computer Programmingstejada/csci101/slides/wk4b-arrays2.pdfCS101: Fundamentals of Computer Programming! Dr. Tejada stejada@usc.edu stejada Week 4: Arrays,Strings,

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

Page 31: CS101 Fundamentals of Computer Programmingstejada/csci101/slides/wk4b-arrays2.pdfCS101: Fundamentals of Computer Programming! Dr. Tejada stejada@usc.edu stejada Week 4: Arrays,Strings,

>> 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

Page 32: CS101 Fundamentals of Computer Programmingstejada/csci101/slides/wk4b-arrays2.pdfCS101: Fundamentals of Computer Programming! Dr. Tejada stejada@usc.edu stejada Week 4: Arrays,Strings,

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

Page 33: CS101 Fundamentals of Computer Programmingstejada/csci101/slides/wk4b-arrays2.pdfCS101: Fundamentals of Computer Programming! Dr. Tejada stejada@usc.edu stejada Week 4: Arrays,Strings,

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; }

Page 34: CS101 Fundamentals of Computer Programmingstejada/csci101/slides/wk4b-arrays2.pdfCS101: Fundamentals of Computer Programming! Dr. Tejada stejada@usc.edu stejada Week 4: Arrays,Strings,

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

Page 35: CS101 Fundamentals of Computer Programmingstejada/csci101/slides/wk4b-arrays2.pdfCS101: Fundamentals of Computer Programming! Dr. Tejada stejada@usc.edu stejada Week 4: Arrays,Strings,

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

Page 36: CS101 Fundamentals of Computer Programmingstejada/csci101/slides/wk4b-arrays2.pdfCS101: Fundamentals of Computer Programming! Dr. Tejada stejada@usc.edu stejada Week 4: Arrays,Strings,

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;

}

Page 37: CS101 Fundamentals of Computer Programmingstejada/csci101/slides/wk4b-arrays2.pdfCS101: Fundamentals of Computer Programming! Dr. Tejada stejada@usc.edu stejada Week 4: Arrays,Strings,

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