Exercise 2-8 (Floatvector)

Chapter_2     Exercise_2-7     Intvector Exercise_2-9







Exercise 2-8     TCP1, p. 120


Exercise 2-8. Create a vector<float> and put 25 floating-point numbers into it using a for() loop. Display the vector.




Floatvector.cpp         download


// Creating a vector that holds floats
#include <iostream>
#include <vector>
using std::cout;
using std::endl;
using std::vector;

int main()
{
vector<float> v;

for(float f = 0.0; f < 25; f++) // iterate over float with integer values
{v.push_back(f/2);}

for(int i = 0, size = v.size(); i < size; i++) // iterate over integer i
{
cout << v[i] << ", ";
if (i == size/2) {cout << endl;}
}
cout << endl;
}
/*
g++ Floatvector.cpp -o Floatvector
./Floatvector
0, 0.5, 1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5, 5, 5.5, 6,
6.5, 7, 7.5, 8, 8.5, 9, 9.5, 10, 10.5, 11, 11.5, 12,
*/





Note:  Inside the second for() loop, the function call v.size() is executed only once, when the integer size is initialized.









Chapter_2     Exercise_2-7     Intvector BACK_TO_TOP Exercise_2-9



Comments

Popular posts from this blog

Contents