prerequisite review

32
Prerequisite Review Prerequisite Review CS215 UK Computer Science

Upload: charlotte-davis

Post on 02-Jan-2016

69 views

Category:

Documents


2 download

DESCRIPTION

Prerequisite Review. CS215 UK Computer Science. Why Review?. There are several major skills which are necessary from day one in CS215 that incoming students often have not learned or mastered. Manipulating Input and Output Streams File Input and Output Stream States Sentinel Loop Logic - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Prerequisite Review

Prerequisite ReviewPrerequisite ReviewCS215UK Computer Science

Page 2: Prerequisite Review

Why Review?Why Review?There are several major skills which

are necessary from day one in CS215 that incoming students often have not learned or mastered.◦Manipulating Input and Output Streams◦File Input and Output

Stream States◦Sentinel Loop Logic

Sentinel Loops End of File Loops

◦Arrays Declaration, Use, and Traversal

Page 3: Prerequisite Review

Manipulating I/O StreamsManipulating I/O StreamsStreams are special locations in

memory through which input and output flow

An input stream is a source of input data, and an output stream is a destination for output data

Some default streams exist, but most streams are defined by the programmer, much like a variable

Page 4: Prerequisite Review

Stream OperationsStream OperationsStreams are not magic!Operations must be performed on

the streams in order to gather input or produce output.

Each stream operation effects the reading or writeing marker (cursor) in some way.

By knowing how each command effects the cursor, you can master input and output!

Page 5: Prerequisite Review

Stream OperationsStream OperationsCommon Input Operations

◦>> (extraction)◦getline◦ignore

Common Output Operations◦<< (insertion)◦endl

Page 6: Prerequisite Review

Console I/OConsole I/OConsole I/O refers to input and

output using the keyboard and monitor

“cin” and “cout” are predefined streams◦“cin” is an input stream lining your

program to the keyboard◦“cout” is an output stream linkint

your program to the monitor

Page 7: Prerequisite Review

An ExampleAn Example#include <iostream> //include library for console I/O

//variables “cin” and “cout” are declared in this library#include <string>using namespace std; //apply the standard namespaceint main(){int X; //declare an integer variable named Xstring Sentence; //declare a string variable named sentencecout<<“Please enter an positive integer: ”; //promptcin>>X; //extract the next integer from the input stream

“cin”//store that extracted data into the variable called “X”

cout<<“Please type a sentence:”<<endl; //promptcin.ignore(255,’\n’); //Why is there an ignore here?getline(cin, sentence); //get the next line of input from

“cin”//store that line into the variabel called “sentence”

for( int i=0; i<X; i++ )cout<<sentence<<endl; //output the sentence on X lines

return 0;}

Page 8: Prerequisite Review

Output ManipulationOutput ManipulationSimply inserting items to the output

stream using << provides limited control of the output appearance.◦tabs and new lines

There is a library available which provide greater control of output appearance.◦scientific or decimal output◦precision of decimal output◦column alignment

Page 9: Prerequisite Review

The <iomanip> LibraryThe <iomanip> LibraryCommon Output Manipulation

◦fixed – disable scientific notation◦showpoint – show the decimal point◦setprecision – display a given number

of digits past the decimal point◦setw – set the character width of the

next output item

◦There are more which we won’t use…

Page 10: Prerequisite Review

An ExampleAn Example#include <iostream> //include library for console I/O#include <iomanip> //include library for stream manipulation#include <string>using namespace std; //apply the standard namespaceconst float PI = 3.14159;int main(){cout<<fixed; //disable scientific notation for the cout

streamcout<<showpoint; //have the cout stream show decimal pointscout<<setprecision(4); // have the cout stream show 4 placescout<<PI<<endl<<endl; //what will be output?

//output a table with columns alignedcout<<setw(8)<<“Pi”<<setw(12)<<“Multiplier”<<setw(10)<<“Resu

lt”;cout<<endl;

cout<<setw(8)<<PI<<setw(12)<<2<<setw(10)<<2*PI<<endl;cout<<setw(8)<<PI<<setw(12)<<3<<setw(10)<<3*PI<<endl;cout<<setw(8)<<PI<<setw(12)<<4<<setw(10)<<4*PI<<endl;}

Page 11: Prerequisite Review

The OutputThe Output3.1416

1234567890123456789012345678901234567890

