5/29/2011
1
Lecture 6
Summaryand Solved Problemsfor the first mid-term exam
EEE 241 Computer Programminghttp://eee241.gantep.edu.tr/
summary and solved problems for MT1 2
This document summarizes the topics that youneed to know for the first mid-term exam.
They include:
• C++ Structure• Basic I/O• Data types• Operators• Intrinsic functions• Strings• Control structures:
Selection and Loops
5/29/2011
2
C++ Structure
summary and solved problems for MT1 3
The main function.Input – Calculate – Output
#include <iostream>
#include <cmath>
using namespace std;
int main() {
double circleArea;
cin >> circleArea;
double r = sqrt(circleArea/M_PI);
cout << "radius = " << r << endl;
return 0;
}
Include the headers forthe services you need.
So far in this course we have used:
iostream
and cmath
optional
Basic I/O
summary and solved problems for MT1 4
Example run:Input two reals and two integers:
a = 34.5, b = 6.234, c = 78, d = 36
#include <iostream>
using namespace std;
int main() {
cout << "Input two reals and two integers: ";
double a, b;
int c, d;
cin >> a >> b >> c >> d;
cout << " a = " << a << ", b = " << b
<< ", c = " << c << ", d = " << d << endl;
return 0;
}
4. Output the results
3. Input the values and assign
2. Declare the variables
1. Request input from the user
34.5 6.234 78 36
5/29/2011
3
The are many data types and qualifiers in C++. You can solve most problems using only two: double and int.
int
Use this data type for representing integer numbers
Remember the range is limited to:
-2,147,483,648 (232) to 2,147,483,647 (232-1)
Examples:
int k, i=174;
k = -456;
Data Types
summary and solved problems for MT1 5
Note that variables can beinitialised at declaration.
double
Use this data type for representing floating point numbers.
Remember that the precision is limited to about 15 significant figures,and the range is limited as follows:
negative tiny positivehuge huge
-10+308 -10-324 10-324 +10+308
Examples:
double Weight;
double electronMass = 9.10938188e-31;
summary and solved problems for MT1 6
5/29/2011
4
There are many operators in C++ but all you need are:
Important!be careful with integer division and assignments:
13/5 results in 2 (the division of two integers results in an integer)but 13.0/5 results in 2.6 because integer 5 is automatically cast to 5.0but int n=2.6 results in 2 being assigned to n because n is type integer!
Operators
summary and solved problems for MT1 7
Operator Description Example Result
+ Addition 13 + 5 18
- Subtraction 13 – 5 8
* Multiplication 13 * 5 65
/ Division 13.0/5
13 / 5
2.6
2
%
(integers only)Modulo a % b
13 % 5
(remainder of a/b)3
++ Increment k++ add 1 to k
Sometimes you need to cast:
double y;
int k=8, n=5;
y=k/double(n);
There are many intrinsic functions in C++, a common group being math functions provided by the cmath header:
#include <cmath>
With this inclusion you can now use the following functions:
cos(), sin(), exp(), sqrt(),log(), log10(), pow(), .....
full list at
http://www.cplusplus.com/reference/clibrary/cmath/
For other C++ library groups see:
http://www.cplusplus.com/reference/clibrary/
Intrinsic functions
summary and solved problems for MT1 8
5/29/2011
5
Example:
Intrinsic functions
summary and solved problems for MT1 9
// Velocity of a body after falling s metres
#include <iostream>
#include <cmath>
using namespace std;
int main() {
double g = 9.81; // m/s^2
double s = 100.; // m
double v = sqrt(2*g*s);
cout << v << " m/s" << endl;
return 0;
}
44.2945 m/sOutput
Example
Strings
summary and solved problems for MT1 10
#include <iostream>
using namespace std;
int main () {
string s1 = "one_", s2, s3;
s2 = "two";
s3 = s1 + s2;
cout << s3 << endl;
return 0;
}
one_twoOutput
5/29/2011
6
Three basic selection control structures:
Control: Selection
summary and solved problems for MT1 11
if (condition) {
statements
.
.
}
if (condition) {
statements1
.
.
} else {
statements2
.
.
}
if (condition1) {
statements1
.
.
} else if (condition2) {
statements2
.
.
} else {
statements3
.
.
}
If a condition is truethen the block, defined by the braces {...}, is executed.
Remember that variables defined inside the block are local to that block. i.e they are not visible outside of the defining block.
summary and solved problems for MT1 12
if ( x < y ) { ... } if x is less than yif ( x <= y ) { ... } if x is less than or equal to yif ( x > y ) { ... } if x is greater than yif ( x >= y ) { ... } if x is greater than or equal to yif ( x == y ) { ... } if x is equal to yif ( x != y ) { ... } if x is not equal to y
if ( x > 2 && y == 3 ) { ... } if x is greater than 2and y is equal to 3
if ( x > 2 || y == 3 ) { ... } if x is greater than 2 or y is equal to 3if ( !(x < y) ) { ... } if x is not less than yif ( x ) { ... } this is false if x==0, otherwise it is true
Relational and logical operators
Not that the operator == makes a comparison while the operator = makes an assignment. Common mistake:
if ( x = y ) { ... DON’T DO THIS!
The value of y is assigned to x, and the relation is always true!
5/29/2011
7
summary and solved problems for MT1 13
Example (also exemplifies a “flow chart”)
Note that variable c needs to be declaredoutside the if block so that it is visible atthe output statement (see scoping).
start
Input a
b = a + 2
a > 2 c = ln(a+b)
Output a, c
TF
end
c = b5
#include <iostream>
#include <cmath>
using namespace std;
int main() {
double a, b, c;
cin >> a;
b = a + 2.0;
if ( a > 2.0 ) {
c = log(a+b);
} else {
c = pow(b,5.0);
}
cout << a << " "
<< c << endl;
return 0;
}
Control: Loops
summary and solved problems for MT1 14
Three basic loop (repetitive) structures:
while (condition) {
statements
.
.
}
do {
statements
.
.
} while (condition);
for (initialisation; condition; increment) {
statements
.
.
}
Also, the break statement allows you to break out of a loop.The continue statement executes the next turn in the loop.
5/29/2011
8
summary and solved problems for MT1 15
Example (also exemplifies “pseudo code”)These are all equivalent counted loops
#include <iostream>
using namespace std;
int main() {
for (int i=1; i<7; i++) {
double x = 0.1*i;
cout <<i<<" "<<x<< endl;
}
}
Pseudo code:
loop i = 1 to 6
x = 0.1i
output i, x
end loop#include <iostream>
using namespace std;
int main() {
int i=1;
while (i<7) {
double x = 0.1*i;
cout <<i<<" "<<x<<endl;
i++;
}
}
#include <iostream>
using namespace std;
int main() {
int i=1;
do {
double x = 0.1*i;
cout <<i<<" "<<x<<endl;
i++;
} while (i<7);
}
#include <iostream>
using namespace std;
int main() {
int i=1;
while (1) {
double x = 0.1*i;
cout <<i<<" "<<x<<endl;
if (i==6) break;
i++;
}
}
1 0.1
2 0.2
3 0.3
4 0.4
5 0.5
6 0.6
That’s all the C++ syntax you needfor the first mid-term exam!
After the break we willlook at some solved problems ......
+
16summary and solved problems for MT1
Don’t forget to bring your
calculator to the exam!
5/29/2011
9
Solved Problems
summary and solved problems for MT1 17
This section presents problems and their solutions.
Problems:
1. Exponential growth of bacteria (revisited)
2. Heat flow in foods
summary and solved problems for MT1 18
Exponential growth of bacteria
Recall that in Lecture 2 we wrote a program to calculate the number nof bacteria after filtration and growth periods t1 and t2.
1. Exponential growthof bacteria (revisited)
input , Q, t1, t2
m = Q t1 n = m e t2
outputm , n
begin
end
= 0.468
Given a 24-hour period (i.e. t1+t2 = 24) wewant to optimize t1 and t2 to maximise the final number of bacteria n.
5/29/2011
10
#include <iostream>
#include <cmath>
using namespace std;
int main () {
double b = 0.468; // growth constant [1/hr]
double a, Q, t1, t2; // inputs
cout << "Input the volume number of bacteria [1/L]: ";
cin >> a;
cout << " Input the volume flow rate [L/hr]: ";
cin >> Q;
cout << " Input is the filtration duration [hr]: ";
cin >> t1;
cout << " Input the growth duration [hr]: ";
cin >> t2;
double m = a*Q*t1; // Number of filtered bacteria
double n = m*exp(b*t2); // Number of bacteria after growth
cout << " Number filtered bacteria = " << m << endl;
cout << "Number of bacteria after growth = " << n << endl;
}
Exponential growth of bacteriaThe program developed in Lecture 2
19summary and solved problems for MT1
Input the volume number of bacteria [1/L]: 0.25
Input the volume flow rate [L/hr]: 36
Input is the filtration duration [hr]: 5
Input the growth duration [hr]: 19
Number filtered bacteria = 45
Number of bacteria after growth = 327310
Example outputs of the program developed in Lecture 2
Input the volume number of bacteria [1/L]: 0.25
Input the volume flow rate [L/hr]: 36
Input is the filtration duration [hr]: 4
Input the growth duration [hr]: 20
Number filtered bacteria = 36
Number of bacteria after growth = 418118
24 hrs
24 hrs
Let’s rewrite the program to use a loop to search values of t1 to find the maximum value of n. We can make the values of and Q constant so
that the only variable is t1 with t2 = 24 - t1.
Exponential growth of bacteria
20summary and solved problems for MT1
5/29/2011
11
#include <iostream>
#include <cmath>
using namespace std;
int main () {
double a = 0.25; // volume number of bacteria [1/L]
double Q = 36.0; // volume flow rate [L/hr]
double b = 0.468; // growth constant [1/hr]
for (int i=1; i<=20; i++) { // loop over twenty periods
double t1 = i*0.2; // Filtration period (0.2-hour steps)
double t2 = 24-t1; // Growth period
double m = a*Q*t1; // Number of filtered bacteria
double n = m*exp(b*t2); // Number of bacteria after growth
cout << fixed << "t1=" << t1 << " n=" << n << endl;
} // end loop
return 0;
}
Exponential growth of bacteria
The modified program - to search for a maximum.
21summary and solved problems for MT1
t1=0.200000 n=123770.789824
t1=0.400000 n=225422.984054
t1=0.600000 n=307921.128718
t1=0.800000 n=373876.581528
t1=1.000000 n=425586.959955
t1=1.200000 n=465071.359521
t1=1.400000 n=494101.783271
t1=1.600000 n=514231.178315
t1=1.800000 n=526818.434839
t1=2.000000 n=533050.666589
t1=2.200000 n=533963.059029
t1=2.400000 n=530456.541976
t1=2.600000 n=523313.517015
t1=2.800000 n=513211.846226
t1=3.000000 n=500737.287359
t1=3.200000 n=486394.541410
t1=3.400000 n=470617.061292
t1=3.600000 n=453775.754781
t1=3.800000 n=436186.701040
t1=4.000000 n=418117.987514
Exponential growth of bacteriaSearch in steps of 0.2 hours
t1=1.800000 n=526818.434839
t1=1.850000 n=528929.386168
t1=1.900000 n=530660.886035
t1=1.950000 n=532029.357415
t1=2.000000 n=533050.666589
t1=2.050000 n=533740.140107
t1=2.100000 n=534112.581268
t1=2.150000 n=534182.286124
t1=2.200000 n=533963.059029
t1=2.250000 n=533468.227729
t1=2.300000 n=532710.658031
t1=2.350000 n=531702.768037
t1=2.400000 n=530456.541976
t1=2.450000 n=528983.543623
t1=2.500000 n=527294.929345
We see the maximum occurs at
t1 = 2.15 hours (t2 = to 21.85 hours)
Any value 1.9 < t1 < 2.4 is good.
Refined the search (0.05 hours):
22summary and solved problems for MT1
5/29/2011
12
summary and solved problems for MT1 23
Graphical view of the search for a maximum
Exponential growth of bacteriaDiscussion
Our numerical solution is t1 = 2.15 0.05 hours
and any value in the range 1.9 < t1 < 2.4 hours is good.
The analytical solution looks like this:
m = Q t1 n = m e t2 = Q t1 e t2 = Q t1 e (24- t1)
For a maximum dn/dt1 = 0So d/dt1 [ Q t1 e (24- t1) ] = 0 So d/dt1 [ Q t1 e 24 e -t1 ] = 0 Q e 24 e - t1 - Q t1 e 24 e - t1 = 0 Q e 24 e - t1 (1- t1) = 0(1- t1) = 0 => t1 = 1/ = 1/ 0.468 = 2.14 hours
That was not too difficult; but often an analytical solution is difficult
or impossible to obtain and so we use a numerical method
requires Computer Programming!
Also our numerical method shows us that a wide range of values are
close to optimal, i.e. we gained some extra information by using a
numerical method. 24summary and solved problems for MT1
5/29/2011
13
2. Heat flow in foods
summary and solved problems for MT1 25
The Problem
A solid food has a temperature
difference T between two sides.Heat flows via conduction at arate Q through a surface area Aaccording to the equation:
Q = k A T / L
where k is the thermal conductivity given by:
k = 0.25 mc + 0.155 mp + 0.160 mf + 0.135 ma + 0.580 mm
where m are the food mass fractions (mc + mp + mf + ma + mm = 1) c = “carbohydrate”, p = “protein”, f = “fat”, a = “ash”, and m = “moisture”.
See “Fourier's Law of Conduction”
A [m2]
L [m]T [oC]
Q [W]
Heat flow in foods
summary and solved problems for MT1 26
The Task
Write a program that inputs the required data andoutputs the rate of heat flow through the food.
Analysis
We want Q = k A T / L
[ 0.25 mc + 0.155 mp + 0.160 mf + 0.135 ma + 0.580 mm ]
condition that food mass fractions mc + mp + mf + ma + mm = 1
input: A, T, L
input: mc , mp , mf , ma , mm
Heat flow in foods
5/29/2011
14
summary and solved problems for MT1 27
Flow chart
input:A, T, L
input:
mc , mp , mf ,
ma , mm
output: Q
mc+mp+mf +ma+mm = 1 ?
start
false
k = 0.25 mc + 0.155 mp + 0.160 mf
+ 0.135 ma + 0.580 mm
true
Q = k A T / L
end
Heat flow in foods
summary and solved problems for MT1 28
Algorithm
(Follow the flow chart, but add some instructions to the user)
1. output “enter the mass fractions mc , mp , mf , ma , mm”
2. input mc , mp , mf , ma , mm
3. if ( mc+mp+mf + ma+mm ≠ 1 )output “Mass fraction sum should equal 1!”go back to step 1
4. k = 0.25 mc + 0.155 mp + 0.160 mf + 0.135 ma + 0.580 mm
5. input A, T, L
6. Q = k A T / L
7. output Q
Heat flow in foods
5/29/2011
15
summary and solved problems for MT1 29
Implementation in C++ (Follow the algorithm but adding more instructions)
#include <iostream>
using namespace std;
int main() {
double Mc, Mp, Mf, Ma, Mm;
bool badSum;
do {
cout << "Input the Carbohydrate mass fraction: "; cin >> Mc;
cout << "Input the Protein mass fraction: "; cin >> Mp;
cout << "Input the Fat mass fraction: "; cin >> Mf;
cout << "Input the Ash mass fraction: "; cin >> Ma;
cout << "Input the Moisture mass fraction: "; cin >> Mm;
double sum = Mc + Mp + Mf + Ma + Mm;
badSum = ( sum < 0.999 || sum > 1.001 ); // allow 0.1% error
if ( badSum ) cout << "Mass fraction sum (" << sum
<< ") should equal 1!" << endl;
} while ( badSum );
Heat flow in foods
summary and solved problems for MT1 30
.... continued from previous page
we have at this point values for Mc, Mp, Mf, Ma, Mm ....
// compute the thermal conductivity
double k = 0.250*Mc + 0.155*Mp + 0.160*Mf + 0.135*Ma + 0.580*Mm;
// Input the area, temperature difference and length
double A, dT, L;
cout << "Input the conduction surface area [m^2]: "; cin >> A;
cout << "Input the temperature difference [C]: "; cin >> dT;
cout << "Input the conduction length [m]: "; cin >> L;
// calculate and output the rate of heat flow
double Q = k * A * dT / L;
// Output the result
cout << "Rate of heat flow = " << Q << " Watts" << endl;
return 0;
}
Heat flow in foods
5/29/2011
16
summary and solved problems for MT1 31
Input the Carbohydrate mass fraction: 0.15
Input the Protein mass fraction: 0.18
Input the Fat mass fraction: 0.23
Input the Ash mass fraction: 0.02
Input the Moisture mass fraction: 0.52
Mass fraction sum (1.1) should equal 1!
Input the Carbohydrate mass fraction: 0.15
Input the Protein mass fraction: 0.08
Input the Fat mass fraction: 0.23
Input the Ash mass fraction: 0.02
Input the Moisture mass fraction: 0.52
Input the conduction surface area [m^2]: 0.2
Input the temperature difference [C]: 25.
Input the conduction length [m]: 0.05
Rate of heat flow = 39.1 Watts
Example run:
Heat flow in foods
In this lecture we summarised the C++ syntax and structure you need for the first 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/
andhttp://www.learncpp.com/
Finally
32summary and solved problems for MT1
5/29/2011
17
summary and solved problems for MT1 33
http://www1.gantep.edu.tr/~eee241/labs.php
This week’s lab exercise sheet contains some
example first mid-term exam questions.
First try solving the questions by hand,
then program your solutions in the lab hour.
THE FIRST MID-TERM EXAM IS NEAR
DON’T FORGET TO BRING A CALCULATOR
TO THE EXAM!
Exercises for Lab 6
#include <iostream>
#include <cmath>
#include <cstdlib>
using namespace std;
int main() {
double Area;
cin >> Area;
double r = sqrt(Area/M_PI);
int n, m;
cin >> n >> m;
int k = pow(n,m);
string name;
cin >> name;
string s = "Hello " + name;
bool p=true;
bool q = (n>m);
cout << r << " " << k
<< " " << s << " " << p
<< " " << q << endl;
return 0;
}
if (condition) {
statements
}
if (condition) {
statements1
} else {
statements2
}
if (condition1) {
statements1
} else if (condition2) {
statements2
} else if (condition3) {
statements3
} else {
statements4
}
for (int i=1; i<7; i++) {
statements
}
int i=1;
while (i<7) {
statements
i++;
}
int i=1;
do {
statements
i++;
} while (i<7);
int i=1;
while (true) {
statements
if (i==6) break;
i++;
}
Loop structures [i = 1 to 6]
if ( x < y ) ...
if ( x <= y ) ...
if ( x > y ) ...
if ( x >= y ) ...
if ( x == y ) ...
if ( x != y ) ...
if ( !(x < y) ) ...
if ( x ) ...
if ( x > 2 && y == 3 ) ...
if ( x > 2 || y == 3 ) ...
sin() cos() tan()
asin() acos() atan()
fabs() sqrt() pow()
exp() log() log10()
int() double() rand()
Basic structure, headers, data types, I/O
Selection structures
logical operators
Intrinsic functions
Also the continue statement
EEE241 MT1 reference sheet 27/02/11
This information will be provided in the exam.
Return only your answer sheet to the invigilator.
Cheating is a serious offence, do not pass /
receive any information to/from another student.