1. Introduction to C++ Programming

What We Will Cover


Exercise 1.1

Instructions

Use the next 10 minutes to complete the following.

  1. Join a group of 3-4 people and prepare an answer to one of the following questions.
  2. Select one member from your group as a representative to describe your answer to the class.

Exercise Questions

  1. What "burning questions" do you have about the course?
  2. What can you hope to learn by the time you complete this course?
  3. How do you plan to balance the work required by this course with the other activities in your life?

Note: You do not have to turn in the answers to this exercise. However, you are expected to submit answers to subsequent exercises.

1.2: Succeeding in This Course

Objectives

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

  • Describe how to study effectively for this course
  • Use computers in the CTC for homework
  • Install software used in this course at home

1.2.1: Elements of Success

  • Programming requires you to know many facts and procedures
  • Also, you must learn how to solve problems
  • To help you master the materials, I provide you with exercises and assignments in addition to lectures
  • To succeed in this course, you need to make use of this material

Attend Class

  • You need to attend class and pay attention
  • When asked questions, you need to respond
  • When you cannot attend class for some reason, you need to catch up before the next class meeting

Complete In-Class Exercises During Class

  • In-class exercises are problems you are given class-time to complete
  • You should complete these problems during the allotted time in class
    • However, you have about one-week to complete them after class
    • See WebCT for the exact date and time
  • You can discuss them with partners or the instructor
    • Much easier to solve problems in the classroom than at home
  • You should submit the exercises to WebCT before you leave the classroom
    • Ensures that something is turned in on time
    • You can always unsubmit them if you want to make changes during the week
  • Graded on a best-effort basis
    • You get full credit for just attempting to complete the exercise

Complete On-line Exercises On-time

  • Online exercises (CodeLab) are due about a week after we discuss the topics
  • CodeLab gives you a series of graduated exercises with "instant" feedback
  • I suggest that you complete the on-line exercises before the homework assignment

Complete Homework Assignments On-time

  • Homework assignments have you apply and explore lecture concepts
  • Homework assignments can include reading, quizzes and writing code
  • If you get confused about or stuck on an assignment:
  • Submit homework to WebCT at least the day before it is due
    • Even if you are not done, turn it in
    • You get some credit for what you did complete
    • Make sure to state an accurate status in the README.txt file
  • Note that homework deadlines are real -- late homework is not accepted
  • Instead, most homework has extra credit possibilities

Study for Exams

  • Most students do not have perfect memories
  • You need to refresh your memory about programming details before an exam
  • Plan on spending time studying for exams
  • I will discuss study techniques before the exams

1.2.2: Time Estimates

  • Students often ask how much times is needed for a course
  • Estimated average course time per week:
    • 1 hour reading the lecture notes and textbook before class
    • 4 hours in the classroom
    • 8 hours for on-line exercises and homework assignments (excluding extra credit)
  • I collect time estimates from students for homework assignments

1.2.3: Using the CTC for Homework Assignments

  • First you will need a login and password
  • You can use either Linux, Macintosh or Windows computers for your assignments
  • For more information, follow the link to the CTC homepage

1.2.4: Can I Run This On My Own Computer?

  • All the technology we use runs on most any computer
  • Compiler used is called g++ and is free from GCC
  • For Windows, you can Install Cygwin, which contains the g++ compiler
  • For Linux/UNIX/OS-X users, you can just install gcc and g++ compilers.

1.2.5: Summary

  • Elements of success in this course:
    1. Attend class and actively participate
    2. Submit the in-class exercises before you leave
    3. Complete on-line exercises on-time
    4. Do your homework assignments and turn them in on time
    5. Prepare for and attend exams
  • You can complete homework assignments in the CTC
  • Also, you can install the necessary software at home or work

Exercise 1.2

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

  1. Start a text file named exercise1.txt
    You will be adding to this file during the lesson, so save it often.
  2. Prepare the exercise header as described in the HowTo on submitting exercises
  3. Label this exercise: Exercise 1.2
  4. Submit all exercises for this lesson in one file unless instructed otherwise
  5. Complete the following and record the answers to any questions in exercise1.txt.

Specifications

  1. List the elements of success for this course
  2. What is the average time you can expect to spend outside the classroom on this course?
  3. Where do you plan to work on your programming assignments?

1.3: Programming and Problem Solving

Objectives

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

  • Describe the programming process
  • Solve simple computational problems

