"Morals" were formed because at some point in out evolution the subject of natural selection switched from the individuals to groups. What we call "morals " was beneficial and later it was incorporated into religion. As was the "us vs them" mentality and many other not so good for humanity as a whole, but useful for the group things.
Basically, in really general terms, millions of years ago two hominids (hominidae) (or even further back really) were competing for resources. One was entirely motivated by selfish impulses while the other began to develop altruistic tendencies to help his kin when it could benefit him.
The one that was able to cooperate was more successful and therefore was more likely to pass on his genes and that characteristic to the next generation, while the one with no altruistic tendencies was less likely to pass on his genes to the next generation and therefore his selfish tendencies.
However, it is important to note that our altruistic tendencies are generally present when they can benefit us in some way (directly in our interest), so people generally would not be expected to engage in completely selfless deeds.
Basically, if you expend energy on someone else with a low likelihood of energy in return or a scenario where the sum is not greater than the parts, then you would be increasing the fitness of another while decreasing your own. Those with the greater energy expended on their survival would be more likely to survive, while those with the lower energy expended would be less likely to survive.
We learned to work together for our own (selfish) benefit.
We have also developed mechanisms to deal with those who would take advantage of our altruistic tendencies while not reciprocating, which is why if you do a good dead for someone and they blatantly do not return the favor it can be so infuriating and why the majority of people tend to despise freeloaders.