C++ Programming Notes
Software
Software is programs written to perform specific tasks.
Two types of programs:
System programs
Application programs
System Programs
System programs control the computer.
The operating system is the first program to load when a computer is turned on.
Operating System (OS)
OS monitors overall computer activity and provides services.
Example services:
Memory management
Input/output activities
Storage management
Application Programs
Written using programming languages.
Perform specific tasks.
Run by the OS.
Example programs:
Word processors
Spreadsheets
Games
Language of a Computer
Machine language: the most basic language of a computer.
A sequence of 0s and 1s.
Every computer directly understands its own machine language.
A bit is a binary digit, 0 or 1.
A byte is a sequence of eight bits.
Evolution of Programming Languages
Early computers programmed in machine language.
Assembly languages were developed to make the programmer’s job easier.
In assembly language, an instruction is an easy-to-remember form called a mnemonic.
Assembler: translates assembly language instructions into machine language.
Instructions in Assembly and Machine Language
Examples of instructions in assembly language and machine language:
Assembly Language: LOAD, STOR, MULT, ADD, SUB
Machine Language: 100100, 100010, 100110, 100101, 100011
Evolution of Programming Languages
High-level languages make programming easier.
Closer to spoken languages.
Examples:
Basic
FORTRAN
COBOL
C/C++
Java
What is Computer Programming?
It is the process of planning a sequence of steps (called instructions) for a computer to follow.
Programming Life Cycle Phases
Problem-Solving
Implementation
Maintenance
Problem-Solving Phase
ANALYZE the problem and SPECIFY what the solution must do.
Develop a GENERAL SOLUTION (ALGORITHM) to solve the problem.
VERIFY that your solution really solves the problem.
Sample Problem
A programmer needs an algorithm to determine an employee’s weekly wages.
How would the calculations be done by hand?
One Employee’s Wages
In one week, an employee works 52 hours at the hourly pay rate of $24.75.
Assume a 40.0-hour normal work week and an overtime pay rate factor of 1.5.
What are the employee’s wages?
40 \times $24.75 = $990.00
12 \times 1.5 \times $24.75 = $445.50
Total: $1435.50
Weekly Wages, in General
If hours are more than 40.0, then wages = (40.0 * payRate) + (hours - 40.0) * 1.5 * payRate
Otherwise, wages = hours * payRate
Recall example: (40 \times $24.75) + (12 \times 1.5 \times $24.75) = $1435.50
An Algorithm is…
A step-by-step procedure for solving a problem in a finite amount of time.
Algorithm to Determine an Employee’s Weekly Wages
Get the employee’s hourly payRate.
Get the hours worked this week.
Calculate this week’s regular wages.
Calculate this week’s overtime wages (if any).
Add the regular wages to overtime wages (if any) to determine total wages for the week.
What is a Programming Language?
It is a language with strict grammar rules, symbols, and special words used to construct a computer program.
Implementation Phase: Program
Translating your algorithm into a programming language is called CODING.
With C++, you use:
Documentation -- your written comments
Compiler -- translates your program into machine language
Main Program -- may call sub-algorithms
Implementation Phase: Test
TESTING your program means running (executing) your program on the computer to see if it produces correct results.
If it does not, then you must find out what is wrong with your program or algorithm and fix it -- this is called debugging.
Maintenance Phase
USE and MODIFY the program to meet changing requirements or correct errors that show up in using it.
Maintenance begins when your program is put into use and accounts for the majority of effort on most programs.
Programming Life Cycle
Problem-Solving Phase
Analysis and Specification
General Solution (Algorithm)
Verify
Implementation Phase
Concrete Solution (Program)
Test
Maintenance Phase
Use
Maintain
A Tempting Shortcut?
The slide depicts a diagram where thinking is the primary component, that leads to code, after revision the process ends in a test to check if it is debugged and reaches the goal. This process can be tempting for some.
Three C++ Program Stages
SOURCE: written in C++
OBJECT: written in machine language (via compiler)
EXECUTABLE: written in machine language (via linker), includes other code from libraries, etc.
Example files:
myprog.cpp(SOURCE)myprog.obj(OBJECT)myprog.exe(EXECUTABLE)
A simple C++ program
The code is written with
#include <iostream.n>, the color is blue and the background color in the text editor is now white, ready for text.When you are ready to compile, click here, then Build again.
The C++ reserved keywords are blue.
Your First Program
#include <iostream>
using namespace std ;
int main( )
{
// This is a comment
cout << “Hello Computer Engineering Students. “;
cout << “This is your Intro to CPE Course.”;
return 0;
}
Output of program on the screen
Hello Computer Engineering Students.
This is your Intro to CPE Course.
Shortest C++ Program
int main ( )
{
return 0;
}
intis the type of returned value andmainis the name of function.
What is in a heading?
int main() {}
intis the type of returned valuemainis the name of the functions says no parameters
Block (Compound Statement)
A block is a sequence of zero or more statements enclosed by a pair of curly braces { }.
Syntax:
{
Statement (optional)
...
}
Every C++ function has 2 parts
int main()
{
// heading
// body block
return 0;
}
What is an Identifier?
An identifier is the name used for a data object (a variable or a constant) or for a function in a C++ program.
C++ is a case-sensitive language.
Using meaningful identifiers is good programming practice.
Identifiers
An identifier must start with a letter or underscore, and be followed by zero or more letters (A-Z, a-z), digits (0-9), or underscores.
VALID: ageofdog, taxRateY2K, PrintHeading, ageOfHorse
NOT VALID (Why?): age#, 2000TaxRate, Age-Of-Cat, First Name
C++ Simple Data Types
simple types
integral
char
short
int
long
bool
enum
unsigned
floating
float
double
long double
Standard Data Types in C++
Integral Types:
Represent whole numbers and their negatives
Declared as
int,short, orlong
Floating Types:
Represent real numbers with a decimal point
Declared as
float, ordouble
Character Types:
Represent single characters
Declared as
char
Samples of C++ Data Values
int sample values: 4578, -4578, 0
float sample values: 95.274, 95., .265
char sample values: ‘B’, ‘d’, ‘4’, ‘?’, ‘*’
What is a Variable?
A variable is a location in memory which we can refer to by an identifier, and in which a data value that can be changed is stored.
Example:
int x = 27;An area of memory sufficient to accommodate an integer value is set aside.
This area of memory is referenced in the program by the identifier x.
At the machine level, this memory area has an address (say 5678).
The area of memory is initialized with the binary pattern representing decimal 27.
Declaring a variable means specifying both its name and its data type.
What Does a Variable Declaration Do?
A declaration tells the compiler to allocate enough memory to hold a value of this data type, and to associate the identifier with this location.
Examples:
int ageOfDog;float taxRateY2K;(4 bytes)char middleInitial;(1 byte)
C++ Data Type String
A string is a sequence of characters enclosed in double quotes.
string sample values: "Hello", "Year 2000", "1234"
The empty string (null string) contains no characters and is written as "".
Giving a Value to a Variable
You can assign (give) a value to a variable by using the assignment operator
=VARIABLE DECLARATIONS:
string firstName;char middleInitial;char letter;int ageOfChild;
VALID ASSIGNMENT STATEMENTS:
firstName = “Fido”;middleInitial = ‘X’;letter = middleInitial;ageOfChild = 12;
What is an Expression in C++?
An expression is a valid arrangement of variables, constants, and operators.
In C++, each expression can be evaluated to compute a value of a given type.
The value of the expression 9 + 5 is 14.
Assignment Operator Syntax
Variable = Expression;First, the Expression on the right is evaluated, then the resulting value is stored in the memory location of the Variable on the left.
NOTE: An automatic type coercion occurs after evaluation but before the value is stored if the types differ for Expression and Variable
Insertion Operator (<<)
Variable
coutis predefined to denote an output stream that goes to the standard output device (display screen).The insertion operator
<<called “put to” takes 2 operands.The left operand is a stream expression, such as
cout. The right operand is an expression of a simple type or a string constant.
String Concatenation (+)
Concatenation is a binary operation that uses the
+operator.At least one of the operands must be a string variable or named constant -- the other operand can be string type or char type.
Concatenation Example
const string WHEN = “Tomorrow” ;
const char EXCLAMATION = ‘!’ ;
string message1 ;
string message2 ;
message1 = “Yesterday “ ;
message2 = “and “ ;
message1 = message1 + message2 + WHEN + EXCLAMATION ;
//message1 contains the string: “Yesterday and Tomorrow!”
Output Statements
SYNTAX:
cout << Expression << Expression . . . ;These examples yield the same output:
cout << “The answer is “ ;cout << 3 * 4 ;cout << “The answer is “ << 3 * 4 ;
Function Concept in Math
f(x) = 5x - 3
When x = 1, f(x) = 2 is the returned value.
When x = 4, f(x) = 17 is the returned value.
Returned value is determined by the function definition and by the values of any parameters.
Name of function, Parameter of function, Function definition
Program With Three Functions
#include <iostream>
int Square( int ); // declares these two value-returning functions
int Cube( int );
using namespace std ;
int main( )
{
cout << “The square of 27 is “ << Square(27) << endl; // function call
cout << “The cube of 27 is “ << Cube(27) << endl; // function call
return 0;
}
Rest of Program
int Square( int n )
{
return n * n;
}
int Cube( int n )
{
return n * n * n;
}
Function Call Syntax
FunctionName ( Argument List )
The argument list is a way for functions to communicate with each other by passing information.
The argument list can contain 0, 1, or more arguments, separated by commas, depending on the function.
A void function call stands alone
#include <iostream>
void DisplayMessage ( int n ) ; // declares function
int main( )
{
DisplayMessage( 15 ) ; //function call
cout << “Good Bye“ << endl ;
return 0 ;
}
A void function does NOT return a value
void DisplayMessage ( int n )
{
cout << “I have liked math for “ << n << “ years” << endl ;
}
Two Kinds of Functions
Value-Returning: Always returns a single value to its caller and is called from within an expression.
Void: Never returns a value to its caller and is called as a separate statement.
C++ Program
// ******************************************************
// PrintName program
// This program prints a name in two different formats
// ******************************************************
#include <iostream> // for cout and endl
#include <string> // for data type string
using namespace std;
const string FIRST = “Ahmad”; // Person’s first name
const string LAST = “Hasan”; // Person’s last name
const char MIDDLE = ‘M’; // Person’s middle initial
int main()
{
string firstLast; // Name in first-last format
string lastFirst; // Name in last-first format
firstLast = FIRST + “ “ + LAST ;
cout << “Name in first-last format is “ << endl << firstLast << endl;
lastFirst = LAST + “ , “ + FIRST + ’ ’ ;
cout << “Name in last-first-initial format is “ << endl << lastFirst << MIDDLE << ’.’ << endl;
return 0;
}
Output of Program
Name in first-last format is
Ahmad Hasan
Name in last-first-initial format is
Hasan, Ahmad M.
Statement Types? Basic Control Structures
A sequence is a series of statements that execute one after another.
Selection (branch) is used to execute different statements depending on certain conditions.
Looping (repetition) is used to repeat statements while certain conditions are met.
A subprogram is used to break the program into smaller units.
SEQUENCE
Statement
Statement
Statement
SELECTION (branch)
IF Condition THEN Statement1 ELSE Statement2
LOOP (repetition)
WHILE Condition DO Statement1
SUBPROGRAM (function)
A meaningful collection of SEQUENCE, SELECTION, LOOP, SUBPROGRAMs.
Week’s Wages, in General
If hours are more than 40.0, then wages = (40.0 * payRate) + (hours - 40.0) * 1.5 * payRate
Otherwise, wages = hours * payRate
RECALL EXAMPLE: (40 \times $24.75) + (12 \times 1.5 \times $24.75) = $1435.50
Algorithm for Company Payroll Program
Initialize total company payroll to 0.0
Repeat this process for each employee:
Get the employee’s ID empNum
Get the employee’s hourly payRate
Get the hours worked this week
Calculate this week’s wages
Add wages to total company payroll
Write empNum, payRate, hours, wages to file
Write total company payroll on screen
Payroll program
// ***************************************************
// Payroll program
// This program computes each employee’s wages and
// the total company payroll
// ***************************************************
#include <iostream> // for keyboard/screen I/O
#include <fstream> // for file I/O
using namespace std;
void CalcPay ( float, float, float& ) ;
const float MAX_HOURS = 40.0; // Maximum normal hours
const float OVERTIME = 1.5; // Overtime pay factor
int main()
{
float payRate; // Employee’s pay rate
float hours; // Hours worked
float wages; // Wages earned
float total; // Total company payroll
int empNum; // Employee ID number
ofstream payFile; // Company payroll file
payFile.open( “payfile.dat” ); // Open file
total = 0.0; // Initialize total
cout << “Enter employee number: “; // Prompt
cin >> empNum; // Read ID number
while ( empNum != 0 ) // While not done
{
cout << “Enter pay rate: “;
cin >> payRate ; // Read pay rate
cout << “Enter hours worked: “;
cin >> hours ; // and hours worked
CalcPay(payRate, hours, wages); // Compute wages
total = total + wages; // Add to total
payFile << empNum << payRate << hours << wages << endl;
cout << “Enter employee number: “;
cin >> empNum; // Read ID number
}
cout << “Total payroll is “ << total << endl;
return 0; // Successful completion
}
// ***************************************************
void CalcPay (
/* in */ float payRate ,
/* in */ float hours ,
/* out */ float& wages
)
// CalcPay computes wages from the employee’s pay rate
// and the hours worked, taking overtime into account
{
if ( hours > MAX_HOURS )
wages = (MAX_HOURS * payRate ) + (hours - MAX_HOURS) * payRate * OVERTIME;
else
wages = hours * payRate;
}
Parameter List
Is the means used for a function to share information with the block containing the call to the function.
Example Prototype:
void GetRoots ( float, float, float, float&, float& );
Classified by Location
Arguments: Always appear in a function call within the calling block.
Parameters: Always appear in the function heading, or function prototype.
Value Parameter vs. Reference Parameter
Value Parameter: The value (25) of the argument is passed to the function when it is called.
Reference Parameter: The memory address (4000) of the argument is passed to the function when it is called.
In the case of a value parameter, the argument can be a variable identifier, constant, or expression. In the case of a reference parameter, the argument must be a variable identifier.
Pass By Value Example
By default, parameters (of simple types like int, char, float, double) are always value parameters unless you do something to change that.
Pass By Reference Example
To get a reference parameter you need to place ‘&’ after the type in the function heading and prototype.
When to Use Reference Parameters
Reference parameters should be used when you want your function to give a value to, or change the value of, a variable from the calling block without an assignment statement in the calling block.
Using a Reference Parameter
Is like giving someone the key to your home.
The key can be used by the other person to change the contents of your home!
"pass-by-value" and the function will not be able to change the contents of age. It is still 25 when you return.
BUT, if you pass 4000, the address of age to a function, it is called “pass- by-reference” and the function will be able to change the contents of age. It could be 23 or 90 when you return.
Pass-by-reference is also called…
pass-by-address, or
pass-by-location
Example of Pass-by-Reference
We want to find 2 real roots for a quadratic equation with coefficients a,b,c. Write a prototype for a void function named GetRoots( ) with 5 parameters. The first 3 parameters are type float. The last 2 are reference parameters of type float.
Prototype
void GetRoots ( float, float, float, float&, float& );
Function Definition and Prototype
void GetRoots(float a, float b, float c, float& root1, float& root2);
// prototype
void GetRoots(float a, float b, float c, float& root1, float& root2)
{
float temp; // local variable
temp = b * b - 4.0 * a * c;
root1 = (-b + sqrt(temp) ) / ( 2.0 * a );
root2 = (-b - sqrt(temp) ) / ( 2.0 * a );
return;
}
In the code, the function is receiving 3 incoming values a, b, c from the calling block. It calculates 2 outgoing values root1 and root2 for the calling block. They are the 2 real roots of the quadratic equation with coefficients a, b, c.
Example calling code
#include <iostream>
#include <fstream>
#include <cmath>
void GetRoots(float, float, float, float&, float&);
using namespace std;
void main ( )
{
ifstream myInfile;
ofstream myOutfile;
float a, b, c, first=0.0, second=0.0;
int count = 0;
...... // open files
while ( count < 5 )
{
myInfile >> a >> b >> c;
GetRoots(a, b, c, first, second); //call
myOutfile << a << b << c << first << second << endl;
count++ ;
}
// close files
......
}