1.3.1: What Programming is About

  • Programming is about solving problems using a computer program
  • A few terms and definitions you need to learn:
  • Algorithm: A sequence of precise instructions which leads to a solution

    Computer programming: An algorithm expressed in a language the computer can understand

  • Programming is a creative process
  • No complete set of rules for creating a program
  • However, programs are best developed in two phases

Program Development Phases

  • Programs are developed in two general phases:
    1. Problem-solving phase
      • Result is an algorithm that solves the problem
    2. Implementation phase
      • Result is the algorithm translated into a programming language
  • Each of these phases has several general steps to them

  1. Problem definition
    • First step is to analyze and understand the problem
    • We will look at this step in more detail in the next section
  2. Algorithm design
    • Next step is to define an algorithm
    • Set of steps that a computer can use to perform a task
    • We will look at this step in more detail as well
  3. Desktop testing
    • After developing an algorithm, you need to verify it is correct
    • Develop a sample problem
    • Walk through each step mentally or manually
    • If there is an error, change the algorithm
  4. Translate to C++
    • After you are sure the algorithm works, then write the program code
    • Code is written using a programming language
    • The language we use for this course is called C++
    • As you write the program code, you translate human-readable source code into a language understood by the computer
    • You check your translation using a program called a compiler
    • Discuss compiling later today
  5. Testing
    • After code compiles, you test it to make sure it:
      1. Does what it is supposed to do
      2. Does not do what it is not supposed to do
      3. Does what it used to do
  6. Working program
    • When it works well, you document and deliver the program

1.3.2: Analyzing Problems

  • The first step in solving a problem is to understand it
  • You need to examine the data and conditions of the problem
  • The topics in this section suggest some ways to help you analyze the problem and gain an understanding

Paraphrase the Problem

  • A good way to start analyzing a problem is to write it down in your own words
  • Often times writing down the problem will lead to other ways of analyzing it

Ask Questions

  • If you are given a problem, you naturally ask questions like: What? When? Why? Where? How?
  • Here are some questions that are often useful to ask when faced with a programming problem:
    1. What output is expected?
    2. What format is required for the output?
    3. What calculation must be performed?
    4. What data is needed for the calculations?
    5. What data do I have to work with?
    6. Where will I get the data I do not have?
    7. What do the data items look like?
    8. How will I know when I have processed all the data?
    9. How many times is the process going to repeat?
    10. What special error conditions might happen?
  • Try reviewing the list and answering the questions that seem pertinent

Draw a Diagram

  • You have heard the old saying, "a picture is worth a thousand words"
  • Sometimes a visualization of the problem can help you understand it
  • For example, if the problem is about a rectangle then you draw a rectangle

Look for Similarities

  • Often a problem reminds you of other problems you have seen before
  • Recognizing similarities can give you insight into understanding the current problem
  • For example, if you have seen a problem for a list of numbers then you may see similarities when given a problem dealing with a list of names

Separate the Parts

  • If you have a large or complex problem, then you can often break it into smaller pieces that are easier to understand
  • For example, if you have to travel from one location to another, you can plan the journey in steps

More Information

1.3.3: Developing Algorithms

  • A computer algorithm is a set of steps that a computer can use to perform a task
  • Coming up with a step-by-step method for solving a problem is not always easy
  • It is often a trial-and-error process requiring many attempts and refinements
  • This is made more complicated because the computer can only do certain things
  • Our algorithm must only contain steps that a computer can perform

Operations a Computer Can Perform

  • Get data from a keyboard or other input device
  • Display data on a screen or other output device
  • Move data from one location to another
  • Store data into and retrieve data from memory
  • Perform arithmetic, such as addition and subtraction, very quickly
  • Compare two data values for equality or inequality
  • Process instructions in a sequence (in order)
  • Process different instructions depending on conditions that are met
  • Repeat a set of instructions while certain conditions are met

Devising a Plan

  • There are several approaches to solving problems algorithmically
  • We will look at several during this course
  • One approach you may find useful is: Using a Formula

1.3.4: Using a Formula

  • Formulas are a powerful tool we can borrow from mathematics
  • Oftentimes, you can easily solve a computing problem using a formula
  • For an example, we will use the problem:
  • Find out how big around a rectangle is.

Starting the Analysis

  • We first start by rephrasing the problem in our own words
  • We state our problem as precisely as we can:
  • Calculate the perimeter of a rectangle.

Understanding the Problem

  • We continue our analysis by trying to understand the problem in more depth
  • We select some of the questions that seem pertinent to the problem
    1. What output is expected?
    2. What calculation must be performed?
    3. What data is needed for the calculations?
    4. Where will I get the data I do not have?
  • What are the answers to these questions for our example problem?
  • Thinking about these questions improve our understanding of the problem
  • We can see that we can solve the problem by using a formula

