C++ for Engineers and Scientists - Problem Solving Using C++

Problem Solving Using C++

Objectives

Introduction to C++

Programming Style

Data Types

Arithmetic Operations

Variables and Declaration Statements

Applying the Software Development Procedure

Applications

Common Programming Errors

 

Introduction to C++

Modular Program: a program consisting of interrelated segments arranged in a logical and understandable form

Easier to develop, correct, and modify than other kinds of programs

Module: a small segment which is designed to perform a specific task

A group of modules is used to construct a modular program

 

 

Modules in C++ can be classes or functions

Function: accepts an input and produces an output by processing the input in some fashion

A functions processing is encapsulated and hidden within the function

Class: contains both data and functions used to manipulate the data

Function: encapsulates a set of operations, while a class encapsulates data plus one or more sets of operations

Identifier:  a name given to an element of the language, such as a class or function

Rules for forming identifier names:

First character must be a letter or underscore

Only letters, digits, or underscores may follow the initial letter (no blanks allowed)

Keywords cannot be used as identifiers

Max length of an identifier = 1024 characters

Use underscores to separate multiple words in a name, or capitalize the first letter of each word

 

 

Function names

Require a set of parentheses at the end

Can use mixed upper and lower case

Should be meaningful, or be a mnemonic

Mnemonic: a word designed as a memory aid

     Examples of function names:

     easy()   c3po()     r2d2()     theForce()

Note that C++ is a case-sensitive language!

                                         

Introduction to C++: The main() Function

Overall structure of a C++ program contains one function named main(), called the driver function

All other functions are invoked from main()

 

Function header line: the first line of a function, which contains

The type of data returned by the function (if any)

The name of the function

The type of data that must be passed into the function when it is invoked (if any)

Arguments: the data passed into a function

Function body: the statements inside a function (enclosed in braces)

 

 

Each statement inside the function must be terminated with a semicolon

return: a keyword causing the appropriate value to be returned from the function

return 0 in the main() function causes the program to end

Figure 2.4  The structure of a main() function.

 

Introduction to C++: The cout Object

cout object: an output object that sends data to a standard output display device

Preprocessor command: starts with a #; causes an action before the source code is compiled into machine code

#include : causes the named file to be inserted into the source code

C++ provides a standard library with many pre-written classes that can be included

Header files: files included at the head (top) of a C++ program

 

Escape sequence: one or more characters preceded by a backslash, \

 

Programming Style

Programming Style: Comments

Comments: explanatory remarks in the source code added by the programmer

Line comment: begins with // and continues to the end of the line

Line comment can be on a line by itself, or at the end of a line of code

Line comment cannot be longer than one line

 

 

Block Comment: a comment that spans across two or more lines

Block comment begins with /* and ends with */

            Example:

   /* This is a block comment that

        spans

        across three lines */

 

 

Data Types

Data Types: Integer

int data type: whole numbers, optionally with + or sign

     Example:  2

char data type: individual character; any letter, digit, or special character enclosed in single quotes

     Example: A

Character values are usually stored in ASCII code

 

 

Escape character: the backslash, \; indicates an escape sequence

Escape sequence: tells compiler to treat the following characters as special instruction codes

Escape sequences

bool data type: represents Boolean (logical) data; restricted to two values: true or false

sizeof operator: shows the number of bytes used to store values of any data type

Values returned by sizeof are compiler dependent

Signed data type: one that permits negative, positive, and zero values

Unsigned data type: permits only positive and zero values

An unsigned data type provides essentially double the range of its signed counterpart

 

Data Types: Floating-Point Types

Floating-point number (real number): zero or any positive or negative number containing a decimal point

     Examples:   +10.625         5.   -6.2

No special characters are allowed

Three floating-point data types in C++:

float (single precision)

double (double precision)

long double

 

 

Data Types: Exponential Notation

Floating point numbers can be written in exponential notation, where e stands for exponent

Arithmetic Operations


Arithmetic Operations:
Expression Types


Arithmetic Operations:
Integer Division


Arithmetic Operations:
Negation


Arithmetic Operations
Summary of Operators


Arithmetic Operations:
Operator Precedence & Associativity

Rules for writing arithmetic expressions:

Never place  two consecutive binary arithmetic operators side by side

Use parentheses to form groupings; contents within parentheses are evaluated first

You may nest parentheses within other parentheses; evaluated from innermost to outermost

Use the * operator for multiplication, not parentheses

Expressions with multiple operators are evaluated by precedence of operators:

All negations occur first

Multiplication, division, and modulus are next, from left to right

Addition and subtraction are last, from left to right


Variables and Declaration Statements

Assignment statement: used to store a value into a variable

