Sketch 1

int trigPin = 8;
int echoPin = 9;
int distance;

void setup() {
pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
pinMode(echoPin, INPUT); // Sets the echoPin as an Input
pinMode(2, OUTPUT);
Serial.begin(9600); // Starts the serial communication
}
void loop() {
distance = getDistance();
Serial.println(distance);
delay(300);
}

int getDistance()
{
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
long duration = pulseIn(echoPin, HIGH);
int dist= duration*0.034/2;
return dist;
}

Sketch 2

int trigPin = 8;
int echoPin = 9;
int distance;

void setup() {
pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
pinMode(echoPin, INPUT); // Sets the echoPin as an Input
pinMode(2, OUTPUT);
Serial.begin(9600); // Starts the serial communication
}
void loop() {
distance = getDistance();
Serial.println(distance);
delay(300);
}

int getDistance()
{
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
long duration = pulseIn(echoPin, HIGH);
int dist= duration*0.034/2;
return dist;
}