chapter 2 c++ basics

33
Chapter 2 Chapter 2 C++ Basics C++ Basics Goals: Goals: To introduce the concept of a variable and its assignment To introduce the concept of a variable and its assignment To explore primitive input and output operations To explore primitive input and output operations To survey the primitive data types in C++ To survey the primitive data types in C++ To examine the use of arithmetic expressions To examine the use of arithmetic expressions To define flow of control via conditionals and loops To define flow of control via conditionals and loops

Upload: hu-tucker

Post on 31-Dec-2015

28 views

Category:

Documents


2 download

DESCRIPTION

Chapter 2 C++ Basics. Goals:. To introduce the concept of a variable and its assignment. To explore primitive input and output operations. To survey the primitive data types in C++. To examine the use of arithmetic expressions. To define flow of control via conditionals and loops. - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Chapter 2 C++ Basics

Chapter 2Chapter 2C++ BasicsC++ Basics

Goals:Goals:

• To introduce the concept of a variable and its To introduce the concept of a variable and its assignmentassignment• To explore primitive input and output operationsTo explore primitive input and output operations

• To survey the primitive data types in C++To survey the primitive data types in C++

• To examine the use of arithmetic expressionsTo examine the use of arithmetic expressions

• To define flow of control via conditionals and loopsTo define flow of control via conditionals and loops

Page 2: Chapter 2 C++ Basics

Chapter 2Chapter 2CS 140CS 140 Page Page 22

VariablesVariables

Variables are memory locations within RAM.Variables are memory locations within RAM.

RAMRAMRAM is divided RAM is divided into 8-bit into 8-bit segments segments

called called bytesbytes..

Each byte is Each byte is numbered with numbered with

a binary a binary addressaddress..

Binary Binary Address Address

0000000000000000

Binary Binary Address Address

1111111111111111

When a program When a program variable is variable is declareddeclared, , adequate space in adequate space in

RAM is reserved for RAM is reserved for it.it.

The variable is named The variable is named with an with an identifieridentifier and and can be given a can be given a valuevalue..

That value is stored That value is stored at its memory at its memory

address, which is address, which is known as a known as a pointerpointer..

Variable Variable of typeof type charchar

Variable Variable of typeof type intint Variable of Variable of

typetype double double

Page 3: Chapter 2 C++ Basics

Chapter 2Chapter 2CS 140CS 140 Page Page 33

IdentifiersIdentifiers

Variables names, or identifiers, must start with an Variables names, or identifiers, must start with an underscore or an alphabetic symbol, and all the underscore or an alphabetic symbol, and all the remaining symbols must be alphanumeric or remaining symbols must be alphanumeric or underscores.underscores.

Page 4: Chapter 2 C++ Basics

Chapter 2Chapter 2CS 140CS 140 Page Page 44

Reserved C++ Keywords -Reserved C++ Keywords -Can’t Be Used As Identifiers!Can’t Be Used As Identifiers!

asmasm autoauto badbad__castcast badbad__typeidtypeidboolboolbreakbreak casecase catchcatch charchar classclassconstconst constconst__castcast continuecontinue defaultdefaultdeletedeletedodo doubledouble dynamicdynamic__castcast elseelse enumenumexceptexcept explicitexplicit externextern falsefalse finallyfinallyfloatfloat forfor friendfriend gotogoto ififinlineinline intint longlong mutablemutablenamespacenamespacenewnew operatoroperator privateprivate protectedprotectedpublicpublicregisterregister reinterpret_castreinterpret_cast returnreturn shortshortsignedsignedsizeofsizeof staticstatic staticstatic__castcast structstruct switchswitchtemplatetemplate thisthis throwthrow truetrue trytrytypetype__infoinfo typedeftypedef typeidtypeid typenametypename unionunionunsignedunsigned usingusing virtualvirtual voidvoid volatilevolatilewhilewhile

