Understanding Loops in Programming with Examples
Q: What is a loop, and can you give an example of how you would use one to solve a problem?
- Programmer
- Junior level question
Explore all the latest Programmer interview questions and answers
ExploreMost Recent & up-to date
100% Actual interview focused
Create Programmer interview for FREE!
A loop is a fundamental programming construct that allows you to execute a block of code repeatedly based on a specified condition. Essentially, it enables you to automate repetitive tasks without having to write the same code multiple times. There are various types of loops, but the most common ones are the `for` loop and the `while` loop.
For example, let’s say we want to calculate the sum of all numbers from 1 to 100. Instead of writing a separate line of code for each number, we can use a loop to perform this task efficiently. Here’s how we could do this using a `for` loop in Python:
```python
total_sum = 0
for number in range(1, 101):
total_sum += number
print(total_sum)
```
In this code snippet, we initialize `total_sum` to 0. The `for` loop iterates over each integer from 1 to 100 (inclusive), adding each `number` to `total_sum`. By the end of the loop, `total_sum` will hold the value of 5050, which is the sum of all the numbers from 1 to 100.
This demonstrates how loops can simplify our code and make it more efficient and maintainable, especially when handling repetitive tasks or working with large datasets.
For example, let’s say we want to calculate the sum of all numbers from 1 to 100. Instead of writing a separate line of code for each number, we can use a loop to perform this task efficiently. Here’s how we could do this using a `for` loop in Python:
```python
total_sum = 0
for number in range(1, 101):
total_sum += number
print(total_sum)
```
In this code snippet, we initialize `total_sum` to 0. The `for` loop iterates over each integer from 1 to 100 (inclusive), adding each `number` to `total_sum`. By the end of the loop, `total_sum` will hold the value of 5050, which is the sum of all the numbers from 1 to 100.
This demonstrates how loops can simplify our code and make it more efficient and maintainable, especially when handling repetitive tasks or working with large datasets.


