Notes2 - Chapter 2 C++ Basics Goals: To introduce the...

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: 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 Variables Variables are memory locations within RAM. Binary Address 00000000 RAM is divided into 8bit segments called bytes. Each byte is numbered with a binary address. Variable of type int CS 140 RAM Variable of type char Variable of type double Chapter 2 When a program variable is declared, adequate space in RAM is reserved for it. The variable is named with an identifier and can be given a value. That value is stored at its memory address, which is known as a pointer. Binary Address 11111111 Page 2 Identifiers Variables names, or identifiers, must start with an underscore or an alphabetic symbol, and all the remaining symbols must be alphanumeric or underscores. CS 140 Chapter 2 Page 3 Reserved C++ Keywords Can't Be Used As Identifiers! asm break const do except float inline new register sizeof template this type_info typedef unsigned using while CS 140 auto case const_cast double explicit for int operator reinterpret_cast static throw typeid virtual bad_cast bad_typeid catch char continue default dynamic_cast else extern false friend goto long mutable private protected return short static_cast struct true try typename union void volatile bool class delete enum finally if namespace public signed switch Chapter 2 Page 4 Variable Declarations Variables must be declared before being used in a program. int count; float salaryPerWeek; char middleInitial; int nbr_of_rings, nbr_of_knocks; float MonPay, TuePay, WedPay, ThuPay, FriPay; double measurement1, measurement2; CS 140 Chapter 2 Page 5 Assignment Statements Variables may be "assigned" values via the assignment operator (=) in assignment statements. count = 0; salaryPerWeek = 40 * salaryPerHour; middleInitial = `P'; nbr_of_rings = 2 * nbr_of_knocks - 1; MonPay = TuePay = WedPay = 47.25F; ThuPay = FriPay = (float)62.75; measurement2 = measurement1 / count; CS 140 Chapter 2 Page 6 Initializing Variables Variables may be "initialized" in their declarations to possess specific values. int value = 0; float Radius = 16.00F; bool flag = false; double errorMargin = 0.00000003; char firstltr = `A', lastltr = `Z'; int loserCount(0), winnerCount(0); float GPA(4.00F); CS 140 Chapter 2 Page 7 Values may be output to the monitor by means of output statements that use the output operator (<<) to stream to the output file cout. cout << 1492; int val = 56; cout << val; Output to the Monitor via cout Output: Output: 56 1492 Output: 2002was great!I made a fortune! cout << 2002 << "was great!"; cout << "I made a fortune!"; cout << 2002 << " was great!\n"; cout << "I made a fortune!"; cout << val << "million\n\ndollars!"; CS 140 Chapter 2 Output: 2002 was great! I made a fortune! Output: 56million dollars! Page 8 #include <iostream> using namespace std; void main() { cout << "1Aa\azzz\aZZZ" cout << "2Bb\bzzz\bZZZ" cout << "3Cc\nzzz\nZZZ" cout << "4Dd\rzzz\rZZZ" cout << "5Ee\tzzz\tZZZ" cout << "6Ff\'zzz\'ZZZ" cout << "7Gg\"zzz\"ZZZ" cout << "8Hh\\zzz\\ZZZ" return; } When a character value contains a character preceded by a backslash (\), then it represents a single symbol known as an escape sequence. \a \b \n \r \t \' \" \\ CS 140 Escape Sequences << << << << << << << << endl; endl; endl; endl; endl; endl; endl; endl; Bell (alert) Backspace New line Carriage return Horizontal tab Single quotation mark Double quotation mark Backslash Chapter 2 Page 9 To ensure that real numbers are output with decimal points, an integer part, and a specific number of decimal places, the following lines should be included before outputting: Avoids Scientific Notation. Formatting Real Number Output cout.setf(ios::fixed); cout.setf(ios::showpoint); cout.precision(4); Shows Decimal Point & Trailing Zeros. Shows 4 Digits After Decimal Point. CS 140 Chapter 2 Page 10 Sample Program #include <iostream> #include <iomanip> 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; } CS 140 Chapter 2 Page 11 Values may be input from the keyboard by means of input statements that use the input operator (>>) to stream from the input file 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; } CS 140 Chapter 2 Page 12 Input from the Keyboard via cin Data 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; CS 140 } Chapter 2 Page 13 Data Types FloatingPoint #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; } CS 140 Chapter 2 Page 14 Data Types Characters and Booleans #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; CS 140 Chapter 2 Page 15 Type Incompatibilities #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; } CS 140 The compiler gives warning messages for each underlined statement, but allows the program to run nevertheless. Chapter 2 Page 16 Floating Point Arithmetic There are four arithmetic operators for floatingpoint numbers. + * / Addition Subtraction Multiplication 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; } CS 140 Chapter 2 Page 17 #include <iostream> using namespace std; void main() { int nbrOfLargePizzas; int nbrOfSmallPizzas; int piecesPerLargePizza = 8; int piecesPerSmallPizza = 4; 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; } CS 140 Chapter 2 Page 18 Integer Arithmetic There are five arithmetic operators for integers. + * / % Addition Subtraction Multiplication Integer Division Modulus Arithmetic Precedence Rules When evaluating arithmetic expressions, C++ uses specific precedence rules to determine which operators should be executed in which order. Parentheses take the highest precedence Multiplication, division, and modulus come second. Addition and subtraction take the lowest precedence. Precedence ties are handled in lefttoright fashion. 100 - 5 * 4 + 75 = 100 - 20 + 75 = 80 + 75 = 380 + 75 = 155 455 (100 - 5) * 4 + 75 = 95 * 4 + 75 = 100 - 5 * (4 + 75) = 100 - 5 * 79 = CS 140 Chapter 2 100 - 395 = -295 Page 19 Additional Assignment Operators value = value + otherValue; value += otherValue; Certain shorthand operators can be used when a variable's value is being altered by performing a simple operation on it. x = x - y * z; x -= y * z; probability = probability / 100; probability /= 100; dayOfYear = dayOfYear % 365; dayOfYear %= 365; CS 140 Chapter 2 salary = salary * 3.5; salary *= 3.5; Page 20 Increment and Decrement Operators number = number + 1; ctdown = ctdown - 1; The order in which the increment or decrement operator is applied will determine whether the operation is applied before or after a value is returned. CS 140 Incrementing or decrementing a numerical value by one can be done with an even simpler mechanism. number++; ctdown--; ++number; --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; } Chapter 2 Page 21 Branching There may be circumstances in a program when the next step to perform depends on a particular condition. Did the employee work over 40 hours? Pay 40 hours at regular rate & extra hours at timeanda half Is the chosen letter anywhere in the puzzle? Pay total hours worked at regular rate Increment the player's winnings by the dollar amount times the number of occurrences of the letter Proceed to the next player CS 140 Chapter 2 Page 22 Branching via if and else In C++, simple branching is done with ifelse statements. Branch is determined by a boolean "less-thanor-equal-to" operator #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) Branch is determined by discount = 0.20; a boolean "greaterelse than" operator 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; Chapter 2 Page 23 CS 140 cout << "Is this an in-state order? cin >> yOrN; if ((yOrN == 'y') || (yOrN == 'Y')) inState = true; else Boolean inState = false; variable Enter Y or N: "; if (inState) tax = 0.0675 * (orderAmt - discount * orderAmt); else AND and tax = 0.00; if ((discount > 0.0) && (!inState)) discount /= 2; examined Equality and OR operators NOT operators 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; } CS 140 Chapter 2 Page 24 #include <iostream> using namespace std; void main() { int favNbr, leastFavNbr; Another ifelse Example By using compound statements (enclosed in braces) ifelse statements can have more complex branches. 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; Because the if (leastFavNbr = 13) assignment { cout << "SILLY SUPERSTITION!\n"; operator was cout << "Grow up, already!\n\n\n"; used instead } of the equality else operator! { 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; } Chapter 2 Page 25 Why did this happen? CS 140 One More ifelse Example #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 << << << << << return; } "This month (year month (year month's paydays are on " << '/' << payday1 << '/' % 100) << " and " << '/' << payday2 << '/' % 100) << ".\n\n"; CS 140 Chapter 2 Page 26 Looping There may be circumstances in a program when a certain step should be repeated until a particular condition is true. Has the user entered the letter `Y' or `N' yet? Proceed with rest of program Request another letter from the user CS 140 Chapter 2 Page 27 Looping via while In C++, simple looping may be done with while 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; } CS 140 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; } Chapter 2 Page 28 Counting and Totaling with Loops #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; } CS 140 Chapter 2 Page 29 Branching via do-while With a while statement, the loop condition is checked before executing the loop contents, making it possible to never execute those contents. If the algorithm calls for executing the contents at least once, then it might be better to use a do-while statement, which checks the loop condition after executing the loop contents. check condition execute contents check condition Chapter 2 Page 30 execute contents CS 140 A Simple do-while Example #include <iostream> using namespace std; void main() { int favoriteNumber; do { cout << "Enter your favorite number: "; cin >> favoriteNumber; }while (favoriteNumber != 13); cout << endl << "13! return; } Why, that\'s my favorite number, too!\n\n"; CS 140 Chapter 2 Page 31 Infinite Loops One danger with looping is the prospect of generating an infinite loop, whose exit condition is never met. #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!!! return; } CS 140 Chapter 2 Page 32 The computer FINALLY guessed your value!\n\n"; This condition may never be true! ...
View Full Document

This note was uploaded on 08/26/2009 for the course CS 140 taught by Professor Staff during the Fall '08 term at Southern Illinois University Edwardsville.

Ask a homework question - tutors are online