Thursday, January 19, 2023

Penggunaan Pengulangan ( Loops ) Pada Programming-R

 


Penggunaan Pengulangan ( Loops ) :

1. For Loop 

Format :

for (value in vector) {  

   statements  


Contoh 1 :

# Create fruit vector  

fruit <- c('Apple', 'Orange',"Guava", 'Pinapple', 'Banana','Grapes')  

# Create the for statement  

for ( i in fruit){   

    print(i)  


Contoh 2 :

# Creating an empty list  

list <- c()  

# Creating a for statement to populate the list  

for (i in seq(1, 5, by=1)) {  

  list[[i]] <- i*i  

}  

print(list)    


Contoh 3 :

# Creating a matrix  

mat <- matrix(data = seq(10, 21, by=1), nrow = 6, ncol =2)  

# Creating the loop with r and c to iterate over the matrix  

for (r in 1:nrow(mat))     

    for (c in 1:ncol(mat))    

         print(paste("mat[", r, ",",c, "]=", mat[r,c]))   

print(mat)


2. Repeat Loop

Format :

repeat {   

   commands   

   if(condition) {  

      break  

   }  

}


Contoh 1 :

v <- c("Hello","repeat","loop")  

cnt <- 2  

repeat {  

   print(v)  

   cnt <- cnt+1  

     

   if(cnt > 5) {  

      break  

   }  


Contoh 2 :

a <- 1            

repeat {      

  if(a == 10)    

    break    

  if(a == 7){    

    aa=a+1  

    next       

  }  

  print(a)    

  a <- a+1      

}


3. While Loop

Format :

while (test_expression) {  

   statement  

}


Contoh 1 :

v <- c("Hello","while loop","example")  

cnt <- 2  

while (cnt < 7) {  

   print(v)  

   cntcnt = cnt + 1  

}}


Contoh 2 :

n <- readline(prompt="Masukan nilai : ")  

n <- as.integer(n)  

num<-n  

rev<-0  

while(n!=0){  

    rem<-n%%10  

    rev<-rem+(rev*10)  

    n<-as.integer(n/10)  

}  

print(rev)  

if(rev==num){  

    cat(num,"is a palindrome num")  

}else{  

    cat(num,"is not a palindrome number")  

}


Memunculkan Simbol & Emoji Pada OS Mac

  Memunculkan Simbol & Emoji  1. Buka aplikasi Pages / Notes pada Macbook. 2. Klik pada Menubar Edit --> Pilih Emoji and Symbols a...