Writing C++ Programs

Authors
Dr. Nicholas Del Grosso | Dr. Sangeetha Nandakumar | Dr. Ole Bialas

C++ source code are usually written in the form of human-readable text files which cannot be understood by the machine. A compiler (like g++ or gcc) acts as a traslator to convert the source code into machine-readable form and creates an executable. Finally, the executable is run by the computer’s operating system where the CPU executes the machine instructions to produce the output. So, when we write a C++ program, it involves three steps

  1. Writing the source code with an extension cpp
  2. Compiling the source code to generate an executable file
  3. Executing the executable file to see our output

You can also combine steps 2 and 3 in one command line. For each of these exercises, create a new file with .cpp extension.

Section 1: Printing to the terminal

This section introduces how to display output in C++ using the terminal. It explains the role of the #include <cstdio> directive for accessing the printf() function and the structure of the main() function, which serves as the program’s entry point. Learners practice writing their first program to print text, compile it using the g++ compiler, and run the resulting executable. By the end of this section, one understands how source code is transformed into an executable file and how to verify that a program runs correctly by printing messages to the terminal.

Code Description
#include <cstdio> Gives access to the printf() function to print text to the terminal.
int main(){} The main function that runs automatically when the program starts.
printf("Hi!\n"); Prints the text "Hi!" (or "Hello!") to the terminal.
cd 1_hello Changes the current directory to the 1_hello directory.
cd .. Changes the current directory to the parent directory.
g++ hello.cpp -o hello Runs the g++ compiler to create an executable file (hello) from the source code.
./hello Runs the compiled executable.
g++ hello.cpp -o hello && ./hello Compiles and runs the program in a single command.

Exercises

Exercise: Save the function below to a file hello.cpp and run the cell below to compile and execute the code.It should print the text, “Hello World!” to the terminal.

// content of hello.cpp
#include <cstdio>

int main(){
    printf("Hello, World!\n");
}
!g++ hello.cpp -o hello.out && ./hello.out
Hello, World!

Section 2: Writing functions

Functions in C++ help perform a specific task and make the code reusable. To write a function:

  1. Start with the return type — this defines what kind of value the function will give back (for example, int).
  2. Write the function name — choose a name that describes what it does (for example, mul).
  3. Add parameters in parentheses — these are the inputs the function will use (for example, (int x, int y)).
  4. Write the function body — inside curly braces {}, write the statements that perform the task.
  5. Call the function — inside main(), use the function name with actual values (for example, mul(3, 4)).
  6. Print or use the result — display the returned value using printf() or store it in a variable.

Each function runs only when called, and it helps keep programs clean, organized, and easy to reuse.

Code Description
#include <cstdio> Includes the C standard I/O library, which provides functions like printf().
printf("%d\n", 4) Prints the integer 4 followed by a new line.
printf("%d,%d\n", 5, 6) Prints 5,6 followed by a new line.

For a detailed table of format specifiers and usage for printf() see the printf() format reference .

Exercises

Example: Create a file mul.cpp with the following functions:

  • int multiply(int x, int y): multiplies x and y
  • int main(): calls multiply() on the numbers 3 and 4 and prints the result

Then, run the cell below to compile and run the code.

// content of mul.cpp
#include <cstdio>

int multiply(int x, int y) {
    return x * y;
}

int main(int argc, char *argv[]) {
    printf("%d\n", multiply(3, 4));
}
!g++ mul.cpp -o mul.out && ./mul.out
12

Exercise: Create a file mul3.cpp with the following functions:

  • int multiply3(int x, int y, int z): multiplies the numbers together.
  • int main(): calls multiply3() on the numbers 4, 5, and 6, and prints the result.
Solution
// content of mul3.cpp
#include <cstdio>

int multiply3(int x, int y, int z) {
    return x * y * z;
}

int main(int argc, char *argv[]) {
    printf("%d\n", multiply3(4, 5, 6));
}
!g++ mul3.cpp -o mul3.out && ./mul3.out
120

Bonus: Let’s make the multiply3() function sharable by seperating it from the main() function:

  1. Put the multiply3() function into a file called mul.h,
  2. Put #include “mul.h” in the header to import the code.

