The microcontroller can't provide enough power to light up 40 leds at the same time.
There are some limits in regards to how much power can be provided on each pin, and how much power can be provided through all pins - for example, each pin could output 10-20mA but the microcontroller may only be able to do 100-150mA through all pins.
You can use transistors or mosfets to turn on or off leds... mosfets would be better because with transistors you'd still use a bit of power (under 1mA for each transistor) to turn the transistor on and off. Note that normally you'd still have to use at least one resistor to limit the current going through the leds, you don't want to limit the current using the transistor.
If you don't want to use additional parts, you can do multiplexing ... for example see tip 2 in this collection of tips and tricks from microchip:
http://ww1.microchip.com/downloads/en/DeviceDoc/01146B.pdf You can easily expand this trick to 40 leds and to work around the limitations of the power, you can add code to turn on and off leds very fast so that at any time, only 10 or 20 out of those 40 leds are turned on.
A proper way to do it would be to use led drivers, there are chips that can control up to 16 leds.. the microcontroller simply sends a series of bits to the chip and the chip takes care of limiting current to each led and turning them on and off according to the bits you send.
Other solutions, cheaper and without complexity, that are normally used are shift registers (send stream of bits to shift register, shift register then turns on or off 8 pins to which you can connect leds) or darlington arrays like uln2003a for example (google it and read datasheet).