Search code examples
c++arraysfor-loopif-statementcoding-style

Condensing for 5 for-loops that display an array into 1?


Is there a way to condense five for-loops into one and have them display different variables and letters for each? Currently, I have one loop with five other loops and if/else to keep it condense, but this seems redundant and defeats the very purpose of making the loop.

So I decided to post the whole source code so people can understand what I am trying to get at more. This is a program that creates 100 random grades everytime it runs and I have to sort them, then display them. I am aware I could do 5 for loops, but I want to write code that is more condensed and efficient.

The hard part is writing a loop that can display 5 arrays consistently even though the size of the array changes every run.

#include <iostream>
#include <vector>
using namespace std;

int main(){
    int grades[100];
    int sizeA=0, sizeB=0, sizeC=0, sizeD=0, sizeF=0;
    std::vector<int> gradeA, gradeB, gradeC, gradeD, gradeF;

    srand(time(NULL));

    for(int i = 0; i < 100; i++){
        grades[i] = rand() % 100 + 1;  
    }

    for(int i = 0; i < 100; i++){
        if (grades[i] < 100 || grades[i] > 0){
            if (grades[i]>=90)
                gradeA.push_back(grades[i]);
            else if (grades[i]>=70)
                gradeB.push_back(grades[i]);
            else if (grades[i]>=50)
                gradeC.push_back(grades[i]);
            else if (grades[i]>=20)
                gradeD.push_back(grades[i]);
            else if (grades[i])
                gradeF.push_back(grades[i]);
        } else {
            cout << "uhh.. ";
            return(0);
        }
    }

    sizeA = gradeA.size();
    sizeB = gradeB.size();
    sizeC = gradeC.size();
    sizeD = gradeD.size();
    sizeF = gradeF.size();


    /**toggle ? showgrades(gradeA, size) : (int?)null;**/

}   

Solution

  • How about using a function to do the looping and call it with the required information

    void printGrades(const std::vector<int>& grades, char level) {
      cout << num << " " << level << " students: ";
      for(int i = 0; i < grades.size(); i++){
        cout << grades[i] << " ";
      cout << endl;
    }
    

    So when you want to print them all:

    printGrades(gradeA, 'A');
    printGrades(gradeB, 'B');
    printGrades(gradeC, 'C');
    printGrades(gradeD, 'D');
    printGrades(gradeF, 'F');