Ernesto
Ernesto

Reputation: 295

Calling a function through a for loop

Forgive my English and my ignorance (Also, I have searched a lot and could not find this question answered).

I have a program that has 5 integer variables with the creative names of "num1" through "num5". I have a secondary function that requires two parameters, the first parameter is a number, 1-5, while the second parameter is the value of the variables num1 through num5 (If it helps you conceptualize, I am counting the number of words of specific lengths within a single user entry).

For example, if a user enters the phrase "The black cat ate a fried fish for lunch" the values would be:

num1 = 1 (a)
num2 = 0
num3 = 4 (the, cat, ate, for)
num4 = 1 (fish)
num5 = 3 (black, fried, lunch)

My code looks like this for the most part (I am only posting the applicable parts, so assume that the num1-num5 variables have been given values elsewhere):

int main()
{
    int num1, num2, num3, num4, num5;

    printCount(1, num1);
    printCount(2, num2);
    printCount(3, num3);
    printCount(4, num4);
    printCount(5, num5);
}

void printCount(int numberLetters, int numberWords)
{
    cout << numberLetters << "-letter words: " << numberWords << endl;
}

I am trying to find a way to avoid 5 lines of code calling printCount(), but I cannot find a way to have the second parameter change with a loop. Is there a way to handle this using very simple methods?

Upvotes: 2

Views: 73

Answers (3)

boriaz50
boriaz50

Reputation: 858

Use an array:

int nums[5];

// initialize array elements

for (int i = 0; i < 5; i++)
{
    printCount(i + 1, nums[i]);
}

But also you need to pass words.

And what if sentence contains words with more than 5 letters? So using fixed-size array is not the flexible way.

I suggest you to create a function with the following prototype. Function takes std::string and returns extracted words:

vector<vector<string>> extractWords(const string& sentence);

Function would return vector of vectors. Every inner vector would contain the words with the same length. Read about std::vector.

Upvotes: 2

U.Malik
U.Malik

Reputation: 111

Just modify main function by adding loop.

    int main()
        {
            int num1, num2, num3, num4, num5;
           int arr1[5] = {1,2,3,4,5};
           int arr2[5] = {num1,num2,num3,num4,num5};
           for(int i = 0 ; i <=sizeof(arr1)-1 li++){
                printCount(arr1[i], arr2[i]);
         }      

}

Upvotes: 0

frslm
frslm

Reputation: 2978

Very simply, you need an array. This is what your main() function might look like using one:

int num[5];

for (int i = 0; i < 5; i++) {
    printCount(i+1, num[i]);
}

Upvotes: 1

Related Questions