Before we get started…. First, a few things… Weighted Grading System Programming Style Submitting your assignments… The char and string variable types.

Post on 18-Jan-2016

218 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

Transcript

Before we get started…

First, a few things…

Weighted Grading System Programming Style Submitting your assignments… The char and string variable types

Weighted Grading System (WGS)

Provides greater flexibility Does not require knowing exactly how many

points each assignment will be. I use the weighted system because the

portion of your grade that each type of assignment affects remains the same.

Illustration…

Programming Projects 400 pts. 40%

Homework 200 pts. 20%

Quizzes 100 pts. 10%

Exams 300 pts. 30%

At the end of the semester, if the homework total ends up being 130 pointsand the quiz total ends up being 80 points, how does this change the effectthat programming projects and exams have on your grade?

Illustration…

Programming Projects 400 pts. 44%

Homework 130 pts. 14%

Quizzes 80 pts. 9%

Exams 300 pts. 33%

The programming projects and exams end up having a larger effect onyour grade—I don’t like when that happens.

Estimating Your Grade

A = totalHWPointsEarned / totalHWPointsPossible B = totalQuizPointsEarned / totalQuizPointsPossible C = totalProgProjPointsEarned / totalProgProjPointsPossible D = midtermPointsEarned / midtermPointsPossible E = finalPointsEarned / finalPointsPossible

If you do not have any assignments for a given category then you have to substitute it with a 1.

So far we do not have any points in the categories C, D and E so substitute a 1 for these three.

Grade = A * 0.25 + B * 0.15 + C * 0.40 + D * 0.10 + E * 0.10

Programming Style

A style sheet will not be distributed The purpose of the class is to introduce you to

programming, and programming style The style sheet will be built during the

semester as we learn new concepts The main thing we need to worry about for

now in regards to style is the proper use of tabs.

Programming Style (continued)

For the most part, Microsoft Visual Studio 2005 (and many other development environments) will take care of the tabbing issue for you.

A general rule of thumb, all blocks should be tabbed

Submitting Assignments

I ask that assignments are submitted in a clasp envelope for several reasons It keeps the printed part of the assignment and

the media (diskette or CD) together. If there are materials that I need to distribute I

can put them inside of the envelope and hand each person one thing.

Requirements for submitting assignments are stated in the syllabus in the homework and programming project sections.

char Variable Type

char ch;

ch = ‘8’; // line 1ch = 8; // line 2

These two statements are very different! Line 1 sets the value of the variable ch to the

character 8 Line 2 sets the value of the variable ch to the

backspace character

string Variable Type

To set the value of a string variable to a string use double quotes.

string myString;

myString = “This is my string.”;

string Variable Type (contd.)

To access a character in the string at a certain position use [ ].

The position of a character in the string variable begins at zero

myString[0] is the character ‘T’myString[3] is the character ‘s’

string Variable Type (contd.) Using the string variable type as a filename to use with input and output

streams.

ofstream outputStream;string myOutputFileName;

cout << “Please enter the output file name: ”;cin.ignore( 10000, ‘\n’ ); // skip extraneous data

// in input stream

getline( cin, myOutputFileName );

outputStream.open( myOutputFileName.c_str() );

// do what you need to do with the file

outputStream.close();

Chapter 5

Control Structures II (Repetition)

Types of Looping in C++

while Looping

do...while Looping

for Looping

The while Loop

General form of a while loop:

while ( expression )statement

expression - usually a logical expression - decision maker

- provides entry into loop

statement - may be simple or compound- called the body of the loop

The while Loop (continued)

statement continues to execute until expression evaluates to false

An infinite loop occurs when expression never evaluates to false

while Loop Diagram

Types of Exit Conditions

Counter-Controlled while Loop

Sentinal-Controlled while Loop

Flag-Controlled while Loop

EOF-Controlled while Loop

Counter-Controlled while Loop

Number of iterations is known Must initialize loop control variable Test loop control variable each iteration Update the counter in the body of the loop

int counter = 0;

while ( counter < 10 )

{

cout << “Counter Value is: ” << counter << endl;

counter ++;

}

Sentinel-Controlled while Loop Have a known special value, or sentinel value

loop ends when value encountered. Read first value before loop

Known as the priming read

const char SENTINEL = ‘!’;char newChar;ofstream outStream;outStream.open(“output.txt”);

cin >> newChar;

while ( newChar != SENTINEL ){

cin >> newChar;outStream << newChar;

}

Flag-Controlled while Loop

Uses a bool variable as exit condition.

found = false;

while ( !found )

{

if ( expression )

found = true;

}

EOF-Controlled while Loop

Uses the end of file marker to control the loop The logical value returned by cin can be used as an exit

condition in an EOF controlled while loop.

int x = 0;cin >> x;while ( cin ) {

cout << “x = ” << x << endl;cin >> x;

}

Input: 1 21 3 0 7 9 11 c 56 7 9

Input Streams and the eof Function

The eof function determines the end of file status.

Syntax:

istreamVar.eof();

where istreamVar is an input stream variable.

The for Loop

General form of a for loop

for ( initial statement; loop condition; update statement )

statement

The initial statement, loop condition and update statement are called for loop control statements

The for Loop

How it works…1. The initial statement executes

2. The loop condition is evaluated If loop condition evaluates to true,

The statement is executed The update statement is executed

