Download as pdf or txt
Download as pdf or txt
You are on page 1of 4

Home Assignment -2

CO2

22CA1101OJ- Problem Solving Through Programming

1. Discuss the various looping statements? Explain the syntax giving one example to each?

In C programming, there are three types of looping statements: the `for` loop, the `while`
loop, and the `do-while` loop. These looping statements allow you to repeat a block of code
multiple times based on a specific condition. Let's discuss each loop and provide an example
with its syntax:

1. `for` Loop:

The `for` loop is commonly used when you know the number of iterations in advance.

Syntax:

```c

for (initialization; condition; increment/decrement) {

// Code to be executed in each iteration

```

Example:

```c

for (int i = 1; i <= 5; i++) {

printf("%d ", i);

```

Output:
```

12345

```

Explanation: In this example, the loop will iterate from `i = 1` to `i = 5`. In each iteration, the
value of `i` is printed. The loop continues as long as the condition `i <= 5` is true. The `i++`
statement increments the value of `i` by 1 in each iteration.

2. `while` Loop:

The `while` loop is suitable when the number of iterations is not known beforehand, and the
loop continues until a specific condition is no longer true.

Syntax:

```c

while (condition) {

// Code to be executed in each iteration

```

Example:

```c

int count = 1;

while (count <= 5) {

printf("%d ", count);

count++;

```

Output:

```

12345
```

Explanation: In this example, the loop continues as long as the condition `count <= 5` is true.
The value of `count` is printed in each iteration, and `count` is incremented by 1 using
`count++`.

3. `do-while` Loop:

The `do-while` loop is similar to the `while` loop, but it guarantees that the code block is
executed at least once, as the condition is checked after the execution.

Syntax:

```c

do {

// Code to be executed in each iteration

} while (condition);

```

Example:

```c

int num = 1;

do {

printf("%d ", num);

num++;

} while (num <= 5);

```

Output:

```

12345

```
Explanation: In this example, the loop executes the code block at least once, as the
condition `num <= 5` is checked after the first iteration. The value of `num` is printed, and
`num` is incremented by 1 using `num++`. The loop continues as long as the condition is
true.

Each looping statement has its own use cases, and understanding their syntax and behavior
allows you to control the flow of your program and repeat code as needed based on specific
conditions.

You might also like