Page 5: Chapter 2 C++ Basics

Chapter 2Chapter 2CS 140CS 140 Page Page 55

Variable DeclarationsVariable Declarations

Variables must be declared before being used in a Variables must be declared before being used in a program.program.

int count;int count;

float salaryPerWeek;float salaryPerWeek;

char middleInitial;char middleInitial;

string first_name, last_name, full_name;string first_name, last_name, full_name;

float MonPay, TuePay, WedPay,float MonPay, TuePay, WedPay, ThuPay, FriPay;ThuPay, FriPay;

double measurement1, measurement2;double measurement1, measurement2;

Page 6: Chapter 2 C++ Basics

Chapter 2Chapter 2CS 140CS 140 Page Page 66

Assignment StatementsAssignment Statements

Variables may be “assigned” values via the Variables may be “assigned” values via the assignment operator (=) in assignment statements.assignment operator (=) in assignment statements.

count = 0;count = 0;

salaryPerWeek = 40 * salaryPerHour;salaryPerWeek = 40 * salaryPerHour;

middleInitial = ‘P’;middleInitial = ‘P’;

full_name = first_name + “ “ + last_name;full_name = first_name + “ “ + last_name;

MonPay = TuePay = WedPay = 47.25F;MonPay = TuePay = WedPay = 47.25F;ThuPay = FriPay = (float)62.75;ThuPay = FriPay = (float)62.75;

measurement2 = measurement1 / count;measurement2 = measurement1 / count;

Page 7: Chapter 2 C++ Basics

Chapter 2Chapter 2CS 140CS 140 Page Page 77

Initializing VariablesInitializing Variables

Variables may be “initialized” in their declarations to Variables may be “initialized” in their declarations to possess specific values.possess specific values.

int value = 0;int value = 0;

float Radius = 16.00F;float Radius = 16.00F;

bool flag = false;bool flag = false;

double errorMargin = 0.00000003;double errorMargin = 0.00000003;

char firstltr = ‘A’, lastltr = ‘Z’;char firstltr = ‘A’, lastltr = ‘Z’;

int loserCount(0), winnerCount(0);int loserCount(0), winnerCount(0);

string greeting(“hello”);string greeting(“hello”);

Page 8: Chapter 2 C++ Basics

Chapter 2Chapter 2CS 140CS 140 Page Page 88

Output to the Monitor viaOutput to the Monitor via cout coutValues may be output to the monitor by means of Values may be output to the monitor by means of output statementsoutput statements that use the output operator (<<) that use the output operator (<<) to stream to the output fileto stream to the output file cout cout..

cout << 1492;cout << 1492;

int val = 56;int val = 56;cout << val;cout << val;

cout << 2009 << “was great!”;cout << 2009 << “was great!”;cout << “I made a fortune!”;cout << “I made a fortune!”;

cout << val << “million\n\ndollars!”;cout << val << “million\n\ndollars!”;

cout << 2009 << “ was great!\n”;cout << 2009 << “ was great!\n”;cout << “I made a fortune!”;cout << “I made a fortune!”;

Output:Output:14921492

Output:Output:5656Output:Output:

2009was great!I made a fortune!2009was great!I made a fortune!

Output:Output:2009 was great!2009 was great!I made a fortune!I made a fortune!

Output:Output:56million56million

dollars!dollars!

Page 9: Chapter 2 C++ Basics

Chapter 2Chapter 2CS 140CS 140 Page Page 99

Escape SequencesEscape Sequences

\a Bell (alert)\a Bell (alert)

#include <iostream>using namespace std;void main(){ cout << "1Aa\azzz\aZZZ" << endl; cout << "2Bb\bzzz\bZZZ" << endl; cout << "3Cc\nzzz\nZZZ" << endl; cout << "4Dd\rzzz\rZZZ" << endl; cout << "5Ee\tzzz\tZZZ" << endl; cout << "6Ff\'zzz\'ZZZ" << endl; cout << "7Gg\"zzz\"ZZZ" << endl; cout << "8Hh\\zzz\\ZZZ" << endl; return;}

