C++ Operators, Conditional Statements, and Loops

String Manipulators and File I/O Review

  • Review of string manipulators and forwarding outputs.
  • Header file required: iostream and iomanip (IO, MAD, IP).
  • String manipulators covered: setposition, fixed, setw (set width/space), and showpoint.
  • File I/O example discussed: writing to a file.
  • Reading from a file was also covered.

Basic File Input/Output

  • Steps for using a file in C++ (similar to MATLAB):
    • Open the file.
    • Access the file (read/write).
    • Close the file.
  • Special header file required: <fstream> (file stream header file).
  • Create a file object (file stream object):
    • ifstream for input file.
    • ofstream for output file.
    • File object for both input and output.
  • Example:
    • ifstream infile; (input file)
    • infile.open("filename.txt"); (opening the file; full location can be specified)
  • Accessing the file: similar to cout and cin.
    • Writing to a file: use the redirect operator << (e.g., outfile << data;)
    • Reading from a file: use the redirect operator >> (e.g., infile >> data;)
  • Closing the file: use the close() member function (e.g., infile.close();)
  • Reading text with spaces:
    • Use string data type.
    • Include <string> header.
    • Use getline() to read lines from the file.

Assignments and Arithmetic Operators

  • Similar to MATLAB, but with some differences.
  • Operators:
    • Assignment operator (=)
    • Arithmetic operators (+, -, *, /)
    • Modulo operator (%)
    • Compound assignments (+=, -=, *=, /=, %=)
    • Increment/Decrement operators (++, --)
  • Creating a new project in Visual Studio:
    • File -> New -> Project
    • Choose Console App (C++).
    • Select location and project name.
  • Running the code:
    • Start without debugging (Ctrl+F5).
    • Start with debugging (F5).
  • Output window: displays output.
  • Error list: displays errors.
  • using namespace std; avoids the need to use std:: prefix.

Assignment Operator

  • Syntax: variable = value; (e.g., a = 5;)
  • Assignment goes from right to left.
  • Multiple assignment operators: a = b = c = 5; (means c = 5, b = c, a = b)
  • sum = sum + 1; (adds 1 to the existing value of sum)
Examples
  • If x = 6:
    • x += 4; (x becomes 10)
    • x -= 3; (x becomes 3)
    • x *= 10; (x becomes 60)
    • x /= 2; (x becomes 3)
    • x %= 4; (x becomes 2; remainder of 6 divided by 4)
Modulo Operator (%)
  • Calculates the remainder of the division between two values.
  • Example: 11 % 3 is 2 (remainder when 11 is divided by 3).

Algebraic Expressions

  • area = l * w; (instead of lw)
  • s * s or pow(s, 2) (instead of s2s^2)
  • Use parentheses to ensure correct order of operations:
    • (y2 - y1) / (x2 - x1)

Compound Assignment

  • Shorthand notation for assignments.
  • a += 5; (same as a = a + 5;)
  • a /= b; (same as a = a / b;)
  • a *= b + 1; (same as a = a * (b + 1);)
  • a++; (same as a = a + 1; or a += 1;)
Increment/Decrement Operators
  • a++ means adding one to a.
  • ++a does the same thing, but there's a difference in when the increment happens.
Examples Showing Difference between Postfix and Prefix Increment
  • a = 2, b = 5

    • c = a++ * b; (c is 10, a becomes 3 - post-increment: multiplies first then increments a)
    • c = ++a * b; (c is 15, a becomes 3 - pre-increment: increments a first then multiplies)

Relational and Equality Operators

  • == (equal to)
  • != (not equal to)
  • > (greater than)
  • < (less than)
  • >= (greater than or equal to)
  • <= (less than or equal to)

Logical Operators

  • ! (NOT)
  • && (AND)
  • || (OR)

Bitwise Operators

  • & (bitwise AND), | (bitwise OR), ^ (bitwise XOR). Not covered in detail in the class
  • << (left shift), >> (right shift)

Conditional Operator

  • Syntax:
    • condition ? result_if_true : result_if_false;
  • Example:
    • c = (a > b) ? a : b; (if a is greater than b, c equals a; otherwise, c equals b)

Comma Operator

  • Valid but not recommended for use, can complicate code

Explicit Type Casting

  • Forcing a variable to be of a certain type.
  • Important when performing operations with different data types.

Precedence of Operators

  • Follow PEMDAS/BODMAS rule.
  • Increment/decrement operators and other C++ specific operations come before standard arithmetic operations.

If Statement

  • Similar to MATLAB but uses curly brackets {} instead of end.
  • Single statement after if does not require curly brackets.
  • Multiple statements after if require curly brackets.
  • else if in C++ (not elseif or else if).
  • Avoid semicolon after if condition (can lead to errors).

Switch Statement

  • Similar to MATLAB switch statement, Used to replace many if-else statements
  • Used for menu-driven programs and choice selections.
  • Must include break; after each case.
  • default: case for handling unknown values.

Loops

While Loop

  • Syntax: while (condition) { statements; }
  • Statements are executed as long as the condition is true.
  • Can be used for input validation.
  • Infinite loops: while (1) { statements; } (use carefully with break command for termination).

Do-While Loop

  • Syntax: do { statements; } while (condition); (note semicolon at the end)
  • Statements are executed at least once regardless of the condition.
  • Good for input validation and menu-driven programs.
  • Post-test loop (condition is checked after the loop body).

For Loop

  • Syntax: for (initialization; condition; update) { statements; }
  • Used when the number of iterations is known.
  • Pre-test loop (condition is checked before the loop body is executed).
  • Initialization, condition, and update sections are separated by semicolons.
  • Can initialize multiple variables and have multiple updates using the comma operator (but avoid unnecessary use).
Scope of Variables
  • Scope is from initialization expression up to the end of the code block.
  • If a variable is declared inside the for loop, it is only accessible inside the loop.

Nested Loops

  • One loop inside another loop.
  • The inner loop completes all its iterations for each iteration of the outer loop.
  • The total number of iterations is the product of individual iterations.

Exit Statement

  • exit(0); can exit the C++ program. Can be used within if-else structure to determine program exit on certain parameters.
  • Returns a value of zero (success).
  • Avoid using exit() unnecessarily; use proper logic to exit the program.