2: Basic Coding Skills

What We Will Cover


Continuations

Homework Questions?

Questions from last class?

  1. What to do when WebCT has problems
  2. Room Policies
  3. How To Purchase CodeLab

2.1: Introduction to C++

Learner Outcomes

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

  • Describe how source code becomes a running program
  • Start a command-line session
  • Navigate directories from the command line
  • Compile and run C++ programs when given the source code
  • Display program output to the command line

2.1.1: About C++

  • Once you develop an algorithm, you need to translate it into instructions for the computer
  • To start the translation, you convert your algorithm into a programming language
    • A programming language is a way to describe instructions to a computer
  • The second step is to convert between the programming language and machine-level instructions
    • This second step uses a compiler program, which we will discuss later
  • C++ is a high-level programming language
  • High-level programming languages are easier to use than low-level languages

History of C++

  • C developed by Dennis Ritchie at AT&T Bell Labs in the 1970s
    • 1973 - UNIX kernel rewritten in C
    • 1978 - K&R C specified based on the book The C Programming Language
    • 1989 - ANSI C standard released
  • C++ developed by Bjarne Stroustrup at AT&T Bell Labs in the 1980s
    • 1979 - Stroustrup begins work on "C with Classes"
    • 1982 - Name changed to C++
    • 1983 - First used by AT&T
    • 1985 - First commercial use
    • 1988 - ANSI C++ standard released
    • 1998 - ANSI-ISO standard released (ISO/IEC 14882)

More information

2.1.2: Creating a C++ Program

Converting C++ source code into a program takes several steps

  1. Writing and saving the source code
    • Source code is instructions for a computer written in a programming language like C++
    • A programming language has rules and syntax like a natural language
    • Because computers are limited, a programming language is very picky
    • You have to describe your instructions carefully and precisely
  2. Compiling the source code
    1. Compiling the source code to object code
      • A compiler is a program that converts source code to machine language
      • The machine-language version of source code is called object code
    2. Linking the object modules
      • C++ has many code modules included with the language called libraries
      • As you develop programs, you may produce many object modules
      • The linker combines all these object modules into one executable file
  3. Executing (running) the program
    1. Loading the executable code
      • The computer must load the executable files from storage into main memory
      • A program called a loader does this task
    2. Executing (running) the machine code
      • The final step is to start the program running
      • Many programs run at the same times in most computer systems
      • However, then run in different parts of main memory

Let's discuss each step in more detail.

2.1.3: Writing, Editing and Saving Source Code

  • You can use almost any text editor to write and save C++ source code
  • We use TextPad in the classroom and you can download it for use at home

About Using IDEs

  • Many Integrated Development Environments (IDEs) are available for C++
    • Typically provide visual tools for designing forms and debugging code
  • I do not recommend using an IDE while learning C++
    • IDE will generate code for you, which does not help you learn
    • IDEs are complex tools that themselves are difficult to learn
    • An IDE Can distract you from your goal of learning C++
  • I do recommend using IDEs once you have a good understanding of C++
    • Easier to develop user interfaces
    • Improves programmer productivity
  • Any program you submit for this course must run within Cygwin

2.1.4: Example C++ Source Code

  • Here is an example program we can save as a source code file
  • #include <iostream>
    using namespace std;
    
    int main() {
        cout << "Hello, World!\n";
        return 0;
    } // end of main function
    
  • Copy this into a text editor and save the file as: hello.cpp
    • Save the code to the Desktop directory
    • That way you can see your code files on your computer screen
  • Make sure to save the source-code file using the extension: .cpp
    • hello.cpp
    • All C++ source code files must have the extension: .cpp
    • Otherwise, the compiler program will not work
  • Note each line of code -- what purpose do you think they have?
  • Next step is to compile and run the program
  • To compile and run the code, I need to show you how to use the compiler

2.1.5: Introducing Cygwin

  • The compiler we use runs under a program named Cygwin
  • Cygwin is free and you can install it at home or work
  • Cygwin provides a UNIX-like environment for Windows
  • UNIX is an operating system that was originally written in the C programming language
  • To use Cygwin, you type commands at a command prompt
  • $ ls
    • $ is the command prompt
    • ls is the command you type
  • After typing a command, you press the Enter key

Starting Cygwin

  • Select the Cygwin Bash Shell from the Start menu

Stopping Cygwin

  • At the command prompt, type exit

Stopping a Program

  • You can stop any program running under Cygwin by typing Ctrl-C
    (pressing the Ctrl and C keys at the same time)

