This course seems to focus a lot on C++. I am going to try and finish the handout I have first, then I’ll read Programming principles and practice using c++. I have no idea which version of c++ is being used in the pdf.
I tried reading the handout and writing notes but it didn’t work. So I just read it like a novel to know which part of C++ it covers.
I’ll be using “Programming principles and practice using C++ by Bjarne Stroustroup” for the C++ part. The book teaches programming through C++.
We want “the machine” to do things that are difficult enough for us to want help with them, but computers are nitpicking, unforgiving, dumb beasts.
I use g++ on WSL ubuntu 22.04 for compilation and running. All these tools are command line based; if you’re the GUI type, you could try visual studio (the IDE not the text editor). Bjarne Stroustrop, the command line is supprisingly easy; so give it a shot.
A computer program is a sequence of instructions written to perform a specified task. The instruction is written in a language that a computer can understand; I.E. a programming language. Thus a programming language is the language in which computer programs are written. The instructions are like commands that tell the computer what to do.
A program is a precise representation of our understanding of a topic.
Unlike human language, most programming languages are specific and detailed in nature. For example, if you ask 10 people to give another person a specific command in English, you’ll get different variations of the command. On the other hand, a computer has a set of commands it knows (E.G. add not sum) and if you give it a command it doesn’t know, you’ll have to deal with it . If you’re lucky, you’ll get an error. If you’re unlucky, the computer will crash.
There are currently 5 generations of programming languages. Unlike generations of computers, most generations of programming languages are still in use and some are built on top of others.
First generation languages (abbreviated as 1GL): These are machine languages consisting of bits (1’s and 0’s). This is the actual language that the computer understands.
Computerphile has a video on youtube “Inside the CPU” that helps with understanding how computers works with bits.
Second generation languages (2GL): This generation allows the use of symbolic names called mnemonics. The mnemonics represents the instructions the computer understands and some data is also written as mnemonics. Writing a program with mnemonics such as load, add and jmp is going to be so much easier than writing it with 100011, 000000 and 000010. Although programs were written on punch cards back in those days.
After writing the program it has to be converted to binary for the computer to be able to execute it. 2GL is also known as assembly language.
Third generation languages (3GL): These languages use words and symbols that are much easier to understand. A compiler is needed to convert / translate code in 3GL to machine code. Other languages like python uses interpreters which are in machine code to execute high level codes. These languages are also known as high level languages and they include C++, Javascript, python and ocamel.
Forth Generation languages (4GL): These languages are closer to human language than high level languages and they are usually used for specific cases. For example, SQL is used for accessing data in a database. Here is an example of an SQL code:
1^^I^^I^^ISELECT name FROM students WHERE age > 20;
Fifth Generation Languages (5GL): These languages are currently used for neural networks. A neural network is a form of artificial intelligence that attempts to imitate how the brain works.
Here are two videos that explains the basics of neural networks:
C++ is a general purpose programming language that was developed by the Danish computer scientist Bjarne Stroustrup as an extention of the C language. He wanted an efficient and flexible language simillar to C that provides high level program features for program organization.
C++ has object oriented, general, functional features in addition to low level memory manipulation facilities.
This course will focus largely on C++.
Object oriented programming is a programming paradime based on the concept of objects which can contain data and code; data in the form of fields (properties or attributes) and code in the form of procedures (methods). In OOP, computer programs are designed by making them out of objects that interacts which each other.
Here are some features of object oriented programming:
Structured programming is a programming paradime aimmed at improving the clarity, quality and development time of a program by using the structured control flow constructs.
According to the structured programming theorum, three ways of combining programs are enough for expressing any computable function. These ways are:
This has to do with executing the code as it is. Execute the first instruction, followed by the second instruction, until the last instruction. I can’t imagine a program that doesn’t work this way A.
This involves selecting a block or group of instructions (AKA statements in 3GL) to execute based on a condition. If statements and switch or match statements are used for the selections.
In this case, a block statement is executed based on the truth-ness of an expression. An example of an expresssion is 3 > 2.
Here is a list of the possible ways of using an if statement. I’ll use braces ({}) to indicate a block.
Only if statement:
statement1 if condition { statement2 statement3 } statement4
In this case, statement1 will execute first. If condition is true, statement2 and statement3 will execute, and lastly statement4. On the other hand, if condition is false, statement2 and statement3 will not execute.
if followed by else statements:
statement1 if condition { statement2 } else { statement3 } statement4
If condition is true, statement2 will execute then it will jump to statement4. On the other hand, if condition is false, statement3 will execute without executing statement2 and then statement4 will then execute.
It’s possible to chain multiple if statements with different conditions to allow only the right statement to execute.
The switch statement works by comparison. You’ll give it something to compare with; a variable, the result of an expression or the value a function returns. It will then compare it to the known forms and execute the block that matches. If it doesn’t match, the default block is executed. This sounds conffusing .
Here is an example:
switch variable { case value1: statement1 case value2: statement2 default: statement3 }
Switch statements are used for executing a block of code for specific values.
If variable matches with value1, statement1 will execute. If it matches with value2, statemet2 will execute. If it doesn’t match with all the values, statement3 will execute. You can have multiple values.
This involves executing a block of statements until a condition is met. This control flow is also known as loops. Here are some examples of loops.
while loop
while condition { statements; }
While statements are usually used for executing a block of statment until a condition is true.
The program will start by checking if condition is true. If it’s true, it will execute statements and then it will go and check condition again. This will continue until condition is false. If condition is false on the first check, statements will never executes.
for loops:
for initialization; condition; increment { statements; }
For loops are usually used for executing a block of statements a number of times.
I don’t think this is the place to explain how a for loop works. The main thing to note is; a for loop runs a number of times (in most cases).
C++ was developed in the 1980s by Bjarne Stroustroup as an extention of C language. It was later on standardized in 1998. C++ added features like objects (OOP), error handling using exceptions and more standard library features. C++ is like a super set of C.
Below is an example of a C++ program.
1// This program converts miles to kilometers. 2// From Problem Solving, Abstraction, & Design Using C++ 3#include <iostream> 4using namespace std; 5 6int main() { 7 const float KM_PER_MILE = 1.609; // 1.609 kilometers in a mile. 8 float miles, /// input: distance in miles 9 kms; // output: distance in kilometers 10 11 // Get the distance in miles 12 cout << "Enter the distance in miles: "; 13 cin >> miles; 14 15 // convert the distance to kilometers and display it. 16 kms = KM_PER_MILE * miles; 17 cout << "The distance in kilometers is " << kms << endl; 18 return 0; 19}
Programming is a skill and skills are best learned by practising.
In this chapter, we will write a C++ program and execute or run it.
I realised most people have expectations when they hear write and run a program. The program we’re going to right is a console (command line) program; it’s input is through the keyboard in form of characters and it’s output is through the monitor in form of characters also. There won’t be any buttons, planes or charts; those are mainly found in Graphical User Interface (GUI) programs.
If you can’t appreciate a console (command line) program, then I’d suggest you should try learning javascript.
If you still have to learn C++, then I’d suggest you should find a way to start appreciating it. You can just think about all the programs that have been built with C++ (Google it).
Below is a program that will output the text “Hello, World! ” on your monitor when you run it.
1// This program outputs the message "Hello, World!" to the monitor 2#include "std_lib_facilities.h" 3 4int main() { 5 // C++ programs starts with executing the main function. 6 cout << "Hello, World!\n"; // output "Hello, World!" 7 return 0; 8}
In the next few sections, we’ll explain what each line of the program does and how to compile it.
Comments are text that are added to a source code for humans (programmers) to read. Others will benefit from it by reading what a chunk of code does, and you will benefit from it when you come back to your code after a while and you’ve forgotten why you wrote the code the way you wrote it.
Comments starts with double forward slash “//” on C++. Everything after the slashes will be ignored by the compiler as it’s not part of the code.
The first line in our Hello World source code explains what the program is supposed to do. It gives the reader an idea of what to expect.
We have another comment on the line that starts with cout. The comment explain what the code on that line does.
The line that starts with #define makes sure we have the necessary code to print text on the monitor. The file specified between the double code is called a header file. The main thing to know for now is that it provides us with the code written by other programmers as part of the c++ standard library.
The program starts at the first line of code (statement) in the main function. Therefore it’s important to have a main function in every C++ program in order to tell the computer where to start.
A function is made up of four part:
From the above, we can deduce that the most minimal C++ code will look like this:
1^^Iint main() {}
It’s the line that starts with cout that will print the text “Hello, World! ” on your screen when you run the hello world program.
cout is pronounced c-out. It is an abbreviation for character output stream.
Characters can be inserted into cout with the << operator.
The text surrounded by the quotation mark is known as a string; A string contains text. The text
“
n” at the end of the string represents a new line.
Every statement in C++ ends with a semi colon.
1^^Icout << "Hello, World!"; // comment
The text after the double forward slashes is a comment; everything after it is just text, not part of c++ syntax.
The return statement returns data to the caller of the function. It could represent a result, conclusion or status. In this case it’s more of a status. Returning 0 from the main function of a program on unix systems means the program exited successfully.
1^^Ireturn 0;
The return statement also ends with a semi colon.
C++ is a compiled language. the human readable code we wrote is known as a source code. It must be translated to an executable (object code or machine code) so that the computer will be able to run it. The compiler follows a set of rules when translating. If any rule is broken, the source code will not compile. It is case sensitive; it differentiates between upper and lower case letters. It wouldn’t compile if you forget a semi colon or a bracket.
It is ment to be a friend that tells us our mistakes before we run the code.
Source codes are generally comprised of several part. In our case, we have the part that contains the main function and the part that contains the standard library code we used for cout. A linker is the program that links the two programs together to create an executable.
To program, we need a programming language. We also need a compiler and maybe a linker. Further more, we’ll need a software to write the program in it. And most importantly, we’ll need a browser for looking for documentation or seeking for help online.
In some cases, most of the tools we need and more are bundled into one application called an IDE (Integrated Development Environment). An example will be microsoft visual studio for c++. IDEs will provide you with an interface to write your code; it will have syntax highlighting to allow you to spot typos easily, it will also have an analysis tool that will continuously check your code for errors. Another feature common with IDEs is auto complete; some are powered by LLMs (Large Language Models - AKA AI) like copilot.
It could be overwhelming to try to master your IDE of choice. So, just learn what you need to create a project, write and save source code, and run and debug your code.
Apart from IDEs, there are programs that does one thing. For example, a code editor for writing code (EX visual studio code or notepad++) and a compiler (EX g++).
As for me, my environment starts with windows, with either Mozilla Firefox or Google Chrome as my browser. I have grown used to the linux eco system, so I have installed WSL (Windows Sub system for Linux). WSL allows a seemless integration between a linux distribution like ubuntu and windows.
I use neovim code editor; it starts simple and allows you to add most of the IDE features as you grow. I found visual studio code overwhelming when I tried using it but I am planning to go back and try it very soon.
Lastly, I use g++ as my compiler and linker together.
It doesn’t really matter what you use, just learn the hell out of it and use it kawai.
The drill of this chapter focuses on making you used to your development environment. I doubt I could provide any insight here as I have grown very acquainted to my development environment.
Any ways, I’ll write and run the code:
1#include "std_lib_facilities.h" 2int main() { 3 // C++ programs starts by executing the function main 4 5 cout << "Hello, World!\n"; // Output "Hello, World!" 6 keep_window_open(); // wait for a character to be entered 7 return 0; 8}
We have a new line that wasn’t in the last code. It’s needed on windows to stop the windo from closing before you have a chance to read the output.
We need to have std_lib_facilities.h to be able to compile the program. You can find it on Stroustrup’s website or right here on this website.
If you’re going to use a separate folder (directory) for each chapter, you should keep std_lib_facilities.h in the parent folder (I.E. the folder outside the chapter folder) and use it like this instead:
1#include "../std_lib_facilities.h"
The “../” before the name of the file tells the compiler to look in the parent directory for the file.
Lastly, here is how I compiled and run my program:
1^^I$ g++ 3-hello_world_drill.cpp -o hello_world 2^^I$ ./hello_world 3^^IHello, World! 4^^IPlease enter a character to exit 5^^Iq 6^^I$
If your environment is not like mine, don’t worry about understanding what is going on. The most important thing to know is that it works and you’ll need to type a character and press enter to close it.
This chapter focuses on the uses of objects, types and values. It explains how to get input, how to store data and how to perform operations on data.
Real programs tends to produce results based on the input we give them rather than repeating the same thing each time we execute them.
To accept input from a user we’ll need a place to store it. An object is a region of memory with a type. A named object is known as a variable. We can say an object is like a box that can store specific types of values. We can store values of integer or string type into an int or string object.
1cout << "Enter your first name (followed by enter):\n "; 2string first_name; // first_name is a variable of type string 3cin >> first_name; // Read characters into first_name 4cout << "Hello " << first_name << "!\n";
The #include directive and the main function wasn’t added in the previous example. You should add it if you want to test it. For example:
1#include "std_lib_facilities.h" 2int main() { 3^^I// Your code goes here... 4}
I have a file called tmp.cpp where I write and execute the examples. It’s very important to write the code fully with your fingers rather than copying it.
Back to the example!
1^^Icout << "Enter your first name (followed by enter):\n ";
The first line prints a sentence encouraging the user to write his or her first name. It is known as a prompt.
1^^Istring first_name; // first_name is a variable of type string
The next line sets aside an area of memory for holding a string of characters and give it the name first_name:
A statement that introduces a new name into a program and sets aside memory for a variable is known as a variable.
1^^Icin >> first_name; // Read characters into first_name
The next line waits for the user to type his or her name and press enter, then it will store what the user types into first_name. The name cin is a standard input stream defined in the standard library . It is pronounced c-in for character in.
1^^Icout << "Hello " << first_name << "!\n";
This prints “Hello ” (with a space in front) followed by the value of first_name (EX: Abdulqadir), then and exclamation mark followed by a new line:
Hello Abdulqadir!
The part where the program waits for the user to press enter is useful because it allows a user to write and edit possible typos. It’s just like the address bar in a browser.
There are a number of things to note in the last line.
For starters, the << operator was chained to output 3 values. We could have separated it so that each value is paired with it’s own cout but that means more typing and more possible bugs.
Secondly, note how first_name was used without a quotation mark. Quotes are used when a literal string is needed. On the other hand, writing the name of the variable means we’re passing the object instead. Consider:
1^^Icout << "first_name" << " is " << first_name;
Here, "first_name" gives us the 10 characters first_name, while first_name gives us the value in the variable first_name (Abdulqadir from the previous run).
A named object with a type is known as a variable. The statement used in defining a variable is known as a definition statement. E.G.
1^^Iint age; // Define a named object age of type integer 2^^Istring school; // Define a string of type string
A variable could b initialized when defining it by setting it to a value. E.G.
1^^Iint age = 20; // Define a named object called age and store the integer 20 in it 2^^Istring school = "University of Jos"; // Same here but type is string and value is "University of Jos"
Initializing a variable when defining it is encouraged. We’ll talk in details about it in a different section.
C++ provides a rather large number of types but you can create a perfect program with these 5:
1^^I int year = 2024; // An integer type 2^^I double pi = 3.142; // A floating point number AKA a real number 3^^I char dollar_symbol = '$'; // A character type for individual characters 4^^I string town = "J Town"; // A string of characters annd lastly 5^^I bool yes = true; // A logical variable; either true or false
Each of these types has it’s own literals.
The character input stream is sensitive to types. That is, you can input more than just a string.
1// Read name and age 2#include "std_lib_facilities.h" 3 4int main() { 5 cout << "Please enter your first name and age\n"; 6 int age; // Integer variable 7 string first_name; 8 cin >> first_name; 9 cin >> age; 10 cout << "Hello, " << first_name << " (age " << age << ")\n"; 11}