TOC PREV NEXT INDEX

C++: A Dialog


4.8. Exercises


So that you can test your understanding of this material, here are some exercises.
1. If the program in Figure 4.19 is run, what will be displayed?
FIGURE 4.19. Exercise 1 (code\morbas00.cpp)
#include <iostream>
#include "Vec.h"
using namespace std;

int main()
{
Vec<short> x(5);
short Result;
short i;

for (i = 0; i < 5; i ++)
{
x[i] = 2 * i;
}

for (i = 0; i < 5; i ++)
{
Result = Result + x[i];
}

cout << Result << endl;

return 0;
}
2. If the program in Figure 4.20 is run, what will be displayed?
FIGURE 4.20. Exercise 2 (code\morbas01.cpp)
#include <iostream>
#include "Vec.h"
using namespace std;

int main()
{
Vec<short> x(4);
short Result;
short i;

x[0] = 3;
for (i = 1; i < 4; i ++)
x[i] = x[i-1] * 2;

Result = 0;
for (i = 0; i < 4; i ++)
Result = Result + x[i];

cout << Result << endl;

return 0;
}
3. Write a program that asks the user to type in a weight, and display the weight on the screen.
4. Modify the program from exercise 3 to ask the user to type as many weights as desired, stopping as soon as a 0 is entered. Add up all of the weights entered and display the total on the screen at the end of the program.
Answers to exercises can be found at the end of the chapter.

www.steveheller.com
steve@steveheller.com
TOC PREV NEXT INDEX