Value of the expression on the right side of the = is assigned to the memory location of the variable on the left side of the =

     Examples:

            num1 = 45;

     num2 = 12;

     total = num1 + num2;

 

Declaration statement: specifies the data type and identifier of a variable; sets up the memory location

     Syntax:       ;

Data type is any valid C++ data type

     Example:    int sum;

Declarations may be used anywhere in a function; usually grouped at the opening brace

 

Character variables: declared using the char keyword

Multiple variables of the same data type can be declared in a single declaration statement

     Example:

   double grade1, grade2, total, average;

Variables can be initialized in a declaration

     Example:    double grade1 = 87.0

A variable must be declared before it is used

 

Declaring a variable causes memory to be allocated based on the data type

 

Definition statement: a declaration that causes the computer to allocate storage for the variable

Three items associated with each variable:

Data type

Actual value stored in the variable (its contents)

Memory address of the variable

Address operator (&) provides the variables address

 

Applying the Software
Development Procedure

Step 1: Analyze the problem

Understand the desired outputs

Determine the required inputs

Step 2: Develop a solution

Determine the algorithms to be used

Use top-down approach to design

Step 3: Code the solution

Step 4: Test and correct the program

 

Applications: Radar Speed Trap

Step 1: Analyze the Problem 

Output: speed of the car

Inputs: emitted frequency and received frequency 

Step 2: Develop a Solution

Algorithm:   

Assign values to f0 and f1

Calculate and display speed

Step 3: Code the Solution

Step 4: Test and Correct the Program



Applications:
Telephone Switching Networks

Number of lines required for a directly connected network: 

 

Step 1: Analyze the Problem

Outputs: number of direct lines for 100 phones, and additional number of lines to add 10 more phones

Inputs: number of telephones (n)

Step 2: Develop a Solution

Calculate total number of lines for 100 subscribers

Calculate total number of lines for 110 subscribers

Subtract to get additional lines needed

Display number of lines for 100 subscribers

Display number of additional lines needed

Step 3: Code the Solution

Step 4: Test and Correct the Program

 

Common Programming Errors

Missing parentheses after main

Missing or incorrect braces around function body

Misspelling a reserved word

Missing ending double quotes on string literal

Missing semicolon at end of statement

Adding a semicolon at end of #include statement

Missing \n to indicate new line

Substituting letter O for zero and vice versa

Failing to declare all variables

Storing incorrect data type into a variable

Attempting to use a variable with no value

Dividing integer values incorrectly

Mixing data types in the same expression


Summary

C++ program contains one or more functions, one of which must be called main()

All C++ statements must be terminated by a semicolon

Data types include int, float, bool, char

cout object can be used to display data

cout object requires the preprocessor command #include

Variables must be declared with their data type

A variable can be used only after it has been declared

Variables may be initialized when declared

Definition statement causes computer to allocate memory for a variable

sizeof() operator yields the amount of storage reserved for a variable


C++ for Engineers and Scientists - Introduction

Introduction

Objectives
Introduction to Programming
Problem Solution and Software Development
Algorithms
Common Programming Errors
Computer Hardware and Storage Concepts

Introduction to Programming
Program: self-contained set of instructions used to operate a computer to produce a specific result
Also called software
Programming: the process of writing a program, or software


Introduction to Programming: Machine Language
Machine language programs, also called executables, consist of binary instructions
Each instruction has two parts:
Instruction part: the operation to be performed; also called an opcode
Address part: memory address of the data to be used
Each class of computer has its own particular machine language
Writing in machine language is tedious!

Introduction to Programming: Assembly Languages
Assembly Language: programming language with symbolic names for opcodes, and decimals or labels for memory addresses
            Example:
            ADD  1, 2
            MUL  2, 3
Assembly language programs must be translated into machine instructions, using an assembler

Introduction to Programming: Low- and High-Level Languages
Low-level languages: languages that use instructions tied directly to one type of computer
            Examples: machine language, assembly language
High-level languages: instructions resemble written languages, such as English,and can be run on a variety of computer types
            Examples: Visual Basic, C, C++, Java

Source code: the programs written in a high- or low-level language
Source code must be translated to machine instructions in one of two ways:
Interpreter: each statement is translated individually and executed immediately after translation
Compiler: all statements are translated and stored as an executable program, or object program; execution occurs later

Large C++ programs may be stored in two or more separate program files due to
Use of previously written code
Use of code provided by the compiler
Modular design of the program (for reusability of components)
Linker: combines all of the compiled code required for the program

Introduction to Programming: Procedural and Object Orientations
Programs can also be classified by their orientation:
Procedural: available instructions are used to create self-contained units called procedures
Object-oriented: reusable objects, containing code and data, are manipulated
Object-oriented languages support reusing existing code more easily
                                                           
