Home > Back-end >  Array assignment error in C , What is wrong with my code?
Array assignment error in C , What is wrong with my code?

Time:03-31

I am trying this code in CodeBlocks but the result is some random numbers! I appreciate if you check the code and let me know what my mistake is. It should result in multipliers of 25:

#include <iostream>

using namespace std;

main(){

    const int array_size = 10;
    int numbers[array_size];
    int counter = 0;

    while(counter < array_size){
        numbers[counter] = 25 * counter;
        counter  ;
        cout << "number[" << counter << "] = " << numbers[counter] << endl;
    }
}

Thanks in advance.

CodePudding user response:

You are incrementing counter after setting the value of numbers[counter]. After that. numbers[counter] (with the new value of counter) is a new uninitialized element.

You should move the increment after the printing:

#include <iostream>

using namespace std;

int main(){

    const int array_size = 10;
    int numbers[array_size];
    int counter = 0;

    while(counter < array_size){
        numbers[counter] = 25 * counter;
        cout << "number[" << counter << "] = " << numbers[counter] << endl;
        counter  ;
    }
}

Or simply avoid using an array (in this case):

#include <iostream>

int main(){

    const int array_size = 10;
    int counter = 0;

    while(counter < array_size){
        std::cout << "number[" << counter << "] = " << 25 * counter << std::endl;
        counter  ;
    }
}

Another way is using two loops -- one for initialization and one for printing:

#include <iostream>

using namespace std;

int main(){

    const int array_size = 10;
    int numbers[array_size];
    int counter = 0;

    while(counter < array_size){
        numbers[counter] = 25 * counter;
        counter  ;
    }

    counter = 0;
    while(counter < array_size){
        cout << "number[" << counter << "] = " << numbers[counter] << endl;
        counter  ;
    }
}

CodePudding user response:

You are outputting an uninitialized element of the array after incrementing of the variable counter.

    counter  ;
    cout << "number[" << counter << "] = " << numbers[counter] << endl;

The reason of the error is usage of an inappropriate loop.

Instead of the while loop it is better to use for loop.

For example

for ( int counter = 0; counter < array_size; counter   ){
    numbers[counter] = 25 * counter;
    cout << "number[" << counter << "] = " << numbers[counter] << endl;
}

Pay attention to that the function main without parameters shall be declared like

int main()

That is you may not omit the function return type.

CodePudding user response:

change for this code

const int array_size = 10;
    int numbers[array_size];
    int counter = 0;

    while(counter < array_size){
        numbers[counter] = 25 * counter;
        cout << "number[" << counter << "] = " << numbers[counter] << endl;
        counter  ;
    }
  • Related