1 / 33

Chapter 2 C++ Basics

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.

hu-tucker
Download Presentation

Chapter 2 C++ Basics

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Chapter 2C++ 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

  2. Variables Variables are memory locations within RAM. 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 00000000 RAM RAM is divided into 8-bit segments called bytes. Each byte is numbered with a binary address. Variable of type char Variable of type int Variable of type double Binary Address 11111111 CS 140

  3. Identifiers Variables names, or identifiers, must start with an underscore or an alphabetic symbol, and all the remaining symbols must be alphanumeric or underscores. theValueThatIsUsedWhenIAmInAGoodMood x27 Cost_of_living _b4Value 8AMtemperature Largest Value amt_in_$ vice-president CS 140

  4. Reserved C++ Keywords -Can’t Be Used As Identifiers! asm auto bad_castbad_typeid bool break case catch char class const const_cast continue default delete do double dynamic_cast else enum except explicit extern false finally float for friend goto if inline int long mutable namespace new operator private protected public register reinterpret_cast return short signed sizeof static static_cast struct switch template this throw true try type_info typedef typeid typename union unsigned using virtual void volatile while CS 140

  5. Variable Declarations Variables must be declared before being used in a program. int count; float salaryPerWeek; char middleInitial; string first_name, last_name, full_name; float MonPay, TuePay, WedPay, ThuPay, FriPay; double measurement1, measurement2; CS 140

  6. Assignment Statements Variables may be “assigned” values via the assignment operator (=) in assignment statements. count = 0; salaryPerWeek = 40 * salaryPerHour; middleInitial = ‘P’; full_name= first_name + “ “ + last_name; MonPay = TuePay = WedPay = 47.25F; ThuPay = FriPay = (float)62.75; measurement2 = measurement1 / count; CS 140

  7. 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); string greeting(“hello”); CS 140

  8. Output: 1492 Output: Output: 56 2009was great!I made a fortune! Output: 2009 was great! I made a fortune! Output: 56million dollars! Output to the Monitor via cout 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; cout << 2009 << “was great!”; cout << “I made a fortune!”; cout << 2009 << “ was great!\n”; cout << “I made a fortune!”; cout << val << “million\n\ndollars!”; CS 140

  9. #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; } Escape Sequences When a character value contains a character preceded by a backslash (\), then it represents a single symbol known as an escape sequence. \a Bell (alert) \b Backspace \n New line \r Carriage return \t Horizontal tab \' Single quotation mark \" Double quotation mark \\ Backslash CS 140

  10. Formatting Real Number Output 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. cout.setf(ios::fixed); cout.setf(ios::showpoint); cout.precision(4); Shows Decimal Point & Trailing Zeros. Shows 4 Digits After Decimal Point. CS 140

  11. #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; } Sample Program CS 140

  12. Input from the Keyboard via cin 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

  13. 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; unsignedint UnNTjurJ = 5, UnNTjurK = UINT_MAX; cout << "UNSIGNED INTEGERS:" << endl << UnNTjurJ << endl << UnNTjurK << endl << endl << endl; return; } CS 140

  14. Data 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; longdouble 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

  15. 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

  16. 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; } #include <iostream> using namespace std; void main() { intNTjurA = 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"; boolbooQ = 467, booR = 467.927F, booS = 467.927, booT = 'w'; cout << booQ << '\t' << booR << '\t' << booS << '\t' << booT << "\n\n"; return; } The compiler gives warning messages for each underlined statement, but allows the program to run nevertheless. CS 140

  17. String 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; } CS 140

  18. #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; } Floating-PointArithmetic There are four arithmetic operators for floating-point numbers. + Addition - Subtraction * Multiplication / Division CS 140

  19. #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; } IntegerArithmetic There are five arithmetic operators for integers. + Addition - Subtraction * Multiplication / Integer Division % Modulus CS 140

  20. 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 left-to-right fashion. 100 - 5 * 4 + 75 = 100 - 20 + 75 = 80 + 75 = 155 (100 - 5) * 4 + 75 = 95 * 4 + 75 = 380 + 75 = 455 100 - 5 * (4 + 75) = 100 - 5 * 79 = 100 - 395 = -295 CS 140

  21. Additional Assignment Operators Certain shorthand operators can be used when a variable’s value is being altered by performing a simple operation on it. value = value + otherValue; x = x - y * z; value += otherValue; x -= y * z; probability = probability / 100; probability /= 100; dayOfYear = dayOfYear % 365; salary = salary * 3.5; dayOfYear %= 365; salary *= 3.5; CS 140

  22. Increment and Decrement Operators Incrementing or decrementing a numerical value by one can be done with an even simpler mechanism. number = number + 1; number++; ++number; ctdown = ctdown - 1; 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 increment or decrement operator is applied will determine whether the operation is applied before or after a value is returned. CS 140

  23. 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? Is the chosen letter anywhere in the puzzle? No No Yes Yes Pay 40 hours at regular rate & extra hours at time-and-a-half 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

  24. Branchingvia ifand else #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; In C++, simple branching is done with if-else statements. Branch is determined by a boolean “greater-than” operator Branch is determined by a boolean “less-than-or-equal-to” operator CS 140

  25. 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 and OR operators Boolean variable examined AND and NOT operators CS 140

  26. #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; } Anotherif-elseExample By using compound statements (enclosed in braces) if-else statements can have more complex branches. Because the assignment operator was used instead of the equality operator! Why did this happen? CS 140

  27. 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"; } One Moreif-else 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; CS 140

  28. Looping There may be circumstances in a program when a certain step should be repeated until a particular condition is true. Did the user enter an unacceptable letter? Proceed with rest of program No Yes Request another letter from the user CS 140

  29. 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; } Loopingvia 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

  30. #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 and Totaling with Loops CS 140

  31. check condition execute contents execute contents check condition 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. while loop do-while loop CS 140

  32. 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! Why, that\'s my favorite number, too!\n\n"; return; } CS 140

  33. 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!!! The computer FINALLY guessed your value!\n\n"; return; } This condition may never be true! CS 140

More Related