ECE OOP Lab1
ECE OOP Lab1
1. std::cout << is used to print a result to the console. std::cin >>, on the other hand, is
used to read a input parameter in from the keyboard. Write code that asks a user to enter
two integers from the keyboard and then writes the product of these integers to the screen.
3. Sum of
N
X
S= k2 , (1)
k=1
4. Sum of
1 1 1 1
S =1+ + + + + ... (2)
2 4 8 16
for all elements greater than an inputted tolerance, e.g. 4e − 3.
5. Use the following code to complete the tasks. The following cases are independent from one
another. If a variable is not specified, it is inputted from users by std::cin >>.
1 # include < iostream >
2 int main ()
3 {
4 double p , q , x , y ;
5 int j ;
6 return 0 ;
7 }
(a) Set the variable x to the value 5 if either p is greater than or equal to q, or the variable
j is not equal to 10.
(b) Set the variable x to the value 5 if both y is greater than or equal to q, and the variable
j is equal to 20. If this compound condition is not met, set x to take the same value as
p.
(c) Set the variable x according to the following rule.
0, p > q,
x= 1, p ≤ q, and j = 10, .
2, otherwise
6. What is the output result of each of the following cases? Are they correct? If not, investigate
what is wrong.
Write a code to approximate the π number with 5 terms, 10 terms, and 100 terms. Check how
much the accuracy is improved. Try to implement your code using two different approaches:
(i) Use the for loop; (ii) Use the while loop.
Zxm
1 1
f (x)dx ≈ h f0 + f1 + . . . + fm−1 + fm , (5)
2 2
x0
and compare your obtained estimate with the exact solution. Try with different values of m.
Page 2
ECE OOP - Lab 1 Page 3 of 3
f (xi−1 )
xi = xi−1 − , x = 1, 2, 3, . . . , (7)
f ′ (xi−1 )
where the iteration is terminated if the approximation sufficiently approaches to the fixed
point solution by the estimate
f (x) = ex + x3 − 5 = 0 (9)
with ε = 1.0E − 5 and x0 = 0 as an initial guess. Print out the convergent solution at each
iteration.
Hint:
You don’t need to store all xi for each iteration. Just use xn and xp for xi and xi−1 .
Use assert to check if the denominator in Eq. (7) is zero or not.
Page 3