burntraisin

C++ Project Design Workshop: Part 2

During March and April of this year, I coordinated and taught a C++ Project Design workshop at Bergen Community College. This serves as an introduction to programming in C++, as well as some introduction to Linux and software development ideologies, such as Agile.

This was a four-part workshop, each lesson an hour long.

This post contains the second lesson of the workshop.


Workshop Outline

  1. Setup
  2. Programming fundamentals (today!)
  3. Project introduction
  4. Software methodologies

Today’s Outline


What is C++?

width:300px

^ This is Keith, the unofficial mascot of C++.

C++ is a procedural programming language, based on C. It’s an extension of the C programming language. There has been object-oriented (OOP) and functional features added to the language since the mid-1980s. You’ve probably heard of it being popular in video game development and embedded systems!

Side Note: Procedural vs. Functional PLs


Install G++ 🐃

g++ --version # Check if it's already installed!
sudo apt install build-essential

For MacOS users, you will likely need to install GCC.

brew install gcc

Install the C++ Extensions on VS Code

  1. Open VS Code
  2. Select the Extensions view and search for C++
  3. Install the extensions

alt text


Anatomy of a C++ Program

  1. Preprocessor directives
  2. using namespace std;
    • The program will access entities whose names are part of the namespace std (“standard”)
  3. main()
#include <iostream> // Preprocessor directive
using namespace std;

int main() { // Starting point of the program
    cout << "Hello world!";
    return 0;
}

Interacting with our C++ Programs: cout, cin, endl

The iostream library handles input and output. The common objects are:

#include <iostream>
using namespace std;

int main() {
    cout << "Enter a number: "; // Waits for input by the user
    int x = 0;
    cin >> x;
    cout << "You entered " << x << '\n';

    return 0;
}

Variables

A variable is a named location in RAM. Think of it as a bucket where you can store a value.

Declaring and Assigning Variables

#include <iostream>
using namespace std;

int main() {
    int number; // Variable declaration
    number = 5; // = is an assignment operator; number now holds the value 5

    int width, length = 5; // width is declared, but not initialized. length is initialized.
}

Variable Initialization

Variable initialization is assigning a variable a value at the time it’s defined. There are 3 ways to do this:

  1. Functional notation
  2. Brace notation
  3. Copy initialization (most common)
int value(5); // (1)
int value{5}; // (2)
int value = 5; // (3)

More Variable Terminology!

alt text

Variable names are typically written in camelCase.

Constant Variables

Constant variables are read-only and can’t be changed later in the program. These must be initialized when defined.

The syntax: const <DataType> <VARIABLE_NAME> = <exp>;

The convention is to write constant variable names in all CAPITAL_LETTERS.

const double INTEREST_RATE = 0.069;

Try: Initializing and Displaying Variables

Task: Initialize an integer variable (give it any name) and give it any value. Then, display the variable back to the user.

To compile and and generate an executable: g++ main.cpp -o main

Then, run the executable with ./main

Note: Try using Git! Create another repo for these exercises with mkdir exercises. Initialize your local repo with git init -b main. If you want to push it to GitHub, create a new empty repo on GH and copy the remote repo URL (SSH). In your terminal, git remote add origin <URL> and then push your commits.

Bad Practice: Multiple Assignment (·•᷄‎ࡇ•᷅ )

a = b = c = d = 12;

Primary Data Types

Numeric

alt text

^ From “Starting Out with C++: Early Objects” (10th Ed.) by Tony Gaddis, Judy Walters, and Godfrey Muganda


Operators

Arithmetic Operators

OperatorDefinitionExample
+Additionx = x + 1;
-Subtractionx = 10 - y;
*Multiplicationz = x * y;
/Divisionz = 10 / x;
%Moduloz = 10 % 3;
++Incrementz++
Decrement--y

Try: Using Arithmetic Operators

Task: Create 2 variables x and y. Initialize them to be 12.3 and 67, respectively. Perform three arithmetic operations with x and y, assigning each of the results to their own variables. Display the three results in the console.

Solution

#include <iostream>
using namespace std;

int main() {
    float x = 12.3;
    int y = 67;
    float sum, difference, product;

    sum = x + y;
    difference = y - x;
    product = x * y;

    cout << "The sum is: " << sum << "\n";
    cout << "The difference is: " << difference << "\n";
    cout << "The product is: " << product << "\n";

    return 0;
}

Combined Assignment Operators

OperatorExample
+=x += 5; instead of x = x + 5;
-=y -= 2;
*=z *= 10;
/=a /= b;
%=c %= 3;

Relational Operators

OperatorDefinition
==Equal to
!=Not equal to
>Greater than
<Less than
>=Greater than or equal to
<=Less than or equal to

Logical Operators

Logical operators connect 2 or more relational expressions into 1.

OperatorMeaningEffect
&&ANDBoth must be true for the expression to be true
||OROne or both expressions must be true for the expression to be true
!NOTMakes a true expression false and a false expression true

Precedence

  1. !
  2. &&
  3. ||

Examples

if ((temperature < 20) && (minutes > 12)) {
    cout << "The temperature is in the danger zone.";
}

if (moreData == true) {
    cout << "Do cool stuff!";
}

Conditionals

if Statement

The if statement is a control structure. When the condition is true (or false), certain statements are executed.

if (expression) {
    // Code here
}

Can be written without the {} if only 1 line is going to be conditionally executed.

#include <iostream>
using namespace std;

int main() {
    int score1, score2, score3;
    double average;

    cout << "Enter 3 test scores and I will average them: ";
    cin >> score1 >> score2 >> score3;
    
    average = (score1 + score2 + score3) / 3.0;
    cout << "Your average is " << average << endl;

    if (average == 100) {
        cout << "Congrats! That's a perfect score!" <<< endl;
    }

    return 0;
}

if-else

The else block is run when the conditional statement is false.

if (expression) {
    // These statements run if the expression is true
}
else {
    // These statements run if the expression is false
}

if-else if

if (expression) {
    // These statements run if the expression is true
}
else if (expression) {
    // These statements run if the expression is true
}
else {
    // Statements run if all of the above expressions are false
}

Try: Write an if-else

Task: Take an integer input from the user and then display if the number is odd or even.

Solution

#include <iostream>
using namespace std;

int main() {
    int num;
    cout << "Enter an integer: ";
    cin >> num;

    if (num % 2 == 0) {
        cout << num << " is even." << endl;
    }
    else {
        cout << num << " is odd." << endl;
    }
}

#Guide