You are on page 1of 21

Introduction to C++

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

2. A Simple C++ Program

A C++ program consists of:


• a set of data & function definit ions, and
• the main function (or driver)

Example 2.1: Stock value program


• Input:
o # of units, user is going to buy
o unit price
• Output:
o total cost of transaction

#include <iostream>

using namespace std;

int main()
// Main function. Gets the stock price and units, calculates
// and prints the total cost
{
int units;
double price;
double cost;

cout << “Enter # of units and unit price: \n”;


cin >> units;
cin >> price;

cost = units * price * 1.05;

cout << “The total cost is $ “;


cout << cost;
cout << endl;

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.

Example 2.2 : A better implementation of example 2.1

#include <iostream>

using namespace std;

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;

cout << “Enter # of units and unit price: \n”;


cin >> units >> price;

cout << “The total cost is $ “


<< totalCost( units, price)
<< endl;

return 0;
}

Points

(1) Function Definition header or


• <return type> <function name>( <parameter list> ) prototype
{
<statements>
} function body
• i.e. function totalCost
• a function must have name (C++ has no anonymous functions ) and return type

(2) Local Variables


• parameters and variables declared inside the function are only known in the function
• var “units” inside totalCost is different than “units” inside main
- are two different memory locations

(3) Return statement


• terminates function
• returns a value to caller

(4) Function Call


• to call a fn, write the fn name with the list of arguments in ()
• i.e. totalCost( 10, 100);
• a call creates a new environment with the function’s parameters and local var’s and executes
the function

Intro to C++ 4
3. Control Structures

Most structured languages have at least 3 types of control structures


• simple selection
if ... else
• multiple selection
switch
• repetition
while
do ... while
for

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)

• Example 3.1: A function returning the max of 3 numbers

double max3( double a, double b. double c )


{
if ( a > b && a > c)
return a;
else
if ( b > c)
return b;
else
return c;
}

3.2 While Loop

• while ( <condition> )
{
<statements>
}

• evaluate condition
if it is true execute statements (the body of the loop)
repeat until condition is false

• Example 3.2 : A power function

double power( double base, int exponent)


// Raises base to the exponent power; exponent is a positive integer
{
double result = 1;

while ( exponent > 0 )


{
result = result * base;
exponent = exponent –1;
}
return result;
}

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 );

3.4 For loop

• used for counter-controlled iteration

• for ( <initialization>; <condition>; <update> )


{
<statements>
}

• Example 3.4: Power function using for-statement

// Raises base to the exponent power; exponent is a positive integer

double power( double base, int exponent)


{
double result = 1;
counter, known inside for loop only
for ( int i =1; i <= exponent; i++ )
{ increment operator
result = result * base;
}
return result; test; if true repeat the loop; if it
} is false, exit the loop

Intro to C++ 7
3.5 More C++ operators

Suppose i is an int and x is any numeric variable

Operator Usage Meaning


++ i++ increases i by 1 returns old value of i
++i increases i by 1 returns new value
-- i-- decreases i by 1 returns old value of i decreases i by
--i 1 returns new value

+= 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 :

void print_rank( char grade )


// Get a letter grade and print the ranking:
// 1st class, 2nd class, pass or fail
{
switch ( grade )
{
case ‘A’ :
cout << "First class" ;
break; // exits switch

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
}
}

break & continue


• Used inside loops (break is also used inside a switch )
• break causes immediate exit from the loop
• continue skips the rest of the body of the loop and starts a new step

Intro to C++ 9
3.7 A Complete Example: Tax culculations
#include <iostream>
using namespace std;

const float BASIC_EXEMPT = 6800;


const float LOW_INCOME = 30000;
const float BASIC_TAX_RATE = float(0.3);

double getIncome()
// Reads and returns a positive amount. If the input is negative,
// it asks for another input.
{
double income;

cout << "Enter your 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;

cout << "Enter the number of your dependents: ";

do
{
cin >> dependents;

if ( dependents < 0 )
cout << "Quantity should be positive. Enter another:";
} while ( dependents < 0 );

return dependents;
}

double exempt( int dependents )


// Returns the amount that is exempted from taxation
{
if ( dependents == 0 )

Intro to C++ 10
return BASIC_EXEMPT;
else if (dependents <= 2)
return 1.2 * BASIC_EXEMPT;
else
return 1.5 * BASIC_EXEMPT;
}

double tax( double income, int dependents)


// Calculates and returns the tax amount for a given
// income and dependents
{
double taxable = income - exempt( dependents);
float rate;

if (taxable <= 0)
return 0;
if (taxable <= LOW_INCOME )
rate = BASIC_TAX_RATE;
else
rate = 1.5 * BASIC_TAX_RATE;

return taxable * rate;


}

int get_action()
// Prints menu and gets user's choice
{
int choice;

cout << endl << endl


<< "You may choose one of the following actions:"
<< endl;
cout << "\t 0 Quit" << endl;
cout << "\t 1 Calculate Taxes" << endl;
cout << "\t 2 Calculate Exemption" << endl << endl;
cout << "Please enter your choice: " ;

cin >> choice;

return choice;
}