When a character value When a character value contains a character contains a character preceded by a backslash preceded by a backslash ((\\), then it represents a ), then it represents a singlesingle symbol known as an symbol known as an escape sequence.escape sequence.

\b Backspace\b Backspace\n New line\n New line\r Carriage return\r Carriage return\t Horizontal tab\t Horizontal tab\' Single quotation mark\' Single quotation mark\" Double quotation mark\" Double quotation mark\\ Backslash\\ Backslash

Page 10: Chapter 2 C++ Basics

Chapter 2Chapter 2CS 140CS 140 Page Page 1010

Formatting Real Number OutputFormatting Real Number OutputTo ensure that real numbers are output with decimal To ensure that real numbers are output with decimal points, an integer part, and a specific number of points, an integer part, and a specific number of decimal places, the following lines should be included decimal places, the following lines should be included before outputting:before outputting:

cout.setf(ios::fixed);cout.setf(ios::fixed);

cout.setf(ios::showpoint);cout.setf(ios::showpoint);

cout.precision(4);cout.precision(4);

Avoids Scientific Notation.Avoids Scientific Notation.

Shows Decimal PointShows Decimal Point& Trailing Zeros.& Trailing Zeros.

Shows 4 DigitsShows 4 DigitsAfter Decimal Point.After Decimal Point.

Page 11: Chapter 2 C++ Basics

Chapter 2Chapter 2CS 140CS 140 Page Page 1111

Sample ProgramSample Program

#include <iostream>using namespace std;

void main(){ cout.setf(ios::fixed); cout.setf(ios::showpoint); cout.precision(8); cout << 9876.543210 << endl; cout << 0.246813579 << endl; cout << 37.00000000 << endl << endl;

cout.precision(4); cout << 9876.543210 << endl; cout << 0.246813579 << endl; cout << 37.00000000 << endl << endl;

cout.precision(2); cout << 9876.543210 << endl; cout << 0.246813579 << endl; cout << 37.00000000 << endl << endl;

}

Page 12: Chapter 2 C++ Basics

Chapter 2Chapter 2CS 140CS 140 Page Page 1212

Input from the Keyboard viaInput from the Keyboard via cin cinValues may be input from the keyboard by means of Values may be input from the keyboard by means of input statementsinput statements that use the input operator (>>) to that use the input operator (>>) to stream from the input filestream from the input file cin cin..#include <iostream>using namespace std;

void main(){ int nbr; cin >> nbr;

char init1, init2, init3; cin >> init1 >> init2 >> init3;

float temp; cout << "Enter the temperature: "; cin >> temp;

return;}

Page 13: Chapter 2 C++ Basics

Chapter 2Chapter 2CS 140CS 140 Page Page 1313

Data Types - IntegersData Types - Integers#include <iostream>#include <limits>using namespace std;

void main(){ int NTjurA = 5, NTjurB = INT_MAX, NTjurC = INT_MIN; cout << "REGULAR INTEGERS:" << endl << NTjurA << endl << NTjurB << endl << NTjurC << endl << endl;

long NNNNNTjurD = 5, NNNNNTjurE = LONG_MAX, NNNNNTjurF = LONG_MIN; cout << "LONG INTEGERS:" << endl << NNNNNTjurD << endl << NNNNNTjurE << endl << NNNNNTjurF << endl << endl;

short nTjurG = 5, nTjurH = SHRT_MAX, nTjurI = SHRT_MIN; cout << "SHORT INTEGERS:" << endl << nTjurG << endl << nTjurH << endl << nTjurI << endl << endl;

unsigned int UnNTjurJ = 5, UnNTjurK = UINT_MAX; cout << "UNSIGNED INTEGERS:" << endl << UnNTjurJ << endl << UnNTjurK << endl << endl << endl; return;}

