You are here:

C++/How to sum values in a for loop

Advertisement


Question
Hello Vijayan,
    I am trying to write a program that does a Reimann sum and finds the areas of each trapezoid, but I can't figure out how to save each area calculated in the for loop. Thanks very much!

Answer
To save each of the calculated areas, use a std::vector<>
http://www.mochima.com/tutorials/vectors.html

Something like:

std::vector<double> calculated_areas ;

..... loop ....
{
       ....
       double area = ( ( y1 + y2 ) / 2.0 ) * ( x2 - x1 ) ;
       calculated_areas.push_back(area) ;  
}

If all you want is the sum of the areas, then just accumulate it in a total_area

double total_area = 0.0 ;

..... loop ....
{
       ....
       double area = ( ( y1 + y2 ) / 2.0 ) * ( x2 - x1 ) ;
       total_area += area ;
}

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


vijayan

Expertise

my primary areas of interest are generic and template metaprogramming, STL, algorithms, design patterns and c++11. i would not answer questions about gui and web programming.

Experience

about 15 years or so

Education/Credentials
post graduate engineer

©2016 About.com. All rights reserved.