Course
Data Frames
Convert a List to a DataframeCreate an Empty DataframeCombine Two Dataframe into OneChange Column Name of a DataframeExtract Columns From a DataframeDrop Columns in a DataframeReorder Columns in a DataframeSplit DataframeMerge Multiple DataframesDelete Rows From DataframeMake a List of DataframesIntroduction
"Hello World" ProgramAdd Two VectorsFind Sum, Mean and Product of Vector in R ProgrammingTake Input From UserGenerate Random Number from Standard DistributionsSample from a PopulationFind Minimum and MaximumSort a VectorStrings
Concatenate Two StringsFind the Length of a StringCheck if Characters are Present in a StringExtract n Characters From a StringReplace Characters in a StringCompare two StringsConvert Factors to CharactersTrim Leading and Trailing WhitespacesVectors
Concatenate a Vector of StringsCheck if a Vector Contains the Given ElementCount the Number of Elements in a VectorFind Index of an Element in a VectorAccess Values in a VectorAdd Leading Zeros to VectorR Program to Find the Sum of Natural Numbers
Example 1: Find sum of natural numbers without formula
# take input from the user
num = as.integer(readline(prompt = "Enter a number: "))
if(num < 0) {
print("Enter a positive number")
} else {
sum = 0
# use while loop to iterate until zero
while(num > 0) {
sum = sum + num
num = num - 1
}
print(paste("The sum is", sum))
}
Output
Enter a number: 10
[1] "The sum is 55"
Here, we ask the user for a number and display the sum of natural numbers upto that number.
We use while loop to iterate until the number becomes zero. On each iteration, we add the number num to sum, which gives the total sum in the end.
We could have solved the above problem without using any loops using a formula.
From mathematics, we know that sum of natural numbers is given by
n*(n+1)/2
For example, if n = 10, the sum would be (10*11)/2 = 55.
Example 2: Find sum of natural numbers using a formula
# take input from the user
num = as.integer(readline(prompt = "Enter a number: "))
if(num < 0) {
print("Enter a positive number")
} else {
sum = (num * (num + 1)) / 2;
print(paste("The sum is", sum))
}
Output
Enter a number: 10
[1] "The sum is 55"