Вы находитесь на странице: 1из 17

5/29/2011

EEE 241 Computer Programming


http://eee241.gantep.edu.tr/

Lecture 6

Summary
and Solved Problems
for the first mid-term exam

This document summarizes the topics that you


need 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

summary and solved problems for MT1

5/29/2011

C++ Structure
The main function.
Input Calculate Output
#include <iostream>
#include <cmath>

Include the headers for


the services you need.

using namespace std;

So far in this course we


have used:

int main() {
double circleArea;
cin >> circleArea;
double r = sqrt(circleArea/M_PI);

iostream
and cmath

cout << "radius = " << r << endl;


return 0;

optional

}
summary and solved problems for MT1

Basic I/O
#include <iostream>
using namespace std;
int main() {

1. Request input from the user


cout << "Input two reals and two integers: ";
double a, b;
2. Declare the variables
int c, d;
cin >> a >> b >> c >> d; 3. Input the values and assign
cout << " a = " << a << ", b = " << b
<< ", c = " << c << ", d = " << d << endl;
return 0;

4. Output the results

Example run:
Input two reals and two integers: 34.5 6.234 78 36
a = 34.5, b = 6.234, c = 78, d = 36
summary and solved problems for MT1

5/29/2011

Data Types
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;

Note that variables can be


initialised at declaration.

summary and solved problems for MT1

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
huge

tiny

positive
huge

-10+308

-10-324 10-324

+10+308

Examples:
double Weight;
double electronMass = 9.10938188e-31;

summary and solved problems for MT1

5/29/2011

Operators
There are many operators in C++ but all you need are:
Operator

Description

Example

Result

Addition

13 + 5

18

Subtraction

13 5

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

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.0
but int n=2.6 results in 2 being assigned to n because n is type integer!

Sometimes you
need to cast:
double y;
int k=8, n=5;
y=k/double(n);

summary and solved problems for MT1

Intrinsic functions
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/
summary and solved problems for MT1

5/29/2011

Intrinsic functions
Example:
// 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;

}
Output 44.2945 m/s
summary and solved problems for MT1

Strings
Example
#include <iostream>
using namespace std;
int main () {
string s1 = "one_", s2, s3;
s2 = "two";
s3 = s1 + s2;
cout << s3 << endl;
return 0;
}
Output one_two

summary and solved problems for MT1

10

5/29/2011

