filmov
tv
Find the sum of first 10 natural numbers || Java Programming || Core java

Показать описание
In this video I've discussed about how to find the sum of first 10 natural numbers.
We know that natural numbers start from 1
So the initial value of i is 1
We are taking sum as a variable inorder to store the total sum of the first 10 natural numbers.
Q. Till when does the loop execute?
As the condition in the for loop becomes false, the control of the program will exit the loop and next statement is executed.
Q. Why sum is written outside the loop and not inside the loop?
We write the sum variable outside the loop so that the value of sum changing in each iteration does not reset to 0.
Q. Why is the initial value of sum 0 and not 1?
0 has to be the initial value of sum before starting the iteration.
If initially the value of sum is 1 then we would get the output as 56 which is mathematically wrong.
Q. Can't we directly store the total sum as int sum = sum + i?
In java, declaration and using += to update the value in the same line is not allowed. You can use += only after the variable has been initialized.
I hope you have understood the program.
Subscribe to our channel
Thank you and keep watching
We know that natural numbers start from 1
So the initial value of i is 1
We are taking sum as a variable inorder to store the total sum of the first 10 natural numbers.
Q. Till when does the loop execute?
As the condition in the for loop becomes false, the control of the program will exit the loop and next statement is executed.
Q. Why sum is written outside the loop and not inside the loop?
We write the sum variable outside the loop so that the value of sum changing in each iteration does not reset to 0.
Q. Why is the initial value of sum 0 and not 1?
0 has to be the initial value of sum before starting the iteration.
If initially the value of sum is 1 then we would get the output as 56 which is mathematically wrong.
Q. Can't we directly store the total sum as int sum = sum + i?
In java, declaration and using += to update the value in the same line is not allowed. You can use += only after the variable has been initialized.
I hope you have understood the program.
Subscribe to our channel
Thank you and keep watching