Mark As Completed Discussion

Control Structures in Practice

Control structures play a vital role in real-world programming scenarios. They allow us to make decisions and execute specific code blocks based on certain conditions. Let's look at an example.

Suppose we want to determine whether a person is an adult or a minor based on their age. We can use an if/else statement to make this decision. Take a look at the following code snippet:

TEXT/X-C++SRC
1#include <iostream>
2using namespace std;
3
4int main() {
5  int age;
6  cout << "Enter your age: ";
7  cin >> age;
8
9  if (age >= 18) { // If the age is greater than or equal to 18
10    cout << "You are an adult.";
11  } else { // Otherwise
12    cout << "You are a minor.";
13  }
14
15  return 0;
16}

In this code, we prompt the user to enter their age using the cout and cin statements. The if statement checks if the entered age is greater than or equal to 18. If it is, the message "You are an adult." is displayed. Otherwise, the message "You are a minor." is displayed.

Try running this code and enter different ages to see the output.

This is just one simple example of how control structures are used in practice to make decisions based on specific conditions. Control structures are commonly used in programming in various ways to handle different scenarios.

CPP
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment