Lucky Four, C++

theres a problem when im trying to output the value of an array and it always at the last index, please help T_T. Im using C++.

SC:

#include
using namespace std;

int main() {
int t;
cin >> t;
int n[t];

for (int i=0; i<t; i++){
    cin >> n[i];
}

int j=0;
int check=0;
int tot[t];
while (n[j]!=0 && j<t){
    if (n[j] % 10 == 4){
        check ++;
        tot[j] = check;
    }
    n[j] = n[j] / 10;
    if (n[j] == 0){
        j++;
        check = 0;
    }
}
for (int i=0; i<t; i++){
    cout << tot[i] << endl;
}

}

Could you link the problem and format your code and say what the actual issue is

2 Likes

Problem : LUCKFOUR Problem - CodeChef
SC : CodeChef: Practical coding for everyone

The output at the last index of array is some random number

sorry, im quite new so i dont really understand to use this discussion forum properly

Isn’t there a globally pinned post that helps you with how to ask a question?

1 Like

Okay, first things first. I highly, highly, highly recommend not handling all the test cases at once. For example, my code for this problem would look something like this:

code
// magical header file that has EVERYTHING
#include <bits/stdc++.h> 

using namespace std;

// handle each test case separately
void solve() {
  int n;
  cin >> n;
  int nfours = 0;
  while (n > 0) {
    if (n % 10 == 4) ++nfours;
    n /= 10;
  }
  cout << nfours << '\n';
}

int main() {
  int T;
  cin >> T;
  for (int tc = 0; tc < T; tc++) solve();
}

where I process each test case and output its answer before moving on to the next one. Sometimes it’s better not to do it this way, but almost always it’s a good idea.

Now. You get a garbage value because you haven’t initialized the values of tot (I guess it’s explained here). Set them all to 0 initially and you’ll get what you want.

2 Likes

don’t Do anything ,just use string instead of integer to take input, and count everytime the four occurs .U can use STL count(str.begin(),str.end(),‘4’).
#include<bits/stdc++.h>
using namespace std;
int main()
{
int t;
cin>>t;
for(int i=0;i<t;i++)
{
string str;
cin>>str;
cout<<count(str.begin(),str.end(),‘4’)<<"\n";
}
}

Yes, that will fix their problem, but only accidentally