Pi Multiplier Result

3.1416 2 6.2832

3.1416 3 9.4248

3.1416 4 12.5664

Press any key to continue . . .

setw(8)width of 8positions 1-8right-aligned

setw(12)width of 12positions 9-20right-aligned

setw(10)width of 10positions 21-30right-aligned

Page 12: Prerequisite Review

File I/OFile I/OThe same input and output

operations can be performed using files as the source or destination.

Input and Output streams connected to files must be created by the programmer, unlike “cin” and “cout” which are already created.

Page 13: Prerequisite Review

Five Steps for Using File Five Steps for Using File I/OI/O

1) Include the <fstream> library2) Declare your file stream variables…

“ifstream” type for input files“ofstream” type for output files

3) Open the file streams to associate them with the file on disk

4) Use your file stream variables as you would use any other I/O stream

>>, getline, ignore<<, endl, fixed, showpoint,

setprecision, setw5) Close your file stream variables

Page 14: Prerequisite Review

An ExampleAn Example#include <iostream> //include library for I/O commands#include <fstream> //include library for file I/O#include <string>using namespace std; //apply the standard namespaceint main(){int X; //declare an integer variable named Xstring Sentence; //declare a string variable named sentenceifstream fileIn; //declare an input file stream named

“fileIn”fileIn.open(“data.txt”); //connect “fileIn” to the file

“data.txt”fileIn>>X; //extract the next integer from the file streamfileIn.ignore(255,’\n’); //Why is there an ignore here?getline(fileInin, sentence); //get the next line of file

input

for( int i=0; i<X; i++ )cout<<sentence<<endl; //output the sentence on X lines

return 0;}

Page 15: Prerequisite Review

Stream StatesStream StatesFile streams can enter a “fail state”

during operation.Any further I/O operation on a

stream which is in a fail state is not performed properly Thus, you can get garbage input, no output, and your program is ineffective.

Even worse, no error or warning message is given, and the program does not terminate!

Page 16: Prerequisite Review

Causes of a Fail StateCauses of a Fail StateInput File Streams Enter a Fail State When…

◦You try to open a file that doesn’t exist or cannot be found.

◦You try to read data of an incompatible type.◦You try to read past the end of the file.

Output File Streams Enter a Fail State When…◦You try to create a file with an invalid name.◦You try to create/write to a write-protected file.◦You try to create/write to a file on a full device.

Page 17: Prerequisite Review

Determining the Stream Determining the Stream StateStateLuckily, it is simple to check the

state of a file stream to determine if any of these things have occurred!

The name of the stream can be used as a Boolean variable to check stream state!◦TRUE – Stream State is OK◦FALSE – Stream is in Fail State

Page 18: Prerequisite Review

An ExampleAn Exampleifstream fin;

int data;

fin.open(“data.txt”);

if( ! fin ) //if the bool value of “fin” is false

