Martensite is formed in the heat-affected zone (HAZ) of medium carbon steel when the cooling rate is very rapid, such as during welding. The rapid cooling prevents the formation of pearlite and austenite, causing the material to undergo a phase transformation into martensite, which is a hard and brittle structure.