//This program is intended to demonstrate simple serial programming where a vectors element gets modified serially.
//
#include <iostream>
#include <vector>
#include <cmath>
using std::cout;
using std::endl;
using std::vector;
void increase_magnitude(float *starting_address,unsigned int size_vec, float mag_multiplyer)
{
//the variable *starting_address is a pointer which will point to (or contain address of), the first element of the array.
for (int i=0;i<size_vec;i++)
{
*starting_address=*starting_address * mag_multiplyer;
starting_address+=1;
}
//in this way at the same memory location we will have modified the vector.
}
double magnitude_finder(float *starting_address_vec,unsigned int size)
{
//This function will return the magnitude of the vector.
double sum=0.0;
for (int i=0;i<size;i++)
{
sum+=pow((*starting_address_vec),2);
starting_address_vec+=1;
}
return pow(sum,0.5);
}
int main(int argc, char *argv[])
{
unsigned int N=1<<31; //the number implies 31 zeroes in front of 1. So it is 2^31.
vector<float> vec; //whenever we declare an vector, it has undefined size(if we don't provide the size). Unless we declare it with some size.
//let us fill the vector with N natural numbers(1,2,.......N).
for (int i=0;i<N;i++)
{
vec.push_back(i);
}
//let us define a pointer to integer vector
float *ptr_to_vec=&vec[0]; //giving address of first element. Or we can just write:
//we shall modify the vector by multiply it with some real number.
//Real numbers are stored in float data types(require 4byte per real number) and double data types(8bytes).
float multiplier=4.0;
//Let us find the magnitude before changing the vector,
double mag_before=magnitude_finder(ptr_to_vec,N);
increase_magnitude(ptr_to_vec,N,multiplier);
double mag_after=magnitude_finder(ptr_to_vec,N);
double ratio_of_magnitudes=mag_after/mag_before;
printf("Value of magnitude before multiplying the vector is %0.f \n",mag_before);
printf("Value of magnitude after multiplying the vector is %0.f \n",mag_after);
cout<<"the final vector has magnitude "<<ratio_of_magnitudes<<" times the earlier one"<<endl<<"which should be equal to the multiplier (which is: "<<multiplier<<")"<<endl;
return 0;
}
Output:
```
Value of magnitude before multiplying the vector is 57455839005302
Value of magnitude after multiplying the vector is 229823356021209
the final vector has magnitude 4 times the earlier one
which should be equal to the multiplier (which is: 4)
real 3m8.202s
user 2m59.683s
sys 0m6.290s
```
Remarks: we can have a look at the time it takes for different parts of the code