Search code examples
c++for-loopvectorcountinginteger-division

Im trying to create a a code that count numbers divisible by 9 by putting numbers into an array and count the numbers in it


Im trying to create a a code that count numbers divisible by 9 by putting numbers into an array and count the numbers in it but it only prints 1 instead of the number of numbers divisible by 9 please help me i want to use array to count those numbers

#include <iostream>
using namespace std;
int main(){
    int a,b,i;
    int numbers[]={i};
    cin >>a>>b;
    for (i=a; i<=b; i++)
        if (i%9==0){
            cout << sizeof(numbers)/sizeof(numbers[0]);
        }        
}

Solution

  • Nowhere in your code are you adding numbers to the array. Anyhow, it is not possible to add elements to arrays, because they are of fixed size. Your array has a single element.

    Moreover, int numbers[]={i}; is undefined, because i has not been initialized.

    Further, it is not clear what is the purpose of sizeof(numbers)/sizeof(numbers[0]) in your code. sizeof(numbers) is the size of a single int because the array has a single element. sizeof(numbers[0]) is the size of a single int as well. Hence the result is 1 always. (Its a compile time constant btw.)

    If you want to count how many numbers fullfil some condition you best use a counter and print its value after the loop:

    #include <iostream>
    
    int main(){
        int a,b;
    
        cin >> a >> b;
        unsigned counter = 0;
        for (int i=a; i<=b; i++) {
            if (i%9==0){
                ++counter;
            }
        }
        std::cout << counter;
    }
    

    i want to use array for my learning porpuses please help me

    You chose the wrong example to train working with arrays, because as already mentioned, arrays have fixed size. It is an opportunity to learn about std::vector. You can add elements to a std::vector at runtime and query its size:

    #include <iostream>
    #include <vector>
    
    int main(){
        int a,b;
        std::vector<int> by9divisables;
        std::cin >> a >> b;
        for (int i=a; i<=b; i++) {
            if (i%9==0) {
                by9divisables.push_back(i);
            }
        }
        std::cout << by9divisables.size();
    }
    

    However, other than to see how std::vector is working, the vector has no place in this code. As you can see above, the result can be obtained without it.