Professional Documents
Culture Documents
1. General
• C++ is an Object oriented extension of C which was derived from B (BCPL)
• Developed by Bjarne Stroustrup (AT&T Bell Labs) in early 1980’s
#include <iostream>
int main()
// Main function. Gets the stock price and units, calculates
// and prints the total cost
{
int units;
double price;
double cost;
return 0;
}
Sample Dialogue
>Enter # of units and unit price:
10 5
Intro to C++ 1
> The total cost is $ 52.5
Main Points
Main function
• defined as : int main()
• every C++ program has a main function
• It is called when the program starts (by the operating system)
• it returns an int value to the op. system
- 0 : success
- else : some error
Statements
• perform an action
• end with a ‘;’
Variable declarations
• reserve memory space
• format: <type> <list of variables>;
• i.e. int units;
- declares a variable (location) “units” of type integer
• variable names can have
- letters, digits and “_”
- are case sensitive
• every variable must be given a type
• some built-in types:
Type Represents Size
int integer 16 or 32 bits
float real number 32 bits
double real number 64 bits
char character 8 bits
bool boolean 1 bit (two values: true, false)
• variables can be initialized
- int x = 0, y = 5;
- int x(0), y(5);
Input
• cin is the standard input device (keyboard)
• cin >> units
- reads a value from cin and stores it in units
• can do: cin >> x >> y
Output
• cout << “ Enter...\n”
- displays the string “Enter...” on the standard output “cout”
• “cout” is usually set to be the monitor
• endl or “\n” is the end-of-line character
• cout << cost displays the value of cost
Intro to C++ 2
• can output multiple items::
- cout << “....” << “....” ;
Expressions
• return a value
• use variables, constants and operators
• arithmetic operators:
- + - * / % (remainder)
• C++ uses infix notation (operator is between operands)
• i.e. units * price * 1.05
Assignment Operator ( =)
• <variable> = <expression>
• assigns the value of expression to variable
Return statement
• return <expression>;
• terminates the function
• returns the value of the expression
Preprocessor Commands
• Usually written at the beginning
• Perform tasks before the program is compiled.
• # include <filename>
- includes a file
Comments
• from // to end of line, or
• from /* to */
Namespaces
• C++ allow the user to define environments (called namespaces)
• std is the standard environment (default for most compilers)
• for some compilers you need to tell the compiler which namespace to use
Functions
A program is usually broken down into small tasks. Each task is implemented by a function.
#include <iostream>
Intro to C++ 3
double totalCost( int units, double unit_price )
{
double cost;
cost = units * unit_price * 1.05;
return cost
}
int main()
// Main function. Gets the stock price and units, calculates
// and prints the total cost
{
int units;
double price;
return 0;
}
Points
Intro to C++ 4
3. Control Structures
3.1 if –statement
• Format:
if ( <condition> )
<statements>
[ else
<statements>
]
• <statements> is either
- one statement, or
- a block of statements
{
statement1
...
statement n
}
• eg.
int grade;
...
if ( grade >= 50 )
cout << “passed”;
else
cout << “failed";
• Conditions contain:
• expressions and
• relational operators:
Symbol Usage
== equal x == y
!= not equal x != y
> x>y
>= x >= y
< x<y
<= x <= y
Intro to C++ 5
• Simple conditions can be joined to larger conditions using logical operators:
&& logical and x>5 && y < 20
|| logical or x>5 || y < 20
! logical not !( x > 5)
• while ( <condition> )
{
<statements>
}
• evaluate condition
if it is true execute statements (the body of the loop)
repeat until condition is false
Intro to C++ 6
3.3 Do-while Loop
• do
{
<statements>
} while ( <condition> );
• Same as while except that the body is executed before the condition is checked
• e.g.
int n;
cour << “Enter a positive integer
do
{
cin >> n;
} while ( n <= 0 );
Intro to C++ 7
3.5 More C++ operators
+= x += 5 x=x+5
-= x -= 5 x=x -5
*= x *= 5 x=x*5
/= x /= 5 x=x/5
%= x %= 5 x=x%5
Operator Precedence
Operators Associativity
() function call left to right
++ -- right to left
! left to right
* / % “
+ - “
<< >> “
< <= > >= “
== != “
&& “
|| “
?: (conditional op.) right to left
= += -= *= /= %= right to left
, left to right
Intro to C++ 8
3.6 Switch statement
• Consists of a series of case labels and optional default case
• Example :
case 'B' :
case 'C' :
cout << "Second class" ;
break; // exits switch
case 'D' :
cout << "Pass" ;
break; // exits switch
case 'F' :
cout << "Fail" ;
break; // exits switch
default :
cout << "Wrong grade" ;
break; // optional
}
}
Intro to C++ 9
3.7 A Complete Example: Tax culculations
#include <iostream>
using namespace std;
double getIncome()
// Reads and returns a positive amount. If the input is negative,
// it asks for another input.
{
double income;
do
{
cin >> income;
if ( income < 0 )
cout << "Amount should be positive. Enter another:";
} while ( income < 0 );
return income;
}
int getDependents()
// Reads and returns a positive integer number. If the input is
// negative, it asks for another input.
{
int dependents;
do
{
cin >> dependents;
if ( dependents < 0 )
cout << "Quantity should be positive. Enter another:";
} while ( dependents < 0 );
return dependents;
}
Intro to C++ 10
return BASIC_EXEMPT;
else if (dependents <= 2)
return 1.2 * BASIC_EXEMPT;
else
return 1.5 * BASIC_EXEMPT;
}
if (taxable <= 0)
return 0;
if (taxable <= LOW_INCOME )
rate = BASIC_TAX_RATE;
else
rate = 1.5 * BASIC_TAX_RATE;
int get_action()
// Prints menu and gets user's choice
{
int choice;
return choice;
}
Intro to C++ 11
cout << " MnM's Super Tax Calculator" << endl << endl;
while ( action != 0 )
{
switch (action)
{
case 1: // calculates the tax amount
income = getIncome();
dependents = getDependents();
cout << "The amount of taxes is: "
<< tax(income, dependents)
<< endl;
break;
default:
cout << "Wrong command. Please try again. "
<< endl;
}
action = get_action();
}
cout << " Thank you for using MnM's Tax Calculator " << endl;
return 0;
}
Intro to C++ 12
Sample Output
Intro to C++ 13
4. Functions
• Function Definition:
<return type> <fn name>( <parameter list>)
{
<body>
}
parameter names may be omitted in
• Function declaration ( or prototype) a function declaration
• similar but without the body
• i.e.
double power( double base, int exp )
• Scope of a name:
- portion of program where the name is known
• scope of a variable:
- block in which it is declared
• scope of function parameters and local variables:
- the function body
• First attempt:
void swap( int a, int b)
{
int tmp = a;
a = b;
b = tmp;
}
values are a
5 10
x 5 copied from
y 10 caller to call 10 5 b
5 tmp
Intro to C++ 14
• To do that we need to use reference parameters (not value parameters)
• During a call a reference parameter is an alias of the actual argument (passed to function):
no values
x 5 10 a are copied tmp
y 10 5 b 5
Intro to C++ 15
6. Arrays
An array is a group of consecutive memory locations, all having the same name and same type.
I.e . the following declares an array throw of 5 integers (representing 5 die throws):
int throw[5]; /5 dice throws
i.e.
throw
throw[0]
throw[1]
throw[4]
Note:
• <size> in an array declaration must be a constant.
• An array subscript always starts at 0.
Array initialization:
• int a[5] = { 20, 30, 10, 5, 40};
Intro to C++ 16
• double c[] = {5, 10, 20};
c has 3 elements of type double
throw[0] = 5;
throw[2] = throw[1];
....
// can print all the elements
cout << " The outcomes are: ";
Intro to C++ 17
Passing an array to a function
• function parameter for array does not show size
• size is passed using another parameter
• i.e. to pass a to function f, f's prototype could be
void f( int array_par[], int size)
Intro to C++ 18
Example 6.1 A program that collects responses how much a student spends for lunch at the SUB, and
prints out the min, max and the average of the responses.
#include <iostream>
float
max(float array[], int size)
// returns the max value in an array of integers
{
int result= array[0];
float
min(float array[], int size)
// returns the min value in an array of integers
{
// Write the code for this function as an exercise
}
float
average(float array[], int size)
// returns the mean from an array of integers
{
int sum= 0;
float
get_response()
Intro to C++ 19
// gets a response for the survey
{
float response;
cout << "Enter the amount you spend for lunch at SUB or a negative to quit: ";
cin >> response;
return response;
}
int
main()
{
float poll[MAX_NO_OF_RESPONSES];
int count = 0;
return 0;
}
Intro to C++ 20
Example 6.2 : An array of points
Point hex[6];
3
4
5
The following functions calculates the length of the i-th side and the perimeter of a hexagon:
double
length( Point hexar [], int i)
// side 1 is from hexar[0] to hexar[1], ... , side 6 is from hexar[5] to hexar[0]
{
if ( i<1 || i>6 )
{
cout << "Error: Not a valid side ";
return 0;
}
double
perimeter( Point hexar [])
{
double perim = 0;
for(int i=1; i<=6; i++)
perim = perim+ length(hexar, i);
return perim;
}
Intro to C++ 21