AltF4ToWin
AltF4ToWin

Reputation: 15

(C++) Specific values in an array

I'm not sure how to title my question, but here goes. I am testing some features, and I have hit a snag.

What I want to know is how can I set up a "for" or "if" statement to only put values in an array that meet a criteria? For example, find every divisor for a number, but only put factors in an array.

Any help would be loved, source code can be provided if needed :). Yes, I am new, so be gentle!

#include <iostream>
using namespace std;

int main(){
    int n;
    int counter = 1;
    cout << "What number would you like to use? ";
    cin >> n;
    int DiviArray[n];
    for (int k=0,j=1;k<n;k++,j++)
    {
        DiviArray[k] = n-k;
    }
    int k = 3;
    int factn[n];
    cout << "Factors of " << n << ": " << endl;

    for (int i=0, j=1;i<n;i++,j++)
    {
        factn[i] = n/DiviArray[i];
        if(factn[i]*DiviArray[i]==n)
        {
            cout << counter << ". " << factn[i] << " x " << DiviArray[i] << endl;
            counter++;
        }
    }
    return 0;
}

EDIT: Decided to go with vectors, not sure if I can get it to work, but thanks for the feedback guys :)

Upvotes: 1

Views: 401

Answers (2)

Ben Voigt
Ben Voigt

Reputation: 283624

Since you don't know in advance how many values will meet the condition, you should use a std::vector.

As a benefit, it keeps track of how many elements you've already added, so push_back will always use the next available index.

This also fixes

cin >> n;
int DiviArray[n];

which isn't legal C++.

Upvotes: 1

Karl Knechtel
Karl Knechtel

Reputation: 61498

If you only want to put the values into the array that match the condition, then you should only put a number into the array when the condition is matched. To do that, the statement that puts a number into the array has to be inside the if-block for the condition. I hope I don't need to explain why :)

This is the only time in your program where you actually do want two indices: one that is incremented every time through the loop (to count how many times to run the process), and one that is incremented only when you put a number in the array (to figure out where the next number goes). Everywhere else, you've created a completely useless j variable (the uselessness should be apparent from the fact that there is no code that actually uses the value, only code to set it).

Upvotes: 0

Related Questions