How to stop a program during executation?

Hello, on the Mega, how do I stop a program while it is being executed? Will I damage the hardware if I just turn off the power switches and in some cases also the usb cable connecting to my computer?

Power switches are meant to be turned off, and you can do so safely on the Arduino. It is also safe to unplug the USB cable.

On computer systems, we need to unmount the storage drive first. How about Arduino and sd card? While the program is doing data logging, will I damage the sd card if I physically removing it?

I doubt you will physically damage it. But you have a good chance on corrupted data if you're constantly writing and you remove the card during a write.

Yes you will, or rather can damage the SD card if it or the power is removed during access.
There is nothing to stop this unless you write it into your code.

How to stop it in program? Is there a sample code? Somewhere I read that I should use the close command to close the log file at the end of the execution of the program. However, I do data logging in the loop (i.e. void loop()). Thus, I cannot put a close statement inside the loop.

Can't you add a toggle switch (or removable jumper, or serial command, or . . . ) to indicate that you've finished logging, and that you want to close the file?

You can stop code with:-

while(1){}

This puts it into an infinite loop which will never end, in effect stopping the code from doing anything.

Grumpy_Mike:
You can stop code with:-

while(1){}

This puts it into an infinite loop which will never end, in effect stopping the code from doing anything.

I open the file in setup(). Given that I collect data inside the void loop() loop, where should I put it?

Wherever it is you want to stop execution.
(It doesn't actually stop anything, it just puts the processor into infinite thumb-twiddling mode)

Given that I collect data inside the void loop() loop, where should I put it?

After an if statement that checks the switch or button that you press if you want to stop the code.