0
0
R Programmingprogramming~5 mins

Why control flow directs execution in R Programming

Choose your learning style9 modes available
Introduction

Control flow tells the computer which steps to do and when. It helps the program make choices and repeat actions.

When you want the program to choose between different options.
When you need to repeat some steps multiple times.
When you want to stop doing something if a condition is met.
When you want to run different code depending on user input.
When you want to handle errors or special cases in your program.
Syntax
R Programming
if (condition) {
  # code to run if condition is TRUE
} else {
  # code to run if condition is FALSE
}

for (variable in sequence) {
  # code to repeat for each item in sequence
}

while (condition) {
  # code to repeat while condition is TRUE
}

The if statement checks a condition and runs code based on TRUE or FALSE.

The for loop repeats code for each item in a list or sequence.

Examples
This checks if x is bigger than 3 and prints a message.
R Programming
x <- 5
if (x > 3) {
  print("x is greater than 3")
} else {
  print("x is not greater than 3")
}
This repeats printing numbers 1 to 3.
R Programming
for (i in 1:3) {
  print(i)
}
This repeats printing numbers 1 to 3 using a while loop.
R Programming
count <- 1
while (count <= 3) {
  print(count)
  count <- count + 1
}
Sample Program

This program checks if a number is even or odd, then counts from 1 to 3 with a for loop, and finally counts from 1 to 2 with a while loop.

R Programming
number <- 4
if (number %% 2 == 0) {
  print("Even number")
} else {
  print("Odd number")
}

for (i in 1:3) {
  print(paste("Counting", i))
}

count <- 1
while (count <= 2) {
  print(paste("While loop count", count))
  count <- count + 1
}
OutputSuccess
Important Notes

Control flow helps your program make decisions and repeat tasks.

Without control flow, programs would just run one step after another without choice.

Summary

Control flow directs which parts of code run and when.

Use if, for, and while to control execution.

This makes programs flexible and powerful.