Practicum Week 4 ~ Syntax and Control Flow

logo week 10

Nazwa Nur Ramadhani

Undergraduate Student in Data Science at Institut Teknologi Sains Bandung

Introduction

Syntax and control flow are fundamental concepts in programming that determine how a program is written and how it executes instructions. Syntax refers to the rules and structure that must be followed when writing code, while control flow manages the order in which statements are executed in a program.

In this practicum, several control flow structures such as conditional statements, loops, and control flow commands are implemented to process an employee dataset.

Dataset

library(DT)

# membaca dataset
employees <- read.csv("C:/Users/Asus/OneDrive/Desktop/New folder/employees.csv")

# menampilkan dataset dalam bentuk tabel interaktif
datatable(employees)

1.Conditional Statements

Conditional statements let a program execute different code depending on whether a condition is true or false.

  • if statement → Executes code only if a condition is true.

  • if-else statement → Executes one block if true, another if false.

  • if-elif-else statement → Checks multiple conditions.

Determine bonus levels based on employee performance:

Very Good→ 20% of salary

Good→ 10% of salary

Average→ 5% of salary

library(DT)

# membaca dataset
employees <- read.csv("C:/Users/Asus/OneDrive/Desktop/New folder/employees.csv")

# tabel untuk menyimpan hasil bonus
bonus_table <- data.frame(Name = character(), Salary = numeric(), Bonus = numeric())

# melakukan loop untuk membaca setiap data karyawan
for(i in 1:nrow(employees)){
  
  # mengambil nilai salary
  salary <- employees$Salary[i]
  
  # mengambil nilai performance
  performance <- employees$Performance[i]
  
  # menentukan bonus berdasarkan performance
  if(performance == "Very good"){
    bonus <- salary * 0.20
  } else if(performance == "Good"){
    bonus <- salary * 0.10
  } else{
    bonus <- salary * 0.05
  }
  
  cat("Name:", employees$Name[i], ", Bonus:", bonus, "\n")
  
  # menyimpan hasil ke tabel
  bonus_table <- rbind(bonus_table,
                       data.frame(Name = employees$Name[i],
                                  Salary = salary,
                                  Bonus = bonus))
}
## Name: Bagas , Bonus: 500 
## Name: Joan , Bonus: 350 
## Name: Alya , Bonus: 325 
## Name: Dwi , Bonus: 1000 
## Name: Nabil , Bonus: 600
# menampilkan tabel
datatable(bonus_table)

Interpretation:

The conditional statement is used to calculate employee bonuses based on their performance. Employees with higher performance receive a larger bonus percentage, while lower performance results in a smaller bonus. This shows how conditional statements can apply different rules in processing data based on specific conditions.

2.For Loop

Loops allow programs to repeat actions multiple times.

For Loop → Used when the number of iterations is known. The counter is set, the condition is checked, the code executes, then the counter increments until the condition is no longer met.

library(DT)

# membaca dataset
employees <- read.csv("C:/Users/Asus/OneDrive/Desktop/New folder/employees.csv")

# memilih karyawan dengan salary lebih dari 6000
high_salary <- employees[employees$Salary > 6000, c("Name", "Salary")]

row.names(high_salary) <- NULL

for(i in 1:nrow(high_salary)){
  cat("Name:", high_salary$Name[i], ", Salary:", high_salary$Salary[i], "\n")
}
## Name: Joan , Salary: 7000 
## Name: Alya , Salary: 6500 
## Name: Dwi , Salary: 10000 
## Name: Nabil , Salary: 12000
# menampilkan tabel
datatable(
  high_salary,
  caption = "Employees with Salary Greater Than 6000",
  options = list(pageLength = 5, autoWidth = TRUE)
)

Interpretation:

The for loop is used to iterate through the employee dataset and identify employees whose salary is greater than 6000. As a result, only employees who meet this condition are displayed, showing how loops can be used to filter data based on specific criteria.

3.While Loop

While Loop → Used when looping should continue as long as the condition is true. If the condition remains valid, the code executes and is checked again until the condition becomes false.

library(DT)

# membaca dataset
employees <- read.csv("C:/Users/Asus/OneDrive/Desktop/New folder/employees.csv")

i <- 1
result <- data.frame(Name = character(), Position = character())