Page 14: Chapter 2 C++ Basics

Chapter 2Chapter 2CS 140CS 140 Page Page 1414

Data Types - Floating-PointData Types - Floating-Point

#include <iostream>#include <cfloat>using namespace std;void main(){ float floA = 9.87654321F, floB = FLT_EPSILON, floC = FLT_MAX, floD = FLT_MIN; cout << "REGULAR FLOATS:" << endl << floA << endl << floB << endl << floC << endl << floD << endl << endl;

double dubE = 9.87654321, dubF = DBL_EPSILON, dubG = DBL_MAX, dubH = DBL_MIN; cout << "DOUBLE FLOATS:" << endl << dubE << endl << dubF << endl << dubG << endl << dubH << endl << endl;

long double ldI = 9.87654321, ldJ = LDBL_EPSILON, ldK = LDBL_MAX, ldL = LDBL_MIN; cout << "LONG DOUBLE FLOATS:" << endl << ldI << endl << ldJ << endl << ldK << endl << ldL << endl << endl << endl;

return;}

Page 15: Chapter 2 C++ Basics

Chapter 2Chapter 2CS 140CS 140 Page Page 1515

Data Types - Characters and Data Types - Characters and BooleansBooleans

#include <iostream>using namespace std;void main(){ char chA = 'T'; char chB = '\t'; char chC = '\\';

cout << chA << chB << chC << endl << chB << chC << chA << endl << chC << chA << chB << endl << endl;

return;}

#include <iostream>using namespace std;void main(){ bool booX = true; bool booY = false; bool booZ = (532 > 738);

cout << booX << endl << booY << endl << booZ << endl << endl;

return;}

Page 16: Chapter 2 C++ Basics

Chapter 2Chapter 2CS 140CS 140 Page Page 1616

#include <iostream>using namespace std;void main(){ int NTjurA = 9.635F, NTjurB = 9.635, NTjurC = '&’, NTjurD = true; cout << NTjurA << '\t' << NTjurB << '\t' << NTjurC << '\t' << NTjurD << "\n\n";

float floE = 65, floF = 65.34, floG = 'Q’, floH = false; cout << floE << '\t' << floF << '\t' << floG << '\t' << floH << "\n\n";

double dubI = 14, dubJ = 14.92F, dubK = '?’, dubL = true; cout << dubI << '\t' << dubJ << '\t' << dubK << '\t' << dubL << "\n\n";

char chM = 3, chN = 3.1416F, chO = 3.1416, chP = true; cout << chM << '\t' << chN << '\t' << chO << '\t' << chP << "\n\n";

bool booQ = 467, booR = 467.927F, booS = 467.927, booT = 'w'; cout << booQ << '\t' << booR << '\t' << booS << '\t' << booT << "\n\n";

return;}

#include <iostream>using namespace std;void main(){ int NTjurA = 9.635F, NTjurB = 9.635, NTjurC = '&’, NTjurD = true; cout << NTjurA << '\t' << NTjurB << '\t' << NTjurC << '\t' << NTjurD << "\n\n";

float floE = 65, floF = 65.34, floG = 'Q’, floH = false; cout << floE << '\t' << floF << '\t' << floG << '\t' << floH << "\n\n";

double dubI = 14, dubJ = 14.92F, dubK = '?’, dubL = true; cout << dubI << '\t' << dubJ << '\t' << dubK << '\t' << dubL << "\n\n";

char chM = 3, chN = 3.1416F, chO = 3.1416, chP = true; cout << chM << '\t' << chN << '\t' << chO << '\t' << chP << "\n\n";

bool booQ = 467, booR = 467.927F, booS = 467.927, booT = 'w'; cout << booQ << '\t' << booR << '\t' << booS << '\t' << booT << "\n\n";

return;}

Type IncompatibilitiesType Incompatibilities

