What are Loops in C++?

Loops in C++ are used to execute a block of code repeatedly as long as a given condition is true. Instead of writing the same code multiple times, loops allow us to run it again and again automatically.

A loop first checks a condition, and if it is true, the code inside the loop executes. This process continues until the condition becomes false. Loops help in making programs short, efficient, and easy to manage.

Types of Loops in C++

Why Do We Use Loops?

  • To repeat a task multiple times.
  • To reduce code repetition.
  • To make programs easier and faster.
  • To handle large data easily.

How Loop Works?

  • First, a condition is checked.
  • If the condition is true, the loop runs.
  • After execution, the condition is checked again.
  • This continues until the condition becomes false.

Note:If condition is always true, it becomes an infinite loop.

Simple Example

#include <iostream>
using namespace std;

int main() {
    int n, i = 1;

    cout << "Enter number: ";
    cin >> n;

    while (i <= n) {
        cout << i << endl;
        i++;
    }

    return 0;
}

Output:

Enter number: 5

1

2

3

4

5

Explanation:

  • The user enters n = 5.
  • The loop starts from i = 1.
  • The condition i <= n is checked.
  • Numbers from 1 to 5 are printed.
  • i++ increases the value each time.
  • After printing 5, i becomes 6.
  • Now the condition 6 <= 5 becomes false, so the loop stops.

Summary:

  • Loops are used to repeat a block of code.
  • They reduce code length and improve efficiency.
  • C++ provides while, do-while, and for loops.

Welcome to ShikshaSanchar!

ShikshaSanchar is a simple and helpful learning platform made for students who feel stressed by exams, assignments, or confusing topics. Here, you can study with clarity and confidence.

Here, learning is made simple. Notes are written in easy English, filled with clear theory, code examples, outputs, and real-life explanations — designed especially for students like you who want to understand, not just memorize.

Whether you’re from school, college, or someone learning out of curiosity — this site is for you. We’re here to help you in your exams, daily studies, and even to build a strong base for your future.

Each note on this platform is carefully prepared to suit all levels — beginner to advanced. You’ll find topics explained step by step, just like a good teacher would do in class. And the best part? You can study at your pace, anytime, anywhere.

Happy Learning! – Team ShikshaSanchar