Introduction to Programming (22C:16, 22C:106)

Solution to Homework 3

Problem 1:

 
	 void sumSubnum(long int n)
	 {
		 long int sum = 0;
		 while (n >= 10)
		 {
			 sum = sum + n % 100;
			 n = n / 10;
		 }
		 cout << "The sum of the 2-digit subnumbers is " << sum << endl;
	 }

Problem 2:

 
	 void interact()
	 {
		 string response;
		 long int n;
		 cout << "Would you like to type a positive integer [YES or NO]?" << endl;
		 cin >> response;
		 while (response == "YES")
		 {
			 cout << "Please type a positive integer: ";
			 cin >> n;
			 sumSubnum(n);
			 cout << "Would you like to type a positive integer [YES or NO]?" << endl;
			 cin >> response;
		 }
	 }

Problem 3:

3.5
Because first the subexpression ifahr - 32 is evaluated. Then the subexpression 5/9 is evaluated. This subexpression evaluates to 0 (note the integer division) and therefore the entire expression evaluates to 0. This does not change if we replace ifahr by dfahr.

3.6
Assuming that 40 is typed in response to the first prompt from Program 3.2, the expression ifahr - 32 * 5 / 9 is evaluated as follows:
 
		40 - 32 * 5 / 9
		= 40 - 160 / 9
		= 40 - 17
		= 23
If we type 40 in response to the second prompt from the program, the answer does not change much - the expression evaluates in the same way to 23.0.

3.7
Assuming that 40 is typed in response to the first prompt from Program 3.2, the expression (ifahr - 32.0) * 5 / 9 is evaluated as follows:
 
		(40 - 32.0) * 5 / 9
		= 8.0 * 5 / 9
		= 40.0 / 9
		= 4.4444

3.10
The expression (8 + 4) / 2 * 2 is evaluated as follows:
 
		(8 + 4) / 2 * 2
		= 12 / 2 * 2
		= 6 * 2
		= 12

The other expression (8 - 4) / 2 * 2 evaluates in a similar manner to 4.



Sriram Pemmaraju
Mon Feb 17 13:12:39 CST 1997