2. Operators and Flow Control

About this Tutorial –

Objectives –

This course is aimed at students who need to get up to speed in C++. The course introduces object-oriented concepts and shows how they are implemented in C++. The course does not require awareness or familiarity with object-oriented programming techniques, but programming experience would be useful but not necessarily required.

Audience

Students who are new to object orientation (or programming) and need to learn C++.

Prerequisites

No previous experience in C++ programming is required. But any experience you do have in programming will help. Also no experience in Visual Studio is required. But again any experience you do have with programming development environments will be a valuable.

Contents

The C++ course covers these topics and more:

  • Introduction to C++: Key features of C++; Defining variables; Formulating expressions and statements; Built-in data types; Console input/output
  • Operators and types: Assignment; Compound Assignment; Increment and decrement operators; Const declarations; Type conversions
  • Going Further with Data Types: Enumerations; Arrays; Using the standard vector class; Using the standard string class; Structures

Download Solutions

Java tutorial


Overview

Estimated Time – 0.5 Hours

Not what you are looking? Try the next tutorial – Functions

Lab 1: Operators

Lab 1: Operators
  1. Arithmetic Operators
    • Basic binary operators
      • a + b (addition)
      • a – b (subtraction)
      • a * b (multiplication)
      • a / b (division)
      • a % b (modulo, i.e. remainder)
    • Basic unary operators
      • +a (unary plus)
      • -a (unary negation)
      • a++ (postfix increment by 1)
      • ++a (prefix increment by 1)
      • a– (postfix decrement by 1)
      • –a (prefix increment by 1)
  2. Conditional Operator
    • The conditional operator is like an in-situ if test – (condition) ? trueResult : falseResult
    • Example:
      bool isMale;
      int age;
      ...
      int togo = (isMale) ? (65 - age) : (60 - age);
      cout << "You have " << togo << " years to retirement";
  3. Assignment Operators
    • Basic assignment operator
      • a = b (assign b to a)
      • Performs widening conversion implicitly, if needed (see later)
    • Example:
      int a = 100;
      int b = 200;
      b = 42;
      a = b;
      // OR
      int a, b, c;
      ...
      a = b = c = 0;
    • Compound assignment operators:
      • a += b (calculate a + b, then assign to a)
      • a -= b (calculate a – b, then assign to a)
      • a *= b (calculate a * b, then assign to a)
      • a /= b (calculate a / b, then assign to a)
      • etc…
    • Example:
      // Use *= compound operator:
      x *= a + b;
      // Equivalent to the following (note the precedence):
      x = x * (a + b);
  4. Casting
    • Implicit conversions:
      • C++ implicitly converts less-precise expns to more-precise expns
      • char -> short -> int -> long -> float -> double
    • Explicit conversions (aka casting):
      • You can explicitly cast an expression into a compatible other type
      • (type)expression –or– type(expression)
      • Might result in a loss of precision
    • Explain the following example: What would happen? can you do this without explicit casting?
      int judge1Score;
      int judge2Score;
      int judge3Score;
      ...
      double averageScore = (double) (judge1Score + judge2Score + judge3Score) / 3;
  5. Relational Operators
    • There are 6 relational operators (all return bool):
      • == (equality)
      • != (inequality)
      • >(greater-than)
      • >= (greater-than-or-equal)
      • < (less-than)
      • <= (less-than-or-equal)
  6. Logical Operators
    • There are 3 relational operators (all return bool):
      • && (logical AND)
      • || (logical OR)
      • ! (logical NOT)
    • Note:
      • && and || perform short-circuit evaluation
  7. Bitwise Operators
    • Bitwise AND and OR binary operators
      • & (bitwise AND)
      • ^ (bitwise exclusive OR)
      • | (bitwise inclusive OR)
    • Bitwise NOT unary operator
      • ~ (bitwise NOT)
    • Bitwise shift operators
      • << (shift bits left)
      • >> (shift bits right)
  8. Order of Precedence
    • Operators have the following precedence (use parens to override this precedence):
    • T2P1

