lists

Let’s make it easy for me, lists are big in programming and we need them for pretty much everything we do when handling database information. From just displaying their content to adding elements or removing its elements, lists are just necessary and I don’t know what I would do without them. According to Scratchwiki:

list (also called an array in other programming languages) is a tool that can be used to store multiple pieces of information at once. It can also be defined as a variable containing multiple other variables. A list consists of a numbers paired with items. Each item can be retrieved by its paired number.

With that being said, I will let you have an example that I needed to create during one of my college classes. Getting used to them is not that hard as long as you learn the basic stuff; what data type you need?; how many elements does your list needs?; do you need to remove them after certain action?, etc.

You can test this program in my repl,

// Kevin. Array vs Vector
// Income Calculator using C++ v.11 10/29/2019
#include <iostream>
#include <vector>
#include <algorithm> // sort && reverse
#include <iomanip> // for setprecision
#include <numeric>

using namespace std;

// Prototypes
void arrayBank(double array[], int sizeOfArray);
void vectorBank(vector  &vect);


// Definitions
void arrayBank(double array[], int sizeOfArray) {

  double sum = 0.0;
  
  sort(array, array+sizeOfArray); // Sort it 
  reverse(array, array+sizeOfArray); // Reverse it
  cout << "\nArray Output" << endl;
  for(int i = 0; i < sizeOfArray; i++){
    cout << fixed << setprecision(2) << "$" << array[i] << endl;
    // Sum
    sum += array[i];
  }

  cout << "Your total deposit should be " << fixed << setprecision(2) << "$" << sum << endl;

};

void vectorBank(vector  &vect){
  
  double sum = 0.0;

  sort(vect.begin(), vect.end());
  reverse(vect.begin(), vect.end());
  cout << "\nVector Output" << endl;
  sum = accumulate(vect.begin(), vect.end(), 0.0);
  for(double x : vect) {
    cout << fixed << setprecision(2) << "$" << x << endl;
    // sum += x;
  }

  cout << "Your total deposit should be " << fixed << setprecision(2) << "$" << sum << endl;

}

int main() {
  // This is Array style
  double makeBankArray[6] = { 800.77, 4276.24, 2000, 1345.21, 300.00 };
  makeBankArray[5] = 500.00;

  arrayBank(makeBankArray, 6);

  // This is Vector style
  vector makeBankVector {800.77, 4276.24, 2000, 1345.21, 300.00};
  makeBankVector.push_back(500.00);

  vectorBank(makeBankVector);

  return 0;
}

That is it, don’t forget to share it with your friends in you have found it useful!.

In case you have any interets on C++, you can check my articles here

Leave a Reply

Back to Top