If you check Bitcoin on coinmarketcap website, you will notice that there will only be a maximum supply of 21 million bitcoins. So where does this 21 million bitcoin number come from?
Each time a miner mines a block, they get bitcoin as a reward. The reward halves ever 210000 blocks mined successfully. This comes from the following piece of code which is currently located in validation.cpp file.
Note: consensusParams.nSubsidyHalvingInterval is defined in the chainparams.cpp with a value of 210000.
From the above code you will notice that the subsidy is halved every 210000 blocks. Therefore with a little help from excel, we can work out the maximum number of coins that will exist when reward/block approaches zero.
As bitcoin reward/block approaches zero, the total bitcoins turns out to be close to 21 million.
From the code we can also get a rough estimation when we will reach the max cap of 21 million bitcoins. Based on reward halving every 4 years and bitcoin network coming into existence in 2009, we will reach 21 million cap in 2141.
NOTE: The above table does not take into account increase in mining power. Therefore the year when last bitcoin will be mined could be less than 2141.