How to cancel an order programmatically?

Use the cancel() or registerCancellation() method of the \Magento\Sales\Model\Order class.
The cancel() method calls the registerCancellation() method internally, and additionally makes a payment transaction for the cancellation.

See also:

how can we delete them ?