# while loop
while(i <= nrow(employees)){
  
  name <- employees$Name[i]
  position <- employees$Position[i]
  
  cat("Name:", name, ", Position:", position, "\n")
  
  # menambahkan ke tabel hasil
  result <- rbind(result, data.frame(Name = name, Position = position))
  
  # jika sudah menemukan Manager maka berhenti
  if(position == "Manager"){
    cat("(Stop here)\n")
    break
  }
  
  i <- i + 1
}
## Name: Bagas , Position: Staff 
## Name: Joan , Position: Supervisor 
## Name: Alya , Position: Staff 
## Name: Dwi , Position: Manager 
## (Stop here)
# menampilkan tabel
datatable(
  result,
  caption = "Employees Until Manager is Found",
  options = list(pageLength = 5, autoWidth = TRUE)
)

Interpretation:

The while loop displays employee data sequentially from the dataset until a specific condition is met. In this case, the loop stops when an employee with the position “Manager” is found, demonstrating how a loop can control the flow of program execution based on a condition.

4.Break Statements

Break → Stops the loop early, immediately exiting the loop without completing all iterations.

library(DT)

# membaca dataset
employees <- read.csv("C:/Users/Asus/OneDrive/Desktop/New folder/employees.csv")

i <- 1
result <- data.frame(Name = character(), Salary = numeric())

# loop membaca data sampai ditemukan salary > 10000
while(i <= nrow(employees)){
  
  salary <- employees$Salary[i]
  name <- employees$Name[i]
  
  # jika salary lebih dari 10000 maka loop berhenti
  if(salary > 10000){
    cat("(Stopped because", name, "has salary above 10000)\n")
    break
  }
  
  cat("Name:", name, ", Salary:", salary, "\n")
  
  # menambahkan data ke tabel hasil
  result <- rbind(result, data.frame(
    Name = name,
    Salary = salary
  ))
  
  i <- i + 1
}
## Name: Bagas , Salary: 5000 
## Name: Joan , Salary: 7000 
## Name: Alya , Salary: 6500 
## Name: Dwi , Salary: 10000 
## (Stopped because Nabil has salary above 10000)
# menampilkan tabel
datatable(
  result,
  caption = "Employees Until Salary Above 10000 is Found",
  options = list(pageLength = 5, autoWidth = TRUE)
)

Interpretation

The break statement is used to stop the loop when a specific condition is met. In this case, the loop stops when an employee with a salary greater than 10000 is found, so only employees before that condition are displayed.

5.Continue Statements

Continue → Skips the current iteration without stopping the loop, returning directly to the condition check for the next iteration. The loop stops when the condition is no longer met or a break statement is used. The loop continues if the condition remains true unless a break occurs.

library(DT)

# membaca dataset
employees <- read.csv("C:/Users/Asus/OneDrive/Desktop/New folder/employees.csv")

result <- data.frame(Name = character(), Performance = character())
skipped_msg <- ""

# loop membaca setiap data karyawan
for(i in 1:nrow(employees)){
  
  name <- employees$Name[i]
  performance <- employees$Performance[i]
  
  # jika performance Average maka dilewati dulu
  if(performance == "Average"){
    skipped_msg <- paste(name, "is skipped because the performance is Average")
    next
  }
  
  cat("Name:", name, ", Performance:", performance, "\n")
  
  result <- rbind(result, data.frame(
    Name = name,
    Performance = performance
  ))
}
## Name: Bagas , Performance: Good 
## Name: Joan , Performance: Very Good 
## Name: Dwi , Performance: Good 
## Name: Nabil , Performance: Very Good
cat(skipped_msg, "\n")
## Alya is skipped because the performance is Average
# menampilkan tabel
datatable(
  result,
  caption = "Employees with Non-Average Performance",
  options = list(pageLength = 5, autoWidth = TRUE)
)

Interpretation

The continue statement is used to skip certain data during the loop. In this case, employees with “Average” performance are skipped in the main process, so other employees are displayed first while the skipped data appears afterward.

Conclusion

From this practicum, it can be concluded that syntax and control flow play an important role in programming to manage how a program runs and processes data. By using conditional statements, loops, and control statements such as break and continue, data can be processed based on specific conditions and rules. This practicum also helps demonstrate how different programming structures can be applied to analyze and organize data effectively.

References

[1] Siregar, B. (n.d.). Data Science Programming: Chapter 02: Syntax and Control Flow. dsciencelabs. https://bookdown.org/dsciencelabs/data_science_programming/02-Syntax-and-Control-Flow.html