R For Loop
🔁 R For Loop
A for loop in R is used to repeat a block of code for a fixed number of times. It is one of the most important topics for exams, interviews, and real programs.
1️⃣ What is a For Loop in R?
A for loop executes a set of statements for each value in a sequence (vector, list, range).
Syntax
2️⃣ Simple For Loop Example
Output
3️⃣ For Loop with Vector
4️⃣ For Loop with Calculation
Square of Numbers
5️⃣ For Loop with If Condition
Even / Odd Check
6️⃣ Nested For Loop
Multiplication Table
7️⃣ Storing Results Using For Loop
8️⃣ For Loop with break and next
break (Exit Loop)
next (Skip Iteration)
9️⃣ For Loop vs While Loop
| Feature | For Loop | While Loop |
|---|---|---|
| Iterations | Fixed | Unknown |
| Use case | Known range | Condition-based |
| Risk | Low | Infinite loop |
📌 Interview Questions & Answers (Very Important)
Q1. What is a for loop in R?
Answer:
A for loop is a control structure that repeats a block of code for each element in a sequence.
Q2. Write syntax of for loop in R.
Answer:
Q3. Difference between for loop and while loop?
Answer:
For loop: Used when number of iterations is known
While loop: Used when iterations depend on a condition
Q4. Write a program to print numbers from 1 to 10.
Q5. How do you stop a for loop in R?
Answer:
Using the break statement.
Q6. How do you skip an iteration in for loop?
Answer:
Using the next keyword.
Q7. Can for loop work with vectors and lists?
Answer:
Yes, a for loop can iterate over vectors, lists, matrices, and data frames.
Q8. Is for loop faster than vectorized operations in R?
Answer:
No. Vectorized operations are generally faster than for loops in R.
Q9. What is a nested for loop?
Answer:
A for loop inside another for loop is called a nested for loop.
Q10. Write a program to calculate sum of first n numbers using for loop.
🔥 Exam Tips
✔ Always know syntax
✔ Practice dry run of loop
✔ Understand break & next
✔ Prefer loops in exams, vectorization in real code
✅ Summary
For loop repeats code for a sequence
Used with numbers, vectors, lists
Supports
break,next, nested loopsVery important for BA / BSc exams & interviews
