# loops in c

# 🔄 Loops in C Language

A **loop** in C means repeating a block of code multiple times until a condition becomes false.  
It saves us from writing the same code again and again.

---

## 1\. **for loop**

👉 Used when you know **exactly how many times** you want to repeat.

**Syntax:**

```javascript
for(initialization; condition; update) {
    // code to repeat
}
```

* **initialization** → set starting value (e.g., `int i = 1`)
    
* **condition** → loop runs as long as this is true
    
* **update** → changes the loop variable each time (e.g., `i++`)
    

**Example:**

```javascript
#include <stdio.h>
int main() {
    for(int i = 1; i <= 5; i++) {
        printf("%d\n", i);
    }
    return 0;
}
```

✅ Output:

```javascript
1
2
3
4
5
```

---

## 2\. **while loop**

👉 Used when you **don’t know how many times** to repeat, and it depends only on a condition.

**Syntax:**

```javascript
while(condition) {
    // code to repeat
}
```

**Example:**

```javascript
#include <stdio.h>
int main() {
    int i = 1;
    while(i <= 5) {
        printf("%d\n", i);
        i++;
    }
    return 0;
}
```

✅ Output:

```javascript
1
2
3
4
5
```

---

## 3\. **do-while loop**

👉 Similar to `while`, but the body runs **at least once**, even if the condition is false.

**Syntax:**

```javascript
do {
    // code to repeat
} while(condition);
```

**Example:**

```javascript
#include <stdio.h>
int main() {
    int i = 1;
    do {
        printf("%d\n", i);
        i++;
    } while(i <= 5);
    return 0;
}
```

✅ Output:

```javascript
1
2
3
4
5
```

---

## 🔑 Quick Difference:

* **for loop** → best when number of iterations is **fixed**.
    
* **while loop** → runs **0 or more times**, based on condition.
    
* **do-while loop** → runs **at least once**, then checks condition.
