Assignment2_Solution
Assignment2_Solution
1. Covert decimal number 27 to the equivalent binary number. [ Hint: (27) 10 = (?)2 ]
Solution: 11011
Step 1: divide the number repeatedly by 2 until you get ‘0’ as the quotient
step 2: write the remainders in the reverse order
2. Write a C++ program to calculate the volume of 1 mole of an ideal gas at STP
(Standard Temperature and Pressure = 0 °C, 1 atm)? [ Hint: PV = nRT. R = 0.08206 L.
atm. K-1 mol-1 ]
#include <iostream>
using namespace std;
int main()
{
double V;
float P = 1.0;
float n = 1.0;
float R = 0.08206;
float T = 273; // 0 degree C = 273 K
V = (n*R*T)/P;
cout << V;
return 0;
}
3. Write a C++ code to output whether a student has passed or failed a test. The
minimum mark to pass the test is 40. [Hint: you should use the “cin” command to
input the marks during runtime. Also, use “ternary conditional operator” (?:) to check
for pass or fail.]
Solution:
#include <iostream>
using namespace std;
int main()
{
double marks;
// take input from users
cout << "Enter your marks: ";
cin >> marks;
return 0;
}
OR
#include <iostream>
#include <string>
using namespace std;
int main()
{
double marks;
cout << "You " << result << " the exam.";
return 0;
}
#include <iostream>
using namespace std;
int main()
{
cout << 0++ << endl;
return 0;
}
Solution: It does not compile with the error: lvalue required as increment operand (0
must be assigned to a variable first)
5. What is the output of the program below? Does this swap the values of x and y?
#include <iostream>
using namespace std;
int main()
{
int x = 10, y = 20, z;
z = y;
y = x;
x = z;
cout << "x = " <<x << endl;
cout << "y = " <<y << endl;
return 0;
}
Solution:
x = 20;
y = 10;
#include<iostream>
using namespace std;
int main()
{
short a = 10;
// a++ returns the old value and then adds one to the value of a
cout << a++ << endl;
cout << a << endl;
a = 10;
//++a adds one to the value of a and return the new value of a
cout << ++a << endl;
cout << a << endl;
return 0;
}
Solution:
10
11
11
11