How to take inputs using "range based for loop"

1.1k Views Asked by At

The loop containing "cin" doesn't change the values. What is happening inside the loop? And how can I use this(range based loop) to take inputs?

INPUT:-

#include<iostream>
using namespace std;

int main()
{
    int arr[]={1,2,3,4,5};

    //with outputs/cout it work properly
    for(auto x:arr)
    {
        cout<<x<<" ";
    }
    cout<<endl;


    //Now suppose, I want to change them
    for(auto x:arr)
    {
        cin>>x;
    }

    //now again printing
    for(auto x:arr)
    {
        cout<<x<<" ";
    }
}

OUTPUT:-

1 2 3 4 5
9 8 7 6 5
1 2 3 4 5
1

There are 1 best solutions below

0
On BEST ANSWER

Its pretty simple!! we just have to use ampersand operator with the created variable.

INPUT:-

int main()
{
    int arr[4];

    //INPUT VALUES
    for(auto &x:arr)
    {
        cin>>x;
    }

    //PRINTING VALUES
    for(auto x:arr)
    {
        cout<<x<<" ";
    }
}

OUTPUT:-

1 2 3 4
1 2 3 4