Docsity

Basic Elements in C++ | Programming Fundamentals I | CSCI 151, Study notes of Computer Science

Toggle sidebar
bg1
Ch 2 Basic Elements in C++
This chapter will show us how to do arithmetic in a program, how to do
unformatted output, and how to read data from the keyboard. There are
a lot of little pieces of how things work that will come together at the end
of the chapter when we see how we can use all these pieces to create a
program.
p. 31
In any programming language there are certain words and symbols which
have meaning for the compiler. Some of these words are reserved (we
can’t use them for any other purpose) and some of them may be redefined
to use them for other purposes (that’s not usually a good idea, though,
because it can be confusing). The complete list of reserved words is shown
in Appendix A in the back of your book (p. 1219 in 4ed).
We’ll be creating names (called identifiers) for various components in our
programs:
variables (values which can be changed by the program)
wages = rate * hours;
areaCircle = 3.14159 * radius * radius;
areaRectangle = length * width;
avgRainfall = totalInches / 31;
taxAmt = salesTotal * .0825;
amountDue = salesTotal + taxAmt;
constants (values which cannot be changed by the program)
areaCircle = PI * radius * radius;
avgRainfall = totalInches / DAYS_IN_AUG;
amountDue = salesTotal + salesTotal * SALES_TAXRATE;
functions (collections of statements that perform a logical task)
main is the only function we’ve seen so far
These identifiers can consist of only
decimal digits 0 – 9
uppercase letters A – Z
lowercase letters a – z
an underscore _
and no other characters (no blanks, no other special characters).
An identifier may not begin with a digit.
From problems at the end of the chapter:
Which of the following are valid C++ identifiers?
a. RS6S6
b. MIX-UP MIX_UP MIXUP
c. STOP!
d. exam1
e. September1Lecture
f. 2May May2 TwoMay
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff

Partial preview of the text

Download Basic Elements in C++ | Programming Fundamentals I | CSCI 151 and more Study notes Computer Science in PDF only on Docsity!

Ch 2 Basic Elements in C++

This chapter will show us how to do arithmetic in a program, how to do unformatted output, and how to read data from the keyboard. There are a lot of little pieces of how things work that will come together at the end of the chapter when we see how we can use all these pieces to create a program. p. 31 In any programming language there are certain words and symbols which have meaning for the compiler. Some of these words are reserved (we can’t use them for any other purpose) and some of them may be redefined to use them for other purposes (that’s not usually a good idea, though, because it can be confusing). The complete list of reserved words is shown in Appendix A in the back of your book (p. 1219 in 4ed). We’ll be creating names (called identifiers) for various components in our programs:  variables (values which can be changed by the program) wages = rate * hours; areaCircle = 3.14159 * radius * radius; areaRectangle = length * width; avgRainfall = totalInches / 31; taxAmt = salesTotal * .0825; amountDue = salesTotal + taxAmt;  constants (values which cannot be changed by the program) areaCircle = PI * radius * radius; avgRainfall = totalInches / DAYS_IN_AUG; amountDue = salesTotal + salesTotal * SALES_TAXRATE;  functions (collections of statements that perform a logical task) main is the only function we’ve seen so far These identifiers can consist of only  decimal digits 0 – 9  uppercase letters A – Z  lowercase letters a – z  an underscore _ and no other characters (no blanks, no other special characters). An identifier may not begin with a digit. From problems at the end of the chapter: Which of the following are valid C++ identifiers? a. RS6S b. MIX-UP MIX_UP MIXUP c. STOP! d. exam e. September1Lecture f. 2May May2 TwoMay

g. Mike’s grade Mikesgrade Mikes_grade h. First Exam i. J j. Three There are many kinds of naming schemes for identifiers. A company might want all its programmers to create identifiers according to the same format so that all the company’s programs would have the same look and feel. My only requirement is that you choose an identifier which describes the value to be represented by that identifier: for an average, use average or avg rather than a for a salary, use salary or employeeSalary or monthly_salary but not s C++ is a case-sensitive language – you must spell all identifiers exactly as they were defined. For example, sum , SUM , and Sum are three different identifiers which would represent three different values in memory. Reserved and predefined identifiers are usually written in all lower case. The identifiers we create can be whatever we want as long as we follow the rules. My preferences: salary monthlySalary TAX_RATE Data types p. 34 When we use a computer program to solve problems, we try to model real-world data in a form the computer can understand. The computer allows us to store numbers and characters, and computer languages provide some standard data types for which operations have been defined. Numbers We can represent numbers with or without a decimal point. Numbers with a decimal point are called floating-point values; numbers without decimal points are integers. For storing integer values we are given these types to choose from:  short  int  long  unsigned short  unsigned int  unsigned long Each type is allotted a certain number of bytes of memory which allows us to store a value within a specific range. These are the sizes for most PC-type computers:

