Homework 5 Solution
1. With super vision you look into your computer and see that a particular
byte in memory has contents 00101011
.
If we interpret that byte as a char
,
what character does it represent? If we interpret that byte as a bool
,
what boolean value does it
represent?
00101011 = 0*27 + 0*26 + 1*25 + 0*24 +1*23 + 0*22 + 1*21 + 1*20 = 0 + 0 + 32 + 0 + 8 + 0 + 2 + 1 = 43. Looking in the ASCII chart for 43 we see it represents the character '+'. Hence if the byte of memory is interpreted as a char, the char would be '+'.
Since all 8 bits of 00101011 are not zero, if the byte of memory is interpreted as a bool, it would be true.
2. Convert each of the following binary numbers into an equivalent decimal number (base 10). Show your work.
(a) 10011101 = 1*27 + 0*26 + 0*25
+ 1*24 +1*23 + 1*22 + 0*21 + 1*20
=
128 + 0 + 0 + 16 + 8 + 4 + 0 + 1 = 157
(b) 00100101 = 0*27 + 0*26 + 1*25
+ 0*24 +0*23 + 1*22 + 0*21 + 1*20
=
0 + 0 + 32 + 0 + 0 + 4 + 0 + 1 = 37
3. Convert each of the following decimal numbers into an equivalent binary number expressed as a byte. Show your work.
(a) 77
Method 1 |
Method 2 |
77 / 27 = 0 and 77 % 27
= 77 |
77 % 2 = 1 and 77 / 2
= 38 |
(b) 253
Method 1 |
Method 2 |
253 / 27 = 1 and 253 %
27 = 125 |
253 % 2 = 1 and 253 /
2 = 126 |
4. Write a program that reads in a 3-letter word in lowercase letters and prints out the same word with the first letter capitalized. A typical run of the program should look like:
Input a 3-letter word in lowercase letters: cat
With leading letter capitalized this is : Cat
Hint look at the ASCII table and think about how to go from the ASCII value of a lowercase letter to the ASCII value of the same letter in uppercase. For example, consider the effect of the following code:
char charUpper,
charLower;
charLower = 'd';
charUpper = charLower
- 'a' + 'A';
cout << charLower << '' '' <<
charUpper << endl;
Turn in written answers to the first four questions, your source code, and a screen capture of your program running.
Solution
// KGS
// Homework 5
// This program inputs a three letter word and prints
it with the first letter capitalized.
#include <iostream>
using namespace std;
int main ()
{
// Keep prof happy
cout << "This was written by KGS." << endl;
// Prompt and get a three letter
word.
char c1, c2, c3;
cout << "Enter a three letter word all in lower case. ";
cin >> c1 >> c2
>> c3;
// Convert the first letter to
uppercase
char u1;
u1 = c1 - 'a' + 'A';
// Print the word
cout << "With leading letter capitalized this is: ";
cout << u1 << c2
<< c3 << endl;
return 0;
}