The compiler gives warning messages for each underlined statement, but allows the program to run

nevertheless.

Page 17: Chapter 2 C++ Basics

Chapter 2Chapter 2CS 140CS 140 Page Page 1717

String VariablesString Variables#include <iostream>

#include <string>

using namespace std;

void main()

{

string firstName = "Fred";

string lastName = "Flintstone";

string fullName = firstName + ' ' + lastName;

cout << fullName << endl << endl;

fullName = "Wilma";

fullName += ' ';

fullName += lastName;

cout << fullName << endl << endl;

cout << "Enter your first and last names: ";

cin >> fullName >> lastName;

cout << fullName << endl << lastName << endl;

return;

}

Page 18: Chapter 2 C++ Basics

Chapter 2Chapter 2CS 140CS 140 Page Page 1818

Floating-Floating-PointPointArithmeticArithmeticThere are four There are four arithmetic arithmetic operators for operators for floating-point floating-point numbers.numbers.

+ Addition+ Addition- Subtraction- Subtraction* Multiplication* Multiplication/ Division/ Division

#include <iostream>using namespace std;void main(){ double interestRate = 0.075; double balance = 278.93; double depositAmount = 309.14; double withdrawalAmount = 416.72; int daysUntilPayday = 19; double interestEarned; double dailyAllowance;

balance = balance + depositAmount - withdrawalAmount; interestEarned = interestRate * balance; balance = balance + interestEarned; dailyAllowance = balance / daysUntilPayday;

cout.setf(ios::fixed); cout.setf(ios::showpoint); cout.precision(2); cout << "Until payday, you\'ll have to get by on $" << dailyAllowance << " per day!" << endl << endl;

return;}

Page 19: Chapter 2 C++ Basics

Chapter 2Chapter 2CS 140CS 140 Page Page 1919

IntegerIntegerArithmeticArithmetic

There are five There are five arithmetic arithmetic operators for operators for integers.integers.

+ Addition+ Addition- Subtraction- Subtraction* Multiplication* Multiplication/ Integer Division/ Integer Division

#include <iostream>using namespace std;

void main(){ int nbrOfLargePizzas; int nbrOfSmallPizzas; int piecesPerLargePizza = 12; int piecesPerSmallPizza = 8; int nbrOfConsumers; int nbrOfPieces; int piecesPerConsumer; int nbrOfSparePieces;

cout << "How many large pizzas? "; cin >> nbrOfLargePizzas; cout << "How many small pizzas? "; cin >> nbrOfSmallPizzas; cout << "How many consumers? "; cin >> nbrOfConsumers;

nbrOfPieces = nbrOfLargePizzas * piecesPerLargePizza + nbrOfSmallPizzas * piecesPerSmallPizza; piecesPerConsumer = nbrOfPieces / nbrOfConsumers; nbrOfSparePieces = nbrOfPieces % nbrOfConsumers;

cout << "\nOn the average, " << piecesPerConsumer << " pieces each.\n" << "(with " << nbrOfSparePieces << " pieces left over!)" << endl << endl;

return;}

% Modulus% Modulus

Page 20: Chapter 2 C++ Basics

Chapter 2Chapter 2CS 140CS 140 Page Page 2020

Arithmetic Precedence RulesArithmetic Precedence RulesWhen evaluating arithmetic expressions, C++ uses When evaluating arithmetic expressions, C++ uses specific specific precedence rulesprecedence rules to determine which to determine which operators should be executed in which order.operators should be executed in which order.

• Parentheses take the highest precedenceParentheses take the highest precedence• Multiplication, division, and modulus come Multiplication, division, and modulus come second.second.• Addition and subtraction take the lowest Addition and subtraction take the lowest precedence.precedence.• Precedence ties are handled in left-to-right Precedence ties are handled in left-to-right fashion.fashion.

100 - 5 * 4 + 75 = 100 - 5 * 4 + 75 =