We’ve talked about representing characters. We are given a type called char to represent the value of a single character. That value can be a letter, digit, or special character. Examples of char constants: ‘A’ ‘a’ ‘7’ this is not the same as an integer 7 (without the quotes) ‘$’ ‘ ’ this is the character representing a blank space ‘\n’ \ is an escape character; \n represents a newline character The complete list of escape characters is on p. 75 (4ed) or p. 76 (3ed) A string is a value which includes zero or more characters. A string constant must be represented in your program inside double quotes (single quotes mean a single character). There is no check for spelling or grammar, and the contents of a string have no meaning for the compiler – they’re just a collection of chars. A blank is a significant character in a string. Examples of string constants: “Hi Mom!” “September 8, 2008” “903-886-5494” “9038865494” An escape sequence can be included as a character anywhere within a string. Example: cout << endl << “Hi” << endl << “Mom!” << endl; causes this output: Hi Mom! We could produce exactly the same output with this statement: cout << “\nHi\nMom!\n”; Arithmetic Operators p. 40 (4ed) or 39 (3ed) Symbols: + addition

- subtraction ***** multiplication (what would the compiler think x is supposed to be?) / division (result is the quotient) % modulus (mod) (result is the integer remainder)

  • and – can be unary (one operand) or binary (two operands) unary operators: -15 or + -b take the value of b and reverse its sign +b has no effect on the value of b

binary operators In simple expressions like 3 + 4 and 9 – 3 and 4 * 6 and 3 - 5 there’s only one operator, so there’s no confusion as to the order in which arithmetic operations are performed. 3 + 4 is 7 9 – 3 is 6 4 * 6 is 24 3 – 5 is - Division is a little more complicated. 5 / 2 12 / 4 29 / 10 2 / 5 4 / 12 10 / 29 When you divide an integer by an integer, you get integer division. The result is the integer quotient, and any remainder is discarded. 5 / 2 is 2 because 2 goes into 5 two times 12 / 4 is 3 29 / 10 is 2 2 / 5 is 0 because 5 goes into 2 zero times 4 / 12 is also 0 10 / 29 is also 0 The % operator does the same integer division that / does, but the result is the integer remainder instead of the quotient. 5 % 2 12 % 4 29 % 10 2 % 5 4 % 12 10 % 29 5 % 2 is 1 because 2 goes into 5 two times with a remainder of 1 12 % 4 is 0 29 % 10 is 9 2 % 5 is 2 because 5 goes into 2 zero times with a remainder of 2 4 % 12 is 4 10 % 29 is 10 Why would you need a modulus operator? examples: x % 2 can be used to tell whether x is even or odd numEggs / 12 and numEggs % 12

A statement like: 10.0 % 5. is invalid and would cause a compile error. Order of precedence If there is more than one operator in an arithmetic expression, we have to worry about the order in which they are executed. 2 * length + width amount + amount * TAX_RATE For the symbols we have so far, any kind of multiplication or division will be done first, in the order the operators are encountered from left to right. Then any addition or subtraction is done, also in the order the operators are encountered from left to right. If 2 * length + width is supposed to calculate the perimeter of a rectangle, we need the addition to take place before the multiplication, so we need to use parentheses to change the order of precedence: 2 * ( length + width ) In amount + amount * TAX_RATE the multiplication is done before the addition, which is exactly what we want, so no parens are necessary. If you want to be absolutely sure, you can always use extra parens even if they’re not needed: amount + ( amount * TAX_RATE ) Revised order of precedence:  anything in parentheses (inner parentheses to outer parentheses)  multiplication and division * and / and %  addition and subtraction Evaluate these examples: 4 * (10 – 3) / 5


4 * 7 / 5

