5/5/2011
EEE 241 Computer Programming
Lecture 11
Summary
and Solved Problems
for the second mid-term exam
This document summarizes the topics that you
need to know for the second mid-term exam.
Second mid-term exam topics include:
- First mid-term topics (see first mid-term summary lecture)
- and the following:
Functions
Vectors
File processing
Data structures
EEE 241
These topics are
summarised in this
document
summary and solved problems for MT2
5/5/2011
Functions
#include <iostream>
#include <cmath>
using namespace std;
double CircleArea(double);
int main() {
double r;
cin >> r;
double A = CircleArea(r);
cout << "Area = " << A << endl;
return 0;
}
double CircleArea(double r) {
if (r<0) {
cout << "Error: Negative radius"
<< " in CircleArea()"
<< endl;
return -1.0;
} else {
return M_PI*r*r;
}
}
EEE 241
Function prototypes introduce to the compiler
functions that will be defined later.
main is a function, it returns an integer
value (to the operating system).
A user-defined function: CircleArea()
(remember this was prototyped at the top)
This function separates the details of a task
from the main program, the main program
simply
uses
the
resource
called
CircleArea().
summary and solved problems for MT2
Functions that return values have a type (e.g. int or double)
and if parameters exist, the parameters also have types.
The following program contains a programmer-defined function that returns a type double value
that is the result of the division of two integers (without truncation).
Notes:
#include <iostream>
using namespace std;
// prototype
double fraction(int, int);
int main() {
int a = 4, b = 5;
double f = fraction(a, b);
cout << a << " / "
<< b << " = "
<< f << endl;
}
// definition
double fraction(int x, int y) {
return double(x)/double(y);
}
The output is: 4 / 5 = 0.8
EEE 241
If you use a function before it is defined, then
you need to declare it with a prototype.
The arguments in a function call
should match (in number, order and type) the
parameters in the function definition.
A function returns a value of a specific type.
A void function returns no value:
// function to output n dashes
void dashes(int n) {
for (int i=0; i<n; i++) cout << "-";
cout << endl;
}
Example: dashes(8) outputs: --------
summary and solved problems for MT2
5/5/2011
Passing arguments by reference
Classic example: swapping two values
Notes:
#include <iostream>
using namespace std;
void swap(double&, double&);
int main() {
double x = 22.2, y = 33.3;
cout << x << " " << y << endl;
swap (x, y);
cout << x << " " << y << endl;
}
void swap(double& a, double& b) {
double c = a;
a = b;
b = c;
}
EEE 241
The ampersand (&) symbol marks the
parameters as references to the arguments. This
appears in the function prototype and function
definition.
In the function swap(), parameters a and b
refer to the x and y variables in the main
program block.
Any changes to a and b in the function also
affect x and y in the main program block.
The output is:
22.2 33.3
33.3 22.2
summary and solved problems for MT2
Vectors
#include <iostream>
#include <vector>
using namespace std;
You need to include the vector header.
int main() {
Declaration of a vector a that has 5
elements all of type double
vector<double> a(5);
a[0]=8.4; a[1]=3.6; a[2]=9.1; a[3]=4.7; a[4]=3.9;
Output
0
1
2
3
4
for (int i=0; i<5; i++)
cout << i << "\t" << a[i] << endl;
}
8.4
3.6
9.1
4.7
3.9
values
indices
Note that vector a has 5 elements, and the index goes from 0 to 4.
For example the 4th element is a[3] which contains the value 4.7
EEE 241
summary and solved problems for MT2
5/5/2011
Passing vectors to functions
Example: mean of the values in a vector.
#include <iostream>
#include <vector>
using namespace std;
double vectorMean(vector<double>);
int main() {
To pass by reference,
simple add & to the
function argument
and parameters.
vector<double> a(6);
a[0]=8.4; a[1]=3.6; a[2]=9.1;
a[3]=4.7; a[4]=3.9; a[5]=5.1;
cout << vectorMean(a) << endl;
}
double vectorMean(vector<double> x) {
double sum=0.0;
for (int i = 0; i < x.size(); i++) sum = sum+x[i];
return sum/x.size();
}
The output is:
5.8
EEE 241
summary and solved problems for MT2
Building a vector with the .push_back method
Example: Construct a vector that contains the first 40 Fibonacci numbers.
The Fibonacci numbers are the integer sequence: 0 1 1 2 3 5 8 13 21 34 ...
i.e. Fibk+1 = Fibk + Fibk-1
See http://en.wikipedia.org/wiki/Fibonacci_number
#include <iostream>
#include <vector>
using namespace std;
Output
0 1 1 2 3 5 8 13 21 34 55 89 144
233 377 610 987 1597 2584 4181
6765 10946 17711 28657 46368
75025 121393 196418 317811
514229 832040 1346269 2178309
3524578 5702887 9227465 14930352
24157817 39088169 63245986
int main() {
vector<int> Fib;
Fib.push_back(0);
Fib.push_back(1);
Fib.push_back(1);
do {
int k = Fib.size()-1;
Fib.push_back( Fib[k] + Fib[k-1] );
} while ( Fib.size() < 40 );
// Output the resultant vector
for (unsigned int i=0; i<Fib.size(); i++) cout << Fib[i] << " ";
}
EEE 241
summary and solved problems for MT2
5/5/2011
File processing
To perform I/O with files you need to include the fstream (file stream) header.
Example: Input six values from a file and store them in a vector.
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
int main() {
vector<double> x(6);
ifstream myInputFile("exampleInput.txt");
for (int i=0; i<6; i++) {
myInputFile >> x[i];
cout << x[i] << endl;
}
myInputFile.close();
}
Just like cin >> x[i];
Program screen output
1
0.5
0.33333
0.25
0.2
0.16667
exampleInput.txt 1.00000
0.50000
0.33333
This file must
0.25000
already exist.
0.20000
0.16667
EEE 241
Open a file for input (ifstream);
The object myInputFile points
to the file exampleInput.txt
summary and solved problems for MT2
Example: Output six values to a file.
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
int main() {
vector<double> x(6);
x[0]=8.4; x[1]=3.6; x[2]=9.1;
x[3]=4.7; x[4]=3.9; x[5]=5.1;
ofstream myOutputFile("exampleOutput.txt");
for (int i=0; i<6; i++) {
myOutputFile << x[i] << endl;
}
myOutputFile.close();
Open a file for output (ofstream);
The object myOutputFile points to
the file exampleOutput.txt
Just like
cout << x[i] << endl;
}
The result of executing the program is the creation of the
file exampleOutput.txt with the following contents:
EEE 241
summary and solved problems for MT2
8.4
3.6
9.1
4.7
3.9
5.1
10
5/5/2011
Data structures
Below is a list of all data types we have used in this course, including data structures:
Using data structures
Scalars
int
double
string
bool
body
#include <iostream>
using namespace std;
x;
x;
x;
x;
x;
struct body{
int age;
int height;
double weight;
};
Vectors
vector<int>
vector<double>
vector<string>
vector<bool>
vector<body>
x;
x;
x;
x;
x;
int main () {
body dog, cat;
cout << "Input values for the dog: ";
cin >> dog.age >> dog.height >> dog.weight;
cout << "Input values for the cat: ";
cin >> cat.age >> cat.height >> cat.weight;
.
.
Here data type body
is the data structure:
}
EEE 241
summary and solved problems for MT2
11
Passing data structures to functions
Example: a function that outputs a data structure to the screen.
#include <iostream>
using namespace std;
To pass by reference,
simple add & to the
function parameters.
struct body{
int age;
int height;
double weight;
};
void displayBody(body x) {
cout << "
Age: " << x.age
<< " Yr" << endl;
cout << "Height: " << x.height << " mm" << endl;
cout << "Weight: " << x.weight << " kg" << endl;
return;
}
int main() {
body dog = {6, 561, 35.232};
displayBody(dog);
return 0;
The output is:
Age: 6 Yr
Height: 561 mm
Weight: 35.232 kg
}
EEE 241
summary and solved problems for MT2
12
5/5/2011
Together with the first mid-term topics,
thats all the C++ you need for the second mid-term exam!
But feel free to learn more at:
http://cpp.gantep.edu.tr/
http://www.learncpp.com/
And please practice programming as much as possible,
For example by completing all the labs:
http://www1.gantep.edu.tr/~eee241/labs.php
If you want to find more information about any expression you
see in this course, then search C++ expression in google.
EEE 241
summary and solved problems for MT2
13
Solved Problems
EEE 241
summary and solved problems for MT2
14
5/5/2011
Problem 1 - description
Eight samples of lentils are sourced from different suppliers. For each sample the number of
impurities (stones etc) are counted.
The results are stored in a file lentils.txt; the contents are shown below:
EPN
APT
NAS
UKB
TTN
SAN
QUE
PAS
12
16
17
26
21
19
12
13
1.843
1.947
1.432
2.841
2.213
3.391
1.369
2.131
Column 1 the supplier code
Column 2 the number of impurities
Column 3 the sample weight (kg)
The output should look
something like this:
Write a C++ program that reads the data from the file
and outputs to the screen the supplier code and number
of impurities with each sample normalised to 1 kg.
Also, the output corresponding to the sample that has
the least normalised amount of impurities should be
marked with BEST, and the mean number of
normalised impurities and their standard deviation
should be output at the end.
EEE 241
EPN 6.51
APT 8.22
NAS 11.87
UKB 9.15
TTN 9.49
SAN 5.60 BEST
QUE 8.77
PAS 6.10
mean = 8.2 sd = 1.9
summary and solved problems for MT2
15
Problem 1 - Notes
1. The number of stones normalised to 1kg is:
stonesN = stones / weight(kg)
2. The mean and standard deviation of sample data is given by
http://en.wikipedia.org/wiki/Mean
http://en.wikipedia.org/wiki/Standard_deviation
EEE 241
summary and solved problems for MT2
16
5/5/2011
Problem 1 solution: headers and prototypes
#include <iostream>
#include <iomanip>
#include <fstream>
#include <vector>
#include <cmath>
using namespace std;
// Note that these all have global scope.
const int n=8;
// number of samples
vector<string> code(n);
// Sample code
vector<double> stones(n); // Number of stones
// function prototypes
void getData(void);
int
best(void);
void meanSD(double&, double&);
EEE 241
summary and solved problems for MT2
17
Problem 1 solution: main()
int main() {
getData();
int imin = best();
cout << fixed << setprecision(2);
for (int i=0; i<n; i++) {
cout << endl
<< setw(4) << code[i]
<< setw(6) << stones[i];
if (i==imin) cout << " BEST";
}
double mean, sd;
meanSD(mean, sd);
cout << "\n\n" << setprecision(1)
<< " mean = " << mean
<< " sd = " << sd << endl;
Output
EPN 6.51
APT 8.22
NAS 11.87
UKB 9.15
TTN 9.49
SAN 5.60 BEST
QUE 8.77
PAS 6.10
mean = 8.2 sd = 1.9
EEE 241
summary and solved problems for MT2
18
5/5/2011
Problem 1 solution: functions
// Get the data.
void getData(void) {
int s;
// stones
double w; // weight
ifstream lentils("lentils.txt");
for ( int i=0; i<n; i++) {
lentils >> code[i] >> s >> w;
stones[i] = s/w; // stones (normalised).
}
lentils.close();
}
// Calculate mean and standard deviation.
void meanSD(double& mean, double& sd) {
double m1=0.0, m2=0.0;
for ( int i=0; i<n; i++) {
m1 = m1 + stones[i];
m2 = m2 + stones[i]*stones[i];
}
m1 = m1/n; // first moment about the origin
m2 = m2/n; // second moment about the origin
mean = m1;
// mean
sd = sqrt(m2-m1*m1); // standard deviation
}
EEE 241
// Return the index of
// the best supplier.
int best(void) {
int imin=0;
double min=stones[0];
for (int i=1; i<n; i++) {
if (stones[i]<min) {
min=stones[i];
imin=i;
}
}
return imin;
}
summary and solved problems for MT2
19
Problem 1 sharepoint
You can find the data file:
and source code:
lentils.txt
lentils.cpp
at the course sharepoint:
http://www1.gantep.edu.tr/~eee241/sharepoint/
EEE 241
summary and solved problems for MT2
20
10
5/5/2011
Finally
In this lecture we summarised the C++ syntax and structure you
need for the second mid-term exam.
You can find the lecture slides in the course website:
http://eee241.gantep.edu.tr/
For further reading, search for the relevant sections at:
http://cpp.gantep.edu.tr/
and
http://www.learncpp.com/
Note: after the second mid-term exam we will look at
numerical methods as example applications of C++.
summary and solved problems for MT1
21
Exercises for Lab 11
http://www1.gantep.edu.tr/~eee241/labs.php
This weeks lab exercise sheet contains some
example second mid-term exam questions.
First try solving the questions by hand,
then code your solutions in the lab hour.
THE SECOND MID-TERM EXAM IS NEXT WEEK.
DONT FORGET TO BRING A CALCULATOR
TO THE EXAM!
summary and solved problems for MT1
22
11