(100 - 5) * 4 + 75 = (100 - 5) * 4 + 75 =

100 - 5 * (4 + 75) = 100 - 5 * (4 + 75) =

95 * 4 + 75 = 95 * 4 + 75 =

100 - 5 * 79 = 100 - 5 * 79 =

80 + 75 = 80 + 75 =

380 + 75 = 380 + 75 =

155 155

455 455

-295-295

100 - 20 + 75 =100 - 20 + 75 =

100 - 395 =100 - 395 =

Page 21: Chapter 2 C++ Basics

Chapter 2Chapter 2CS 140CS 140 Page Page 2121

Additional Assignment OperatorsAdditional Assignment OperatorsCertain shorthand operators can be used when a Certain shorthand operators can be used when a variable’s value is being altered by performing a variable’s value is being altered by performing a simple operation on it.simple operation on it.

value = value + otherValue;value = value + otherValue;

probability = probability / 100;probability = probability / 100;

x = x - y * z;x = x - y * z;

value += otherValue;value += otherValue;

probability /= 100;probability /= 100;

x -= y * z;x -= y * z;

dayOfYear = dayOfYear % 365;dayOfYear = dayOfYear % 365;

dayOfYear %= 365;dayOfYear %= 365;

salary = salary * 3.5;salary = salary * 3.5;

salary *= 3.5;salary *= 3.5;

Page 22: Chapter 2 C++ Basics

Chapter 2Chapter 2CS 140CS 140 Page Page 2222

Increment and Decrement OperatorsIncrement and Decrement OperatorsIncrementing or decrementing a numerical value by Incrementing or decrementing a numerical value by one can be done with an even simpler mechanism.one can be done with an even simpler mechanism.

number = number + 1;number = number + 1; number++;number++; ++number;++number;

ctdown = ctdown - 1;ctdown = ctdown - 1; ctdown--;ctdown--; --ctdown;--ctdown;#include <iostream>using namespace std;void main(){ int nbr = 57; cout << nbr << endl; cout << nbr++ << endl; cout << nbr << endl; cout << ++nbr << endl; cout << nbr << endl << endl;

return;}

The order in which The order in which the increment or the increment or

decrement decrement operator is applied operator is applied

will determine will determine whether the whether the operation is operation is

applied before or applied before or after a value is after a value is

returned.returned.

Page 23: Chapter 2 C++ Basics

Chapter 2Chapter 2CS 140CS 140 Page Page 2323

Pay total Pay total hours worked hours worked at regular rateat regular rate

Pay 40 hours Pay 40 hours at regular rate at regular rate & extra hours & extra hours at time-and-a-at time-and-a-

halfhalf

BranchingBranchingThere may be circumstances in a program when the There may be circumstances in a program when the next step to perform depends on a particular next step to perform depends on a particular condition.condition.

Did the Did the employee employee

work over 40 work over 40 hours?hours?

Proceed to Proceed to the next the next playerplayer

Increment the Increment the player’s winnings player’s winnings

by the dollar by the dollar amount times the amount times the

number of number of occurrences of occurrences of

the letterthe letter

Is the chosen Is the chosen letter letter

anywhere in anywhere in the puzzle?the puzzle?

Page 24: Chapter 2 C++ Basics

Chapter 2Chapter 2CS 140CS 140 Page Page 2424

BranchingBranchingviavia if ifandand else elseIn C++, simple In C++, simple branching is branching is done withdone with if if--else else statements.statements.

#include <iostream>using namespace std;void main(){ double orderAmt; double orderWeight; double discount; double shipping; char yOrN; bool inState; double tax; double totalAmt;

cout << "Enter the total amount of the order: $"; cin >> orderAmt; if (orderAmt > 100.00) discount = 0.20; else discount = 0.00;

cout << "Enter the weight of the order (in pounds): "; cin >> orderWeight; if (orderWeight <= 1.0) shipping = 0.00; else shipping = 2.00 * orderWeight;