28 / 5

5 (20 – (3 * 4) + 2) * (3 – 1)


(20 - 12 + 2) * (3 – 1)

( 8 + 2) * (3 – 1)

10 * (3 – 1)

Mixed expressions (mixed-mode arithmetic) p. 46 (4ed) 3 + 5.0 / 2 + 4 / 5.0 - .1 * 5


3 + 2.5 + .8 -.

5.5 + .8 -.

6.3 -.

Notice that when we operate an int with a floating-point, the int is converted into floating-point, and floating-point arithmetic is done. This is done automatically but only when necessary. (5 / 4 + 6 * 1.5) / (5 – 1)


( 1 + 9.0 ) / (5 – 1)


10.0 / 4

The conversions in the previous two examples were implicit – the compiler took care of it for us. What if we need to force a conversion to be done? We can do a type-cast (also called type-conversion or type-coercion). p. 48 (4ed) static_cast (value you want converted) Examples: Suppose we want to calculate the average of a collection of integers. We would calculate an integer sum and divide by the number of values summed, which would also be an integer. That would give us an integer result – suppose we wanted a floating-point result so we would have a more accurate average. If variable sum is the sum of 10 integer values, we could calculate the average like this: sum / 10 but that would give us an integer average. If sum has a value of 75, then our average would be 7. If we would rather have the more precise average 7.5, then we have to force floating-point division. If there’s a constant

print it out: cout << 3 + 4 << endl; output would be: 7 It’s probably a good idea to identify what we print, so cout << “3 + 4 = ” << 3 + 4 << endl; output would be: 3 + 4 = 7 What does this statement print? cout << “3 + 4 = ” << 3 * 4 << endl; output would be: 3 + 4 = 12 This doesn’t cause a compile error because the statement can be translated. Instead this is an example of a logic error – we have to look at our output and make sure the program is actually doing what we meant for it to do. Declaring (creating) constants and variables p. 52 (4ed) or p. 51 (3ed) If we want names for our constants or to use identifiers for variables, we have to declare them (tell the compiler in advance what we want). Constants const double PI = 3.14159; const int FEET_PER_MILE = 5280; const double CM_PER_INCH = 2.54; const double TAX_RATE = .0825; const char BLANK = ‘ ’; const char NEWLINE = ‘\n’; const string COURSE_NUM = “CSCI 151.001”; const int DAYS_IN_SEPTEMBER = 30; The semicolon at the end of the statement is how you tell the compiler where the statement ends. C++ is a free-format language – no particular spacing is required, except that you must have a space between any two identifiers. If there is a symbol between two words, no additional spaces are needed, though it’s much easier to read with spaces. const double PI = 3.14159;

could be written as: const double PI=3.14159; Wherever you can have a space, you can have as many spaces as you want, including blank lines. You can’t have a space in the middle of an identifier or a constant or a multi-symbol operator like <<. It’s not recommended because it doesn’t make your program more readable, but a statement like: const double PI = 3.14159; could be written: const double PI =

; So just because the compiler reaches the end of a line doesn’t mean it’s reached the end of a statement – it looks for the semicolon to tell it where a statement actually ends. Variables Anytime we need to store a value in our program so we can retrieve it later, we’ll need a create a variable location in which to store the value. We need to make up a name for it and decide what type would be most appropriate for it. int numStudents; double taxAmount; char letterGrade; string customerName; If we have more than one variable of the same type, we can declare them separately or group them together into a list:

int studentsOnRoster ;

int studentsAttending ;

or

int studentsOnRoster ,

studentsAttending; or

int studentsOnRoster , studentsAttending;

const double PI = 3.14159; int a = 0; int b = FEET_PER_MILE; double e = 2.54; int numStudents = 35; double taxAmount = 10.95; char letterGrade = ‘A’; string customerName = “Monty Python”; Unlike constants, the starting values for variables can be changed later in a program, if necessary. Input (Read) Statement p. 60 (4ed) or p. 58 (3ed) The program can also assign a value to a variable by asking the user of the program to enter the value to be assigned (reading the value). Rules for how C++ reads different types of values: int Skip any leading spaces or blank lines, read digits until encountering a character that is not valid in an integer value, like a blank space or a special character, or a decimal point, or a letter, or the end of the line (result of pressing Enter) doubl e Skip any leading spaces or blank lines, read digits until encountering a character that is not valid in a floating-point value, like a blank space or a special character other than a decimal point, or a letter, or the end of the line. char Skip any leading spaces or blank lines and read the first non-blank character encountered. string Skip any leading spaces or blank lines and read characters until encountering a blank space or the end of the line. #include using namespace std; int main ( ) { int length; int width; int area;

