What is the diffrrence between if statement and while loop ?

So i have a code that counts whenever i push a button then leave it :

int s;
int x;
void setup() {
Serial.begin(9600);
pinMode(2,INPUT);

}

void loop() {
while(digitalRead(2)==HIGH){
s=1;}

if(s==1){
x++;
Serial.println(x);
s=0;
}

}

So why doesn't if work here instead of while in the 1st line after void loop?(when i use if it keeps just counting while i am pushing the button )
and why does both of them work in the 3rd line?

The while() statement is true as long as you are pushing the button. When a while statement is true, the body will be executed and then the condition will be checked again. This continues until the condition is not true (you are not pushing the button).

An if() statement only checks the condition once and then either does or does not execute its body.

here's an example of using the two together. this code detects a button being pressed and times how long the button is pressed. sometimes while-loops are good, other times they're bad because they're a blocking code and will prevent other code from being executed "while" the conditions are true.

byte button = 2;

void setup() {
  Serial.begin(9600);

  pinMode(button, INPUT_PULLUP);
}

void loop() {

  if (digitalRead(button)==0){

    unsigned long tic = millis();

    while (digitalRead(button)==0){
      unsigned long toc = millis() - tic;
    }

    Serial.println(toc);
  }

}

Thanks for the reply guys :).