[question] control Keypad input by for loop

Hi all ,
I am learning Arduino lately.
I am trying “Keypad and Password” project.
I tried to record serial keypad input by for loop:

int key =keypad.getKey();
  if (key != NO_KEY){
  Serial.println(key-48);
  }
  int pwd[key-48];
  for(int i=0;i<key-48;){
    if (key != NO_KEY){
       pwd[i]=keypad.getKey();
       i++;
    }
  }
  for(int i=0;i<key-48;i++){
    Serial.print(i);
    Serial.print(":");
    Serial.println(pwd[i]);
  }

However,ouputs always were 0 .
I found out that others used keypadEvent and password.append.
I just can’t understand why I am wrong.
Thanks

your problem is over here:

for(int i=0;i<key-48;){
    if (key != NO_KEY){

You are using key as a variable that stores the first number pressed, and use it as the length of your password. In the second part, you add the subsequent keystrokes to an array, but only if key != NO_KEY (which it is), and therefore you are getting 0’s added to the array.

Try something like this:

int tmp;
int key =keypad.getKey();
  if (key != NO_KEY){
  Serial.println(key-48);
  }
  int pwd[key-48];
  for(int i=0;i<key-48;){
     tmp = keypad.getKey();
     if (tmp != NO_KEY){
       pwd[i]=tmp;
       i++;
    }
  }
  for(int i=0;i<key-48;i++){
    Serial.print(i);
    Serial.print(":");
    Serial.println(pwd[i]);
  }