Tuesday, 16 December 2025

Control Statements in C++

Control Statements in C++
Control statements determine the flow of execution of a C++ program. They decide which statement executes, how many times, and when.

Types of Statements in C++
1. Declaration Statements
Used to declare variables.

int a;
float marks;

2. Assignment Statements
Used to assign values to variables.

a = 10;
marks = 85.5;

3. Input / Output Statements
Used to take input and display output.

cin >> a;
cout << a;

4. Control Statements
Control the flow of program execution.

A. Selection (Decision) Statements
Used for decision making.

1. if Statement

if (a > 0) {
    cout << "Positive";
}

2. if-else Statement

if (a % 2 == 0)
    cout << "Even";
else
    cout << "Odd";

3. else-if Ladder

if (marks >= 90)
    cout << "Grade A";
else if (marks >= 75)
    cout << "Grade B";
else
    cout << "Grade C";

4. switch Statement

switch(choice) {
    case 1: cout << "One";
            break;
    case 2: cout << "Two";
            break;
    default: cout << "Invalid";
}

B. Iteration (Looping) Statements
Used to repeat statements.

1. for Loop
for(int i = 1; i <= 5; i++) {
    cout << i;
}

2. while Loop
int i = 1;
while(i <= 5) {
    cout << i;
    i++;
}

3. do-while Loop
int i = 1;
do {
    cout << i;
    i++;
} while(i <= 5);

C. Jump Statements
Used to transfer control.

Statement Use
break Exit loop or switch
continue         Skip current iteration
goto Jump to labeled statement
return Exit function

Example:
if (a < 0)
    return 0;

5. Expression Statements
Statements containing expressions.
a = b + c;
x++;

6. Compound (Block) Statements
Group of statements enclosed in { }.
{
    int x = 5;
    cout << x;
}

Breaking Control Statements in C++
Breaking control statements are used to interrupt the normal flow of execution in loops or switch statements, or to exit a function.

1. break Statement
Terminates the nearest loop or switch
Control moves to the statement after the loop/switch

Example (Loop)
for(int i = 1; i <= 5; i++) {
    if(i == 3)
        break;
    cout << i << " ";
}
// Output: 1 2

Example (Switch)
switch(ch) {
    case 'A': cout << "Apple";
              break;
    case 'B': cout << "Ball";
}

2. continue Statement
Skips the current iteration
Loop continues with the next iteration

Example
for(int i = 1; i <= 5; i++) {
    if(i == 3)
        continue;
    cout << i << " ";
}
// Output: 1 2 4 5

3. goto Statement
Transfers control to a labeled statement
Generally not recommended (reduces readability)

Example
int i = 1;
start:
cout << i << " ";
i++;
if(i <= 5)
    goto start;

4. return Statement
Exits from a function
Can return a value

Example
int sum(int a, int b)
{
    return a + b;
}

Difference Between break and continue
Feature break continue
Exits loop Yes         No
Skips iteration No         Yes
Used in switch Yes         No

0 comments

Post a Comment