Print or return string from a for loop

Here is the question- Build a condition to check if all the numbers in the vector marks(passed as argumemts) are greater than 90. If yes, assign the string "Best Class" to the variable ans ,else assign "Needs Improvement".

This is the code i have written-

classmark<-function(marks){
 ans<- marks
 for(i in 1:length(marks)){
 if(marks[i] > 90){
         cat("Best Class")
     }
     else{
         cat("Needs Improvement")
     }
}    
return(ans)
}
print(classmark(c(100,95,94,56)))
print(classmark(c(100,95,94,96)))

Actual Output -

Best Class Best Class Best Class Needs Improvement
Best Class Best Class Best Class Best Class

Output that i got -

Best Class Best Class Best Class Needs Improvement[1] 100 95 94 56
Best Class Best Class Best Class Best Class[1] 100 95 94 96

suggest any changes that need to modify in the code to get the actual output


Solution 1:

Since you only want to print in the loop, remove the return statement from the function.

classmark<-function(marks){
  ans<- marks
  for(i in 1:length(marks)){
    if(marks[i] > 90){
      cat("Best Class\n")
    }
    else{
      cat("Needs Improvement\n")
    }
  }    
}

classmark(c(100,95,94,56))
#Best Class
#Best Class
#Best Class
#Needs Improvement

You can also use a vectorised version with ifelse which does not require for loop.

classmark<-function(marks){
 ifelse(marks > 90, "Best Class", "Needs Improvement")
}

classmark(c(100,95,94,56))
#[1] "Best Class"   "Best Class"   "Best Class"    "Needs Improvement"