Branch is Branch is determined by a determined by a

boolean “greater-boolean “greater-than” operatorthan” operator

Branch is Branch is determined by a determined by a boolean “less-boolean “less-than-or-equal-than-or-equal-to” operatorto” operator

Page 25: Chapter 2 C++ Basics

Chapter 2Chapter 2CS 140CS 140 Page Page 2525

cout << "Is this an in-state order? Enter Y or N: "; cin >> yOrN; if ((yOrN == 'y') || (yOrN == 'Y')) inState = true; else inState = false;

if (inState) tax = 0.0675 * (orderAmt - discount * orderAmt); else tax = 0.00;

if ((discount > 0.0) && (!inState)) discount /= 2;

totalAmt = (orderAmt - discount * orderAmt) + tax + shipping;

cout.setf(ios::fixed); cout.setf(ios::showpoint); cout.precision(2); cout << endl << endl << "Order: +$" << orderAmt << endl << "Discount: -$" << discount * orderAmt << endl << "Shipping: +$" << shipping << endl << "Tax: +$" << tax << endl << endl << "Total: $" << totalAmt << endl << endl;

return;}

Equality Equality and OR and OR operatooperato

rsrs

Boolean Boolean variable variable examinexamin

eded

AND AND and and NOT NOT

operatooperatorsrs

Page 26: Chapter 2 C++ Basics

Chapter 2Chapter 2CS 140CS 140 Page Page 2626

AnotherAnotherifif--elseelseExampleExample

By using compound By using compound statements (enclosed statements (enclosed in braces)in braces) if if--else else statements can have statements can have more complex more complex branches.branches.

#include <iostream>using namespace std;void main(){ int favNbr, leastFavNbr;

cout << "Enter your favorite number: "; cin >> favNbr; if (favNbr == 7) { cout << "LUCKY NUMBER SEVEN!\n"; cout << "The odds are in your favor!\n\n"; } else cout << "What a risk-taker!\n\n";

cout << "Enter your least favorite number: "; cin >> leastFavNbr; if (leastFavNbr = 13) { cout << "SILLY SUPERSTITION!\n"; cout << "Grow up, already!\n\n\n"; } else { cout << "Too bad!\n"; cout << "I was just about to give you " << leastFavNbr << " dollars!\n"; cout << "Oh, well. Maybe next time...\n\n\n"; }

return;}

Because the Because the assignment assignment

operator operator was used was used instead of instead of

the the equalityequality operator!operator!

Why did Why did thisthis

happen?happen?

Page 27: Chapter 2 C++ Basics

Chapter 2Chapter 2CS 140CS 140 Page Page 2727

One MoreOne Moreifif--else else ExampleExample

#include <iostream>using namespace std;void main(){ int month, year, payday1, payday2;

cout << "Enter an integer representing” << " the month: "; cin >> month; cout << "Enter the four-digit year: "; cin >> year;

if ((month == 2) && (year % 4 != 0)) payday1 = 14; else payday1 = 15;

if (month == 2) { if (year % 4 == 0) payday2 = 29; else payday2 = 28; } else { if ((month == 4) || (month == 6) || (month == 9) || (month == 11)) payday2 = 30; else payday2 = 31; }

