Q:

Why this code doesn't allow me to receive the whole array?

#include <bits/stdc++.h>
using namespace std;

string bin(int n){
    string x=""; 
    while(n!=0)
    {
        int z=n%2; 
        x+=to_string(z); 
        n%=2;
    }  
    return x;
}

int main(){
    int t; 
    cin>>t; 
    while(t--)
    {
        int n; 
        cin>>n; 
        int a[n]; 
        for(int i=0;i<n;i++)
        {    
            cin>>a[i]; 
            string x=bin(a[i]); 
            int u=x.size();
            int cnt=0;        
            for(int g=0;g<u;g++)
            {
                if(x[g]=='1') 
                    ++cnt; 
            }
            cout<<cnt<<' ';
       }
        cout<<'\n';
   }
}

This code is given several test cases and each test case will have an array of n integers, for each element in the array I should count the number of ones in the binary representation of it. I wrote a function that expects an integer and returns a string containing the binary representation of it. But I wonder why my code does not end, and not allowing me to receive other numbers in array.
For instance, there's one test case and and only array of 2 integers if I inputted 1 and wait for ever to enter the second number, what's happening?

A:

This is your bin function reduced to the bare minimum:
string bin(int n){
    while(n!=0)
    {
        n%=2;
    }  
    return {};
}

If n is even you will set it to 0 on the first iteration, otherwise you set it to 1 and never change it afterwards (1%2==1). Hence you have a endless loop. I won't spoil you the "fun" of completing the exercise, so I will just point you to using a debugger. If you step trough your code line by line you could have observed how n never changes and why the loop wont stop.
PS: (spoiler-alert) you might want to take a look at std::bitset (end of spoiler)

