Exercise Sheet # 2

advertisement
Tampere University of Technology
Department of Software Systems
OHJ-1106 Programming I
Exercise Sheet # 2 - Solution
(05-10-2012)
(Note: Solutions should be submitted as a printed copy at the beginning of session)
Exercise 1:
Rewrite each of the following statements:
a. SumOfSquares = SumOfSquares + x * x
SumOfSquares+=x*x
b. count = count +1
count+=1
c. count = count-1
count - =1;
Suppose that, when you run the program, you enter input 1 5 4 from the console.
What is the output?
#include<iostream>
using namespace std;
int main() {
double x, y, z;
cin >> x >> y>>z;
cout<< ( x < y && y < z )<<endl;
cout<< ( x < y || y < z )<<endl;
cout<< !( x < y )<<endl;
// output is 1
// output is 1
// output is 0
cout<< ( x + y < z )<<endl;
// output is 0
return 0;
}
Exercise 2:
1. What is the value of the expression ch>’A’ && ch<=’Z’ if ch is ‘A’, ‘p’,
‘E’, or ‘5’? false, true, true, false
2. Is ( x>0 && x<10) the same as ((x>0) && (x<10)) ?
yes, Order of evaluation is same
3. Is (x> 0 || x<10 && y<0) the same as (x>0 || (x<10 && y<0)) ?
yes, Order of evaluation is same
Exercise 3:
Compute the value of each legal expression. Indicate whether the value is an integer or a
floating point value. If the expression is not legal, explain why.
a. 10 + 3 Integer: 13
b. -9.4 - 6.2 Floating point: -15.6
c. 10.0 / 3.0 + 5 * 2
Floating point: 13.333
d. 10 % 3 + 5 % 2 Integer : 2
e. 10 / 3 + 5 / 2 Integer: 5
f. 12.5 + (2.5 / (6.2 / 3.1)) Floating point: 13.75
g.-4 * (-5 + 6) Integer: -4
h. 13 % 5 / 3 Integer: 1
i. (10.0 / 3.0 % 2) / 3 Illegal: 10.0 / 3.0 is a floating point expression, but the % operator
requires integer operands
Exercise 4:
Assume that int a = 1 and double d = 1.0, and that each expression is independent.
What are the results of the following expressions?
1.
2.
3.
4.
5.
a = ( a = 3) + a ; // Output: 6
a + = a+ ( a = 3) ; // Output: 9
a = 5 + 5 * 2 % a--; // Output: 4
a = 4 + 1 + 4 * 5 % ( ++a + 1); // Output: 7
d += 1.5 * 3 + ( ++d); // Output: 8.5
6. d -= 1.5 * 3 + d++ ; // Output: -3.5
Exercise 5:
int year;
cin>>year;
bool isLeapYear = (year%4 == 0) && (year%100 !=0) || (year%400 ==0);
if(isLeapYear)
cout<< “Is yeap year”;
else
cout<<”Is not a leap year”;
From above code snippet, there is a Boolean variable isLeapYear. Write a Boolean
expression by using variable year to check whether a year is a leap year.
(Hint: A year is a leap year if it is divisible by 4 but not by 100 or if it is divisible by
400).
Exercise 6:
Assuming that x is 1. Show the result of the following Boolean expressions
1.
2.
3.
4.
5.
6.
( true ) && ( 3 > 4)
// Output: False
!( x > 0) && ( x > 0) // Output: False
( x>0) || ( x<0)
// Output: True
( x != 0) || ( x == 0) // Output: True
( x >= 0) || ( x < 0) // Output: True
( x != 0) || !( x == 0) // Output: True
Download