Micro-Scholarship, What it is, How can it help me.pdf
Programming in C++
1. MECH-215 TA
C++ Programming
Session #2
Jan 23 2013
Course Lecturer: Ted Obuchowicz
Tutor: Pooya Merat
Concordia University
Disclaimer: The contents provided in this file are intended only as a reference for TA class and might be incomplete or
incorrect. Any reliance upon detailed information presented in this file shall be at reader’s risk.
P. Merat Jan 23 2013
3. Data Types
Integer Numbers:
Syntax
Type
Range
char var1;
short var2;
short int var3;
long var4;
long int var5;
int var6;
Integer
-128 to 127
Integer
-32768 to 32767
Integer
-2147483648
2147483647
to
Any of above could be “unsigned” >> Whole number (from 0 - XX)
Example:
unsigned char var1;
Real Numbers:
Syntax
Type
Range
float Var1;
double Var2;
Real
Real
1e-38 to 3e38
2e-308 to 2e308
P. Merat Jan 23 2013
4. Identifiers
Identifiers are any programmer defined names such as:
Variable Names and Function Names
Rules
1. Cannot contain a white space:
int Variable One; // Wrong!
2.
Cannot start with a number (1…9) or contain any special
characters:
int 5_var; // Wrong!
int va$r; // Wrong!
3. Cannot be the exact C++ directives:
int while; // Wrong!
P. Merat Jan 23 2013
5. Identifiers (Example)
Which of these identifiers (variable names) are correct?
1) double a;
2) float My var;
3) double var1;
4) int > a;
6) short ?Ask;
5) char dWgGD_c123Y_5;
6) double float;
7) int aa+a;
8) long K.1;
A variable name should be a combination of only letters, digits and
underscore.
Note: C++ is case sensitive.
int Variable;
is different from
int vAriable;
P. Merat Jan 23 2013
6. Variable Declaration
You can declare variables of the same type like:
int alpha, beta, theta;
or:
int alpha,
beta,
theta;
or like this:
int alpha;
int beta;
int theta;
P. Merat Jan 23 2013
7. Basic User-Interface - cout
cout function:
// Print on the screen.
cout << "Life is short!";
is the same as:
// Print on the screen.
cout << "Life " << "is " << "short!";
or you can write:
// Print on the screen.
cout << "Life ";
cout << "is ";
cout << "short!";
P. Merat Jan 23 2013
8. Basic User-Interface - cout (Example)
cout function:
Print the value of a variable:
int myID = 1320006;
cout << "Your ID is: " << myID << endl;
// Output: Your ID is: 1320006
Next line:
cout << "n" ; // Go to the next line
cout << endl ; // Go to the next line
P. Merat Jan 23 2013
9. Basic User-Interface - cin
cin function:
int Integer_1;
cout << "Please enter an integer number: ";
// Get a number from the user
cin >> Integer_1;
// Confirm the number
cout << "You just entered number: " << Integer_1 << endl;
P. Merat Jan 23 2013
10. Practice
Find the errors in this code:
#include {iostream}
Using Namespace std;
int main[]
{
// Declare the first variable
int first var =
5;
// Declare the second variable
Int 2nd_Var;
// Print the sum of the two integers on the screen.
cout << "Sum is: first var + 2nd_VAR" << "n";
/* Note that "n" is the same as: endl */
Return0 ;
}
P. Merat Jan 23 2013
11. Practice (Answer)
Corrected code:
#include {iostream} // Must be : <iostream>
Using Namespace std; // Must be : using namespace std
int main[] // Must be : ()
{
//Declare 1st var
int first var =
5; // Could be
// Declare the second variable
Int 2nd_Var; // Could be : int Var2
// Print the
cout << "Sum
// Corrected
cout << "Sum
/* Note that
No change will occur with
this extra space here, but
It will not look good!
: first_var
= 15;
sum of the two integers on the screen.
is: first var + 2nd_VAR" << "n";
one is:
is: " << first_var + Var2 << "n";
"n" is the same as: endl*/
Return0 ; // Should be : return 0;
}
P. Merat Jan 23 2013
12. Common Types of Errors
1)
Syntax Errors
Compiler gives you an error and the output file is not created.
int 2nd_Var; // Bad variable name
integer Var2; // Wrong directive
int Var2 // Missing semicolon
2)
Semantic Errors
Compiler does not care (compiles with no errors), but you still do not
get your desired result.
// Print the sum of the two integers on the screen.
cout << "Sum is equal to : var1 + var2" << "n";
// but here it only prints var1 + var2 and not its value.
Could also be using the wrong variable type, the wrong operation,
etc.
P. Merat Jan 23 2013
13. Practice #1: Age Calculation
Write a program to ask the user’s year of birth and current year and
print out the user’s age and the expected death year (100 years after
birth).
P. Merat Jan 23 2013
14. Practice #2: Cannon Range
Write a code to get the angle (degrees) and velocity (m/s2) of cannon
and find its range (m). [ g = 9.81 ]
V
α
R
Here is the formula:
R = V2 sin(2α) / g
P. Merat Jan 23 2013
15. MECH-215 TA
C++ Programming
Session #3
Jan 30 2013
Course Lecturer: Ted Obuchowicz
Tutor: Pooya Merat
Concordia University
Disclaimer: The contents provided in this file are intended only as a reference for TA class and might be incomplete or
incorrect. Any reliance upon detailed information presented in this file shall be at reader’s risk.
P. Merat Jan 30 2013
16. MECH-215 TA
Topics:
Priority of Math Operators
Variable Type Change
Relational and Boolean
Operators
if-else
switch-case
for loop
while loop
Examples
P. Merat Jan 30 2013
17. Priority of Math Operators
Priority
High
Med
Low
Operator
Multiplication *
Division /
Residue %
Addition +
Subtraction -
Example
1 + 4 / 2 = 3
3 * 5 % 2 + 1 = 2
1 + 2 * 3 = 7
Parentheses change the priority.
Example
int a = 1,
b = 2,
c = 3;
int res1 = a + b * c;
// a + 6
//
7
int res2 = (a + b) * c;
//
3 * c
//
9
P. Merat Jan 30 2013
18. Variable Type Change (Math Operation)
Assume the following:
int a1 = 1, a2 = 2, a3 = 3;
float b1 = 0.1, b2 = 0.2, b3 = 0.3;
In a math operation of the same type of variables:
(a1 + a2) * a3 // this would be of type int
b1 * b2 / b3 // this would be of type float
In a math operation of the different types of variables:
(a1 + b1) * a3 // this would be of type float
b3 * a2 / b2 // this would be of type float
The result would have the type of the most precise variable or the
variable with the widest range.
P. Merat Jan 30 2013
19. Variable Type Change (Assignment)
Assignment of same type (left and right side):
int a1 = 1, a2 = 2, a3 = 3;
float b1 = 0.1, b2 = 0.2, b3 = 0.3;
int a_res;
float b_res;
a_res = (a1 + a2) * a3; // a_res = 9
b_res = b1 * a2 / b3; // b_res = 0.66...
Assignment of different type (left and right side):
a_res = (a1 + b2) * a3; // righ side loses its decimal
b_res = a1 * a2 * a3; // b_res = 6
Note 1: Literals have “Data Type” too.
Note 2: It is possible to change the type of a variable temporarily
by casting:
b_res = (float) a1 / a2; // cast a1 to float before division
P. Merat Jan 30 2013
21. Relational Operators
Usually used in if or while
Sign
>
>=
<
<=
==
!=
Description
Greater than
Greater than or equal
Less than
Less than or equal
Equal
Not equal
Example
if (a > b)
while (a <= b)
if (a == b)
while (a != b)
The result of any relational operation (such as a == b) would be
true (1) or false (0)
Boolean
Note: Do not confuse == (equality) with = (variable assignment).
P. Merat Jan 30 2013
22. Boolean Operators
Again they are usually used in if or while
||
&&
!
OR
AND
Not
if (a1 > b1 || a2 > b2)
if (a1 > b1 && a2 > b2)
if !(a > b)
P. Merat Jan 30 2013
23. if-else
if could be accompanied by an else but it’s not necessary.
Do not forget the braces if necessary (when there is more than one
command).
Example:
float a;
cin >> a;
if (a >
cout
else
{
a *=
cout
}
1)
<< "it's greater than 1.";
2; // a = a * 2;
<< a;
P. Merat Jan 30 2013
24. More on Equality (==)
Equal real numbers?
tolerance (eg. ± 0.1)
There are no two equal real values in reality, there is always a
tolerance for the accuracy of equality of two real numbers.
float a;
cin >> a;
if (a == 1.5) // Bad code !
cout << "1.5";
if (a < 1.6 && a > 1.4) // Good code !
cout << "Close enough to 1.5";
if (fabs(a – 1.5) < 0.1) // Good code !
cout << "Close enough to 1.5";
P. Merat Jan 30 2013
25. switch-case
int a;
cin >> a;
switch(a)
{
case 1:
cout << "one";
break;
case 2:
cout << "two";
break;
case 3:
cout << "three";
break;
}
Do not forget break and colon (:) after each case.
Note: any switch-case could also be implemented using if-else.
P. Merat Jan 30 2013
26. switch-case Replaced by if-else
int a;
cin >> a;
if(a == 1)
cout << "one";
else if(a == 2)
cout << "two";
else if(a == 3)
cout << "three";
This code seems neater when written using switch-case
especially when there are multiple cases.
P. Merat Jan 30 2013
27. for loop
We use it when a similar task should be performed more than once
(usually for a known number of iterations).
The common syntax of for loop is:
for (int c = 0; c < n; c++)
{
// The loop-counter(c) should be of
// type integer (long, short, etc).
// This loop runs for n iterations.
// In the first iteration c is 0.
// In the last iteration c is n-1.
}
P. Merat Jan 30 2013
29. while loop
Like the for loop we use it when a similar task should be performed
more than once (usually for an unknown number of iterations).
1)
while (a > 0)
{
// do this
}
do
{
2)
// this
}
while (a > 0);
Example:
int a;
do
{
cout << "Enter a positive integer: ";
cin >> a;
}
while (a > 0);
cout << "Game over! n";
P. Merat Jan 30 2013
30. Example
1. Write a code to ask the user two numbers (one real and one
whole). Then prints the result of the first number to the power of
the second number.
2. Modify the program so that it keeps doing part1, until the user
enters 0 for both numbers.
P. Merat Jan 30 2013
31. MECH-215 TA
C++ Programming
Session #4
Feb 06 2013
Course Lecturer: Ted Obuchowicz
Tutor: Pooya Merat
Concordia University
Disclaimer: The contents provided in this file are intended only as a reference for TA class and might be incomplete or
incorrect. Any reliance upon detailed information presented in this file shall be at reader’s risk.
P. Merat Feb 06 2013
33. More on for loop
int i;
for (i = 5; i < 7; i++)
{
cout << i;
}
cout << "Loop Finished" << i;
Step 1: i = 5; then go to Step 2
Step 2: if i < 7 is true go to Step 3, otherwise exit the loop
Step 3: cout << i; then go to Step 4
Step 4: i++; then go back to Step 2
So at the end, value of i would be 7.
P. Merat Feb 06 2013
34. More on for loop (Example)
What would be printed on the screen in the following codes?
1
2
3
int i;
for (i = 5; i < 4; i++)
{
cout << i;
}
cout << "Loop Finished" << i;
for (int i = 5; i <= 8; i++)
{
cout << i;
}
cout << "Loop Finished" << i;
int i;
for (i = 8; i > 5; i--)
{
cout << i;
}
cout << "Loop Finished" << i;
P. Merat Feb 06 2013
35. More on for loop (Example)
What would be printed on the screen in the following codes?
4
5
int i;
for (i = 5; i > 4; i++)
{
cout << i;
}
cout << "Loop Finished" << i;
int i;
for (i = 2; i < 7; i = i+2)
{
cout << i;
}
cout << "Loop Finished" << i;
P. Merat Feb 06 2013
36. for loop vs. while loop
In general there’s more flexibility with while loop, but they could be
used interchangeably.
1
2
3
for (int i = 5; i < 8; i++)
{
cout << i;
}
int i = 5;
while (i < 8)
{
cout << i++;
}
int i = 5;
do
{
cout << i++;
}
while (i < 8);
P. Merat Feb 06 2013
37. In-Class Exercise
Write a code which gets two integer numbers from the user, and
prints all the integers from the first integer to the second integer.
Sample behavior (All the red characters are the user input, the rest
is program output):
S = 5
E = 7
S to E : 5, 6, 7,
OR
Write the Code with:
1. for loop
2. while loop
3. do-while loop
S = 9
E = 6
S to E : 9, 8, 7, 6,
P. Merat Feb 06 2013
38. Home Exercise
Implement a program to perform the length unit conversion.
[m(meter), f(foot), k(kilometer), M(miles)]
Sample behavior (All the red characters are the user input, the rest
is program output):
Length : 50 m f
~= 166.667 f
[ 1.0 foot = 0.3 m
,
1.0 mile = 1.6 km ]
P. Merat Feb 06 2013
39. Home Exercise (Hint)
Let’s name things:
Length : 51 m f
In this example:
The first unit (m) : The Origin Unit
The second unit (f) : The Destination Unit
Hint:
One way is to break the problem into two completely separate
problems:
1.
First Convert the Origin Unit to a Standard Unit
(Regardless of the Destination Unit)
2.
Then Convert the Standard Unit to the Destination Unit.
P. Merat Feb 06 2013
40. MECH-215 TA
C++ Programming
Session #5
Feb 27 2013
Course Lecturer: Ted Obuchowicz
Tutor: Pooya Merat
Concordia University
Disclaimer: The contents provided in this file are intended only as a reference for TA class and might be incomplete or
incorrect. Any reliance upon detailed information presented in this file shall be at reader’s risk.
P. Merat Feb 27 2013
42. Library Functions
#include <iostream>
using namespace std;
#include <cmath>
int main()
{
cout << sin(0.2);
cout << sqrt(3);
return 0 ;
}
Note: An output is returned after the sin and sqrt is been called.
P. Merat Feb 27 2013
43. Function Prototype
It’s the function identity information:
1) Name
2) Number and type(s) of input argument(s)
3) Type of output (if any)
P. Merat Feb 27 2013
44. Function Prototype (Example)
A function name is an identifier and should obey the naming rules
(should consists of only letters and numbers and underscore).
int my_iadd (int, int)
int my_imax2 (int, int)
double my_dadd (double, double) int my_imax3 (int, int, int)
float my_fadd (float, float)
float my_fmax2 (float, float)
double my_power (float,
unsigned int)
void my_print (string)
void my_hello ()
void my_hello (void)
double my_dmin7 (double,
double,
double,
double,
double,
double,
double)
What is the prototype of sin function ?
P. Merat Feb 27 2013
45. Function Output
in C++ any function can only have one or no output.
No output:
void my_print (string)
void my_HelloWorld ()
{
void my_HelloWorld ()
cout << "Hello World!"
<< endl;
Using void is necessary.
No need for return at the end.
}
One output:
int my_iadd (int a, int b)
int my_iadd (int, int)
{
return a + b ;
Must have return at the end.
}
P. Merat Feb 27 2013
46. Function Input(s)
Any function can have any number of inputs.
No input:
void my_hello ()
void my_hello (void)
int blah ()
int blah (void)
One or more inputs:
int my_imax3 (int, int, int)
void my_print_power (float, unsigned int)
P. Merat Feb 27 2013
47. Local Variables
main Function
int main ()
{
my_iadd Function
int my_iadd (int a, int b)
{
int X, Y; cin >> X >> Y;
cout << X << Y;
cout << my_iadd(X, Y);
cout << a << b;
return a + b ;
}
return 0;
}
Whenever a function is called, all its local variables are declared
locally and just after the function execution, all those local variables
are removed from memory and de-allocated (except the static
variables).
P. Merat Feb 27 2013
48. Reference (&)
main Function
int main ()
{
int X, Y; cin >> X >> Y;
int res;
my_iadd Function
void my_iadd2 (int a,
int b,
int & c)
{
c = a + b ;
my_iadd2 (X, Y, res);
cout << res;
}
return 0;
}
P. Merat Feb 27 2013
49. Example
What’s the output of this program?
#include <iostream>
using namespace std;
void f1 (double a, int b, double Res)
{
Res = 1;
for (int i = 0; i < b; i++)
Res *= a;
}
int main()
{
double res;
f1 (5, 2, res);
cout << res;
return 0 ;
}
Why the result is not as expected?
P. Merat Feb 27 2013
50. Practice
Write a function to get two variables from the user and send them
back to the main function.
Solution:
#include <iostream>
using namespace std;
void GetTwoNum (int & first, int & second)
{
cout << "enter first num: "; cin >> first;
cout << "enter second num: "; cin >> second;
}
int main()
{
int a, b;
GetTwoNum (a, b); // function call
cout << "first one is: " << a
<< " and second is: " << b << endl;
return 0 ;
}
P. Merat Feb 27 2013
51. Quiz Answer
#include <iostream>
using namespace std;
int main()
{
for (int X = 0; X <= 100; X++)
for (int Y = 0; Y <= 100; Y++)
if (Y*100 + X - 5 == 2*(X*100 + Y))
cout << "X = " << X << " and Y = " << Y << endl;
return 0 ;
}
P. Merat Feb 27 2013
52. Respect the Indentations Rule Please!
There are many Indentation standards.
Allman standard:
#include <iostream>
using namespace std;
Readable Code
int main()
{
for (int X = 0; X <= 100; X++)
{
for (int Y = 0; Y <= 100; Y++)
{
if (Y*100 + X - 5 == 2*(X*100 + Y))
{
cout << "X = " << X << " and Y = " << Y << endl;
}
}
}
return 0 ;
}
P. Merat Feb 27 2013
53. Terrible Indentations
#include <iostream>
using namespace std;
int main() {
for (int X = 0; X <= 100; X++) {
for (int Y = 0; Y <= 100; Y++) {
if (Y*100 + X - 5 == 2*(X*100 + Y))
cout << "X = " << X << " and Y = " << Y << endl;
}
}
return 0 ;
}
Indentations:
Make your code more readable, even for yourself.
And result in better comprehension and less errors.
P. Merat Feb 27 2013
54. MECH-215 TA
C++ Programming
Session #6
March 06 2013
Course Lecturer: Ted Obuchowicz
Tutor: Pooya Merat
Concordia University
Disclaimer: The contents provided in this file are intended only as a reference for TA class and might be incomplete or
incorrect. Any reliance upon detailed information presented in this file shall be at reader’s risk.
P. Merat March 06 2013
56. Functions Interactions with outside
There are several ways for functions to access or pass a value
outside.
Ways that a function can access a foreign variable:
Through its input arguments
Global variables
…
Ways that a function can affect a variable outside:
Through its output (return)
Call by reference (&)
Global variables
...
P. Merat March 06 2013
57. Global Variables
#include <iostream>
using namespace std;
int cnt = 0;
void increase(void)
{
cout << "++" << endl;
cnt ++;
}
int main()
{
for (int i = 0; i < 5; i++)
increase();
cout << cnt << " Bye!" << endl;
return 0;
}
P. Merat March 06 2013
58. Static Variables
#include <iostream>
using namespace std;
int increase(void)
{
static int cnt = 0;
cout << "++" << endl;
cnt ++;
return cnt;
}
int main()
{
int C;
for (int i = 0; i < 5; i++)
C = increase();
cout << C;
return 0;
}
P. Merat March 06 2013
59. Functions and Structures
#include <iostream>
#include <string>
using namespace std;
struct student_type
{
string name;
int age;
int ID;
double GPA;
};
student_type get_student()
{
student_type st;
cout << " Enter name:
cout << " Enter age:
cout << "
Enter ID:
cout << " Enter GPA:
";
";
";
";
cin
cin
cin
cin
>>
>>
>>
>>
st.name;
st.age;
st.ID;
st.GPA;
return st;
}
void Get_student(student_type
{
cout << " Enter name: ";
cout << " Enter age: ";
cout << "
Enter ID: ";
cout << " Enter GPA: ";
}
& s) // Reference
cin
cin
cin
cin
>>
>>
>>
>>
s.name;
s.age;
s.ID;
s.GPA;
P. Merat March 06 2013
61. Practice
Write a Calculator program,
Step 1 : Which gets two operands and one operator ( + - )
Sample behavior:
User Input >> 2 + 5
Program output >> 7
To get the user input, use this code:
cin >> Operand_1 >> Operator >> Operand_2 ;
Step 2 : Write a separate function for each of the operations.
Operation_X (Operand_1, Operand_2)
Step 3 : Extend the calculator to accept these operators: * / ^
and write the corresponding functions.
Step 4 : Program keeps getting the user inputs, until user enters 0 as
the operator.
P. Merat March 06 2013
62. Practice (Solution)
Solution to Step1 and Step2:
#include <iostream>
using namespace std;
double ADD(double a, double b)
{
double Ans = a + b;
return Ans;
}
void SUB (double & A, double a, double b)
{
A = a - b;
}
void MUL(double a, double b)
{
cout << a * b;
}
double DIV(double a, double b)
{
return a / b;
}
P. Merat March 06 2013
63. int main()
{
cout << "Welcome to My Calculator!" << endl;
double o1, o2, ans;
char sign;
cin >> o1 >> sign >> o2;
switch (sign)
{
case '+':
ans = ADD(o1,o2);
cout << ans;
break;
case '-':
SUB(ans, o1, o2);
cout << ans;
break;
case '*':
MUL(o1, o2);
break;
case '/':
ans = DIV(o1, o2);
cout << ans;
break;
}
return 0;
}
P. Merat March 06 2013
64. MECH-215 TA
C++ Programming
Session #7
March 13 2013
Course Lecturer: Ted Obuchowicz
Tutor: Pooya Merat
Concordia University
Disclaimer: The contents provided in this file are intended only as a reference for TA class and might be incomplete or
incorrect. Any reliance upon detailed information presented in this file shall be at reader’s risk.
P. Merat March 13 2013
66. Recursion Example 1
𝐹 (0) = 1
Base case
𝐹 ( 𝑛) = 𝑛 ∗ 𝐹 ( 𝑛 − 1)
Recursive formula
int f(int n) // Recursive
{
if (n == 0) // Base case
return 1;
return n * f(n - 1); // Recursive formula
}
int f(int n) // Explicit
{
int res;
for ( int i = 0 ; i <= n ; i++ )
res *= i;
return res;
}
P. Merat March 13 2013
67. Recursion Example 2
𝐹 (0) = 0
Base case
𝐹 ( 𝑛) = 𝑛 + 𝐹 ( 𝑛 − 1)
Recursive formula
int f(int n) // Recursive
{
// You write the “base case” here to stop the recursion
return n + f(n - 1);
}
int f(int n) // Explicit
{
int res = 0;
for ( int i = 0 ; i <= n ; i++ )
res += i;
return res;
}
int f(int n) // Explicit
{
return (n * (n - 1)) / 2;
}
P. Merat March 13 2013
68. Order of Recursion (1)
void f1(int num)
{
if (num == 0)
return;
cout << num;
f1(num - 1);
}
f1 (4)
cout << 4
f1 (3)
cout << 3
f1 (2)
cout << 2
f1 (1)
cout << 1
f1 (0)
Recursion ends here
P. Merat March 13 2013
69. Order of Recursion (2)
void f2(int num)
{
if (num == 0)
return;
f1(num - 1);
cout << num;
}
f2 (4)
f2 (3)
f2 (2)
f2 (1)
f2 (0)
Recursion ends here
cout << 1
cout << 2
cout << 3
cout << 4
P. Merat March 13 2013
70. Recursion Example 3
void print_star(int n)
{
if ( n == 1 )
cout << "*" << endl;
else
{
print_star(n-1);
for ( int i = 1 ; i <= n ; i++ )
cout << "*" ;
cout << endl;
}
}
The output of this function would look like: (1 or 2 ?)
1
*
**
***
****
*****
******
*******
********
2
********
*******
******
*****
****
***
**
*
P. Merat March 13 2013
71. Towers of Hanoi (1)
1
2
3
1
2
3
1
2
3
1
2
3
Top Disk
Base Disk
In this example:
Rod #1: Origin
Rod #2: Temporary
Rod #3: Destination
P. Merat March 13 2013
72. Towers of Hanoi (2)
1
2
3
1
2
3
1
2
3
1
2
3
Top Disks
Base Disk
void hanoi(int n, int org, int des, int temp)
{
// You write the “base case” here to stop the recursion
hanoi_tower(n-1, org, temp, des);
cout << org << " to " << des << endl; // Base move
hanoi_tower(n-1, temp, des, org);
}
P. Merat March 13 2013
73. Practice
1.
Write the Greatest Common Devisor function using the
following recursive formula:
𝒙
𝒈𝒄𝒅( 𝒙, 𝒚) = { 𝒈𝒄𝒅(𝒚 , 𝒓𝒆𝒎𝒂𝒊𝒏𝒅𝒆𝒓(𝒙, 𝒚))
𝒊𝒇 𝒚 = 𝟎
𝒊𝒇 𝒚 > 𝟎
2.
Write the Hanoi function using the following recursive formula:
(The optimal number of movements)
𝟏
𝒉𝒂𝒏𝒐𝒊( 𝒏) = {
𝟐 ∗ 𝒉𝒂𝒏𝒐𝒊( 𝒏 − 𝟏) + 𝟏
𝒊𝒇 𝒏 = 𝟏
𝒊𝒇 𝒏 > 𝟏
P. Merat March 13 2013
74. MECH-215 TA
C++ Programming
Session #8
March 27 2013
Course Lecturer: Ted Obuchowicz
Tutor: Pooya Merat
Concordia University
Disclaimer: The contents provided in this file are intended only as a reference for TA class and might be incomplete or
incorrect. Any reliance upon detailed information presented in this file shall be at reader’s risk.
P. Merat March 27 2013
76. Arrays
Usually a long series of similar data (of any type).
Usually accompanied with a for loop.
Array >> A series of data
for loop >> doing similar task on a series of data
C++ Definition:
int a[10]; // an array capable of storing 10 integer numbers
Array index
0
1
8
9
Value
4
3
2
8
150
154
182
186
Memory
Address
Note: Never try to access (or assign a value to) out of arrays
boundaries.(for the example above: a[20], a[10] or a[-6])
P. Merat March 27 2013
77. Array Example 1
Get 7 students’ GPAs and store them in an array. Then print out the
average, maximum and minimum GPAs.
float GPA[7];
for (int i = 0; i < 7; i++)
{
cout << "Enter GPA #" << i+1 << ": ";
cin >> GPA[i];
}
float sum = 0, max = GPA[0], min = GPA[0];
for (int i = 0; i < 7; i++)
{
sum += GPA[i];
if (GPA[i] > max)
max = GPA[i];
if (GPA[i] < min)
min = GPA[i];
}
cout << "Average is: " << sum/7.0 << endl
<< "max is: " << max
<< " and min is: " << min << endl;
P. Merat March 27 2013
78. Passing Arrays to Functions
Always the array address is sent to the function, like the call by
reference.
When calling the function only the name to the array should be
included.
When declaring the function (or in function prototype) array name
should come with brackets (empty or with proper size).
o If array is more than one dimension, size of higher
dimensions must be mentioned in the function input
declaration.
The length of the data in the array should be sent if it’s unknown
to the function.
Example:
float Array_fun (float a[], int arr_len) {} // declaring
Array_fun (A, size); // calling
P. Merat March 27 2013
79. Multi-Dimensional Arrays
Declaration:
int A[][] = {{1,2,3},{4,5,6}};
int A[][2][2] = { {{1,2},{3,4}} , {{5,6},{7,8}} };
Note: In multi-dimensional arrays only the first dimension could be
left empty, in definition or in function parameters.
Usually the proper number of nested loops should be used to do an
operation on the array.
Another way to initialize:
int A[2][2][2] = {1, 2, 3, 4, 5, 6, 7, 8};
P. Merat March 27 2013
81. Practice 1
Write a code to get two matrices (2 x 2) from the user and prints out
their addition and multiplication.
Next step: write two functions for aforementioned operations.
P. Merat March 27 2013
82. Practice 2
3-D Matrices
Write a program to print out an arbitrary 2x2x2 matrix.
First print out the orange data, then blue, red and green.
Dim 2
Dim 1
Dim 3
P. Merat March 27 2013
83. Practice 3
1) Write a code that calculates the end-effector position of a planar
(2D) robotic manipulator.
>> Use arrays to store the joint angles and link lengths.
Here is the formula for a three link (2-DOF) manipulator:
𝑥 = 𝐿1 cos(𝜃1 ) + 𝐿2 cos(𝜃1 + 𝜃2 )
+ 𝐿3 cos(𝜃1 + 𝜃2 + 𝜃3 ) + ⋯
𝑦 = 𝐿1 sin(𝜃1 ) + 𝐿2 sin(𝜃1 + 𝜃2 )
+ 𝐿3 sin(𝜃1 + 𝜃2 + 𝜃3 ) + ⋯
2) Use an structure array to store
data.
(x,y)
Link 2
Joint 1
y
Link 1
L1
θ1
x
P. Merat March 27 2013
L2
θ2
Joint 2
84. MECH-215 TA
C++ Programming
Session #9
April 03 2013
Course Lecturer: Ted Obuchowicz
Tutor: Pooya Merat
Concordia University
Disclaimer: The contents provided in this file are intended only as a reference for TA class and might be incomplete or
incorrect. Any reliance upon detailed information presented in this file shall be at reader’s risk.
P. Merat April 03 2013
86. Pointers Intro.
C(++) Operators:
&a
The address of variable a in memory
* b
The data in the address stored in a
int a = 10;
int * a_addr = & a; // declaration and initialization of
// the pointer to a
a
10
2555228
a_addr
2555228
14285484
P. Merat April 03 2013
87. Pointer Example
int a;
int * a_addr; // declare a pointer asterisk sign must be used.
a_addr = & a; // Equate a_addr with the address of a.
a = 20;
cout << a;
*a_addr = 30;
cout << a; // What will be the output?
P. Merat April 03 2013
88. Pointer Common Mistakes
int * a_addr;
a_addr = 20; // There’s no point in doing so, because you do
// not know what is in the memory address of 20.
& a_addr = 20; // Invalid command. You cannot change the
// address of an existing variable.
Note: Pointer type must agree with the type of variable it points to.
float a;
int * a_addr;
a_addr = &a;
P. Merat April 03 2013
89. Pointers and Functions
#include <iostream>
using namespace std;
void f (int * a1, int * a2)
{
// swap a1 and a2
int temp = * a1;
* a1 = * a2;
* a2 = temp;
}
int main()
{
int v1 = 3, v2 = 20;
f (& v1, & v2);
cout << v1 << endl << v2 << endl;
system("pause");
return 0;
}
P. Merat April 03 2013
90. Pointers and Functions Example
Find the errors in this code:
void f(int * a1, int & a2)
{
// swap a1 and a2
int temp = a1;
a1 = a2;
a2 = temp;
return 0;
}
int main()
{
int v1 = 3, v2 = 20, v3;
v3 = f(v1, v2);
cout << v1 << endl << v2 << endl;
system("pause");
return 0;
P. Merat April 03 2013
91. }
Pointers and Functions Example
Here is the corrected code:
void f(int * a1, int & a2)
{
// swap a1 and a2
int temp = *a1; <<<<<< int temp = a1;
*a1 = a2; <<<<<< a1 = a2;
a2 = temp;
}
int main()
{
int v1 = 3, v2 = 20, v3;
f(& v1, v2); <<<<<< v3 = f(v1, v2);
cout << v1 << endl << v2 << endl;
return 0;
}
P. Merat April 03 2013
92. Pointers and Arrays
Arrays in fact use pointers.
When you write:
int a[5] = {1,2,3,4,5};
1
2555228
2
3
a
2555228
14285484
a will contain the address of the first element of the array.
You can also write:
int * a = {1,2,3,4,5};
P. Merat April 03 2013
93. Pointers and Arrays (cont.)
int a[5] = {1,2,3,4,5};
cout << a[2]; // prints 3, the third element of the array.
cout << * (a + 2); // prints 3 again, since a is a pointer.
cout << * a; // prints 1.
cout << a[0]; // prints 1, again.
cout << a; // Address of the first element
cout << & a; // Address of a, refer to the last figure.
So when you declare an array:
First, your computer reserves enough memory for the data of
that array.
Second, a pointer to the first element of the array will be created
with the declared name and type.
P. Merat April 03 2013
94. Pointers, Arrays and Functions
void print_array_1(int a[], int len)
{
for (int i = 0; i < len; i ++)
cout << *(a + i) << 't'; // or cout << a[i]
cout << endl;
}
void print_array_2(int * a, int len)
{
for (int i = 0; i < len; i ++)
cout << a[i] << 't'; // or cout << *(a + i)
cout << endl;
}
int main()
{
int A[] = {1,2,3,4,5};
print_array_1(A, 5); // or print_array_2(A, 5);
return 0;
}
P. Merat April 03 2013
95. Pointers and Strings
Strings are arrays with two main characteristics:
1.
2.
String type is a char array and is intended to store text.
The last character should be the Null character: '0'
char s1[] = "Hi!";
char s1[3] = "Hi!";
char s3[4] = {'H','i','!','0'};
char * s2 = "Hi!";
string s4 = "Hi!"; // Requires #include <string>.
Note: double quote sign ( " ) must be used for strings, and single
quote sign ( ' ) for characters.
P. Merat April 03 2013
96. Pointers and Strings (cont.)
Because of the existence of the Null character at the end, when
passing string to functions, there is no need to send the length of the
string unlike when passing arrays to function.
Some library functions (do not forget to include <string>):
strlen(string) : returns the length of string without '0'.
char * s1 = "Good";
cout << strlen(s1); // Prints 4.
strcmp(string, string): compares two strings, returns 0 on equality.
char s1[] = "Hi !";
char s2[5] = {'H','i',' ','!','0'};
if (strcmp(s1, s2))
cout << "Different";
else
cout << "Same"; // strcmp(s1, s1) returns 0
P. Merat April 03 2013
97. Pointers and Strings (Example 1)
Let’s write our own strlen function:
int my_strlen_1(char s[])
{
int i = 0;
while(s[i++] != '0');
return i-1;
}
Another version (with an error, find it!):
int my_strlen_2(char s[])
{
for(int i = 0; *(s+i) != '0'; i++);
return i;
}
P. Merat April 03 2013
98. Pointers and Strings (Example 2)
Now let’s write our own function for comparing two strings:
bool my_strcmp(char *s1, char s2[])
{
bool equal = true;
int i = 0;
while(s1[i] != '0' && *(s2 + i) != '0')
if ( *(s1 + i) != s2[i++])
equal = false;
return equal; // Note that unlike strcmp this function
// returns true when strings are equal.
}
However:
char s1[] = "C+";
char s2[] = "C++";
cout << my_strcmp(s1, s2); // Prints 1 !
Why ?
P. Merat April 03 2013
99. Pointers to Structures
To access structure pointer field use:
struct_pointer -> field_name NOT *struct_pointer.field_name
struct Contact_t
{
string Name;
string Email;
};
void Get_Contact(Contact_t * c)
{
cout << "Enter Name: "; cin >> c -> Name;
cout << "Enter Email: "; cin >> c -> Email;
}
int main()
{
Contact_t Contact_List[50];
for (int i = 0; i < 50; i++)
Get_Contact(&Contact_List[i]);
return 0;
}
P. Merat April 03 2013
100. Dynamic Memory Allocation
For declaring dynamic variables during program execution.
1. First declare a regular pointer named dyn_pointer:
int * dyn_pointer; // pointer
2. Allocate an integer with an initial value of 5 to a memory
address and put that address in dyn_pointer.
The address will be reserved for this variable.
dyn_pointer = new int (5);
3. When you are done with the array, release its address in
memory:
delete dyn_pointer;
P. Merat April 03 2013
101. Dynamic Memory Allocation (cont.)
These are similar procedure for the dynamic allocation of an array:
int * dyn_pointer_arr; // Declare a pointer with proper type
dyn_pointer_arr = new int [50]; // reserve an array of length
// 50 and set dyn_pointer_arr to the
// address of the first element.
delete [] dyn_pointer_arr; // Release the array memory.
P. Merat April 03 2013
102. MECH-215 TA
C++ Programming
Session #10
April 10 2013
Course Lecturer: Ted Obuchowicz
Tutor: Pooya Merat
Concordia University
Disclaimer: The contents provided in this file are intended only as a reference for TA class and might be incomplete or
incorrect. Any reliance upon detailed information presented in this file shall be at reader’s risk.
P. Merat April 10 2013
104. Classes
Syntax: (They are very similar to structures)
class my_class
{
private:
// Usually variables
int var;
public: // Everything after this line will be public
// Usually functions >> methods
int method_1(void);
};
my_class would be like a data type after its declaration:
my_class a , b;
a and b are objects of this class.
Using dot (.) operator (only) public methods and data members of the
object would be accessible:
cout << a.method_1();
cout << a.var;//var is not accessible outside my_class methods
P. Merat April 10 2013
105. Classes (Example)
class my_class
{
private:
int var;
public:
int get_var(void) // Accessor method
{
return var;
}
void set_var(int x) // Mutator method
{
var = x;
}
};
int main()
{
my_class a;
a.set_var(10);
cout << a.get_var();
return 0;
Note that both functions
(methods) already have
access to var.
There is no need to pass
any class data to methods.
}
P. Merat April 10 2013
106. Declaring Methods outside the Class
class my_class
{
private:
int var;
public:
int get_var(void); // Method protype
void set_var(int); // Method protype
};
int my_class::get_var(void) // my_class Accessor method
{
return var;
}
void my_class::set_var(int x) // my_class Mutator method
{
var = x;
}
Note the :: operator between class name and method name.
P. Merat April 10 2013
107. Class Common Mistake
class my_class
{
private:
int var;
public:
int get_var(void); // Method protype
void set_var(int); // Method protype
};
...
my_class a;
...
When accessing a class entity the (::) operator must be used and
when accessing an object entity dot (.) must be used.
a.set_var
my_class::get_var
There is no something like:
my_class.set_var
a::get_var
P. Merat April 10 2013
108. Class Default Constructors
To initialize an object to some default values.
class my_class
{
private:
int var; // var cannot be initialized here.
public:
my_class() // Default Constructor
Constructor should
{
have the exact same
var = 10;
name as the class.
}
};
Now whenever an object of my_class is declared its var would be 10
by default.
my_class a, b, c;
Note: Constructor has to be public.
P. Merat April 10 2013
109. Overloading
Overloading: Multiple declaration of the same thing.
Function overloading:
int my_add(int a, int b) // First version
{
return a + b;
}
int my_add(int a, int b, int c) // Second version
{
return a + b + c;
}
double my_add(double a, double b, double c) // Third version
{
return a + b + c;
}
int main()
{
cout << my_add(1,2) << endl // First version will be called
<< my_add(1,2,3) << endl // Second version
<< my_add(0.1,0.2,0.3); // Third version
return 0;
}
P. Merat April 10 2013
110. Class Constructor Overloading
class my_class
{
private:
int var1, var2;
public:
my_class()
{
cout << "Default Constructor" << endl;
var1 = 10; var2 = 20; // Initialize to default.
}
my_class(int x)
{
cout << "First Overloaded Constructor" << endl;
var1 = x; var2 = 20; // Initialize only the first var.
}
my_class(int x, int y)
{
cout << "Second Overloaded Constructor" << endl;
var1 = x; var2 = y; // Initialize both vars.
}
// Other Methods ...
};
P. Merat April 10 2013
111. Declaration (in the main function for example):
my_class a1, // First constructor will be called automatically
a2(5), // Second constructor will be called
a3(5,10); // Third constructor
There is no need to call the constructors manually, and you must not
do that!
P. Merat April 10 2013
112. Forward Declaration
It is possible to declare functions or classes after they are used, but
their prototypes must be written before they are used.
void Hello();
class my_class;
int main()
{
Hello();
my_class a;
cout << a.method_1();
return 0;
}
void Hello()
{
cout << "Hello!";
}
class my_class
{
// my_class declaration
};
P. Merat April 10 2013
113. Scope
In C(++), blocks show different levels of program.
Every function, if, for ,while, structure or class has a block.
It is possible to declare most data-types (int, array, string, …)
inside any block, but the data lifetime is limited to that block and
after the block it does not exist (except static or ...).
Every block has access to its parent blocks data and not to its
sub-blocks data.
// Global scope (everything which is not in any block)
int c; // Global variable
int my_add(int a, int b) // Global function
{ return a + b; }
int main()
{ // main function scope
if (...)
{ // if scope
}
return 0;
}
P. Merat April 10 2013
114. Static Variables
In functions:
int increase(void)
{
static int cnt = 0; // It initializes only once
cout << "++" << endl;
cnt ++;
return cnt;
} // cnt never de-allocates (but
// only increase function can access it).
But in classes:
static keyword for data members of a class represents a shared
data between all the objects of that class.
P. Merat April 10 2013
115. Static Variables in Classes
class my_class
{
private:
int private_var;
public:
static int shared_var; // It should be public
};
int my_class::shared_var
// class
int main()
{
my_class a, b;
cout << a.shared_var;
b.shared_var ++;
cout << a.shared_var;
= 5; // Note: accessing the
member not an object member
// Will print 5
// Will print 6
return 0;
}
In this example there are 2 copies of private_variable, but only
one shared_variable is declared.
P. Merat April 10 2013
116. Destructor
Is called when an object of a class is about to be de-allocated. Might be
useful to count the number of objects of a class.
class my_class{
public:
static int num_obj; // Shared data
my_class() // Constructor method
{
cout << "an object just Constructed!";
num_obj++;
}
~ my_class() // Destructor method
Destructor should
{
cout << "an object just Destructed!";
num_obj--;
have the exact same
}
name as the class:
};
int my_class::num_obj = 0;
~class_name
int main()
{
{
my_class a, b;
cout << my_class::num_obj; // Prints 2
}
cout << my_class::num_obj << b.num_obj; // Prints 0 and 0
return 0;
}
P. Merat April 10 2013
117. Operator Overloading
Class = Class + Class
class my_class
{
public:
int var;
my_class(){ var = 10; }
my_class operator+(my_class x)
{
my_class res;
res.var = var + x.var;
return res;
}
};
int main()
{
my_class a, b, c;
c = a + b;
// or c = a.operator+(b);
cout << c.var; // Will print 20
return 0;
}
P. Merat April 10 2013
118. Operator Overloading (cont.)
These are the operators that could be overloaded in classes.
(Overloadable operators)
+
-
*
/
=
<
>
+=
-=
*=
/=
<<
>>
<<=
>>=
==
!=
<=
>=
++
--
%
&
^
!
|
~
&=
^=
|=
&&
||
%=
[]
()
,
->*
->
new
delete
new[]
delete[]
P. Merat April 10 2013
119. Friend Functions in Class
Using a friend keyword before a function prototype, that function
will become friendly to all the members of the class.
class my_class
{
int var1, var2; // private members
public:
my_class(){ var1 = 10; var2 = 20;}
friend void read_my_class_vars(my_class);
...
};
Not a method!
void read_my_class_vars(my_class x) // input type is my_class
{
cout << x.var1 + x.var2; // var1,2 are private members !!
}
int main()
{
my_class a;
read_my_class_vars(a); // if it was method: a.read_my...();
return 0;
}
P. Merat April 10 2013
120. Friendship between Classes
class class_1
{
int var1, var2; // private members
public:
friend class class_2;
...
};
Since class_1 declared class_2 as a friend; methods of class_2
have access to all class_1 private members.
class class_2
{
int var1, var2;
public:
void read_class_1(class_1 x)
{
cout << x.var1 + x.var2;
}
...
};
P. Merat April 10 2013
121. Usage in main function:
int main()
{
class_1 a;
class_2 b;
b.read_class_1(a);
return 0;
}
Note: Class friendships are not necessarily two-way relationships!
P. Merat April 10 2013
122. Final Note
You can use the struct keyword instead of class, but unlike class,
the default member type in struct is public.
struct my_class // using structure instead of class keyword
{
public: // this keyword is not necessary
int var;
my_class(){ var = 10; }
my_class operator+(my_class x)
{
my_class res;
res.var = var + x.var;
return res;
}
};
int main()
{
my_class a, b, c;
c = a + b;
// or c = a.operator+(b);
cout << c.var; // Will print 20
return 0;
}
P. Merat April 10 2013