3. Repeat steps 1 and 2 until the loop condition evaluates to false.

for Loop Diagram

More On for Loops

If loop condition is initially false, the loop body does not execute.

When the update expression is executed it actually changes the value of the loop control variable.

Loop control variable is initialized in initial expression

In the for statement, if the loop condition is omitted it is assumed to be true

All three statements may be omitted

The do…while Loop

General for of a do…while Loop

do

statement

while(expression); // must have semicolon

If statement is compound you must use braces Statement executes first then expression is checked,

if true the statement is executed again Guaranteed to execute at least once

do...while Loop Diagram

The break Statement

The break statement alters the flow of control

The break statement when used in a repetition structure, immediately exits loop

After the break statement exits the loop, the first statement outside of the loop body is executed.

The continue Statement

The continue statement alters the flow of control

The continue statement when used in a repetition structure, immediately proceeds to the next iteration of the loop skipping any statements that follow

Nested Control Structures

Suppose we want to create the following pattern

*

**

***

****

***** In the first line, we want to print one star, in

the second line two stars and so on

Nested Control Structures (contd.)

Since five lines are to be printed, we start with the following for statement

for (i = 1; i <= 5 ; i++)

The value of i in the first iteration is 1, in the second iteration it is 2, and so on

Can use the value of i as limit condition in another for loop nested within this loop to control the number of starts in a line

Nested Control Structures (contd.)

for (i = 1; i <= 5 ; i++)

{

for (j = 1; j <= i; j++)

cout << "*";

cout << endl;

}

Example Program

Create a program that calculates bn. If the base, b, is equal to zero then the result is always

zero If the power, n, is equal to zero then the result is always

one

Have user input values for the base and the power. Output the result Ask the user if they would like to execute the program again.

‘Y’ or ‘y’ for yes ‘N’ or ‘n’ for no Repeat this question until a valid response is entered.

Example Program (continued)

Steps− Declare the variables− Initialize the variables− Get the value of the base− Get the value of the power− Calculate the result (base raised to power)− Print the result− Ask user if they would like to execute again

Example Program (continued)

Variables (declare & initialize)

bool executeAgain = false;

double result = 1.0;

double base = 0.0;

int power = 0;

int absPower = 0;

char response = ‘ ‘;

bool responseValid = false;

Example Program (continued)

Get the values required

cout << “Please enter the base (b): ”;

cin >> base;

cout << “Please enter the power (n): ”;

cin >> power;

Example Program (continued) Calculate the result

if ( base == 0 )result = 0;

else if ( power == 0 )result = 1;

else{

absPower = abs(power);

for ( int counter = 0; counter < absPower; counter++) result *= base;

if ( power < 0 ) result = 1.0 / result;

}

Example Program (continued) Ask the user if he/she would like to execute the program again and

continue until valid response.

while ( !responseValid ){

cout << “Would you like to repeat this program” << “( yes = Y, no = N )? ”;cin >> response;

if ( response == ‘Y’ || response == ‘y’ || response == ‘N’ || response == ‘n’) responseValid = true;else{ cout << “\nInvalid response!” << endl; responseValid = false;}

}

Example Program (continued)

Wrap steps 3-6 in a do…while loop that continues only if response is ‘y’ or ‘Y’

Use input base = 5 and power = a to demonsrate input failure

#include < iostream >#include < string >#include < conio.h >

using namespace std;

int main ( ){

double result = 1;int i = 0;double base = 0;int power = 0;int absPower = 0;bool responseValid = false;char response = ' ';

do { cout << "This program will calculate b^n" << endl << endl

<< "Please enter base (b): "; cin >> base;

cout << "Please enter the power (n): "; cin >> power;

if ( base == 0 ) result = 0;

else if ( power == 0 ) result = 1;

else {

absPower = abs(power);

for ( int counter = 0; counter < absPower; counter++ ) result *= base;

if ( power < 0 ) result = 1 / result;

}

if ( power < 0 ) cout << endl << "b^n = " << base << "^(" << power << ") = " << result << endl <<

endl; else cout << endl << "b^n = " << base << "^" << power << " = " << result << endl << endl;

while ( !responseValid ) { cout << "Would you like to repeat this program ( yes = Y, no = N )? "; cin >> response;

if ( response == 'Y' || response == 'y' || response == 'N' || response == 'n' ) responseValid = true; else { cout << "\nInvalid response!" << endl; responseValid = false; } }

}while ( response == 'y' || response == 'Y' );

cout << "\nPlease press any key to exit." << endl;_getch();

return 0;}

Lab

Write a program to estimate your grade in this course.

Prompt user for input file name Output total points earned / total points possible for

each assignment type Assignment types are:

H or h : homework Q or q : quizzes P or p : programming projects M or m : midterm exam F or f : final exam

Input file should have the form

Q 7 / 10

H 17.5 / 20

H 19 / 20

P 82 / 100

Homework Questions 1. Exercise #1, Pg. 291 2. Write a program that writes the ASCII table to a file named ascii_table.txt. Start with ASCII 33 and end with ASCII 126. The format should resemble the following:

33 !34 “35 #36 $…

Separate the integer value from the character using the tab character ‘\t’

3. Write a program that prompts the user to enter a string and one character. Search the string provided and display a count of the number of times the character is present in the string. 4. Exercise #17, Pg. 305 (a data file will be provided)

top related