Programming in C and C++
Standard Template Library (STL)¶
C++ uses the standard libarary for different variables and functions.std:: must be added to the beginning of variable/function.
By writing using namespace std;, std:: does not have to be written.
Some examples:
#include <iostream>;for user input and output#include <string>;to use std::string data type
Comments¶
// single line comment
/* multi
line
comment */ Data Types and Variables¶
Each variable is a container for a value with a data type.
type variableName = value;
int: stores integersfloat&double: stores decimal values, double can store more decimal placeschar: stores a single letterstd::string: stores textbool: stores eithertrueorfalse
User Input and Output¶
The <iostream> library is needed for user input and output.
declaring a variable
taking in user input and storing it in the variable above
printing to the console (std::endl creates a new line)
std::string name;
std::cin >> name;
std::cout << "Hello " << num << std::endl; Operators¶
Operators are used to manipulate variables in different ways.
Arithmetic (mainly used for integers and decimals):
+ // Addition
- // Subtraction
* // Multiplication
/ // Division
% // Modulus (gives the remainder)
++ // Increment (adds 1 to variable)
-- // Decrement (subtracts 1 from variable) Assignment Operators (Shorthand version of doing an operation and then assigning it to the variable):
+= // addition assignment
-= // subtraction assignment
*= // multiplication assignment
/= // division assignment
%= // modulus assignment Comparison Operators (Compares two statements and returns a boolean):
== // equal to
!= // not equal to
> // greater than
< // less than
>= // greater than or equal to
<= // less than or equal to Logical Operators (Can also compare two statements and returns a boolean):
&& // and
|| // or
! // notC++ Strings¶
To use strings and string functions, <string> is needed.
#include <string>;
std::string a = "Hello";
std::string b = " World";
// String concatenation (adding two strings together will create a new string that contains both strings)
std::string c = a + b;
// Returns the length of the string, .size() does the same
int length = c.length();
// Acessing and changing the first character of the string
b[0] = 'Z';
// C style strings (array of char data types)
char d[] = "apple";
// Escape characters (Special characters that can be added to a string)
\' // Single quote
\" // Double quote
\\ // Backslash
\n // New line
\t // Tab Statements and Loops¶
// If statement
int a;
int b;
if (a > b) {
std::cout << "a is greater";
} else if (b > a) {
std::cout << "b is greater";
} else {
std::cout << "a is equal to b";
}
// While loop
int i = 0;
while (i < 5) {
std::cout << i;
i++;
}
// For loop
for (int i = 0; i < 5; i++) {
std::cout << i;
}
// Break & continue statements
// when placed inside a loop and the break; is reached, the loop will stop and move to the next line of code after the loop
break;
// when placed inside a loop and continue; is reached, the loop will skip the remaining lines of code after the continue statement and the loop will run its next iteration.
continue; Functions¶
// Creating a function
// Functions can return any data type and is declared before the function name (void means return nothing)
// Parameters can be included which pass variable into the functon, or can have no parameters
// By default a variable is passed by value, meaning the variable is copied and any changes to it in the function will not affect the variable outside the function
// & symbol before the parameter is passing a variable by reference. This means the variable is passed directly and changes to it inside the function will be reflected if the variable is outside the function
void functionName( // dataType param1, dataType& param2, ...) {
// code here
}
// Declaring the function
int main() {
functioName( // param1, param2, ... );
return 0;
} Arrays¶
// To declare an array, define the data type stored in the array and the number of arguments
// Arrays can only store one type of data type and elements cannot be added or removed
int numbers[4];
std::string fruits[3] = {"apple", "banana", "orange"};
// Accessing and changing array elements
std::string fruit = fruits[2];
fruits[0] = "pineapple";
// Traversing an array
for (int i = 0; i < fruits.size(); i++) {
std::cout << fruits[i];
}
// Traversing using for each loop
for (int fruit : fruits) {
std::cout << fruits[i];
}
// Multidimensional arrays (array with arrays inside)
int matrix[5][5]; Pointers¶
// Pointers are variables that store the memory adress of another variable
// The memory address is where a variable is stored which can be referenced
int x = 5;
int* ptr = &x; // & means get the adress of the variable
std::cout << ptr << std::endl; // prints something like 0x23f4e6
// Dereferencing pointers (this gets the value of the variable referenced by the pointer)
std::cout << *ptr << std::endl; // prints 5
// Changing pointer values
*ptr = 7; // this also changes x
int y = 3;
int* ptr2 = &y;
ptr = ptr2; // ptr now points to ptr2's variable which is y File I/O¶
#include <iostream>
#include <fstream> // needed to use files
int main() {
// Writing to a file
std::ofstream myInputFile("filename1.txt"); // create and open the file
myInputFile << "Hello World" << std::endl; // writing to the file
myInputFile.close(); // close the file
// Reading to a file
std::ifstream myOutputFile("filename2.txt"); // open input file
std::string line; // used to read line by line of the input file
while (getline(myInputFile, line)) {
std::cout << line << std::endl;
}
myInputFile.close();
} Command line arguments¶
// C++ programs can take arguments from the command line when executing code from the terminal
// argc is the number of command line arguments, (the program name itself is one of the arguments)
// argv is a vector(a type of array) that stores those arguments as c style strings
int main(int argc, char* argv[]) {
// checking number of arguments
if (argc != 2) {
std::cerr << "Wrong number of arguments"; // prints an error message to the console
exit(1); // exits the program
}
// accessing the arguments
std::string programName = argv[0];
std::string argument1 = argv[1];
} Structs¶
// Structs are containers that can group variables into one data type
struct Coordinate {
int x;
int y;
};
// Acessing and setting variables of the struct
int main() {
Coordinate p1;
p1.x = 0;
p1.y = 1;
} Classes & Objects¶
// Classes are templates for objects. Classes by default have private member variables and public member functions.
class Person {
// Member variables
private:
std::string name;
int age;
std::string job;
// Member functions
public:
Person(std::string& personName, int& personAge, std::string& personJob) : name(personName), age(personAge), job(personJob) {} // Constructor (pass in values when creating object)
std::string getName() const { return name;}
void setJob(const std::string& jobTitle) { job = jobTitle; }
};
int main() {
Person john("John", 30, "Scientist");
Person jane("Jane", 25, "Engineer");
john.setJob("Architect");
std::string name2 = jane.getName();
} Vectors¶
// Vectors are dynamic or resizeable arrays
#include <vector>
std::vector<int> nums = {1, 2, 3, 4, 5};
// Acessing and changing elements
int x = nums[2];
nums[0] = x;
// Adding an element
nums.push_back(6);
// Removing the last element
nums.pop_back();
// Get first and last elements
int y = nums.front();
int z = nums.back();
// Check if vector is empty & remove all elements from the vector
bool isEmpty = nums.empty();
nums.clear();
// Traversing vector
for (int num : nums) {
std::cout << num;
} Iterators¶
// Iterators are general form of pointers that can be used to traverse containers
std::vector<int> nums = {1, 2, 3, 4, 5};
std::vector<int>::iterator it; // Used to traverse containers, access & remove elements
std::vector<int>::const_iterator itr; // Iterator values cannot be changed, used to traverse
for (itr = nums.begin(); itr != nums.end(); ++itr) {
std::cout << *it; // Dereference iterator to access value
}
it = nums.erase(it);