CIS 122: Assignment #1 Solution

Posted on July 31 2005

Problem:

1.(20 points) What output will the following code fragments produce? Provide the answers exactly as the output.

(a)
num = 10;
x = 5;
cout << num << " ";
cout << x << " ";
cout << endl;
cout << num << endl;
Answer:
10 5
10
(b)
x = 4;
y = 14;
y = y + x;
x = x + 1;
cout << "x = " << x << '\n';
cout << "y = " << y << '\n';
Answer:
x = 5
y = 18
2.(40 points) The c++ program provided below contains several errors, find them out. Provide the c++ program after correction. Only change the parts with errors.
/************************
 * first.cpp
 * My First C++ file
 * July 18, 2005
 *************************/

main()
{
	int num1;
	int 2ndNum = 3;

	cout >> 'Can I make it all right? \n'

	num1 = 11;
	num_3 = 2ndNum;

	cout >> num1 >> " " >> 2ndNum >> " " >> num3 >> "\n";

}


Answer:
/************************
 * first.cpp
 * My First C++ file
 * July 18, 2005
 *************************/

#include <iostream>
using namespace std;

int main()
{
	int num1;
	int SecondNum = 3;
	int num_3 = 0;

	cout << "Can I make it all right? \n";

	num1 = 11;
	num_3 = SecondNum;

	cout << num1 << " " << SecondNum << " " << num_3 << '\n';

	return 0;

}
3. (40 points)Do the "Critical Thinking" part of Page 45 in your text book. For extra credits (10 points), do
  1. Add a statement that declares 3 float type variables E, F, and G in a single statment, and initialize them to be 3.32, 4.45, and 6.61.
  2. Add a statement to declare an integer named age as an unsigned short. Initialize it to be any number you like, but within the range of unsigned short.
  3. Print E, F, and G to the screen such that the output is one line as "E = 3.32, F = 4.45, G = 6.61".
  4. Print age to the screen such that the output has the format like "My cat Kitty is 3 years old", if the variable age has a value 3.

Compile and run your program, Correct any errors you have made.

Submit the final program fulfilling all the requirements, and also the output.

Answer:
/************************
 * Question 3, Assignment 1
 *
 * July 18, 2005
 *************************/

#include <iostream>
using namespace std;

int main()
{

	const int A = 1;
	const float B = 2.2;
	int C;
	float D;

	float E = 3.32, F = 4.45, G = 6.61;

	unsigned short age = 11;

	C = A;
	D = B;

	cout << "C = " << C << endl;
	cout << "D = " << D << endl;

	cout << "E = " << E << ", " << "F = " << F << ", " << "G = " << G << endl;

	cout << "My nephew Jeremey is " << age << " years old." << endl;

	return 0;

}

Dan Rao
Last modified: Sun Jul 31 15:15:03 PDT 2005