Introduction to Programming: Application and System Software
Application software: programs written to perform particular tasks for users
System software: collection of programs to operate the computer system
System software must be loaded first; called booting the system
Bootstrap loader: a permanent, automatically executed component to start the boot process

Operating system: the set of system programs used to operate and control a computer; also called OS
Tasks performed by the OS include
Memory management
Allocation of CPU time
Control of input and output
Management of secondary storage devices

Multi-user system: a system that allows more than one user to run programs on the computer simultaneously
Multitasking system: a system that allows each user to run multiple programs simultaneously; also called multiprogrammed system


Introduction to Programming: The Development of C++
The purpose of most application programs is to process data to produce specific results
Early procedural languages included
FORTRAN: Formula Translation
ALGOL: Algorithmic Language
COBOL: Common Business Oriented Language
BASIC: Beginners All-purpose Symbolic Instruction Code
Pascal
C
Early object-oriented language:
C++

Problem Solution and Software Development
Problem Solution and Software Development: Phase I. Development and Design
Program requirement:  request for a program or a statement of a problem
After a program requirement is received, Phase I begins
Phase I consists of four steps:
Analysis
Design
Coding
Testing
Step 1: Analyze the Problem
Analyst must understand
What outputs are required
What inputs will be needed
How the inputs can be used to produce the desired outputs
Failure to analyze and understand the requirements leads to a failed solution!

Figure 1.9  Second-level refinement structure diagram.
Step 3: Code the Solution
Also called writing the program, and implementing the solution
Program should contain well-defined patterns or structures of the following types:
Sequence
Selection
Iteration
Invocation
Step 4: Test and Correct the Program
Testing: method to verify correctness and that requirements are met
Bug: a program error
Debugging: the process of locating an error, and correcting and verifying the correction
Testing may reveal errors, but does not guarantee the absence of errors
Testing requires the use of meaningful, representative test data
Impossible to test all possible combinations of data and operations in a complex program
Testing plans must be developed to ensure good coverage in testing
Testing usually requires more time than other steps in Phase I
Relative effort for steps in Phase I

Problem Solution and Software Development: Phase II. Documentation
Many documents may be required, including
Program description
Algorithm development and changes
Well-commented program listing
Sample test runs
Users’ manual

Problem Solution and Software Development: Phase III. Maintenance
Maintenance includes
Ongoing correction of newly discovered bugs
Revisions to meet changing user needs
Addition of new features
Maintenance usually the longest phase, and may be the primary source of revenue
Good documentation vital for effective maintenance

Problem Solution and Software Development: Backup
Backup:  process of making copies of program code and documentation on a regular basis
Backup copies = insurance against loss or damage
Consider using off-site storage for additional protection

Algorithms
   Pseudocode: English-like phrases used to describe the algorithm
   Formula: description of a mathematical equation
   Flowchart: diagram showing the flow of instructions in an algorithm
        Flowcharts use special symbols

Algorithms: Flowcharts
Figure 1.12  Flowchart for calculating the average of three numbers.

Common Programming Errors
   Common errors include
  Starting to write the program before fully understanding the requirements and the algorithm to be used
  Failing to make backups periodically
  Failing to provide complete, precise instructions in the programming language

Summary
         Software: programs used to operate a computer
         Programming language types:
        Low-level languages
         Machine language (executable) programs
         Assembly languages
        High-level languages
         Compiler and interpreter languages
         Software engineering: discipline concerned with creating readable, efficient, reliable, and maintainable programs
         Three phases in software development:
        Program development and design
        Documentation
         Maintenance
Four steps in program development and design:
        Analyze the problem
        Develop a solution
        Code the solution
        Test and correct the solution
         Algorithm: step-by-step procedure that describes how a task is performed
         Computer program: self-contained unit of instructions and data used to operate a computer to produce a desired result

Four fundamental control structures used in coding:
Sequence
Selection
Iteration
Invocation

Appendix: Computer Hardware and Storage Concepts
Computer hardware: components that support the capabilities of the computer
Appendix: Computer Hardware and Storage Concepts (continued)
Appendix: Computer Hardware and Storage Concepts (continued)
Appendix: Computer Hardware and Storage Concepts (continued)
Computer storage:
Bit: smallest unit of data; value of 0 or 1
Byte: grouping of 8 bits representing a single character
Character codes: collection of patterns of 0s and 1s representing characters; examples include
ASCII
EBCDIC

Number codes: patterns used to store numbers
Two’s Complement number code: represents a decimal number as a binary number of 0s and 1s

Word: grouping of one or more bytes
Number of bytes in a word determines the maximum and minimum values that can be stored: