What are Control Statements

Hi everyone, inside this article we will see about Control Statements in C++.

C++ control statements are statements in the C++ programming language that control the flow of execution of a program. They allow you to perform actions based on conditions, repeat actions a specified number of times, or transfer control to another part of the program.

Types of Control Statements

The main control statements in C++ are:

if statement: executes a block of code if a specified condition is true.

switch statement: selects one of many blocks of code to be executed based on the value of an expression.

for loop: repeats a block of code a specified number of times.

while loop: repeats a block of code while a specified condition is true.

do-while loop: similar to while loop, but the block of code is always executed at least once.

break statement: terminates the innermost loop or switch statement.

continue statement: skips the current iteration of the innermost loop and moves on to the next one.

return statement: returns control to the caller of a function.

Some Basic Examples

Let’s see some

Example #1

Here’s an example of using an if-else statement in C++:

#include <iostream>
using namespace std;

int main() {
  int num = 10;

  if (num > 0) {
    cout << num << " is positive." << endl;
  } else {
    cout << num << " is negative or zero." << endl;
  }

  return 0;
}

In this example, the condition num > 0 is checked, and if it is true, the message "10 is positive." is printed to the standard output. If it is false, the message "10 is negative or zero." is printed instead.

10 is positive.

Example #2

Here’s an example of using a for loop in C++:

#include <iostream>
using namespace std;

int main() {
  for (int i = 1; i <= 10; i++) {
    cout << i << " ";
  }
  cout << endl;

  return 0;
}

In this example, the loop variable i is initialized to 1, and the condition i <= 10 is checked before each iteration of the loop. If the condition is true, the loop body is executed, which in this case prints i followed by a space to the standard output. After the loop body is executed, i is incremented by 1. The loop continues to repeat until i becomes greater than 10, at which point the loop terminates. The result is the numbers 1 to 10 printed to the standard output, each separated by a space.

1 2 3 4 5 6 7 8 9 10

We hope this article helped you to understand about Control Statements in C++ in a very detailed way.

Online Web Tutor invites you to try Skillshike! Learn CakePHP, Laravel, CodeIgniter, Node Js, MySQL, Authentication, RESTful Web Services, etc into a depth level. Master the Coding Skills to Become an Expert in PHP Web Development. So, Search your favourite course and enroll now.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.