
Hello Zade, really nice question.
The reason the function is defined as int instead of void is that it actually produces a value â the sum. Whenever a function calculates something and you want to use that result later in the program, the function needs a return type that matches the kind of value it gives back. In this case, the sum of natural numbers is an integer, so the function returns an int.
A void function is different. It performs an action but doesnât hand anything back. For example, a function that only prints something to the screen doesnât need to return a value, so void makes sense there.
So the rule is simple:
If the function gives back a value, choose a matching return type.
If it doesnât return anything, use void.
If you have further questions, I'm here to help.
Our Experts
Sudip BhandariHead of Growth/Marketing
Apekchhya ShresthaSenior Product Manager
Kelish RaiTechnical Content Writer
Abhilekh GautamSystem Engineer
Palistha SinghTechnical Content Writer
Sarthak BaralSenior Content Editor
Saujanya Poudel
Abhay Jajodia
Nisha SharmaTechnical Content Writer
Udayan ShakyaTechnical Content Writer
