2: Basic Coding Skills

What We Will Cover


Continuations

Homework Questions?

Questions from the Previous Classes?

Quiz

2.1: Elements of a C++ Program

Objectives

At the end of the lesson the student will be able to:

  • Write comments in programs
  • Include libraries and use namespaces in programs
  • Identify statements in programs
  • Code main() functions
  • Explain the rules for creating an identifier

2.1.1: Example Program

  • Here is the example program we looked at before
  • 1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    
    /**
     * hello.cpp
     * Purpose: Prints a message to the screen.
     *
     * @author Ed Parrish
     * @version 1.0 8/30/05
     */
    #include <iostream>
    using namespace std;
    
    int main() {
        cout << "Hello, World!\n";
        return 0;
    } // end of main function
    

Brief Explanation by Line Number

  • Lines 1-7: comments -- notes to programmers
  • Line 8: adds a library (prewritten code) to our program
  • Line 9: all the standard libraries use the std namespace
  • Line 10: a blank line that you can use anywhere in your programs
  • Line 11: the main() function where all C++ programs start
  • Line 12-13: programming statements that give instructions to the computer
  • Line 14: the end of the main() function followed by another comment

2.1.2: Comments

  • Comments are ... comments -- notes to people reading the code
  • Comments are ignored by compiler
  • You use comments to document program blocks and describe unusual code
  • Comments can start with // and last to end of the line
  • // this is a comment
  • Comments can span multiple lines: /* ... */
  • /* This is a multi-line comment
          which can be split
       over many lines or a portion of one line. */
    

Programming Style: Block Comments

  • Block comments are the main way to document your code
  • Use block comments like the following at the start of a program file
  • /**
     * CS-11 Asn 0
     * hello.cpp
     * Purpose: Prints a message to the screen.
     *
     * @author Jane User
     * @version 1.0 8/20/03
     */
    
  • We will look at other uses for block comments later in the course

2.1.3: Statements and Whitespace

Statements

  • Statements direct the operation of the program
  • You can start a statement anywhere on a line and continue on the next line
  • Statements usually end in a semicolon (;)
    • Always exceptions in a language
    • Some statements have blocks denoted by curly braces {}
    • Some statements start with a # sign
    • We will look at special cases later
    cout << "Hello, World!\n";
    return 0;
    

Whitespace

  • Whitespace: blank lines, spaces, and tabs
  • Whitespace is ignored by compiler
  • Use whitespace to make programs more readable

Programming Style: Line Length

  • When you write statements, limit your line length to 80 characters
  • Longer lines can cause problems with many text editors and other tools

2.1.4: Using Libraries and Namespaces

  • C++ has a number of standard libraries
  • These libraries place their definitions in the std namespace

Libraries and include Directives

  • Use the include directive to add the contents of a library to your program
  • #include <libraryName>
  • Called a "preprocessor directive"
  • Executes before compiling, and ‘copies’ a library into your program file
  • Most of our programs begin with a declaration like:
  • #include <iostream>
  • This is a library for console I/O
  • Allows us to use the word cout for sending data to a terminal screen
  • Other libraries exist for math, strings and more
  • Note that some compilers are picky about spaces in include directives
    • Do not put spaces before or after the # sign
    • Do not put spaces inside the angle brackets

Namespaces

  • Namespace: a collection of name definitions
  • You can only use a name once within a namespace
  • All standard libraries put their definition in the namespace: std
  • To use these standard names, you need the directive:
  • using namespace std;
  • Thus, most of your programs will begin with two declarations:
  • #include <iostream>
    using namespace std;
    

2.1.5: main() Functions and Blocks

  • C++ programs are structured into subprograms called functions
  • Function - a block of code that performs a task

  • Every C++ program has one or more functions
  • Every C++ application has a main function that is declared like this:
  • int main() {
        // program statements go here
    }
    
  • Programs begin executing at the first line of the main() function
  • int means main returns a value of type int -- cover later
  • For now, mimic the first line of main

Blocks

  • C++ is known as a block-structured language
  • This means that most source code is contained within pairs of matching delimiters
  • C++ uses curly braces { } as delimiters for code blocks
  • Left brace { begins body of every function
  • Right brace } ends body of every function
  • All functions have associated blocks
  • However, as we will see later in the course, you can use blocks other places as well

