Continuously spinning Servo

#include <Servo.h>

Servo myservo;

int pos = 0;
int val = 0;
int num = 0;
const int sw = 3;

void setup() {
  pinMode(sw, INPUT);
  myservo.attach(9);
  Serial.begin(9600);
}

void loop() {
  num = digitalRead(sw);
  Serial.print(num);
  
    while (num == 1) {
      
    if (val <= 3) {
      for (pos = 0; pos <180; pos += 1) {
        myservo.write(pos);
        delay(7);
      }
      for (pos = 180; pos >=0; pos -= 1) {
        myservo.write(pos);
        delay(7);
      }
      val += 1;
    } else {
      myservo.write(0);
    }
  }
}

I want the servo to stop moving after the motor has motioned back and forth three times; however, once the motor has done so it continuously spins. Also, I was wondering if someone knew how to use a button to stop a program during its loop.

Servo that have been modified for continuous rotation use different command values then unmodified servos. For your servo, myservo.write(0); will give maximum speed in one direction, myservo.write(180); will give maximum speed in the opposite direction, and myservo.write(90); should have it stop rotation. You may have to tweak the 90 value a little as there is some variation from servo to servo. You appear to be using a myservo.write(0); to try and stop your servo, so change it to 90 and test again.

Lefty