{ cout<<“Input file not opened properly!”<<endl;

exit(0); //exit program }

fin >> data;

if( fin ) //if the bool value of “fin” is true

cout<<“First piece of data is: “<<data<<endl;

fin >> data;

if( fin ) //if the bool value of “fin” is true

cout<<“Second piece of data is: “<<data<<endl;

Page 19: Prerequisite Review

Sentinel Loop LogicSentinel Loop LogicThe word sentinel refers to an

entity which protects something from unintended entry.

Sentinel Loop Logic refers to a loop which is explicitly designed to prevent bad data from being used in processing.◦The processing part of the loop

cannot be entered if the data is bad!

Page 20: Prerequisite Review

Loop Systems Which UseLoop Systems Which UseSentinel LogicSentinel Logic

Sentinel Loops◦ Data is repeatedly read in and processed until a

special data value is encountered. This special value is called the sentinel value.

◦ EXAMPLE: Read some test scores from the KB. Continue reading test scores until you encounter -1.

End of File (EOF) Loops◦ Data is repeatedly read in from a file and processed

until bad data is encountered or the end of the file is reached.

◦ EXAMPLE: Read all test scores in from the file. There are an unknown number of scores.

Page 21: Prerequisite Review

Loops Using Sentinel LogicLoops Using Sentinel LogicRequire a “Priming Read”Require a “Priming Read”--This code does not work properly!--

--Why? In what cases?--

int testScore;

int scoreSum = 0, scoreCount = 0;

float average;

while( testScore != -1 )

{

cin >> testScore; //read in the next test score

//process this test score

scoreSum = scoreSum + testScore;

scoreCount ++;

}

average = float(scoreSum) / float(scoreCount);

Page 22: Prerequisite Review

Corrected CodeCorrected Codeint testScore;

int scoreSum = 0, scoreCount = 0;

float average;

cin >> testScore; //prime read first test score

while( testScore != -1 )

{

//process this test score

scoreSum = scoreSum + testScore;

scoreCount ++;

cin >> testScore; //read in the next test score

}

average = float(scoreSum) / float(scoreCount);

Page 23: Prerequisite Review

A Correct EOF LoopA Correct EOF Loopint scoreSum = 0, scoreCount = 0;

float average;

ifstrem fin;

fin.open(“data.txt”);

fin >> testScore; //prime read first test score

while( fin ) //stop if file enters fail state

{

//process this test score

scoreSum = scoreSum + testScore;

scoreCount ++;

fin >> testScore; //read in the next test score

}

average = float(scoreSum) / float(scoreCount);

Page 24: Prerequisite Review

Benefits of Correct EOF Benefits of Correct EOF LoopLoop

Does not enter loop if…◦File is not opened properly.◦File is empty.

Loop stops and only valid data is processed if…◦An invalid data entry is encountered.◦The end of the file is encountered.

Does not go through loop one too many or one too few times.

Page 25: Prerequisite Review

ArraysArraysAn array (also called a vector) is a linear collection

of data which is given a single name.Each element in the array is of the same data

type.Each element in the array can be accessed

individually through an index.The name of the array refers to the beginning of

the collection in memory (the “base address”)Indexes into the array are offset from the base

address◦index 0 is the first item, index 3 is the fourth item, etc…

Page 26: Prerequisite Review

26

Declaring an ArrayDeclaring an Array

Declare an array called temps which will hold up to 5 individual float values

float temps[5]; // Declaration allocates memory

temps[0] temps[1] temps[2] temps[3] temps[4]

7000 7004 7008 7012 7016

number of elements in the array

indexes or subscripts

Base Address

Page 27: Prerequisite Review

Accessing Array Accessing Array ComponentsComponentsWhen you declare an array…

◦dataType name[constsize]; A piece of memory appropriately sized for

constsize instances of dataType is reserved and given the specified name

◦cout<<name; //DOES NOT WORK When you give the name of the array, the

compiler retrieves the beginning (base address) of the array, not any of the contents

◦cout<<name[intindex]; //WORKS By providing an index, you are effectively

telling the compiler “start at the beginning of this array and jump forward intindex spaces, give me the value there

Page 28: Prerequisite Review

Array TraversalArray TraversalOften it is useful to scan through

each cell in an array to operate on each piece of information (for example to initialize them), this is known as traversal.

Does it make sense to traverse an array like this?Arr[0] = 0;Arr[1] = 0;…Arr[1000] = 0;

Page 29: Prerequisite Review

Array TraversalArray TraversalArray traversal can more easily

be done using a counter controlled loop. Initialize the counter to 0 and set the stopping criteria to the array size.

for(int i=0; i<1000; i++)Arr[ i ] = 0;

Page 30: Prerequisite Review

30

Parallel ArraysParallel Arrays

Parallel arrays are two or more arrays that have the same index range and whose elements contain related information, possibly of different data types

EXAMPLE

const int SIZE 50;

int idNumber[SIZE];

float hourlyWage[SIZE]; parallel arrays

Page 31: Prerequisite Review

31

const int SIZE 50;const int SIZE 50;

int idNumber[SIZE]; int idNumber[SIZE]; // Parallel arrays hold// Parallel arrays hold

float hourlyWage[SIZE]; float hourlyWage[SIZE]; // Related information// Related information

idNumber[0] 4562 hourlyWage[0] 9.68

idNumber[1] 1235 hourlyWage[1] 45.75

idNumber[2] 6278 hourlyWage[2] 12.71

. . . . . . . . . . . .

idNumber[48] 8754 hourlyWage[48] 67.96

idNumber[49] 2460 hourlyWage[49] 8.97

Page 32: Prerequisite Review

For Further Review…For Further Review…Look at the resources on the

lecture part of the course web page.

Look at the CS115 notes:http://www.cs.uky.edu/~keen/115/115.html