Friday, November 18, 2016

Array, Enum, Function, Typedef



In this example, we have everything we learned in chapters 7 and 8. 

You should have the breakpoints set as shown below and run the code in debugger to visualize how the array is filled and how it is processed one element at a time.

 

#include<iostream>
#include<time.h>
#include<string>
#include<iomanip>

using namespace std;

namespace zoltan{
    enum models{ TOYOTA, FORD, CHEVY, MAZDA, PORSCHE };
    enum colors{ RED, YELLOW, BLUE, BLACK };
    typedef int dealerships[PORSCHE + 1][BLACK + 1];
}
using namespace zoltan;

void fillArray(int [][BLACK+1]);
int totalColor(dealerships,colors);
int totalModel(dealerships,models);
string decodeColor(colors);
string decodeModel(models);

int main(){
    cout << "Hello Enum based Arrays" << endl;
    int dealership[5][4] = { { 2, 3, 4, 5  },
                           { 3, 4, 5, 6  },
                           { 5, 6, 7, 8  },
                           { 7, 8, 9, 10 },
                           { 1, 2, 3, 4  } };
    zoltan::dealerships richland;
    fillArray(richland);
    int color=totalColor(dealership,BLUE);
    int model=totalModel(richland,PORSCHE);
  
    cout << setw(11) << " ";
    for (colors col = RED; col <= BLACK; col = static_cast <zoltan::colors>(col + 1))
        cout <<setw(8)<< decodeColor(col);
    cout << endl;

    for (models row = TOYOTA; row <= PORSCHE; row = static_cast <models>(row + 1)){
        cout << setw(10) << decodeModel(row) << ":";
        for (colors col = RED; col <= BLACK; col = static_cast <zoltan::colors>(col + 1)){
            cout << setw(8)<<richland[row][col];
        }
        cout << endl;
    }

    return 0;
}
void fillArray(dealerships passedArray){
    srand(time(NULL));
    for (models row = TOYOTA; row <= PORSCHE; row = static_cast <models>(row + 1))
    for (colors col = RED; col <= BLACK; col = static_cast <zoltan::colors>(col + 1))   //you can use the namespace or not
        passedArray[row][col] = rand() % 50;
}
int totalColor(dealerships d, colors c){  //Process by column
    int total = 0;
    for (models row = TOYOTA; row <= PORSCHE; row = static_cast <models>(row + 1))
        total+=d[row][c];
    return total;
}
int totalModel(dealerships d, models m){  //process by row
    int total = 0;
    for (zoltan::colors col = RED; col <= BLACK; col = static_cast <zoltan::colors>(col + 1))
        total+=d[m][col];
    return total;
}

string decodeColor(colors c){
    switch (c){
        case RED: return "red";
        case YELLOW: return "yellow";
        case BLUE: return "blue";
        case BLACK: return "black";
    };
}

string decodeModel(models m){
    switch (m){
    case TOYOTA: return "toyota";
    case FORD: return "ford";
    case CHEVY: return "chevy";
    case MAZDA: return "mazda";
    case PORSCHE: return "porsche";
    }
}

No comments:

Post a Comment