Defining the Algorithm

  • Once we understand our problem sufficiently, we develop an algorithm
  • For our example problem, we might define our algorithm as:
    1. Get the length of the rectangle
    2. Get the width of the rectangle
    3. Calculate the perimeter using the equation:
      perimeter = 2 * (length + width)
    4. Display the result of the calculation
  • We must test the algorithm to be certain it is correct

1.3.5: Processing a List

  • Let us look at another problem-solving example
  • One problem that computers are good for solving is to process a list of data
  • For an example, we will use the problem:
  • Count the number of times that a name occurs on a list.

Analyzing the Problem

  • What is a good problem statement?
  • Next, we ask ourselves some questions to improve our understanding
    1. What output is expected
    2. What data do I have to work with?
    3. What do the data items look like?
    4. How will I know when I have processed all the data?
    5. How many times is the process going to repeat?
  • Ask we ask these questions, more questions occur to us like:
    1. How many names are on the list?
    2. What name are we looking for?
  • After answering these, we should be ready to develop a solution

Defining the Algorithm

  • One possible algorithm is:
    1. Get the list of names
    2. Get the name to check
    3. Set a counter to zero
    4. For each name on the list
      1. Compare the name being checked to the name on the list
      2. If the names are the same then add one to the counter
    5. When done, display the value of the counter
  • Once we have an algorithm, we need to test it for correctness

1.3.6: Summary

  • Programming is about solving problems using a computer program
  • Programs are best developed in two phases
    1. Problem-solving phase
    2. Implementation phase
  • In this section we looked at the first phase: problem solving
    • We will look at the second phase in the next section
  • First step to take when solving a problem is to analyze the problem
  • Second step is to develop an algorithm that solves the problem
  • Only after verifying that the algorithm works do you translate it to C++

Check Yourself

  1. What is the first step to take when creating a program?
  2. What are the two main phases of the program design process?
  3. What is the importance of the problem-solving phase?
  4. What is an algorithm?

Exercise 1.3

  1. Label this exercise: Exercise 1.3
  2. Submit all exercises for today's lesson in one file unless instructed otherwise
  3. Complete the following and record the answers to any questions in exercise1.txt.

Specifications

  1. Analyze and define an algorithm for the following problem:
  2. What is the paycheck amount (before taxes) for an employee who is paid hourly? You may assume that the employee does not get paid extra for overtime.

Check your answer

1.4: Introduction to C++

Objectives

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

1.4.1: About C++

  • Once you develop an algorithm, you need to translate it into instructions for the computer
  • To start the translation, we convert our algorithm into a programming language
  • 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

1.4.2: Creating a C++ Program

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

  1. Writing and saving the source code
    • Programs written in a high-level language like C++ are called source code
    • Source code is written in a programming language
    • A programming language has rules and syntax like a natural language
  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 prewritten code modules called libraries
      • In addition, you may produce many object modules for more complex programs
      • 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 steps is to start the program running at the location into which it was loaded
      • Many programs run at the same times in most computer systems

Let's discuss each step in more detail.

1.4.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
    • 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

1.4.4: Example C++ Source Code

  • 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

1.4.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
    • exit 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

1.4.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 hierarchial 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 exercise1.txt
  • You can change to any directory on your computer using the cd command
    • You type cd followed by the path
  • 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 you have to use /cygdrive/c/ to select the C: drive

  • 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

1.4.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 desktop

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

  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.

Further Information

1.4.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. How does a program end?
  4. How does C++ translate 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 1.4

Instructions

  1. Prepare the exercise header as described in the HowTo on submitting exercises
  2. Label this exercise: Exercise 1.4
  3. Complete the following steps and answer the questions.
  4. Note: If you run out of time, you can complete this exercise in the CTC or at home.

Specifications

  1. Start TextPad (or any other editor) and enter this code:
  2. #include <iostream>
    using namespace std;
    
    int main() {
        cout << "Hello, World!\n";
        return 0;
    } // end of main function
    
  3. Save this code to a convenient directory location like the Desktop
  4. Compile the source code using the command line.
  5. Run the program using the command line.
  6. Record your answers to the following question in your exercise1.txt file:
  7. 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?

Note: do not forget to turn in your exercises following the instructions for How To Submit In-Class Exercises.

Wrap Up

Due Next:
A1: Information Please! (9/8/05)
Exercise 1 and CodeLab 1 (9/8/05)

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

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