C/C++, KDEVELOP

Basics

Program Flow

  1. Loops
  2. Conditions

Functions

Classes and Objects

X Window

KDevelop


-----------------
© Alfred Nussbaumer
Updated:
09 December 2021
-----------------

Conditional Statements

The If-Statement

If the condition is true, the statements will be executed, otherwise the execution continues with the following statement. The general form is:

if (condition) {
  statement1;
  statement2;
  ..
}
statement;
...

The statements within an "else"-statement are only executed, when the condition is false:

if (condition) {
  statement1;
  statement2;
  ..
} else {
  statement3;
  statement4;
  ...
}
statement;

There exists a shorthand notation for a simple if-else statment:

result = condition ? expression1 : expression2;

is equivalent to

if (condition) result = expression1;
else result = expression2;

toc

Nested If-Else-Statements

More "if-else"-statements can be nested:

if (condition1) {
  statement1;
  statement2;
  ...
} else if (condition2) {
  statement3;
  statement4;
  ...
} else if (condition3) {
  ...
}
...
} else {
  default_statement1;
  default_statement2;
}
...  

toc

The Switch-Statement

To avoid deeply nested "if-else"-statements you may use "switch"-statements. Commonly called multiway decision trees can be constructed by the following general code:

switch (expression) {
  case value1: statement1; break;
  case value2: statement2; break;
  case value3; statement3; break;
  ...
  default: default_statement;
}

The following example shows how an easy menu could be written...

#include <iostream.h>
#include <ctype.h>
#include <stdlib.h>

char choice;

int main() {
  for (;;) {
    cout << "Your choice: (O)pen - (C)lose - e(X)it ";
    cin >> choice;
    switch (toupper(choice)) {
      case 'O': cout << "... opens a file ... " << endl; break;
      case 'C': cout << "... file has been closed ..." << endl; break;
      case 'X': cout << "... eXit ... cu! " << endl; exit(0);
    }
  }
} 

Here is the famous sample run ;-)

Your choice: (O)pen - (C)lose - e(X)it o
... opens a file ... 
Your choice: (O)pen - (C)lose - e(X)it c
... file has been closed ...
Your choice: (O)pen - (C)lose - e(X)it x
... eXit ... cu!

toc

© Alfred Nussbaumer, Weblog "MiniNuss"