There are two ways to raise the temperature of a gas: (1) heat it (2) compress it.
Heat transfer requires a temperature gradient. Consider a gas housed in a container. The gas atoms are continuously colliding with the atoms of the container’s walls. If the container is at a higher temperature than the gas, the atoms of the wall have higher average KE than the gas atoms. So during those collisions, the atoms of the wall (which are jiggling more energetically) will tend to pass on energy to the gas atoms (which are jiggling less energetically). Heat is thus transferred in this manner until thermal equilibrium is attained.
If you are compressing a gas, you’re doing work on the gas. In the topics of mechanics, you have already learnt that there is work done when a force F pushes a body through a distance Ds
Likewise, there is work done when a constant external pressure p compresses a cylinder of gas by a volume of DV. Let A be the cross-sectional area of the cylinder. The formula can be derived as follow:
If the external pressure p is not constant, then we will have to resort to . This means that the area under the p–V graph represents the work done.
But where does the work done go to? It goes into the microscopic KE of the individual gas particles!
The diagrams below depict the outcome of elastic collisions between a tiny mass and a massive mass.
As you can see, the outcome depends on whether the massive mass is stationary, moving closer, or moving away from the lighter mass. The collisions between a gas particle (tiny mass) and a piston (massive mass) are kind of similar.
If the piston is stationary, then nothing interesting is happening. Microscopically speaking, the gas particles rebound with no change in speed (after colliding with the piston), so the average KE of the gas particles is not changed. Macroscopically speaking, there is no work done on the gas since DV is zero, so the internal energy of the gas is unchanged.
On the other hand, an advancing piston can make a gas hotter. Microscopically speaking, this is because each gas particle rebounds with a speed higher than before the collision, so the average KE of the gas particles increases. Macroscopically speaking, compressing a gas results in positive work on the gas (since the external pressure p and DV are in the same direction), so the internal energy of the gas increases.
On the other hand, a retreating piston can help a gas cool down. Microscopically speaking, this is because each gas particle rebounds with a speed lower than before the collision, so the average KE of the gas particles decreases. Macroscopically speaking, allowing a gas to expand against the piston results in negative work done on the gas (since the external pressure p and DV are in opposite directions), so the internal energy of the gas decreases.
 The outcome of these collisions can be solved very easily because (1) the velocity of the massive mass is practically unchanged and (2) RSOS=RSOA.