cout << “Enter the length of a rectangle in inches: ”; cin >> length; cout << “Enter the width of a rectangle in inches:” << endl; cin >> width; area = length * width; cout << “The area of the rectangle = ” << area << “ square inches” << endl; system(“pause”); return 0; } The output of this program would look like this (values entered from the keyboard shown in bold print): Enter the length of a rectangle in inches: 25 Enter the width of a rectangle in inches: 12 The area of the rectangle = 300 square inches The first two output statements: cout << “Enter the length of a rectangle in inches: ”; and cout << “Enter the width of a rectangle in inches:” << endl; are examples of prompting messages. When we want our program to read data from the keyboard, we need to tell the person running the program what it is our program is waiting for. Otherwise, they just see the cursor blinking on the black screen and they don’t know what the program expects them to do. When I’m reading values from the keyboard, I prefer to prompt the user for one input value at a time. If you ask for multiple values (like both length and width) in the same statement, then you have to explain what kind of spacing is required: there must be at least one blank space to separate the two numbers. cout << “Enter the length and width of a rectangle in inches, leaving at least”; cout << “one space between the values: ”; cin >> length; or cout << “Enter the length and width of a rectangle in inches like this: 10 15” << endl; or cout << “Enter the length and width of a rectangle in inches, press Enter,” cout << “and then enter the width of a rectangle in inches on the next line” << endl; we got to here

regardless of whether the ++ or -- appear before or after the variable (as with x in the quickie comparison above). When the ++ or -- is used in a statement with other operators, there is an additional consideration – what is the result of the entire ++x or x++ expression which is to be used in the next operation performed? The ++ and -- operators have a higher priority than any other arithmetic operators. Examples: y = ++x; assign the result of ++x to y cout << x-- << endl; output the result of x-- y = 2 * x++; double the value of x++ and assign the result to y The value of that result depends on whether you use the operator before or after the variable. When the operator appears before the variable, like ++x or --x the increment or decrement is done first and the value of x is changed, and then the new value of x is used as the result of the operation. When the operator appears after the variable, like x++ or x-- the current value of x is saved to use as the result of the operation, and then the increment or decrement is done and the value of x is changed. When the increment/decrement operators appear in standalone statements (with no other operators involved), the result of the whole increment/decrement expression is discarded, so the only result that is obvious is the change to the incremented/decremented variable. If x is currently 5, then both ++x; and x++; result in x being changed to 6. If x is currently 5, then both --x; and x--; result in x being changed to 6. Output cout << expression or manipulator << expression or manipulator... ; Notice that if you want to output more than one expression in the same cout statement, the expressions must be separated by the << operator.

Each occurrence of << in an output statement must be followed by

something you want to print or by something you want to tell the file manager about the output. Generating output follows two rules:

  1. The expression is evaluated and its value is printed at the current insertion point on the output device (where the cursor is blinking on the screen).
  2. A manipulator can be used to format the output. The only manipulator we’ve seen so far is endl which causes the cursor (insertion point) to move to the beginning of the next line. You can accomplish the exact same output by writing each individual expression or manipulator in separate statements. Example: Assume int variable a has a value of 25. cout << “x = ” << x << endl << “and 2 times x = ” << 2 * x << endl; produces this output: x = 25 and 2 times x = 50 We could obtain the exact same output by coding: cout << “x = ”; cout << x; cout << endl; // or cout << ‘\n’ ; // or cout << “\n”; cout << “and 2 times x = ”; cout << 2 * x cout << endl; Notice that we must repeat cout in every new statement because the semicolon ended the previous statement. It’s not the end of the cout statement that causes the cursor to move from one line to another but if and where you write the endl manipulator (or the char or string value of the newline character \n). Anything following // is considered a comment and is ignored by the compiler – these are explanations for people, not for the computer. Shortcut Assignment Operators p. 88 (4ed) or 89 (3ed)