Professional Documents
Culture Documents
PSP Assignment - 2
PSP Assignment - 2
CO2
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
```
Example:
```c
```
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) {
```
Example:
```c
int count = 1;
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 {
} while (condition);
```
Example:
```c
int num = 1;
do {
num++;
```
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.