Getting Help

  • Once you have a command line, you can use the UNIX help facility: man commandName
  • For example, to view the man(ual) page for the cat command:
  • man cat
    
  • To quit viewing a man page, press the q (for quit) key

2.1.6: Navigating Directories

  • To get around in Cygwin, you need to navigate its directory tree
  • Everything in the file system is stored in a file
  • Files are grouped together into directories, also called folders on Windows
  • Directories are organized in a hierarchical structure starting at the root directory
  • A path is the directories you must go through to get to the file you want
  • You can see this structure in the Windows explorer
    • Right-click on the Start button
    • Select Explore from the list
  • The left-hand side shows the directory structure
  • The Address bar shows the path
  • In Cygwin, we only work with the path

Navigating Cygwin

  • When Cygwin starts, you are located in your home directory
    • Which directory depends on your computer and Cygwin installation
  • You can check the current directory path using pwd (print working directory)
  • pwd
  • You can list the files in the current directory using ls
  • ls
  • You can view the contents of a file using any of the commands: cat, more or less
  • cat hello.cpp
  • You can change directory on your computer using the cd command
  • cd Desktop
  • You can change to your home directory at any time by typing: cd ~
  • cd ~
  • Change to any directory by typing: cd path
  • cd /cygdrive/c/"Documents and Settings"/"All Users"/Desktop

    Note that Cygwin calls the C: drive: /cygdrive/c/

  • Change to a lower subdirectory level: cd directoryName
  • cd Desktop
  • Change up one directory level: cd .. (change directory)
  • cd ..
  • Change to the root of the file system: cd /
  • cd /

More Information

2.1.7: Compiling and Running Programs Using Cygwin

In this section, we introduce the programs we use for compiling and running C++ programs.

Compiling Source Code

  • Cygwin includes a compiler named g++
  • Command for compiling a C++ program:
  • g++ -W -Wall --pedantic -o programName sourceFile.cpp
  • Compiler options:
    • -W: Print extra warning messages for some problems
    • -Wall: Enable all the warnings about questionable code
    • --pedantic: Show all the warnings demanded by strict ISO compliance
    • -o programName: place the output in programName
    • sourceFile.cpp: the name of your source code file

Running a Program

  • To run a program, type ./ and its name after the command prompt
  • ./programName
  • The operating system runs the file named programName.exe
  • Note that an .exe suffix is automatically appended
  • Thus, you do not need to type the .exe part of the program name

Step-By-Step Instructions for Compiling and Running hello.cpp

  1. Save your hello.cpp source-code file.
  2. In the classroom, I suggest you save your file to the Desktop. You can see your file on the computer screen if you save it to the Desktop. At home you should save your files in your Cygwin home directory.

  3. Start Cygwin
  4. Select the Cygwin Bash Shell from the Start menu. In the classroom, Cygwin is located in the CS & CIS submenu.

  5. Change directory (cd) to where you saved your program source code.
  6. cd y:/desktop

    Note that at home, Cygwin will start in a different directory than at school. At home, Cygwin starts in the directory C:\cygwin\home\username where username is different for every computer. Thus, you cannot use cd y:/desktop at home. When using Cygwin at home, I suggest that you save your source code where Cygwin starts, which is: C:\cygwin\home\username

  7. Type the compile command:
  8. g++ -W -Wall --pedantic -o hello hello.cpp

    If no errors occur, the compiler creates the file: hello.exe. You can see this file by typing: ls

  9. At the command prompt type:
  10. ./hello

    You should see the program display a message.

More Information

2.1.8: Summary

  • To write, edit and save source code, you use a text editor
    • Make sure to save the source-code file using the extension: cpp
  • To translate the source code to machine language, you use a compiler
  • Our compiler is included in a program named Cygwin
  • Cygwin provides a UNIX-like environment for Windows
  • To use Cygwin, you type commands at a command prompt
  • To start Cygwin, select the Cygwin Bash Shell from the Start menu
  • To stop Cygwin, type exit at the command prompt
  • To compile your source code using Cygwin, you must position Cygwin to the directory where you saved your source code
  • You can change directories using cd path
  • You can verify the current directory location using pwd
  • You can list the files in the current directory using ls
  • Once you have positioned Cygwin into the correct directory, you can compile your source code
  • To compile a program, use the g++ command with appropriate options
  • g++ -W -Wall --pedantic -o hello hello.cpp
  • To run a program, type ./ and its name after the command prompt
  • ./hello

