Download presentation
1
Problem Solving with C++
The Object of Programming Walter Savitch Chapter 2 C++ Basics Slides by David B Teague, Western Carolina University a constituent institution of The University of North Carolina
2
C++ Basics Variables and Assignments Input and Output
Data Types and Expressions Simple Flow of Control Program Style
3
C++ Basics: 2.1 Variables and Assignments
A C++ variable can hold a number or other types. A C++ variable ALWAYS has a value stored in it. A C++ variable is implemented as a memory location. Information stored is binary -- 0s and 1s. We do not need to know nor do we care what address a particular variable occupies in memory.
4
Names: Identifiers The name of a variable (or anything else in C++ that needs naming) is called an identifier. An identifier must be spelled starting with a letter or an underscore symbol (_) followed by any number of letters, digits, or underscore symbols. Valid Examples x x_1 _abc A2b ThisIsAVeryLongIdentifier Invalid Examples 12 3X %change myFirst.c data-1 Why are these invalid? There are identifiers that are reserved to the use of the C++ language, called keywords, or reserved words. (A complete list is in Appendix 1 of the text.)
5
Names: Identifiers Invalid Examples 12 3X %change myFirst.c data-1
Why are these invalid? 12 , %change, and 3x do not start with a letter myFirst.c has a ‘.’ character that is not permitted data-1 contains a - character that is not permitted. Identifier Spelling Rule: Identifiers must start with a letter or underscore and have only letters, digits or underscores after the first.
6
Display 2.1 A C++ Program (1 of 2)
#include <iostream> using namespace std; int main( ) { int number_of_bars; double one_weight, total_weight; cout << "Enter the number of candy bars in a package\n"; cout << "and the weight in ounces of one candy bar.\n"; cout << "Then press return.\n"; cin >> number_of_bars; cin >> one_weight; total_weight = one_weight * number_of_bars; cout << number_of_bars << " candy bars\n"; cout << one_weight << " ounces each\n"; cout << "Total weight is " << total_weight << " ounces.\n";
7
Display 2.1 A C++ Program (2 of 2)
cout << "Try another brand.\n"; cout << "Enter the number of candy bars in a package\n"; cout << "and the weight in ounces of one candy bar.\n"; cout << "Then press return.\n"; cin >> number_of_bars; cin >> one_weight; total_weight = one_weight * number_of_bars; cout << number_of_bars << " candy bars\n"; cout << one_weight << " ounces each\n"; cout << "Total weight is " << total_weight << " ounces.\n"; cout << "Perhaps an apple would be healthier.\n"; return 0; }
8
Variable Declarations
Every variable in C++ must be declared. A declaration introduces a name to the compiler and specifies the type of data that is to be stored in the variable. A variable declaration has the form Type_name variable_name1, variable_name2, … ; Example: double distance; The kind of data held in a variable is it type. You must declare all variables prior to use.
9
Assignment Statements
total_weight = one_weight + number_of_bars; In an assignment statement, the right hand side expression is evaluated, then the variable on the left hand side is set to this value. Syntax: variable = expression; distance = rate * time; count = count + 2;
10
Pitfall: Uninitialized Variables
A variable that has not been set by your program will have the value left there by the last program to use the memory associated with that variable. This is an UNINITIALIZED variable. It contains garbage in the root sense of the word. This is illegal and incorrect but few compilers will catch this error.
11
Variable initialization
How do we prevent use of uninitialized variables? Take great care with your program that all variables receive a value prior to fetching a value from them. Initialize your variables when they are declared. Syntax: Two different appearing but equivalent initializations: int x = 3; double pi = ; int x(3); double pi( );
12
Programming Tip Use meaningful variable names.
Names that tie your program’s code to the problem being solved will make your code easier to read and easier to debug. Anything that you can do to make your code readable is worth days in debugging time.
13
2.2 Input and Output Output using cout
cout << number_bars << “ candy bars \n”; << is the insertion operator It is illegal to break a string constant across two lines. This is ILLEGAL, though some compilers happily accept it. cout << “Mary had a little lamb. Its fleece was white as snow.\n”; 13
14
Include Directories and Namespaces
#include <iostream> using namespace std; These lines provide declarations necessary to make iostream library available. C++ divides collections of names into namespaces. To access names in a namespace, the second line above, the using directive, is sufficient. It means that your program can use any name in the namespace std. A C++ namespace usually contains more than just names. They usually contain code as well. Older compilers will require the older style, <iostream.h>, and such compilers may not like the using directive. If your compiler doesn’t like the using directive, just omit it. 14
15
Escape sequences The \ (backslash) preceeding a character tells the compiler that the next character does not have the same meaning as the character by itself. An escape sequence is types as two characters with no space between them. \\ is a real backslash character, not the escape character, a backslash that does not have the property of changing the meaning of the next character. \n newline \t tab character (same as control-h) \a alert, or bell \” double quote (that does not end a string literal).
16
Formatting for Numbers with a Decimal Point
The following statements will cause your floating point output to be displayed with 2 places of decimals and will always show the decimal point even when the output has a zero fractional part. cout.setf(ios::fixed); cout.setf(ios::showpoint); cout.precision(2); //Output format: 78.50
17
Input using cin When a program reaches a cin >> statement, it waits for input. You are responsible for prompting the user of your program for proper input. Syntax: cin >> number >> size; cin >> time_to_go >> points_needed;
18
Designing input and output
Echoing your input is frequently requested by problem statements. Even when not requested, it is usually better to echo your input.
19
2.3 Data Type and Expressions The types int and double
From the C++ point of view, 2 and 2.0 are very different. 2 has type int has no fractional part 2.0 has type double has a fractional part, even if the fractional part is 0. An int and a float are stored differently.
20
Other Number types Memory Type used Range Precision
short bytes , NA (a.k.a. short int) to 32,767 int bytes ,147483, NA to 2,147483,647 long bytes same as int NA float bytes approximately digits 10-38 to 1038 double bytes approximately digits to 10308 long double 10 bytes approximately digits to
21
The Types char and bool Memory char is a special type that is designed to hold single members of the ASCII character set. Some vendors have extended ASCII character encoding to include more characters than upper and lower case letters, digits and punctuation. (Notably: IBM, on the PC, which has been adopted in nearly all Microsoft software.) cstring (from C) and string (from the Standard Library) are for more than one char value. More on these in a later chapter. bool is a type that was added to C++ in the1995 Draft ANSI Standard. There are only two values: true and false. Almost all compilers support the bool type.
22
Display 2.3 The Type char #include <iostream> // Blank lines removed to fit code to space available. using namespace std; int main( ) { char symbol1, symbol2, symbol3; cout << "Enter two initials, without any periods:\n"; cin >> symbol1 >> symbol2; cout << "The two initials are:\n"; cout << symbol1 << symbol2 << endl; cout << "Once more with a space:\n"; symbol3 = ' '; cout << symbol1 << symbol3 << symbol2 << endl; cout << "That's all."; return 0; }
23
Arithmetic Operators and Expressions
Common arithmetic operators are encoded: Addition + Multiplication * Subtraction Division / These operators are used to make arithmetic expressions: one_weight * number_of_weights This expression is said to “return a value” that automagically appears where the expression is, and is used in an outside expression. Here the sum is done, value returned, and this value is used as a factor in the multiplication. one_weight * (number_of_weights + off_set) (See precedence, later in the text.)
24
“Automagically” Automagically means automatically, as if by magic.
25
Arithmetic Operators and Expressions
Arithmetic with + = and * behaves as expected for both integer and floating point types. Arithmetic for / behaves as expected for floating point numbers. Arithmetic for / behaves in a somewhat surprising way for integer types (short, int, long) Division for integers is TRUNCATING - it discards the fractional part.
26
Arithmetic Operators and Expressions division /, and modulus %, for integer values
Division /, and modulus % are complementary operations. Mod, or modulus, %, works ONLY for integer types. / 3 is the quotient 3 12 12 % 3 = 12 mod 3 is the remainder / 3 quotient = 3 THIS IS NOT 4.66 3 14 % 3 remainder after dividion See the PITFALL - Whole Number Division, page 70.
27
Arithmetic Operators and Expressions Precedence
When two operators appear in an arithmetic expression, there are PRECEDENCE rules that tell us what happens. Evaluate the expression, X + Y * Z by multiplying Y and Z first then the result is added to X. Rule: Do inside most parentheses first, then multiplication and division next, additions and subtractions next, and break all ties left to right.
28
Arithmetic Operators and Expressions Style
Always follow your instructor’s style requirements. Our suggestion is that in writing an expression, you should write the expression with spaces either side of the operator: We suggest this X + Y * Z but not this X+Y*Z
29
2.4 Simple Flow of Control A simple branching mechanism
Making decision in computer programs requires changing the execution from next instruction next to some other instruction next. This is called flow of control. There are two types of flow of control: selection and looping. Looping repeats an action, and will be discussed a later. Selection chooses between alternative actions. Selection: if (expression) Control Expression returns a bool value action1; Affirmative clause. Executed if Expression is true else action2; Negative clause. Executed if Expression is false
30
Comparison Operators C++ provides comparison operators for making decisions in computer programs. These operators return a value of type bool: true or false. Math C C Math Symbol English Notation Sample Equivalent = equal to == x + 7 == 2 * y x + 7 = 2y not equal to != ans != ‘n’ ans ‘n’ < less than < count < m cout < m + 3 less than <= time <= limit time limit or equal to > greater than > time > limit time > limit greater than >= age >= age 21
31
Logical Operators The ‘and’ operator && Syntax:
(Comparison_1) && (Comparison_2) Example, in an assignment to a bool variable: bool in_range; in_range = (0 < score) && (10 < score); The ‘or’ operator || Example -- in an if-else statement if ( (x ==1) || (x == y) ) cout << “x is 1 or x equals y. \n”; else cout < “x is neither 1 nor equal to y.\n”;
32
PITFALL: strings of inequalities
Suppose x, y and z are integer values. if (x < y < x) // Unfortunately, this is WRONG BUT IT COMPILES. cout << “z is between x and y” ; Here is why the expression is WRONG. In mathematics x < y < z is short hand for x < y && y < z. In C++, this is not true. It is still valid C++, but isn’t what you expect from the mathematics. In C++ the precedence rules require x < y < z be evaluated like this: (x < y) < z The parenthesized expression returns a bool value. The < requires the same type on both sides. The bool value gets converted to the int value 0 (for false) or 1 (for true). Then 0 <z or 1 < z compiles. And gives (most of the time) a wrong answer!
33
PITFALL: using = instead of ==
if (x = 12) // The = should have been == cout << “x is equal to 12”; else cout << “x is not equal to 12”; The second expression is NEVER executed, regardless of the value of x before this statement is encountered. WORSE, after this if statement executes, the expression x = 12 HAS ASSIGNED the value 12 to x. Why? The expression x = 12 returns the value 12, which is converted to the bool value true, which is used by the if. Always write: if (12 == x) // Compiler will say: 12 = x “non-lvalue on left”
34
Simple Loop Mechanisms
Most programs include a mechanism to repeat a block of code multiple times. 30 Students, 30 grades on each test, 100 workers, pay check generator block runs 100 times. C++ provides loops named while for do while The piece of code the loop executes is called the body. Each loop execution of the body is called an iteration.
35
Display 2.10 A while loop #include <iostream>
using namespace std; int main( ) { int count_down; cout << "How many greetings do you want? "; cin >> count_down; while (count_down > 0) cout << "Hello "; count_down = count_down - 1; } cout << endl; cout << "That's all!\n"; return 0;
36
Display 2.13 A do-while loop
#include <iostream> using namespace std; int main( ) { char ans; do cout << "Hello\n"; cout << "Do you want another greeting?\n" << "Press y for yes, n for no,\n" << "and then press return: "; cin >> ans; } while (ans == 'y' || ans == 'Y'); cout << "Good-Bye\n"; return 0; }
37
Pitfall: Stray semicolons
Loop body with several statements while(bool expression) Do not put a semicolon here { This usually causes an several statements infinite loop. (Next section) } Loop body with one statement while(bool expression) Do not put a semicolon here statement; This usually causes an infinite loop.
38
Pitfall: Stray semicolons
Loop body with several statements do { several statements } while(bool expression); Don’t forget the semicolon here. Loop body with one statement statement; while(bool expression); Don’t forget the semicolon
39
Increment and decrement operators
C++ provides the ++ and -- operators, each in each of two forms, prefix and postfix. The text, for good teaching reasons, leaves the use of expressions using ++ and -- to provide a value until later. For now, we use n++; as a synonym for n = n + 1; and n-- for a synonym n = n - 1;
40
PITFALL: Infinite Loops
Any loop in which the Boolean control expression remains true will never terminate. A loop that does not terminate is called an infinite loop. Infinite loops are wrong, and worse, can be hard to find. Examples: This loop terminates: This is an infinite loop: x = 2; x = 1; while (x != 12) while (x != 12) { { cout << x << endl; cout << x << endl; x = x + 2; x = x + 2; } } WHY?
41
Display 2.14 Charge Card Program (1 of 2)
#include <iostream> using namespace std; int main( ) { double balance = 50.00; int count = 0; cout << "This program tells you how long it takes\n" << "to accumulate a debt of $100, starting with\n" << "an initial balance of $50 owed.\n" << "The interest rate is 2% per month.\n";
42
Display 2.14 Charge Card Program (2 of 2)
while (balance < ) { balance = balance * balance; count++; } cout << "After " << count << " months,\n"; cout.setf(ios::fixed); cout.setf(ios::showpoint); cout.precision(2); cout << "your balance due will be $" << balance << endl; return 0;
43
2.5 Programming Style Comments
The most difficult part of any programming language to learn to use properly is the comment. A comment should always tie the code to the problem being solved. In some circumstances, a comment could explain ‘tricky’ code. (It is better to write clear code and omit the comment.) /* comment in this style */ may span more than one line. // these comments run from the // to the end of the line. The text uses the // style comments exclusively. If you do this too, then you can use /*comments*/ to comment out code while developing programs.
44
Indenting Indenting: elements considered a group should be indented to look like a group. if-else, while, and do-while should be indented as in the sample code. The affirmative clause and negative clause of if-else statements should be indented more than surrounding code. The body of loops should be indented more than surrounding code. CONSISTENCY of style is more important than any particular style standard.
45
Program header comments
Comments should be placed at the start of the program that describes the essential information about the program: The file name The author The address or other means to contact the author The purpose of the program What the program does The date written or version number
46
Naming Constants Avoid ‘magic numbers’! Use declared constants.
Example: If the tax rate is 4% (0.04) today, it will go up. Make such numbers declared constants unless you want to hunt through your code to find and replace all instances of 0.04 and try to decide if it is a tax rate, then replace it by the new tax rate, 0.05. Name declared constants with the const keyword. Spell declared constant names with upper case letters, with successive words separated by underscores. const int BRANCH_COUNT = 10; const double TAX_RATE = 0.04;
47
Summary (1 of 2) Use meaningful name for variables.
Check that variables have been declared before use, and have the correct data type. Be sure variables have been assigned a value before use. This can be done by initialization at definition, or by assigning a value before first use. Use enough parentheses to make the order of operations clear. Remember, code is meant to be read, which implies writing for an audience. Always have your program prompt the user for expected input. Always echo user’s input. An if-else statement chooses between two blocks of code to execute. An if statement chooses whether to execute a block of code.
48
Summary (2 of 2) A do-while always executes its body at least once. A while loop may not execute its body at all. Almost all numeric constants should be given meaningful names to be used instead of the numbers. Use the const modifier to do this. Use indenting, spacing, and line break patterns similar to the sample code to group sections of code such as the body of a while statement, or the affirmative and negative clauses of an if-else statement. Insert commentary to explain major subsections of your code, or to explain any unclear part of your program. Make your code clear. Remember, a program is meant to be read by programmers, not just compilers.
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.