Why does the A340 have 4 engines instead of 2?
The A340 was designed at a time when ETOPS (Extended-range Twin-engine Operational Performance Standards) had not been developed. Some airlines preferred two engines which reduced operational costs, while others preferred four engines with increased reliability at an additional cost.

Airbus decided to split the development into distinct aircraft having the same wing and airframe - A330 with two engines and A340 with four engines. 

However, as time has passed, ETOPS has become the norm with improved engine reliability, and A340 production has been stopped. Almost all the civil airliners under development now have two engines.

The Boeing 777, on the other hand, was developed with twin engine operation in mind.