Check Yourself

  1. What is the advantage of a high-level language?
  2. How do you print text in C++?
  3. Where does a program start?
  4. How do you translate C++ source code into machine code?
  5. What do you type at the command line to compile the program: foo.cpp
  6. What do you type at the command line to run the program compiled in the previous question?

Exercise 2.1

In this exercise we edit and compile our first C++ program.

Specifications

  1. Work with no more than one other person on this exercise.
  2. Start TextPad and enter this code:
  3. #include <iostream>
    using namespace std;
    
    int main() {
        cout << "Hello, World!\n";
        return 0;
    } // end of main function
    
  4. Save this code in a file named hello.cpp to a convenient directory location like the Desktop
  5. Compile the source code using the command line.
  6. Run the program using the command line.
  7. In a second text file named questions.txt, record your answers to the following questions:
  8. Q1: What do you type to compile a program named foo.cpp?

    Q2: What do you type to run the source code you compile with question 1?

  9. Submit both helloworld.cpp and questions.txt as the solution to this exercise.

2.2: Elements of a C++ Program

Learner Outcomes

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.2.1: Example Program

  • Here is an example program like 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.2.2: Comments

  • Comments are ... comments -- notes to people reading the code
  • Comments are ignored by the compiler
  • You use comments to document blocks of code and to describe unusual code
  • One form of comments starts with // and lasts to end of the line
  • // this is a comment
  • Another form affects a section of code: /* ... */
  • This form can span multiple lines:
    /* This is a multi-line comment
          which can be split
       over many lines or a portion of one line. */
    
  • Or just a portion of one line

Programming Style: Block Comments

  • Block comments are the main way to document your code
  • You should 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.2.3: Statements and Whitespace

  • Statements are the commands you give a computer in a program
  • One of the many statements of C++ is: cout << something
  • This statement is one way to send output to a console
  • For example, the statement:
    cout << "Hello, World!";
  • Sends "Hello, World!" to the console like this:
    Hello, World!
  • Statements usually end in a semicolon (;)
    • However, some statements have blocks denoted by curly braces {}
    • Also, some statements start with a # sign
  • Examples of typical statements:
  • #include <iostream>
    
    int main() {
        cout << "Hello, World!\n";
        return 0;
    }
    

Whitespace

  • Whitespace: blank lines, spaces, and tabs
  • The compiler ignores most occurrences of extra white space
  • This lets you can add extra whitespace to your code to make it easier to read

Programming Style: Line Length

  • You should not make your statements too long or they are hard to read
  • When you write statements, limit your line length to 80 characters
  • Longer lines can cause problems with many text editors and other tools

2.2.4: Using Libraries and Namespaces

  • In programming terms, a library is a collection of prewritten code you can use in your programs
  • This save you the effort of writing your own code for commonly-used functions
  • C++ has a number of standard libraries
  • These libraries place their code in what is called the std namespace

Libraries and include Directives

  • To use a library, you add the include directive to your program
  • #include <libraryName>
  • Technically, this is called a "preprocessor directive"
  • It 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
  • It 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 statements:
  • #include <iostream>
    using namespace std;
    

2.2.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.2.6: 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 are the commands you give a computer in a program
  • 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()

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?

Exercise 2.2

In this exercise we examine the elements of a C++ program.

Specifications

  1. Work with no more than one other person on this exercise.
  2. Start your text editor and enter the following code:
  3. 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
    
  4. Save the file as "hello2.cpp".
  5. Compile and execute the code.
  6. g++ -W -Wall --pedantic -o hello hello.cpp
  7. In a second text file named questions2.txt, record your answers to the following questions:
  8. Q1: What are the line numbers for the start of each statement? How can you tell?

  9. Delete the block comment from the code and then recompile
  10. Q2: Does a block comment change the way the code compiles?

  11. Remove the directive: using namespace std; and then try to recompile the code.
  12. Q3: What error message does the compiler report?

  13. Submit the questions2.txt file as the solution to this exercise.

2.3: Memory Concepts

Learner Outcomes

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