Then, execute the cell below to compile and run the code.

Solution
// content of mul.h
int multiply3(int x, int y, int z) {
    return x * y * z;
}
Solution
// new content of mul.cpp
#include <cstdio>
#include "mul.h"

int main(int argc, char *argv[]) {
    printf("%d\n", multiply3(4, 5, 6));
}
!g++ mul3.cpp -o mul3.out && ./mul3.out
120

Section 3: Writing endless-loops

Arduino is designed to run code continuously, where actions repeat as long as the board is powered on. This continuous behavior is controlled by the loop() function, which allows tasks like blinking LEDs or reading sensors to happen over and over again with pauses in between. In C++, this idea can be practiced using an endless loop (while(true)) together with time delays created by <chrono> and std::this_thread::sleep_for() from <thread>. The <cstdio> library provides printf() for displaying messages and fflush(stdout) to make them appear immediately. Learning this pattern helps understand how Arduino manages repeated actions with controlled pauses inside its main loop.

Code / Syntax Description
<cstdio> Contains code for input and output to the terminal.
printf("Hi\n") Prints “Hi” followed by a new line.
fflush(stdout) Forces printed output to appear immediately, even without a new line character.
<chrono> Contains code for describing and working with time.
std::chrono::seconds(int secs) Creates a time duration measured in seconds.
std::chrono::milliseconds(int milli) Creates a time duration measured in milliseconds.
<thread> Contains code for interacting with the program’s current thread, independent of the operating system.
std::this_thread::sleep_for(chrono time) Pauses the current thread for the specified duration.
using namespace std; Allows using standard library names without writing std:: each time.
while (true) {} Creates an endless loop that repeats continuously.

Exercises

Exercise: Create a file loop.cpp with the the following functions:

  • void print(char[] message): prints a message to the terminal.

  • void delay(int milliseconds): pauses the program for the specifed amount of time.

  • int main(): Uses the created functions to do the following in an endless loop:

    1. print “Sleeping…”, wait 1.5 seconds,
    2. print, “Awake!”, wait 0.5 seconds,
    3. repeat.

Then run the cell below to compile and run the code (with a timeout after 5 seconds).

Solution
// content of loop.cpp
#include <cstdio>
#include <thread>
#include <chrono>

using namespace std;
int main(){
    while (true) {
        printf("Sleeping...");
        fflush(stdout);

        chrono::duration millis = chrono::milliseconds(1500);
        this_thread::sleep_for(millis);
        printf("Awake!\n");
    }
}
!g++ loop.cpp -o loop.out && timeout 5 ./loop.out
Sleeping...Awake!
Sleeping...Awake!
Sleeping...Awake!
Sleeping...

Section 4: Sending in input to the program through the terminal

In C++, programs can receive values directly from the terminal when they are run. This is done using a special form of the main function, int main(int argc, char *argv[]). Here, argc records how many values are provided, and argv stores those values as text. The <cstdlib> library provides the atoi() function, which converts these text values into integers that the program can use. This allows the program to start with specific inputs already supplied, making it possible to run the same code with different data each time.

Code / Concept Description
int main(int argc, char *argv[]) {} Allows a program to take input directly from the terminal when it is run.
argc Stores the number of inputs provided through the terminal.
*argv[] An array of strings (character arrays) containing each input value.
<cstdlib> Includes useful functions for working with conversions and memory.
int atoi(str) Converts a string value into an integer.

Exercises

Exercise: Create a file mul2.cpp with the following functions:

  • int multiply2(int x, int y): multiplies the integers together.
  • int main(int argc, char *argv[]): calls multiply2() on the integers supplied on the terminal. Then, run the cell below to compile and run the function to multiply the numbers 5 and 3.
Solution
// content of mul2.cpp
#include <cstdlib>
#include<iostream>

using namespace std;

int multiply2(int x, int y){
    return x * y;
}

int main(int argc, char *argv[]) {
    int x = atoi(argv[1]);
    int y = atoi(argv[2]);
    cout << multiply2(x, y);
}
!g++ mul2.cpp -o mul2.out && ./mul2.out 5 3
15