Companies are legal entities which exist to co-ordinate the production of the goods and services - they are where many of us work and from which we buy many of the products we consume. Wherever there are companies, there are shareholders. Shares are traded in a stock market to raise funds.
They are not the only form a business organisation can take. Government-owned companies would be called public corporations. Small businesses may be "sole traders" or partnerships, which are not companies.
A key reason for forming a company is that the shareholders of a modern company have "limited liability". This means that a shareholder can lose what they paid for their shares in a company but they are not liable for the debts of the company beyond that.
Many companies have taken the decision in the past that they want to sell shares on an open market and the largest of these companies will have their shares traded on an organised stock exchange. The benefit to companies from having their shares publicly traded is that they can issue new shares to raise capital for future investment. The only alternative source of funding would be to increase debt (by borrowing more from banks or issuing bonds). The benefit to investors from having shares traded is that they are not locked into the investment for an indefinite period. Shares held can be sold at their current market price whenever the markets are open.
The value of all shares outstanding in a company (the "market cap") is the current market value of the future profit stream that that company is expected to generate. For example, when oil prices rise sharply, investors will calculate that profits of oil companies are likely to rise in future, so prices of shares in companies like Shell and BP will jump up.
Source: Why do we need stock markets?