cout << "This month's paydays are on " << month << '/' << payday1 << '/' << (((year % 100) ? "0" : "") << (year % 100) << " and " << month << '/' << payday2 << '/' << (((year % 100) ? "0" : "") << (year % 100) << ".\n\n";}

Page 28: Chapter 2 C++ Basics

Chapter 2Chapter 2CS 140CS 140 Page Page 2828

Request Request another letter another letter from the userfrom the user

LoopingLoopingThere may be circumstances in a program when a There may be circumstances in a program when a certain step should be repeated until a particular certain step should be repeated until a particular condition is true.condition is true.

Did the user Did the user enter an enter an

unacceptable unacceptable letter?letter?

ProceeProceed with d with rest of rest of prograprogra

mm

Page 29: Chapter 2 C++ Basics

Chapter 2Chapter 2CS 140CS 140 Page Page 2929

LoopingLoopingviavia while whileIn C++, simple In C++, simple looping may be done looping may be done withwith while while statements.statements.#include <iostream>

using namespace std;void main(){ char isItPerishable; int nbrDaysUntilExpire = 90;

cout << "Is the product perishable? " << "(Enter Y or N) "; cin >> isItPerishable; while ((isItPerishable != 'Y') && (isItPerishable != 'y') && (isItPerishable != 'N') && (isItPerishable != 'n')) { cout << "Invalid response. " << "Enter Y or N: "; cin >> isItPerishable; }

if ((isItPerishable == 'Y') || (isItPerishable == 'y')) { cout << "Enter the number of " << "days until the product expires: "; cin >> nbrDaysUntilExpire; while (nbrDaysUntilExpire <= 0) { cout << "Invalid response. " << "Enter a positive number: "; cin >> nbrDaysUntilExpire; } }

cout << endl << "The product expires in " << nbrDaysUntilExpire << " days." << endl << endl;

return;}

Page 30: Chapter 2 C++ Basics

Chapter 2Chapter 2CS 140CS 140 Page Page 3030

#include <iostream>using namespace std;void main(){ int receiptCount = 0; double receiptTotal = 0.00; double receiptAmount; double receiptMean;

cout << "Enter the amount of each receipt." << endl; cout << "When finished, enter -1." << endl << endl; cout << '$'; cin >> receiptAmount; while (receiptAmount >= 0.00) { receiptCount++; receiptTotal += receiptAmount; cout << '$'; cin >> receiptAmount; }

receiptMean = receiptTotal / receiptCount;

cout.setf(ios::fixed); cout.setf(ios::showpoint); cout.precision(2);

cout << endl << endl << "Average receipt amount: $" << receiptMean << endl << endl;

return;}

Counting Counting and and Totaling Totaling with Loopswith Loops

Page 31: Chapter 2 C++ Basics

Chapter 2Chapter 2CS 140CS 140 Page Page 3131

Branching viaBranching via do-while do-whileWith aWith a while while statement, the loop condition is statement, the loop condition is checked before executing the loop contents, making checked before executing the loop contents, making it possible to it possible to nevernever execute those contents. execute those contents.

If the algorithm calls for executing the contents at If the algorithm calls for executing the contents at least once, then it might be better to use aleast once, then it might be better to use a do-while do-while statement, which checks the loop condition statement, which checks the loop condition afterafter executing the loop contents.executing the loop contents.

check condition

execute contentsexecute contents check condition

execute contentsexecute contents

Page 32: Chapter 2 C++ Basics

Chapter 2Chapter 2CS 140CS 140 Page Page 3232

#include <iostream>using namespace std;void main(){ int favoriteNumber;

do { cout << "Enter your favorite number: "; cin >> favoriteNumber; }while (favoriteNumber != 13);

cout << endl << "13! Why, that\'s my favorite number, too!\n\n";

return;}

A SimpleA Simple do-while do-while ExampleExample

Page 33: Chapter 2 C++ Basics

Chapter 2Chapter 2CS 140CS 140 Page Page 3333

#include <iostream>using namespace std;void main(){ int value; int guessedValue;

cout << "Enter a value: "; cin >> value;

guessedValue = 0; while (value != guessedValue) cout << guessedValue++ << endl;

cout << "\nTIME!!! The computer FINALLY guessed your value!\n\n";

return;}

Infinite LoopsInfinite LoopsOne danger with looping is the prospect One danger with looping is the prospect of generating an of generating an infiniteinfinite loop, whose exit loop, whose exit condition is condition is nevernever met. met.

This This condition condition may may nevernever be true!be true!