110 likes | 200 Views
CSE 2341 Honors. Professor Mark Fontenot Southern Methodist University Note Set 02. Quick Review. #include < iostream > using namespace std; void printReverse(int , int , int ); int main () { int a, b , c ; cout << “Hello and welcome!” << endl ;
E N D
CSE 2341 Honors Professor Mark Fontenot Southern Methodist University Note Set 02
Quick Review #include <iostream> using namespace std; void printReverse(int, int, int); int main () { int a, b, c; cout << “Hello and welcome!” << endl; cout << “Enter 3 numbers. -->”; cin >> a >> b >> c; printReverse(a, b, c); return 0; } void printReverse(int a, intb, intc) { cout << c << “ “ << b << “ “ << a << endl; }
Pass by Value vs. Pass by Reference • Pass by Value • argument is copied into parameter variable • changing parameter does not change argument • Pass by Reference • memory location of argument is stored in parameter reference variable • changing parameter reference variable will change the argument
Pass by Value vs. Pass by Reference #include <iostream> using namespace std; intdisplayAndChange(int& test) { cout << “test = “ << test << endl; test = 27; } int main () { int temp = 10; displayAndChange(temp); cout << “temp = “ << temp << endl; return 0; }
Arrays • Characteristics • contiguous block of memory • statically sized • not aware of their size • homogenously typed • size declarator should be const or literal Standard array declaration format: dataTypearrayName [arraySize]; int data[10]; double temps[5] = {99.4, 97.2, 98.1}; char str[15] = “Mark”;
Example Program - Cafeteria Food • 50 students asked to rate the quality of the cafeteria food on a scale of 1 to 10. • 1 – awful • 10 – amazing • Ask the user for the 50 responses • Summarize the results with a histogram/bar chart
Basic Character File I/O • #include <fstream> • Reading from file is similar to reading from keyboard (using cin) • File has special EOF marker after the last byte Input/Reading Output/Writing ifstreamfin(“data.dat”); if (!fstream) exit (1); ofstreamfout(“myData.out”); if(!fstream) exit (1);
Character File I/O ifstreamfin(“data.dat”); if (!fstream) exit (1); int a, b, c; fin >> a >> b >> c; cout << c << b << a; data.dat 27 38 49
Unknown Number of Values in File ifstreamfin(“data.dat”); if (!fstream) exit (1); int sum = 0, temp; while (fin >> temp) sum += temp; cout << sum << endl; data.dat 27 38 49
Remember! • Always close file streams after done using them • need to let OS know that you’re through incase there is a lock on the file for some reason • For output: will flush output buffer to file before closing to make sure all data gets is written. fstreamfout (“data.dat”); if (!fout) exit (1); //write data fout.close();