Exercise 2-9 (Three float vectors)

Chapter_2     Exercise_2-8 Exercise_2-10







Exercise 2-9     TCP1, p. 120


Exercise 2-9. Create three vector<float> objects and fill the first two as in the previous exercise (Exercise_2-8). Write a for() loop that adds each corresponding element in the first two vectors and puts the result in the corresponding element of the third vector. Display all three vectors.




vectors.cpp         download


// Creating three vectors that hold floats
#include <iostream>
#include <vector>
using std::cout;
using std::endl;
using std::vector;

int main()
{
vector<float> v1, v2, v3;

for(float f = 0.0; f < 15; f++) // iterate over float with integer values
{
v1.push_back(f/2);
v2.push_back(f/3);
}

int size = v1.size(); // 15

for(int i = 0; i < size; i++)
{v3.push_back(v1[i]+v2[i]);}

cout << "v1: ";
for(int i = 0; i < size; i++)
{
cout << v1[i] << ", ";
if (i == size/2) {cout << endl << " ";}
}
cout << endl;

cout << "v2: ";
for(int i = 0; i < size; i++)
{
cout << v2[i] << ", ";
if (i == size/2) {cout << endl << " ";}
}
cout << endl;

cout << "v3: ";
for(int i = 0; i < size; i++)
{
cout << v3[i] << ", ";
if (i == size/2) {cout << endl << " ";}
}
cout << endl;
}
/*
g++ vectors.cpp -o vectors
./vectors
v1: 0, 0.5, 1, 1.5, 2, 2.5, 3, 3.5,
4, 4.5, 5, 5.5, 6, 6.5, 7,
v2: 0, 0.333333, 0.666667, 1, 1.33333, 1.66667, 2, 2.33333,
2.66667, 3, 3.33333, 3.66667, 4, 4.33333, 4.66667,
v3: 0, 0.833333, 1.66667, 2.5, 3.33333, 4.16667, 5, 5.83333,
6.66667, 7.5, 8.33333, 9.16667, 10, 10.8333, 11.6667,
*/





Note:  v1, v2, v3 have the same size, 15.









Chapter_2     Exercise_2-8 BACK_TO_TOP Exercise_2-10



Comments

Popular posts from this blog

Contents