2.1.6: Creating Identifiers

  • There are many identifiers in our example program
  • Identifier - the name of a variable, subprogram, class or other programming entity.

  • The purpose of an identifier is to provide a name for something
  • Programmers create identifiers for the names of many things in a program:
    • variables
    • functions
    • files
    • classes
  • Identifiers are made up of a sequence of characters
  • Each character can be a:
    • Letter
    • Digit
    • Underscore: _
    • Dollar sign: $
  • However, identifiers cannot start with a digit
  • Nor can they contain any periods or spaces
  • Also, they cannot be a keyword (e.g. "if, "for", etc.: see C/C++ Keywords)
  • In addition, identifiers do not appear inside double quotes
    • Thus, "Hello, World!\n" is not an identifier
    • Words inside double quotes are called strings
  • Note that identifiers are cAsE sEnSiTiVe!
    • id, ID, iD and Id are all valid but different identifiers

Keywords

  • Keywords are reserved words with predefined meanings
  • We used keywords in our hello.cpp program
    • int
    • using
    • namespace
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    
    /**
     * hello.cpp
     * Purpose: Prints a message to the screen.
     *
     * @author Ed Parrish
     * @version 1.0 8/30/05
     */
    #include <iostream>
    using namespace std;
    
    int main() {
        cout << "Hello, World!\n";
        return 0;
    } // end of main function
    
  • All keywords have special meaning in C++
    • Can only be used for their specified purpose
    • Attempting to use for any other purpose will generate a compiler error
    • Thus you cannot use keywords as your own identifier
  • For a current list, see C/C++ Keywords
  • Note that the entire C++ language has only about 62 keywords
  • Part of learning a language is learning what the words mean

Programming Style

  • Professional programmers follow naming conventions when they choose identifiers
  • You, too, must follow these naming conventions on your programming assignments

2.1.7: Compiling and Running a Program Using TextPad

  • Many text editors have provision for compiling within the editor
  • We use TextPad in our class room as a text editor
  • Note that you can install TextPad at home
  • To make your in-class exercises easier, we have set up TextPad to compile and run C++ programs
  • We will use the following program for demonstration
  • 1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    
    /**
     * hello.cpp
     * Purpose: Prints a message to the screen.
     *
     * @author Ed Parrish
     * @version 1.0 8/30/05
     */
    #include <iostream>
    using namespace std;
    
    int main() {
        cout << "Hello, World!\n";
        return 0;
    } // end of main function
    

Compiling with TextPad

  1. Load your source code into the active TextPad window
  2. Select the Tools menu
  3. Select Compile C++
  4. If there are any syntax errors, you will see a page showing them
  5. Otherwise, you will return to your source code page

Running Programs with TextPad

  1. Load your source code into the active TextPad window
  2. Select the Tools menu
  3. Select Run C++ Application
  4. Your program will run in a console window

2.1.8: Summary

  • C++ has two styles of comments
    • //
    • /* ... */
  • Comments help document what a program does
    • Use block comments at beginning of file and before functions
    • Otherwise, use them sparingly
  • Statements direct what a program does
  • C++ has standard libraries of prewritten code
  • Definitions for these libraries are collected in a namespace called: std
  • Thus, most of your programs will begin with two declarations:
  • #include <iostream>
    using namespace std;
    
  • Every C++ application starts with a function named main()
  • Identifiers are any name a programmer creates in a C++ program
  • Keywords are words with a special meaning and are reserved by C++
    • Cannot use a keyword as an identifier
  • To make your testing and debugging easier, we have set up TextPad to compile and run C++ programs

Check Yourself

  1. What styles of comments are allowed in C++?
  2. How do you include libraries in your C++ programs?
  3. What code do you write for a main() function?
  4. How can you tell which lines are program statements?
  5. What are the rules for creating an identifier?

Exercise 2.1

With no more than a single partner, take 5 minutes to complete the following:

  1. Start a text file named exercise2.txt.
  2. Prepare the exercise header as described in the HowTo on submitting exercises
  3. Label this exercise: Exercise 2.1
  4. Submit all exercises for today's lesson in one file unless instructed otherwise
  5. Complete the following and record the answers to any questions in exercise2.txt.

Specifications

  1. Start your text editor and enter the following code:
  2. 1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    
    /**
     * hello.cpp
     * Purpose: Prints a message to the screen.
     *
     * @author Ed Parrish
     * @version 1.0 8/30/05
     */
    #include <iostream>
    using namespace std;
    
    int main() {
        cout << "Hello, World!\n";
        return 0;
    } // end of main function
    
  3. Save the file as "hello.cpp".
  4. Q1: Which words are identifiers but not keywords? (Please list them)

  5. Compile and execute the code.
  6. g++ -W -Wall --pedantic -o hello hello.cpp

    Q2: Which lines of code start a statement? How can you tell?

  7. Delete the block comment from the code and then recompile
  8. Q3: Does a block comment change the compilation of the code?

  9. Remove the directive: using namespace std; and then try to recompile the code.
  10. Q4: What error message does the compiler report?

2.2: Memory Concepts

Objectives

At the end of the lesson the student will be able to:

  • Describe how to store data in a program
  • Write code for declaring variables and assigning them values
  • Write code for declaring constants and assigning them values

2.2.1: Computer Memory

  • Recall that a computer has five main parts
  • One of these is the main memory

Main Memory

  • Main memory is organized as a long list of memory locations
  • Each memory location contains zeros and ones
  • The contents of a memory location can change while a program runs
  • The smallest unit of memory is the Binary Digit or bit
  • A bit that can only be zero or one

Memory Location

  • Each memory location has eight bits, which are know as a byte
  • The memory address is the number that identifies a memory location
  • Some data is too large for a single byte
  • For instance, most numbers are too large for one byte
  • In these cases, the address refers to the first byte
  • The next few consecutive bytes store the additional bits for larger data

More Information

2.2.2: Memory Addresses and Variables

  • Computer data is stored in and retrieved from main memory
  • Before high-level languages, memory was referred to by its address
  • Storing integers 45 and 12 would allocate memory like the following
  • Quickly becomes cumbersome to write such programs
    • Have to manually keep track of each location
    • Have to make sure locations do not overlap
  • Easier to assign each variable a name
    • Let the computer remember the address and size of the memory
  • Then each memory location can be referred to by a name
  • These named locations are call variables
    • Because the data in them can vary (change)

  • Now our programs can look like the following:
  • num1 = 45;
    num2 = 12;
    total = num1 + num2;
    

2.2.3: Data Types

  • Main memory stores data while a program is running
  • The data is stored in memory locations named by variables
  • The letter 'A’ may look like: 01000001
  • The number 65 may look like: 01000001
  • How does the computer know the meaning of 01000001?
  • Interpretation depends on the data type of the variable

C++ Data Types

  • A data type tells your computer program how to interpret data
    • Specifies how many bytes are needed to store the data
    • Tells the computer the format in which the data is saved
  • There are four general categories of data types that C++ provides:
  • General Type Explanation Examples
    Integer Numbers without decimal points 123, -987
    Floating-Point Numbers with decimal points 1.23, -0.01
    Character Single letters, digits and special symbols 'A', '9'
    Boolean Logical values true or false true, false

  • To specify a data type, you use a keyword that specifies the type
  • The most commonly used C++ data types are:
  • Type Bytes Use
    char 1 All ASCII characters.
    short 2 Short integers from -32,768 to 32,767.
    int 4 Integers from -2,147,483,647 to 2,147,483,647.
    long 4 Integers from -2,147,483,647 to 2,147,483,647.
    float 4 Single-precision, floating-point numbers from about E-45 to E38 with 6 or 7 significant digits.
    double 8 Double-precision, floating-point numbers from E-308 to E308 with from 14 to 15 significant digits.
    bool 1 A true or false value.

  • Note that number of bytes used for storage depends on the system and compiler
  • Which general category does C++ data type belong in?

2.2.4: Declaring Variables

  • All C++ program variables must be declared before using them
  • A declaration statement both names a variable and specifies the data type it can store
  • The data type specifies the size and format of the data
  • General syntax:
  • dataType VariableName1, VariableName2, ...;
    
  • For example:
  • int num1, num2, total;
    long dateNum;
    float firstNum;
    double secNum;
    char letter;
    
  • When variables are declared, computer allocates storage space
  • The contents of the storage space is undefined until a value is assigned
  • For instance, after we declare the following variable, what is its value?
  • char letter;
    

Programming Style: Variable Naming Conventions

  • Use meaningful names that are easy to remember as you code.
  • Two commonly-used styles you may use:
    1. Start with a lower-case letter and use uppercase letters as separators. Do not use underbars ('_').
    2. int myVar
    3. Use all lower case letters and use underbars ('_') as separators.
    4. int my_var
  • You must be consistent and only use one style in a program.
  • The instructor's preference is the first style.

2.2.5: Assigning Values to Variables

  • After you declare a variable, you must assign it a value
  • Use the assignment operator "equals sign" (=)
  • variable = expression;
  • Assigns value of expression (right side) to the variable (left side)
  • The simplest expression is a literal value:
  • length = 25;
    width = 17.5;
    
  • In each statement, the value on right is assigned to the variable on the left
  • Can also assign results of more complex expressions to a variable
  • total = num1 + num2;
    slope = (y2 - y1) / (x2 - x1);
    
  • Reading variables from memory does not change them
  • Values placed into a variable replace (overwrite) previous values

Assigning Initial Values to Variables

  • Initial values may or may not be assigned when variables are declared:
  • // These are not initialized when declared
    // and have unknown values
    int sum, number1, number2;
    
    // These are initialized when declared
    int sum = 0;
    int number1 = 5, number2 = 10;
    
  • Good programming practice: initialize variables when declared

Constant Variables

  • A constant variable (or constant) is a variable that cannot change after being assigned a value
  • Sounds oxymoronic, but is actually quite useful
  • To declare a constant, use the keyword: const
  • const int MY_CONST = 1;
  • Note that you must assign a value when the constant is declared
  • Also note that the name is all uppercase letters with an underscore separator
  • This is a common coding convention that you must follow

2.2.6: Summary

  • Computers store data and code in main memory
  • Variables are how you can store data in your programs
  • Variables can be assigned new values while your program executes
  • Constants are a variable that cannot change after it is first assigned a value
  • Variables and constants must be declared before use.
  • To initialize a variable or constant, declare a name and assign a value.
  • Simple assignment statements have a variable, equals sign and an expression.
  • variable = expression;
  • The expression is computed before the assignment

Check Yourself

  1. How do you store data in a program
  2. What is the purpose of a data type?
  3. What is the code to declare an int variable named foo and assign it a value of 10?
  4. What is the code to declare a constant double named BIG_NUM and assign it a value of 100,000?

Exercise 2.2

  1. Complete the following program and submit the program along with exercise2.txt.
  2. Name the program file: exer2_2.cpp
  3. Note: this is a separate file to submit along with your other exercises for this week. Do NOT copy the code into exercise2.txt.

Specifications

  1. Copy the following program into a text editor, save it as exer2_2.cpp, and then compile and run it
  2. If you have difficulty, ask another student or the instructor for help.

    /**
     * hello.cpp
     * Purpose: Prints a message to the screen.
     *
     * @author Ed Parrish
     * @version 1.0 8/30/05
     */
    #include <iostream>
    using namespace std;
    
    int main() {
        cout << "Hello, World!\n";
        return 0;
    } // end of main function
    
  3. Change the code in main() to declare an int variable named foo and assign it a value of 10.
  4. Add code to display the value of the variable foo.
  5. Compile and run your modified problem.
  6. If you have difficulty, ask another student or the instructor for help.

2.3: Numbers and Arithmetic

Objectives

At the end of the lesson the student will be able to:

  • Distinguish between an integer and a floating-point number
  • Explain what is meant by the term: expression
  • Write C++ code for arithmetic expressions
  • Infer the type returned from a mixed-mode arithmetic expression
  • Explain the term precedence
  • Construct expressions that use mathematical functions

2.3.1: Literal Integers

  • As we saw before, C++ has two general types of numbers: integers and floating-point
  • An integer is zero or any positive or negative number without a decimal point
  • For example:
  • 0   1   -1    +5    -27   1000    -128
  • These examples are known as literals because we write them in the conventional way
  • Literals are a type of constant value in a program
  • Once you have coded the value into your program, there is no way to change it
  • Integer literals cannot have any commas, decimal points or special symbols (like $) in them
  • However, they may have a sign (+ or -) before the number
  • For those interested, the compiler saves these literal integer values as an int by default
  • Thus each of the above examples uses 4 bytes of memory storage

Using Literal Integers

  • As we saw before, we use literal integers for assignment of data to variables and constants
  • int yards = 4;
    int number1 = 5, number2 = 10;
    const int FEET_PER_YARD = 3;
    
  • Another use for literal integer is in arithmetic expressions
  • An expression is a part of a statement that returns a value
  • As an example:
  • int feet = yards * 3;
    
  • In the example above, yards * 3 is an expression
  • Before the program assigns a value to feet, it computes the product of yards * 3
  • The right hand side of an assignment statement is always an expression
  • The right hand side of an assignment statement is always computed before assignment to the left hand side

2.3.2: Literal Floating-Point Numbers

  • A floating-point number is any signed or unsigned number with a decimal point
  • For example:
  • 0.0   1.0   -1.1   +5.   -6.3    3234.56    0.33
  • Note that 0.0, 1.0 and +5. are floating-point numbers, but could be rewritten as integers
  • Like integers, floating-point numbers cannot have any commas or special symbols
  • For those interested, the compiler saves these literal floating-point values as a double by default
  • Thus each of the above examples uses 8 bytes of memory storage

Using Floating-Point Literals

  • Like literal integers, we use literal floating-point numbers in assignment statements
  • double num = 1.23;
    double area = 0.0, radius = 4.5;
    const double PI = 3.14159623;
    
  • We also use them in arithmetic expressions, just like integers
  • area = radius * radius * 3.14159;
    

Exponential Notation

  • Floating-point literals can be written in exponential notation
    • Similar to scientific notation
  • Used to express both very large and very small values in compact form
  • For example:
  • Decimal Notation Scientific Notation Exponential Notation
    1234 1.234 x 103 1.234E3
    98765 9.8765 x 104 9.87654E4
    0.0123 1.23 x 10-2 1.23E-2
    0.000625 6.25 x 10-4 6.25E-4

  • Letter E stands for exponent
  • Number following E represents a power of 10
  • Indicates the number of decimal places to move for standard decimal value
  • A positive power of 10 moves the decimal point to the right
  • A negative power of 10 moves the decimal point to the left

How Large is 1.7E308?

  • Largest possible double is 17 followed by 307 zeros
  • How large is that?
  • Current estimate of the number of atoms in the universe: about 1.0E78
  • Mathematicians use the term "googol" for a very large number: 1.0E100
  • Data type double easily encompasses these numbers
  • What value cannot be represented by type double?

2.3.3: Arithmetic

  • You can write code to perform arithmetic on integers and floating-point numbers
  • C++ uses special symbols to perform the operations:
    • + for addition
    • - for subtraction
    • * for multiplication
    • / for division
    • % for modulus (remainder)
  • Some examples:
  • 3 + 4
    12 - 7
    12.3 + 4.56
    .065 * 1200
    18 / 2
    17.4 / 2.2
    
  • We can use these expressions to perform arithmetic and display the results
  • cout << 3 + 4 << endl; // prints 7

Unary Operators

  • Operators +, -, *, /, % are called binary operators
    • Always need two operands (numbers) to work with them
  • C++ also provides a unary operator: - (minus sign)
    • Reverses the sign of a number
  • For example:
  • -1    -5.3    - -1
  • C++ also provides a plus sign (+) unary operator
    • Generally not used

Notes About Arithmetic Expressions

  1. Parenthesis can be used to group expressions
    • Anything within parenthesis is evaluated first
    • 2 * (10 + 5)
  2. You can have parenthesis within parenthesis
    • Innermost parenthesis evaluated first
    • (2 * (10 + 5))
  3. Parenthesis cannot be used to indicate multiplication
    • Invalid expression: (2)(3)
    • Must use the * operator
  4. Two binary operators cannot be placed side by side
    • Invalid expression: 5 * % 6
    • Operators * and % cannot be next to each other

Programming Style

  • Programming style: add spaces around binary operators
    • 2 + 3, not 2+3
  • Programming style: no spacing after opening or before closing parenthesis
    • (2 / 3), not ( 2/3 )

2.3.4: Operator Precedence

  • Often need to process expressions of greater complexity than two numbers
    • May need more than one operator
  • C++ has certain rules that must be followed

Precedence Rules

  • Precedence: what gets done first
  • Arithmetic operators are processed in algebraic order:
    1. Parenthesis: ( )
    2. Unary operators: +, -
    3. Multiplication, division, modulus: *, /, %
    4. Addition, subtraction: +, -
  • Binary operators of same precedence are evaluated from left to right

Examples of Expressions

Algebra Expression C++ Expression Fully Parenthesized
2(10 + 5)
2 * (10 + 5) (2 * (10 + 5))
1

12.2 + 3 · 7.3
1 / (12.2 + 3 * 7.3) (1 / (12.2 + (3 * 7.3)))
10 - 7

3.3 + 9 · 1.6
(10 - 7) / (3.3 + 9 * 1.6) ((10 - 7) / (3.3 +(9 * 1.6)))
2 · 42
2 * 4 * 4 ((2 * 4) * 4)

  • The fully parenthesized column shows the precedence explicitly

2.3.5: Mixed-Mode Expressions

  • Recall that different data types are stored in different forms
    • An int is stored in 4 bytes
    • A double is stored in 8 bytes
    • The format they are stored in is different as well
  • Computer needs both operands in the same form before it can perform an operation
  • If one operand is different than the other, the compiler converts it to a wider type
  • For example:
  • 2 + 2.2
  • First number (2) is an int
  • Second number (2.2) is a double
  • First number is narrowest (uses the fewest bytes), thus it gets promoted to a double (i.e. 2.0)
  • Then the arithmetic operation can take place to produce a result of 4.2
  • Remember that the result of arithmetic with an int and a double is a double

2.3.6: Integer Division and Modulus

  • Dividing two integers can produce unexpected results for the unwary
  • For example, what is the result of the following expression?
  • 7 / 2
  • Since both numbers are of type int, one does not get a floating-point result
  • Remainder portion is truncated (discarded, thrown away)

Modulus Operator

  • Sometimes you want to know the remainder of an integer division
  • C++ provides the modulus operator: % (percent sign)
  • Returns the remainder of the division of first number by the second
  • For example:
  • 7 % 2 // returns 1
  • 7 % 2 returns 1 because 1 is the remainder when 7 is divided by 2

Check Ourselves

What is the result of the following arithmetic operations?

  • 9 / 4
  • 17 / 3
  • 14 / 2
  • 9 % 4
  • 17 % 3
  • 14 % 2

2.3.7: Mathematical Functions

  • Operators provide only the simplest mathematical operations
  • For more complex operations, you use mathematical functions
  • cout << sqrt(9.0) << endl;
  • C++ provides a standard cmath library that contains many such functions
  • Name Description Example Result
    abs absolute value abs(-3.9)
    abs(3.9)
    3.9
    3.9
    exp exponent exp(1.0) 2.71828
    log natural log log(10.0) 2.30259
    pow powers pow(2.0, 3.0) 8.0
    sqrt square root sqrt(4.0) 2.0

  • In addition, it includes two similar functions: ceil, and floor
  • Name Description Example Result
    ceil ceiling: round up ceil(3.3)
    ceil(3.7)
    4.0
    4.0
    floor floor: round down floor(3.3)
    floor(3.7)
    3.0
    3.0

  • Both return whole numbers, although they are of type double

Using Mathematical Functions

  • How are mathematical functions evaluated?
  • Whatever is within the parenthesis of the function call is evaluated first
  • Thus, in the following example, we get the square root of 9.0
  • cout << sqrt(3.0 * 3) << endl;
  • If the function is used in an arithmetic expression, they are handled just like a number of the type returned
  • For example, in the following, the value 4.0 is stored in the double variable num:
  • double num = 1 + sqrt(3.0 * 3.0);
    cout << num << endl;
    
  • Note that the function evaluates the sqrt(3.0 * 3) before adding it to 1.0
  • Thus functions have a higher precedence than arithmetic operators

2.3.8: Summary

  • C++ uses the following operators for arithmetic
    • + for addition
    • - for subtraction
    • * for multiplication
    • / for division
    • % for modulus (remainder)
  • The dash (minus sign) is also used for negation
  • Arithmetic expressions are combinations of numbers, variables, constants and operators
  • double area = 0.0, radius = 4.5;
    const double PI = 2.44159;
    area = PI * radius * radius;
    
  • Operators have the same precedence as in algebra
    1. Parenthesis: ( )
    2. Function calls
    3. Unary operators: +, -
    4. Multiplication, division, modulus: *, /, %
    5. Addition, subtraction: +, -
  • Results of integer division are truncated
  • Must use modulus operator (%) to get the remainder value
  • More complex mathematical operations are available using the cmath library
  • cout << sqrt(3.0 * 3) << endl;

Check Yourself

  1. How can you tell the difference between a literal integer and a literal floating-point number?
  2. What is meant by the term: expression?
  3. What are the five operators C++ provides for arithmetic?
  4. What type is returned from an expression when an int and a double are added together?
  5. What is the result of the following arithmetic expressions?
  6. 7 / 3
    7 % 3
    
  7. What is meant by the term precedence?
  8. How do you calculate the square root of a number like 27?

Exercise 2.3

  • Label this exercise: Exercise 2.3
  • Complete the following specifications and record the answers to any questions in exercise2.txt.

Specifications

    Through the miracles of computer science, we will now convert your $1000 computer into a $10 calculator!

  1. Copy the following program into a text editor and then save, compile and run the program.
  2. 1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    
    /**
     * hello.cpp
     * Purpose: Prints a message to the screen.
     *
     * @author Ed Parrish
     * @version 1.0 8/30/05
     */
    #include <iostream>
    using namespace std;
    
    int main() {
        cout << "Hello, World!\n";
        return 0;
    } // end of main function
    
  3. Replace the "Hello, World!\n" portion of the program (line 12) with the arithmetic expression (7 + 2) and then recompile and run the program. Specifically, line 5 should read:
  4. cout << (7 + 2) << endl;

    Q1: What value was displayed by the computer?

  5. Use the expression (7 / 2) and then recompile and run the program.
  6. Q2: What value was displayed by the computer? Why?

  7. Change the expression to use (7 % 2) and then recompile and run the program.
  8. Q3: What value was displayed by the computer? Why?

  9. The following are algebraic expressions and an incorrect translation to code. Find the errors and write corrected code. Save the corrected expressions in exercise2.txt.
  10. Algebraic Expression Incorrect Translation
    (2)(3) + (4)(5)
    (2)(3) + (4)(5)
    6 + 18

    2
    6 + 18 / 2
    5

    9
    (100 - 32)
    5 / 9 * (100 - 32)
    2 · 42
    2 * 4 ^ 2

2.4: Interactive Input

Objectives

At the end of the lesson the student will be able to:

  • Generate code to display program output to the console
  • Format numbers during output
  • Generate code to get user input from the console
  • Prompt users when requesting input

2.4.1: About Interactive Input

  • For programs used infrequently, easy to put data directly in the code
  • For instance, to calculate the average of four numbers:
1
2
3
4
5
6
7
8
9
#include <iostream>
using namespace std;

int main() {
    double average = (32.6 + 55.2 + 67.9 + 48.6) / 4;
    cout << "Average = " << average << endl;

    return 0;
}
  • Easy to include the four numbers with the code operating on those numbers
  • However, you must recompile the program if you change any number
  • More convenient for users to enter data without recompiling a program
  • This section discusses how you can display user output to the console
  • Also, it discusses how you can get user input while a program is running

2.4.2: Using cin

  • To get data from a user, we use cin
  • cin >> num;
  • cin is an input stream object bringing data from the keyboard
  • '>>' (extraction operator) points toward where the data goes
  • Waits on-screen for keyboard entry
  • Value entered at keyboard is 'assigned' to num
  • You can input more than one variable in a cin statement
  • cin >> v1 >> v2 >> v3;
  • You cannot use a literal number in a cin statement
  • You must input data into a variable

2.4.3: Prompting Users

  • Good programming practice is to always "prompt" users for input
  • int numOfDragons;
    cout << "Enter number of dragons: ";
    cin >> numOfDragons;
    
  • Note that you do not put a newline at the end of the prompt
  • The prompt waits on the same line for keyboard input as follows:
  • Enter number of dragons: _
  • Where the underscore above denotes where keyboard entry is made
  • Every cin should have a cout prompt before it
  • In addition, often a good idea to echo what the user typed
  • For example:
  • #include <iostream>
    using namespace std;
    
    int main() {
        double num1, num2;
        cout << "First number: ";
        cin >> num1;
    
        cout << "Second number: ";
        cin >> num2;
    
        cout << num1 << " + " << num2 << " = "
             << num1 + num2 << endl;
    
        return 0;
    }
    
  • Maximizes user-friendly input/output

2.4.4: Output Using cout

  • cout sends data to the console
    • Technically, cout is known as an output stream
    • An output stream gets data from some source and sends it to a destination
    • Like a stream that moves water from one place to another
  • The insertion operator "<<" inserts data into the cout stream
  • Any data can be output to the display screen
    • Variables
    • Constants
    • Literals
    • Expressions (which can include all of above)
    int numberOfGames = 12;
    cout << numberOfGames << " games played." << endl;
    
  • 3 values are output:
    • Value of the variable numberOfGames
    • Literal string " games played."
    • A newline character
  • Note that you can have multiple values in one cout

2.4.5: Newlines in Output

  • Recall that '\n' is an escape sequence for the char "newline"
  • A second method is to use the object endl
  • Examples:
  • cout << "Hello World!\n";
  • Sends string "Hello World!" followed by a newline
  • cout << "Hello World!" << endl;
  • Same result as above

2.4.6: Decimal Formatting

  • Numbers may not display as you'd expect!
  • double price = 78.50;
    cout << "The price is $" << price << endl;
    
  • If price (declared double) has value 78.5, you might get:
  • The price is $78.5
  • We must explicitly tell C++ how to output numbers in our programs!
  • "Magic Formula" to force decimal sizes:
  • cout.setf(ios::fixed);     // fixed notation, not scientific
    cout.setf(ios::showpoint); // show decimal point
    cout.precision(2);         // show 2 decimal places
    
  • Now all future values have exactly two digits after the decimal place
  • For example:
  • cout.setf(ios::fixed);
    cout.setf(ios::showpoint);
    cout.precision(2);
    
    double price = 78.5;
    cout << "The price is $" << price << endl;
    
  • Now results in the following:
  • The price is $78.50
  • If you want to reset a flag, use cout.unsetf()
  • For example:
  • cout.setf(ios::fixed);
    cout.setf(ios::showpoint);
    
  • We will cover output formatting in more detail in a few weeks

2.4.7: Summary

  • cin is an input stream bringing data from the keyboard
  • '>>' (extraction operator) points toward where the data goes
  • When designing I/O:
    • Prompt the user for input
    • Echo the input by displaying what was input
  • cout is an output stream sending data to the monitor
  • The insertion operator "<<" inserts data into cout
  • There are two ways to output a newline character:
  • cout << "Hello World!\n";
    cout << "Hello World!" << endl;
    
  • cout includes special tools to specify the output of type double
  • cout.setf(ios::fixed);
    cout.setf(ios::showpoint);
    cout.precision(2);
    
  • Allows you to display numbers with 2 decimal places

Check Yourself

  1. Why do programs need interactive input?
  2. Why is it a good practice to prompt users before input?
  3. What is the escape sequence for a newline?
  4. What is the "magic formula" for outputting numbers with two decimal places?

Exercise 2.4

The following code gets a number from the user.

#include <iostream>
using namespace std;

int main() {
    double num;
    cout << "Enter a number: ";

    // Put your code here

    return 0;
}

Specifications

  1. Save the code as format.cpp
  2. Modify the code to display the number a user enters in both currency and percent formats, like this:
  3. Enter a number: 12.3
    As a dollar amount: $12.30
    As a percent: 12.3%
    

    Note that you will need to have two cout.precision() statements in your code.

  4. Submit your program along with your other exercises for this lesson.

Wrap Up

Home | WebCT | Announcements | Day Schedule | Eve Schedule
Course info | Help | FAQ's | HowTo's | Links

Last Updated: October 13 2005 @15:15:12