Button state changing between 1 and 0 constantly

const int button = 2;

int buttonState = 0;

void setup() {
Serial.begin(9600);
pinMode(button, INPUT);

}

void loop()
{

buttonState = digitalRead(button);
Serial.println(buttonState);

}

when i press the button, the state is 1 but when i release it, his state changes between 0 and 1
Thank you.

Try

pinMode(button, INPUT_PULLUP);

I tried.
The state stays at 1 even if i press the button

How is your button wired? Is it wired to provide + or GND to the input when pressed?

You wired the button incorrectly, there shouldn't be a resistor in series with it.
Connect one leg of the button to ground, the other to the input pin of the Arduino. Then use INPUT_PULLUP.
Fix the logic to interpret a "low" signal as "pressed", "high" as "released".

Pieter

thank you a lot

PieterP:
You wired the button incorrectly, there shouldn't be a resistor in series with it.
Connect one leg of the button to ground, the other to the input pin of the Arduino. Then use INPUT_PULLUP.
Fix the logic to interpret a "low" signal as "pressed", "high" as "released".

Pieter

or what he said. It is way easier to use GND as the active input otherwise if you use + you need an external pull-down resistor.

This post may be useful for you https://forum.arduino.cc/index.php?topic=643756.0