int main(int argc, char* argv[])


// The program performs two tasks:
// 1. calculates the tax amount given the income and
// the number of dependents.
// 2. calculates the tax exemption given the number of
// dependents
{
double income;
int dependents;

Intro to C++ 11
cout << " MnM's Super Tax Calculator" << endl << endl;

int action = get_action();

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;

case 2: // calculates the tax exemption


dependents = getDependents();
cout << "The tax exemption amount is: "
<< exempt(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

MnM's Super Tax Calculator

You may choose one of the following actions:


0 Quit
1 Calculate Taxes
2 Calculate Exemption

Please enter your choice: 1


Enter your income: 60000
Enter the number of your dependents: 2
The amount of taxes is: 23328

You may choose one of the following actions:


0 Quit
1 Calculate Taxes
2 Calculate Exemption

Please enter your choice: 2


Enter the number of your dependents: 2
The tax exemption amount is: 8160

You may choose one of the following actions:


0 Quit
1 Calculate Taxes
2 Calculate Exemption

Please enter your choice: 3


Wrong command. Please try again.

You may choose one of the following actions:


0 Quit
1 Calculate Taxes
2 Calculate Exemption

Please enter your choice: 0


Thank you for using MnM's Tax Calculator
Press any key to continue

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 )

• a function with no parameters that returns no value


- void print_headers()

• 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

4.1 Reference Parameters

• We want a function swap that swaps two integers


i.e.
int x = 5, y = 10;
swap(x, y)
should x be 10 and y be 5.

• First attempt:
void swap( int a, int b)
{
int tmp = a;
a = b;
b = tmp;
}

• It does not work.


• The call " swap(x, y)" creates a new environment, different than caller's environment

caller's environment call's environment

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)

void swap( int & a, int & b)


{
int tmp = a;
a = b;
b = tmp;
}

• During a call a reference parameter is an alias of the actual argument (passed to function):

caller's environment call's environment

no values
x 5 10 a are copied tmp
y 10 5 b 5

• We use reference parameters when:


• the function has to modify its arguments (i.e. swap )
• the function returns a value through its argument
i.e.
void get_date( int& year, int& month, int& day)
• we want to avoid copying the arguments, but we dont want the function to change them
- use references to constant objects
- i.e.
void foo( const double & a)
{
a = 5; X not allowed
....
}

Intro to C++ 15
6. Arrays

An array is a group of consecutive memory locations, all having the same name and same type.

An array declaration looks like:


<element type> <array name>[ <size> ];

I.e . the following declares an array throw of 5 integers (representing 5 die throws):
int throw[5]; /5 dice throws

This allocates the following space for throw


throw

To access an element of an array, we specify its position using subscripts.


For instance the elements of throw are:
throw[0] throw[1] ... throw[4]

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};

• int b[5] = {5};


first element is 5 rest are 0

Intro to C++ 16
• double c[] = {5, 10, 20};
c has 3 elements of type double

Array usage example:

int throw[10] = {0};

throw[0] = 5;

cin >> throw[1];

throw[2] = throw[1];

....
// can print all the elements
cout << " The outcomes are: ";

for (int i =0; i<10; i++)


{
cout << throw[i] << ", " ;
}
cout << endl;

Accessing a position outside an array produces an error.


i.e.
throw[15] = 5; // error
throw[10] = 3; // error

Cannot assign one array to another.


• i.e.
int a[20], b[20];

// read values for a and b


for (int i =0; i<20; i++)
{
cout << "Enter next value for a and b:" ;
cin >> a[i] >> b[i] ;
}
...
a = b; // Error, you cannot do that

• Need to assign element by element:


for (int i =0; i<20; i++)
{
a[i] = b[i] ;
}

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)

• then a call to f that passes a could be:


f(a, 20);

• arrays are passed by reference


• so , if f sets
array_par[2] = 50;
then a[2] is 50.

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>

using namespace std;

const int MAX_NO_OF_RESPONSES = 100;

float
max(float array[], int size)
// returns the max value in an array of integers
{
int result= array[0];

for (int i=0; i<size; i++)


{
if ( array[i] > result )
result = array[i];
}
return result;
}

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;

for (int i=0; i<size; i++)


{
sum += array[i];
}
if ( size > 0 )
return sum/size;
else
return 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;

float response = get_response();

while ( response >= 0 )


{
poll[count] = response;
count++;
response = get_response();
}

cout << "\n Results of the SUB survey: \n"


<< "\t Max: " << max(poll, count) << endl
<< "\t Min: " << min(poll, count) << endl
<< "\t Average: " << average(poll, count) << endl;

return 0;
}

Intro to C++ 20
Example 6.2 : An array of points

We can use an arrayof 6 points to represent a hexagon:

Point hex[6];

Hex looks like:


0
1
2

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;
}

// left point of side i is in i-1 but position of right point depends on i


lnt right = i==6? 0 : i;
int xd = hexar[i-1].getX() - hexar[right].getX();
int yd = hexar[i-1].getY() - hexar[right].getY();

return sqrt(xd*xd – yd*yd);


}

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

You might also like