2.3.1: Computer Memory

  • All computer algorithms require the computer to store data
  • Computers store program data in an area called 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 known 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.3.2: Memory Addresses and Variables

  • Computer data is stored in and retrieved from various places in main memory
  • Before high-level languages, memory was referred to by its address
  • Storing integers 45 and 12 would allocate memory like the following
  • It quickly becomes cumbersome to write such programs
    • You have to manually keep track of each location
    • You have to make sure locations do not overlap
  • Most people can remember a name more easily than a number
  • Thus, the logical thing to do is create a name for each data we want to store
    • Then we let the computer remember the address and size of the memory
  • 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.3.3: Data Types

  • Recall that main memory stores data for a program
  • The data is stored in memory locations named by variables
  • However, different types of data is stored in different ways
  • For instance, the letter 'A’ may look like: 01000001
  • Also, the number 65 may look like: 01000001
  • How does the computer know the meaning of 01000001?
  • You have to tell the computer how to interpret the data by declaring a data type

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 of the data
  • 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.3.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 you declare a variable, the compiler sets aside memory space
  • However, the contents of the storage space is undefined until you assign a value
  • For instance, after we declare the following variable, what is its value?
  • char letter;
    

Naming a Variable

  • A variable name is a sequence of letters, numbers, or underscore characters
  • However, C++ has some limitations on variable names
  • Specifically, the first character must be either a letter or an underscore character ( _ )
    • Cannot be a number
    • A $ is allowed but its use is discouraged
  • Also, the variable name cannot be one of the C++ reserved words (keywords)
  • For a list of reserved words, see: C/C++ Keywords
  • Note that you cannot have spaces in a variable name
  • A space is NOT a letter, number or underscore character
  • Also, variable names are cAsE sEnSiTiVe
    • id, ID, iD and Id are all valid but different names

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.

Check Yourself

Which of the following are valid variable names?

  1. int myHello2;
  2. int 2myHello;
  3. int My_HeLlO;
  4. int my hello;
  5. int a_very_long_variable_name_that_is_hard_to_read;
  6. int hel-lo;

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

2.3.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
  • Variables must be declared before use.
  • To initialize a variable, 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?

Exercise 2.3

In this exercise, we save a value in a variable and then display the variable to the screen.

Specifications

  1. Work with no more than one other person on this exercise.
  2. Copy the following program into a text editor, save it as variables.cpp, and then compile and run it
  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 to the screen.
  5. Compile and run your modified problem.
  6. Submit your program source code as the solution to this exercise.
#include <iostream>
using namespace std;

int main() {
    cout << "Hello, World!\n";
    return 0;
} // end of main function

2.4: Numbers and Arithmetic

Learner Outcomes

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.4.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;
    
  • Another use for a 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.4.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 large number cannot be represented by type double?

2.4.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.3
    
  • 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. You can use parenthesis 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

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.4.4: Operator Precedence

  • You 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.4.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 the wider of the two types
  • For example:
  • 2 + 2.3
  • First number (2) is an int
  • Second number (2.3) 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.3
  • Remember that the result of arithmetic with an int and a double is a double

2.4.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.4.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.40259
    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.4.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 = 3.14159623;
    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.4

Through the miracles of computer science, we will now convert your $1000 computer into a $10 calculator! Along the way, we learn how to work with arithmetic using C++.

Specifications

  1. Work with no more than one other person on this exercise.
  2. Save the following program as arithmetic.cpp and then compile and run the program.
  3. 1
    2
    3
    4
    5
    6
    7
    
    #include <iostream>
    using namespace std;
    
    int main() {
        cout << "Hello, World!\n";
        return 0;
    } // end of main function
    
  4. Replace the "Hello, World!\n" portion of the program (line 5) with the arithmetic expression (7 + 2) and then recompile and run the program. Specifically, line 5 should now read:
  5. cout << (7 + 2) << endl;

    The output when you run the program should be the single digit: 9. If you do not see this single digit, or do not understand why you should see this single digit, then ask a classmate or the instructor for help.

  6. Add another line like the previous that computes the expression (7 / 2) and then recompile and run the program.
  7. You should have two lines now displaying the following output:

    9
    3
    
  8. Add yet another line that computes the expression to use (7 % 2) and then recompile and run the program.
  9. The following are algebraic expressions and an incorrect translation to code. Correct the errors and add statements to your program using the correct translation.
  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

  11. Submit your program source code that displays the output of all seven (7) expressions as the solution to this exercise.

Wrap Up

    Reminders

    Due Next: A1: Information Please! (2/15/07)
    Exercise 1 and CodeLab Lesson 1 (2/15/07)
    A2: Arithmetic Formulas (2/22/07)
    Exercise 2 and CodeLab Lesson 2 (2/22/07)

  • When class is over, please shut down your computer
  • You may complete unfinished exercises at the end of the class or at any time before the next class.

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

Last Updated: February 22 2007 @16:50:41