Control: Selection
Three basic selection control structures:
if (condition) {

if (condition) {

statements
.
.

if (condition1) {

statements1
.
.

statements1
.
.

} else {

If a condition is true
then the block, defined
by the braces {...},
is executed.

} else if (condition2) {

statements2
.
.

statements2
.
.

} else {

Remember that variables defined inside the


block are local to that block. i.e they are not
visible outside of the defining block.

statements3
.
.
}

summary and solved problems for MT1

11

Relational and logical operators


if
if
if
if
if
if

(
(
(
(
(
(

x
x
x
x
x
x

< y )
<= y )
> y )
>= y )
== y )
!= y )

{
{
{
{
{
{

...
...
...
...
...
...

}
}
}
}
}
}

if x is less than y
if x is less than or equal to y
if x is greater than y
if x is greater than or equal to y
if x is equal to y
if x is not equal to y

if ( x > 2 && y == 3 ) { ...

if ( x > 2 || y == 3 ) { ... }
if ( !(x < y) ) { ...
}
if ( x ) { ... }

if x is greater than 2
and y is equal to 3
if x is greater than 2 or y is equal to 3
if x is not less than y
this is false if x==0, otherwise it is true

Not that the operator == makes a comparison while the operator = makes an
assignment. Common mistake:
if ( x = y ) { ...

DONT DO THIS!

The value of y is assigned to x, and the relation is always true!


summary and solved problems for MT1

12

5/29/2011

Example (also exemplifies a flow chart)


#include <iostream>
#include <cmath>
using namespace std;

start
Input a

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

b=a+2
c = b5

a >2

c = ln(a+b)

Output a, c
end

Note that variable c needs to be declared


outside the if block so that it is visible at
the output statement (see scoping).

summary and solved problems for MT1

13

Control: Loops
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.

summary and solved problems for MT1

14

5/29/2011

Example (also exemplifies pseudo code)


These are all equivalent counted loops
#include <iostream>
using namespace std;
int main() {

int i=1;
while (i<7) {
double x = 0.1*i;
cout <<i<<" "<<x<<endl;
i++;
}

Pseudo code:
loop i = 1 to 6
x = 0.1i
output i, x
end loop

int i=1;
do {
double x = 0.1*i;
cout <<i<<" "<<x<<endl;
i++;
} while (i<7);
}

int i=1;
while (1) {
double x = 0.1*i;
cout <<i<<" "<<x<<endl;
if (i==6) break;
i++;
}
}

0.1
0.2
0.3
0.4
0.5
0.6

#include <iostream>
using namespace std;
int main() {

}
#include <iostream>
using namespace std;
int main() {

1
2
3
4
5
6

#include <iostream>
using namespace std;
int main() {

for (int i=1; i<7; i++) {


double x = 0.1*i;
cout <<i<<" "<<x<< endl;
}
}

summary and solved problems for MT1

15

Thats all the C++ syntax you need


for the first mid-term exam!

+
Dont forget to bring your
calculator to the exam!

After the break we will


look at some solved problems ......
summary and solved problems for MT1

16

5/29/2011

Solved Problems
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

1. Exponential growth
of bacteria (revisited)

17

Exponential growth of bacteria

Recall that in Lecture 2 we wrote a


program to calculate the number n
of bacteria after filtration and growth
periods t1 and t2.

begin

= 0.468

input
, Q, t1, t2
m = Q t1
n = m e t2

Given a 24-hour period (i.e. t1+t2 = 24) we


want to optimize t1 and t2 to maximise
the final number of bacteria n.

output
m, n
end

summary and solved problems for MT1

18

5/29/2011

The program developed in Lecture 2

Exponential growth of bacteria

#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;
double n = m*exp(b*t2);

";
";
";
";

// Number of filtered bacteria


// Number of bacteria after growth

cout << "


Number filtered bacteria = " << m << endl;
cout << "Number of bacteria after growth = " << n << endl;
}
summary and solved problems for MT1

19

Exponential growth of bacteria

Example outputs of the program developed in Lecture 2


Input the volume number of bacteria [1/L]:
Input the volume flow rate [L/hr]:
Input is the filtration duration [hr]:
Input the growth duration [hr]:
Number filtered bacteria = 45
Number of bacteria after growth = 327310

0.25
36
5
19 24 hrs

Input the volume number of bacteria [1/L]:


Input the volume flow rate [L/hr]:
Input is the filtration duration [hr]:
Input the growth duration [hr]:
Number filtered bacteria = 36
Number of bacteria after growth = 418118

0.25
36
4
20 24 hrs

Lets 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.
summary and solved problems for MT1

20

10

5/29/2011

Exponential growth of bacteria

The modified program - to search for a maximum.


#include <iostream>
#include <cmath>
using namespace std;
int main () {
double a = 0.25;
double Q = 36.0;
double b = 0.468;

// volume number of bacteria [1/L]


// volume flow rate [L/hr]
// growth constant [1/hr]

for (int i=1; i<=20; i++) { // loop over twenty periods


double
double
double
double

t1 = i*0.2;
//
t2 = 24-t1;
//
m = a*Q*t1;
n = m*exp(b*t2);

Filtration period (0.2-hour steps)


Growth period
// Number of filtered bacteria
// Number of bacteria after growth

cout << fixed << "t1=" << t1 << " n=" << n << endl;
} // end loop
return 0;
}
summary and solved problems for MT1

Search in steps of 0.2 hours


t1=0.200000
t1=0.400000
t1=0.600000
t1=0.800000
t1=1.000000
t1=1.200000
t1=1.400000
t1=1.600000
t1=1.800000
t1=2.000000
t1=2.200000
t1=2.400000
t1=2.600000
t1=2.800000
t1=3.000000
t1=3.200000
t1=3.400000
t1=3.600000
t1=3.800000
t1=4.000000

n=123770.789824
n=225422.984054
n=307921.128718
n=373876.581528
n=425586.959955
n=465071.359521
n=494101.783271
n=514231.178315
n=526818.434839
n=533050.666589
n=533963.059029
n=530456.541976
n=523313.517015
n=513211.846226
n=500737.287359
n=486394.541410
n=470617.061292
n=453775.754781
n=436186.701040
n=418117.987514

21

Exponential growth of bacteria

Refined the search (0.05 hours):


t1=1.800000
t1=1.850000
t1=1.900000
t1=1.950000
t1=2.000000
t1=2.050000
t1=2.100000
t1=2.150000
t1=2.200000
t1=2.250000
t1=2.300000
t1=2.350000
t1=2.400000
t1=2.450000
t1=2.500000

n=526818.434839
n=528929.386168
n=530660.886035
n=532029.357415
n=533050.666589
n=533740.140107
n=534112.581268
n=534182.286124
n=533963.059029
n=533468.227729
n=532710.658031
n=531702.768037
n=530456.541976
n=528983.543623
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.

summary and solved problems for MT1

22

11

5/29/2011

Graphical view of the search for a maximum

summary and solved problems for MT1

23

Exponential growth of bacteria

Discussion

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 = 0
So d/dt1 [ Q t1 e (24- t1) ] = 0 So d/dt1 [ Q t1 e
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

24

-t1 ]

=0

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.
summary and solved problems for MT1

24

12

5/29/2011

Heat flow in foods

2. Heat flow in foods


Q [W]

The Problem
A solid food has a temperature
difference T between two sides.
Heat flows via conduction at a
rate Q through a surface area A
according to the equation:

A [m2]

T [oC]

L [m]

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
summary and solved problems for MT1

25

Heat flow in foods

The Task
Write a program that inputs the required data and
outputs the rate of heat flow through the food.

Analysis

input: A, T, L

We want Q = k A T / L
[ 0.25 mc + 0.155 mp + 0.160 mf + 0.135 ma + 0.580 mm ]
input: mc , mp , mf , ma , mm

condition that food mass fractions mc + mp + mf + ma + mm = 1

summary and solved problems for MT1

26

13

5/29/2011

Heat flow in foods

Flow chart

start

input:

k = 0.25 mc + 0.155 mp + 0.160 mf


+ 0.135 ma + 0.580 mm

mc , mp , mf ,
ma , mm

input:
A, T, L

false

mc+mp+mf +
ma+mm = 1 ?

Q = k A T / L
true
output: Q

end

summary and solved problems for MT1

27

Heat flow in foods

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

summary and solved problems for MT1

28

14

5/29/2011

Implementation in C++

Heat flow in foods

(Follow the algorithm but adding more instructions)


#include <iostream>
using namespace std;
int main() {
double Mc, Mp, Mf, Ma, Mm;
bool
badSum;
do {
cout
cout
cout
cout
cout

<<
<<
<<
<<
<<

"Input
"Input
"Input
"Input
"Input

the Carbohydrate mass fraction: ";


the
Protein mass fraction: ";
the
Fat mass fraction: ";
the
Ash mass fraction: ";
the
Moisture mass fraction: ";

cin
cin
cin
cin
cin

>>
>>
>>
>>
>>

Mc;
Mp;
Mf;
Ma;
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 );
summary and solved problems for MT1

29

Heat flow in foods

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

summary and solved problems for MT1

30

15

5/29/2011

Heat flow in foods

Example run:
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

summary and solved problems for MT1

31

Finally
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/
and
http://www.learncpp.com/

summary and solved problems for MT1

32

16

5/29/2011

Exercises for Lab 6


http://www1.gantep.edu.tr/~eee241/labs.php

This weeks 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


DONT FORGET TO BRING A CALCULATOR
TO THE EXAM!

summary and solved problems for MT1

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.
Basic structure, headers, data types, I/O
#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;
}

33

Selection structures

Loop structures [i = 1 to 6]

if (condition) {
statements
}

for (int i=1; i<7; i++) {


statements
}

if (condition) {
statements1
} else {
statements2
}

int i=1;
while (i<7) {
statements
i++;
}

if (condition1) {
statements1
} else if (condition2) {
statements2
} else if (condition3) {
statements3
} else {
statements4
}

int i=1;
while (true) {
statements
if (i==6) break;
i++;
}

logical operators
if
if
if
if
if
if
if
if

(
(
(
(
(
(
(
(

x < y ) ...
x <= y ) ...
x > y ) ...
x >= y ) ...
x == y ) ...
x != y ) ...
!(x < y) ) ...
x ) ...

if ( x > 2 && y == 3 ) ...


if ( x > 2 || y == 3 ) ...

int i=1;
do {
statements
i++;
} while (i<7);
Also the continue statement
Intrinsic functions
sin()
asin()
fabs()
exp()
int()

cos()
acos()
sqrt()
log()
double()

tan()
atan()
pow()
log10()
rand()

17

Вам также может понравиться