1

I am writing a code that takes a number as the array length and asks the user to input values into it. The problem with my code is that when I print out the values of the array it would give out random values that were never part of the array in the first place. I looked online for all of this and the code just seems right to me but for some reason it is not printing out properly.

#include <iostream>
using namespace std;

int main(){

    int x, input;

    

    cout<<"Enter the number of values: "<< endl;
    cin >> x;

    int arr[x];

    cout<<"Enter the values: "<< endl;
    for(int i = 0; i < x; i++){
        cin>>input;

        input = arr[i];
    }

    cout<<" "<< endl;

    for(int i = 0; i < x; i++){
        cout<< arr[i]<<endl;
    }

return 0;
}
2
  • 3
    not input = arr[i]; but arr[i] = input; Commented Apr 7, 2021 at 7:48
  • int arr[x]; is not standard C++. Just use std::vector for variable length array. Commented Apr 7, 2021 at 7:50

1 Answer 1

1

The problem is with this line of yours-

input = arr[i];

Here you are assigning the value of arr[i] to the input variable, in this way you never actually set the value of arr[i] and which is why it stores a grabage value. You should change it to-

arr[i] = input;

Or may be you don't need to use input variable, you can do something like-

cin >> arr[i]; // it will just take the value and assign it to arr[i]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.