0

I am confused about the code below

++counts[number-1];

What is the purpose of subtracting 1 in this code?

The entire code:

#include <iostream>
#include <iomanip>
#include <ctime>
#include <cstdlib>
#include <fstream>

using namespace std;

int main(){
   srand(time(0));
   const int MAX = 100;
   int totals = 0;
   int randoms[MAX];
   int counts[6] = {0};
   string values[6] = {"ones","twos","threes", "fours","fives","sixes"};

ifstream inFile;
inFile.open("random3.txt");
if(inFile)
    for(int i = 0; i < MAX; i++)
        inFile>>randoms[i];
else{
    cout<<"file not found, creating randoms"<<endl;
    for(int i = 0; i < MAX; i++)
        randoms[i] = 1+rand()%6;
}   
inFile.close();
for(int number : randoms){
    ++counts[number-1];
}

for(int i = 0; i < 6; i++){
    cout<<"\n"<<values[i]<<"\t"<<counts[i];
    totals+=counts[i];
}
cout<<"\ntotals\t"<<totals<<endl;
ofstream outFile;
outFile.open("random2.txt");
for(int num : randoms)
    outFile<<num<<endl;
outFile.close();
return 0;
}
1

This question is nearly impossible to answer without context. It all depends on what number represents and how it's being used.

Having said that, one thing comes to mind. Say that number is being used to count through a list of some kind and the numbers run from 1 to 5. Now, you have this array, called counts. Arrays are numbered starting at 0, not 1. So, the counts for the 1st item would be stored in counts[0], not counts[1]. Subtracting 1 would correlate the array element to the correct item being counted.

There could be a totally different reason, but this is the one that makes the most sense to me. Without seeing the related code and knowing what it was being used for, there's really no way to answer.

| improve this answer | |

Not the answer you're looking for? Browse other questions tagged .