C++ Programming
Previously, I had a bit of experience with C and quite a bit of MATLAB. I have also used some other languages, so it doesn't take too long to get the hang of it.
Here is a set of simple code I wrote in order to get used to the C++ language for future uses. These are mostly based on the different knowledge learnt from tutorials. I tried to cover most of the key aspects on the comments next to the code, so anyone can read it and understand it.
"Hello World!" and other basic statements
#include <iostream> //For including libraries, in this case, on of the most important ones, which is iostream (input output stream). This one contains the standar library.
int main() {//Specify type of output beofre the "main" function. In this case, it will return an integer.
int file_size = 0; //Here we declared our integer variable and, on the same line, a value is assigned to it. We initialized the variable. We can do as much as we want by typing a comma and new variables initialized with their initial value (, counter = 0;).
int counter = 0; //However, it is clearer to initialize each variable on their own line.
double sales = 9.99; //Now, we did the same thing but for a number with two decimals (double).
std::cout << "Hello World!\n"; //std is for standard library and, from that one, we'll use features within that library by typing "::". We want to show characters, therefore, we'll use "cout" (characters out). We need two angle brackets and then double quotes at each end of the desired character output. The line (statement) is terminated with a semicolon. "\n" inserts a new line on hte output.
std::cout << file_size; // With this statement, we are going to show the value on our terminal. It will be printed after the previous output.
return 0; //Returning 0 tells the OS that the program is going to succesfully terminate. No errors encountered.
}
Swapping values from two variables
#include <iostream>
int main() {
int variable_A = 1;
int variable_B = 2;
std::cout << "First we have A=" << variable_A << " and B=" << variable_B << "\n";
int variable_C = variable_B;
variable_B = variable_A;
variable_A = variable_C;
std::cout << "Now we have A=" << variable_A << " and B=" << variable_B << "\n";
}
Arithmetic expressions and increments
#include <iostream>
int main(){
int x = 1;
int y = 2;
double z = 1;
int sum = x + y; // 3
int substraction = x - y; // -1
int multiplication = x * y; // 2
int division_integer_integer = x / y; // 0. Since X is integer, the division only cares about the integer part of the result 0.5. Aart from that, the division itself is an integer type.
int division_integer_double = z / y; // 0. Even though z is double, since the division is an integer type, it only cares about the integer part of the result 0.5.
double division_double_integer = x / y; // 0. Even though the division is double, since x is an integer the division only cares about the integer part of the result 0.5.
double division_double_double = z / y; // 0.5. For a division to prompt a double type value, both the division and the numerator must be double type variables.
int modulus_integer = x % y; // 1. It gives the remainder of the division. In this case, since it is an integer division (0), the remainder is 1. This expression only accepts integer values to compute with.
int post_increment = x++; // post_increment=1 and x becomes 2.
int pre_increment = ++x; // x becomes 3 and pre_increment=3.
int post_decrement = x--; // post_decrement=3 and x becomes 2.
int pre_decrement = --x; // x becomes 1 and post_increment=1.
std::cout << pre_decrement;
return 0;
}
Console output
#include <iostream>
/*
int main(){
int x=10;
// A stream is a sequence of characters. Standard Output means showing values on the terminal. Standard Output Stream is showing a character sequence on the console.
std::cout << "x = " << x << std::endl; // "<<" is the stream insertion operator. std::endl specifies the end of the line, whatever we output next is going to be show on the next line. Apparently, it doesn't take up memory but could be slower than "\n".
return 0;
}
*/
using namespace std; // With this, we don't need to use std:: in front of each cout or endl function.
// Let's do the exercise: sales income and taxes.
int main(){
double sales = 95000; // COuld be int, but it is a good practice to use double for this kind of numerical/monetary programs.
double stateTax = 0.04;
double countyTax = 0.02;
double salesStateTax = sales * stateTax;
double salesCountyTax = sales * countyTax;
double totalTax = salesStateTax + salesCountyTax;
double netIncome = sales - totalTax;
cout << "Sales income = " << sales << endl
<< "State tax = " << salesStateTax << endl
<< "County tax = " << salesCountyTax << endl
<< "Total tax = " << totalTax << endl
<< "Net income = " << netIncome;
}
Reading from console
#include <iostream>
using namespace std;
// << is the stream insertion operator
// >> is the stream extraction operator
// Let's do the exercise: Fahrenheit to Celsius temperature conversion.
int main(){
double fahrenheit;
cout << "Introduce the temperature in Fahrenheit scale: ";
cin >> fahrenheit;
double celsius = (fahrenheit - 32) / 1.8;
cout << "The temperature in Celsius scale is:" << celsius << "ºC.";
return 0;
}
Reading from the Standard Library
#include <iostream>
#include <cmath>
using namespace std;
/*
int main(){
double roundedDown = floor(1.4);
double roundedUp = ceil(1.4);
double twoToThePowerOfThree = pow(2,3);
cout << twoToThePowerOfThree;
return 0;
}
*/
// Let's do the exercise: Calculating area of circle of desired radius.
int main(){
cout << "Introduce the radius of the circle: ";
double radius;
cin >> radius;
const double pi = 3.1416;
double area = pi * pow(radius,2);
cout << "The area is: " << area << " squared units." << endl;
return 0;
}
Initializing variables
#include <iostream>
int main(){
// Specifying each type
double a_1 = 12.5; // double
float b_1 = 3.67; // float
long c_1 = 900000; // long
char d_1 = 'D'; // character
bool e_1 = false; // boolean
// Using auto
auto a_2 = 12.5; // double
auto b_2 = 3.67; // double
auto c_2 = 900000; // double
auto d_2 = 'D'; // character
auto e_2 = false; // boolean
//Forcing specification in order to use auto later
double a_3 = 12.5; // double
float b_3 = 3.67F; // float
long c_3 = 900000L; // long
char d_3 = 'D'; // character
bool e_3 = false; // boolean
// Properly using auto
auto a_4 = 12.5; // double
auto b_4 = 3.67F; // float
auto c_4 = 900000L; // long
auto d_4 = 'D'; // character
auto e_4 = false; // boolean
//
//Let's say we want to enter a double value but we mistakenly set it as a integer
int value_A = 1.2;
int value_B {1.2}; // it is supposed to give an error due to double and integer, but it gives another one...
return 0;
}
Random numbers
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
//Let's do a rolling dice cube example:
int main(){
srand(time(0));
int dice = rand() % 6 + 1;
cout << "The dice gave the number: " << dice << endl;
return 0;
}
String input
#include <iostream>
using namespace std;
//Let's do a personal information formulary example
int main(){
cout << "Introduce your first name: ";
string firstName;
cin >> firstName;
cin.ignore(1,'\n'); // this is to ignore the \n in buffer natural from a cin statement, so that getline does not read it.
cout << "Introduce your last name(s): ";
string lastName; // since there could be multiple words separated by whitespaces, we will use getline instead of cin.
getline(cin, lastName); // this input line is skipped because cin stores \n in buffer and since getline does ot ignore leading whitespace, that is read by getline as the input. To prevent that, we used cin.ignore(1,'\n') right after the cin statement.
cout << "Introduce your age: ";
int age;
cin >> age;
cout << "Let us confirm your personal information." << endl
<< "Your full name is " << firstName << " " << lastName << " and you are " << age << " years old." << endl;
return 0;
}
Booleans
#include <iostream>
#include <ctime>
using namespace std;
int main(){
srand(time(0));
bool redLight = rand()%2; // I made the traffic light random.
cout << "redLight is " << redLight << endl; // just to check the binary value of redLight.
cout << boolalpha << "redLight is " << redLight << endl; // with boolalpha, we get true instead of 1.
if (redLight == true){ // "true" and 1 are the same (false = 0). The whole "== true" can be removed and it functions he same way.
cout << "Stop!" << endl;
} else {
cout << "Go ahead!" << endl;
}
return 0;
}
Relational operators
#include <iostream>
using namespace std;
int main(){
int number1 = 1;
int number2 = 2;
// the parenthesis are needed because the compiler will try to evaluate "<<" before the real comparison "<" since "<<" is on a higher level than "<" and it will give an error.
cout << number1 << " < " << number2 << " --> " << (number1 < number2) << endl; // 1 is smaller than 2... it is true. It will print a "1".
cout << number1 << " > " << number2 << " --> " << (number1 > number2) << endl; // 1 is bigger than 2... it is false. It will print a "0".
cout << boolalpha; // we are going to repeat the lines above after boolalpha and we'll get "true" or "false" instead of "1" and "0".
cout << number1 << " < " << number2 << " --> " << (number1 < number2) << endl; // 1 is smaller than 2... it is true. It will print "true".
cout << number1 << " > " << number2 << " --> " << (number1 > number2) << endl; // 1 is bigger than 2... it is false. It will print "false".
cout << noboolalpha; // from now on, the comparisons will print 1 and 0 back again.
cout << number1 << " <= " << number2 << " --> " << (number1 <= number2) << endl; // 1 is smaller than or equal to 2... it is true. It will print "1".
cout << number1 << " >= " << number2 << " --> " << (number1 >= number2) << endl; // 1 is bigger than or equal to 2... it is false. It will print "0".
cout << number1 << " == " << number2 << " --> " << (number1 == number2) << endl; // 1 is equal to 2... it is false. It will print "0".
cout << number1 << " != " << number2 << " --> " << (number1 != number2) << endl; // 1 is not equal to 2... it is true. It will print "1".
cout << "We can store the comparison result: ";
bool result = (number1 < number2);
cout << boolalpha << number1 << " < " << number2 << " --> " << result << endl;
return 0;
}
Logical operators
#include <iostream>
using namespace std;
int main(){
// we are going to see && (AND), || (OR) and ! (NOT) operators.
bool a = true;
bool b = false;
bool c = true;
cout << boolalpha;
// AND operator will evaluate to "true" when EVERY operand is true, otherwise, "false".
cout << "Basic AND operations:" << endl;
cout << a << " AND " << a << " --> " << (a && a) << endl; // true AND true is true.
cout << a << " AND " << b << " --> " << (a && b) << endl; // true AND false is false.
cout << b << " AND " << a << " --> " << (b && a) << endl; // false AND true is false.
cout << b << " AND " << b << " --> " << (b && b) << endl; // false AND false is false.
cout << a << " AND " << b << " AND " << c << " --> " << (a && b && c) << endl; // true AND false AND true is false.
// OR operator will evaluate to "true" when ANY operand is true. If all of them are false, it will evaluate to "false".
cout << "Basic OR operations:" << endl;
cout << a << " OR " << a << " --> " << (a || a) << endl; // true OR true is true.
cout << a << " OR " << b << " --> " << (a || b) << endl; // true OR false is true.
cout << b << " OR " << a << " --> " << (b || a) << endl; // false OR true is true.
cout << b << " OR " << b << " --> " << (b || b) << endl; // false OR false is false.
cout << a << " OR " << b << " OR " << c << " --> " << (a || b || c) << endl; // true OR false OR true is true.
// NOT operator gives the opposite of the boolean value.
cout << "Basic NOT operations:" << endl;
cout << "NOT " << a << "-->" << !a << endl; // NOT true is false.
cout << "NOT " << b << "-->" << !b << endl; // NOT false is true.
// Combining logical operators
cout << "Combining logical operations:" << endl;
// Let's write:
// NOT((true AND false) OR true).
// the logic behind it will be:
// true and false gives [false].
// [false] and true gives [true].
// NOT[true] gives {false}.
cout << "NOT (( " << a << " AND " << b << ") OR " << c << ") --> " << !((a && b) || c) << endl;
return 0;
}
Output formatting
#include <iostream>
#include <ios>
#include <iomanip>
using namespace std;
// all the following functions are included in "iostream", "ios" and "iomanip" libraries.
//
// "endl" gives a line break.
// "setw(X)"" prints the string in a fixed width determined by X.
// "flush" buffers every string coded and then it prints it all at once. It also forces the output.
// "left" makes the justification to the left.
// "right" makes the justification to the right.
// "internal" makes the justification of the minus sign to the left and the value to the right.
// "setfill('X')" prints a filling character determined by X instead of blank spaces.
// Boolean values naturally show up as 1 and 0. "boolalpha" will turn them into true and false. "noboolalpha" will turn them into 1 and 0 again.
// Positive number naturally do not show the plus sign. "showpos" will print the plus sign. "noshowpos" will hide it again.
// For outputting in different numeral systems: "dec", "hex", "oct".
// "showbase" will show the base of the numeral system. "noshowbase" will disable this (as default).
// "uppercase" will print the alphabetic characters in uppercase. "nouppercase" will disable this.
// Default number output will use scientific format when necessary. "fixed" will give as many digits in the decimal part as specified by the precision field "precision". "scientific" will print the values in scientific format. "cout.unset(scientific|fixed)" will revert the output format to defaults.
// "setprecision(X)" determines the X number of decimal digits.
// "showpoint" shows the decimal point and trailing zeros. "noshowpoint" disables this.
int main(){
//Let's try some of these functions.
// "endl".
cout << "After this message we have a line break" << endl << endl; // And another line break to better read the terminal messages.
// "flush".
cout << "We " << "have " << "several " ;
cout << "strings " << "flushed." << endl << flush << endl; //we're sure it's been sent to terminal
// Unformatted table.
cout << "Unformatted table:" << endl;
cout << "Name " << "Surname " << "Age " << endl;
cout << "Homer " << "Simpson " << "38 " << endl;
cout << "Max " << "Power " << "39 " << endl << endl;
// Formatted table. "setw()".
cout << "Formatted table:" << endl;
cout << setw(10) << "Name " << setw(10) << "Surname " << setw(6) << "Age " << endl;
cout << setw(10) << "Homer " << setw(10) << "Simpson " << setw(6) << "38 " << endl;
cout << setw(10) << "Max " << setw(10) << "Power " << setw(6) << "39 " << endl << endl;
// Formatted table with left justification. "setw()" and "left".
cout << "Formatted table with left justification:" << endl;
cout << left;
cout << setw(10) << "Name " << setw(10) << "Surname " << setw(6) << "Age " << endl;
cout << setw(10) << "Homer " << setw(10) << "Simpson " << setw(6) << "38 " << endl;
cout << setw(10) << "Max " << setw(10) << "Power " << setw(6) << "39 " << endl << endl;
// Formatted table with right justification. "setw()" and "right".
cout << "Formatted table with right justification:" << endl;
cout << right;
cout << setw(10) << "Name " << setw(10) << "Surname " << setw(6) << "Age " << endl;
cout << setw(10) << "Homer " << setw(10) << "Simpson " << setw(6) << "38 " << endl;
cout << setw(10) << "Max " << setw(10) << "Power " << setw(6) << "39 " << endl << endl;
// Formatted table with left justification and fillers. "setw()" and setfil('').
cout << "Formatted table:" << endl;
cout << left;
cout << setfill('-');
cout << setw(10) << "Name " << setw(10) << "Surname " << setw(6) << "Age " << endl;
cout << setw(10) << "Homer " << setw(10) << "Simpson " << setw(6) << "38 " << endl;
cout << setw(10) << "Max " << setw(10) << "Power " << setw(6) << "39 " << endl << endl;
return 0;
}
Numeric limits
#include <iostream>
#include <limits>
using namespace std;
// Let's show in terminal the numeric limits for each numeric type modifier:
int main(){
// short
cout << "For short, the smallest positive number is " << numeric_limits<short>::min() << ", the maximum positive number is " << numeric_limits<short>::max() << " and the lowest negative number is " << numeric_limits<short>::lowest() << endl;
// unsigned short
cout << "For unsigned short, the smallest positive number is " << numeric_limits<unsigned short>::min() << ", the maximum positive number is " << numeric_limits<unsigned short>::max() << " and the lowest negative number is " << numeric_limits<unsigned short>::lowest() << endl;
// int
cout << "For int , the smallest positive number is " << numeric_limits<int >::min() << ", the maximum positive number is " << numeric_limits<int >::max() << " and the lowest negative number is " << numeric_limits<int >::lowest() << endl;
// unsigned int
cout << "For unsigned int , the smallest positive number is " << numeric_limits<unsigned int >::min() << ", the maximum positive number is " << numeric_limits<unsigned int >::max() << " and the lowest negative number is " << numeric_limits<unsigned int >::lowest() << endl;
// long
cout << "For long, the smallest positive number is " << numeric_limits<long>::min() << ", the maximum positive number is " << numeric_limits<long>::max() << " and the lowest negative number is " << numeric_limits<long>::lowest() << endl;
//float
cout << "For float, the smallest positive number is " << numeric_limits<float>::min() << ", the maximum positive number is " << numeric_limits<float>::max() << " and the lowest negative number is " << numeric_limits<float>::lowest() << endl;
// double
cout << "For double, the smallest positive number is " << numeric_limits<double>::min() << ", the maximum positive number is " << numeric_limits<double>::max() << " and the lowest negative number is " << numeric_limits<double>::lowest() << endl;
return 0;
// long double
cout << "For long double, the smallest positive number is " << numeric_limits<long double>::min() << ", the maximum positive number is " << numeric_limits<long double>::max() << " and the lowest negative number is " << numeric_limits<long double>::lowest() << endl;
}
Math functions
#include <iostream>
#include <cmath>
using namespace std;
int main(){
double floatNumber = 7.7;
cout << floatNumber << " is " << floor(floatNumber) << " when rounded down and " << ceil(floatNumber) << " when rounded up." << endl;
cout << "3.4 is halfway rounded to " << round(3.4) << endl;
cout << "3.6 is halfway rounded to " << round(3.6) << endl;
cout << "3.5 is halfway rounded to " << round(3.5) << endl;
int negNumber = -5000;
cout << "The absolute value of " << negNumber << " is " << abs(negNumber) << endl;
cout << "2 to the power of 3 is " << pow(2,3) << endl;
int intNumber = 5;
cout << "The exponential of " << intNumber << " is " << exp(intNumber) << endl;
//exp(x) = e^x
cout << "The natural/neperian logarithm of 148.413 is " << log(148.413) << endl;
cout << "The common/dedadic/base10 logarithm of 100 is " << log10(100) << endl;
cout << "The square root of 2 is " << sqrt(2) << endl;
//There are a whole lot of functions in https://en.cppreference.com/w/cpp/header/cmath
return 0;
}