In this program, You will learn how to print the sum of the first 10 natural numbers in R.
Example: How to print the sum of the first 10 natural numbers in R
1 2 3 4 5 6 7 8 | sum = 0 for (num in 1:10) { sum = sum + num } print(paste("Sum of first 10 natural numbers is :", sum)) |
The output of this program would be:
1 2 3 | [1] "Sum of first 10 natural numbers is : 55" |
This program calculates the sum of the first 10 natural numbers (1, 2, 3, 4, 5, 6, 7, 8, 9, 10) and prints the result to the console.
The for
loop iterates over the sequence of numbers from 1 to 10, and on each iteration, the value of num
is updated to the current number in the sequence. The variable sum
is initialized to 0 before the loop begins, and on each iteration of the loop, the value of sum
is updated to be the current value of sum
plus the current value of num
.
After the loop completes, the final value of sum
is printed to the console using the print()
function. In this case, the final value of sum
is 55, which is the sum of the first 10 natural numbers.