`

Lab
  1. Using operators
    • Start Visual Studio, and create a new C++ project named Dates in the student folder. Write code to manipulate day, month, and year values using operators. Suggestions and requirements:
      • To start off with, declare 3 integers with hard-coded values for the day, month, and year.
        // Declare 3 variables, for a hard-coded date.
        int day = 3, month = 12, year = 2011;
      • View code file.
      • Use a conditional operator (?:) to determine if it’s a leap year. A leap year is: (evenly divisible by 4 AND NOT evenly divisible by 100); Use the remainder operator (%) to help you out here
        // Is the date a leap year?
        bool isLeapYear = ((year % 4 == 0) && !(year % 100 == 0)) || (year % 400 == 0);
        cout << "Is " << year << " a leap year? " << isLeapYear << endl;
      • View code file.
      • Test whether your “is-leap-year” algorithm works for various years.

Lab 2: Conditional statements

Lab 2: Conditional statements
  1. Using if Tests
    • Basic if tests
      if (test) {
       body
      }
    • Blog

    • if-else tests
      if (test) {
       body1
      } else {
       body2
      }
    • Blog

    • if-else-if tests
      if (test1) {
       body1
      }
      else if (test2) {
       body2
      }
      else if (test3) {
       body3
      }
      ...
      else {
       lastBody
      }
    • Notes:
      • Test conditions don’t have to be bool
      • {} are optional if you want a 1-line statement
  2. Nesting if Tests
    • You can nest if tests inside each other
      • Use {} to ensure correct logic, as needed
      • Use indentation for readability
        int age = ... ;
        string gender = ... ;
        if (age < 18) {  if (gender == "Male") {   cout << "boy" << endl;  } else {   cout << "girl" << endl;  } } else {   if (age >= 100) {
           cout << "centurion ";
          }
         if (gender == "Male") {
          cout << "man" << endl;
         } else {
          cout << "woman" << endl;
         }
        }
      • Blog

  3. Using switch Tests
    • The switch statement is useful if you want to test a single expression against a finite set of expected values
    • General syntax:
      switch (expression) {
      case constant1:
       branch1Statements;
       break;
      case constant2:
       branch2Statements;
       break;
      ...
      default:
       defaultBranchStatements;
       break;
      }
    • Expression must be:
      • Integral type (or enum)
      • Note, strings are NOT allowed!
    • Cases:
      • Must be (different) constants
    • If you omit break:
      • Fall-through occurs
    • The default branch:
      • Is optional
      • Doesn’t have to be at the end!
Lab
  1. Using conditional logic
    • Validate the day, month, and year. Output a single message saying if the date is valid. If the date is valid, output it in the format dd/mm/yyyy. Suggestions and requirements:
      • Write an if-statement to validate the month (it must be 1-12).
         // Is the date valid?
         bool isValid;
         if (month < 1 || month > 12)
         {
          isValid = false;
         }
      • Write an if-statement to validate the year (let’s say the year must be 1900…2099).
         else if (year < 0 || year > 2099)
         {
          isValid = false;
         }
      • Write an if-statement to ensure the day is 1 or higher.
         else if (day < 1)  {   isValid = false;  }
      • Write a switch-statement to ensure the day isn't too big. The max value is 28, 29, 30, or 31, depending on the month (and if the month is February, whether it's a leap year).
         else
         {
          int maxDay;
          switch (month)
          {
           case 2: 
            maxDay = (isLeapYear) ? 29 : 28;
            break;
           case 4:
           case 6:
           case 9:
           case 11:
            maxDay = 30;
            break;
           default:
            maxDay = 31;
            break;
          }
          isValid = (day <= maxDay);  }  cout << day << "/" << month << "/" << year << " is valid? " << isValid << endl;
      • View code file.

Lab 3: Loops

Lab 3: Loops
  1. Using while Loops
    • The while loop is the most straightforward loop construct
      • Test is evaluated
      • If true, loop body is executed
      • Test is re-evaluated, etc...
        while (test) {
         loopBody
        }
    • Blog

    • Note:
      • Loop body will not be executed if test is false initially
    • How would you write a while loop...
      • To display 1 - 5?
      • To display the first 5 odd numbers?
      • To read 5 strings from the console, and output in uppercase?
  2. Using do-while Loops
    • The do-while loop has its test at the end of the loop
      • Loop body is always evaluated at least once
      • Handy for input validation
      • Note the trailing semicolon!
        do {
         loopBody
        } while (test);
    • Blog

    • How would you write a do-while loop
      • To keep reading strings from the console, until the user enters "London", "Oslo", or "Amsterdam" (in any case)?
  3. Using for Loops
    • The for loop is the most explicit loop construct
      • Initialization part can declare/initialize variable(s)
      • Test part can incorporate any number of tests
      • Update part can do anything, e.g. update loop variable(s)
      • You can omit any (or all!) parts of the for-loop syntax
        for (init; test; update) {
         loopBody
        }
  4. Unconditional Jumps
    • You can perform an unconditional jump within a loop
      • break
        • Terminates innermost loop
      • continue
        • Terminates current iteration of innermost loop, and starts next iteration
        • If used in a for loop, transfers control to the update part
      • return

      for (initialization; test; update) {
       ...
       if (someCondition)
        break;
       ...
       if (someOtherCondition)
        continue;
       ...

    • Note: C++ also has a goto statement...
Lab
  1. Using loops
    • Refactor your application so that it gets a series of dates from the user, rather than having a single hard-coded date. Suggestions and requirements:
      • Write a do-while loop that allows the user to enter a series of different dates. Each time round the loop, ask the user whether he/she wants to continue (use string here); if the user says "Yes" or "yes", keep on iterating
         int day, month, year;
         string response;
         do
         {
          // Get a date from the user and Error check
          ...
          // Ask the user whether he/she wants to enter another date.
          cout << endl << "Enter another date? ";
          cin >> response;
         }
         while (response == "yes");
         cout << "The End." << endl;
      • View code file.
      • Inside the loop, ask the user to enter a new day, month, and year
          cout << "Day: ";
          cin >> day;
          cout << "Month: ";
          cin >> month;
          cout << "Year: ";
          cin >> year;
      • View code file.
      • For each date, validate it as you did in Exercise 2 above

 

Well done. You have completed the tutorial in the C++ course. The next tutorial is

3. Functions


Back to beginning
Copyright © 2016 TalkIT®





If you liked this post, please comment with your suggestions to help others.
If you would like to see more content like this in the future, please fill-in our quick survey.
Scroll to Top