GO |
Go to C++ |
Intro
Used for creating high-performance application => fast compilation time and run time
It supports concurrency and supports memory management
Some of it's main uses are:
Note: Statically typed means that the variable types are known at compile time
A compiler, like GCC, is needed to translate the Go code into a language that the computer will understand
It supports concurrency and supports memory management
Some of it's main uses are:
- Web development (server-side)
- Developing network-based programs
- Cloud-native development
Note: Statically typed means that the variable types are known at compile time
A compiler, like GCC, is needed to translate the Go code into a language that the computer will understand
Basics
- helloworld.go
import ("fmt") // Import packages
func main() { // function
fmt.Println("Hello World!") // Statement / expression
/* In Go, statements are separated by ending a line (hitting the Enter key) or by a semicolon ";" */
}
In the terminal, execute this: go run .\helloworld.go
> Hello World!
To save the program as an executable, execute this: go build .\helloworld.go
Note: In Go, any executable code belongs to the main package.
Basics of Go: Variables, Constants, Printing, Arrays, operators, condition, Switch, for loops
Variables
Syntax: var variablename type = value | Note: You always have to specify either type or value (or both).
OR: variablename := value | Note: In this case, the type of the variable is inferred from the value while compiling.
/* := can only be used in functions and cannot be used for variable declaration, a value must be given */
Examples
package main
import ("fmt")
func main() {
var student1 string = "John" //type is string
var student2 = "Jane" //type is inferred
x := 2 //type is inferred
/* Without declaring an initial value */
var a string // set to default value => ""
var b int // set to default value => 0
var c bool // set to default value => false
c = true // values can be assigned after initialization
var ay, by, cy, dy int = 1, 3, 5, 7 // Multiple variable declaration (all must be an int type)
ca, da := 7, "World!"
}
Constants
A variable with a fixed value that cannot be changed
Syntax: const CONSTNAME type = value | Note: value must be assigned
Example
package main
import ("fmt")
const PI = 3.14 // Creating a constant w/o type
const A int = 1 // Creating a constant w/ type
const ( // Creating multiple constants
X int = 1
G = 9.81
Z = "Hi!"
)
func main() {
fmt.Println(PI)
}
Syntax: var variablename type = value | Note: You always have to specify either type or value (or both).
OR: variablename := value | Note: In this case, the type of the variable is inferred from the value while compiling.
/* := can only be used in functions and cannot be used for variable declaration, a value must be given */
Examples
package main
import ("fmt")
func main() {
var student1 string = "John" //type is string
var student2 = "Jane" //type is inferred
x := 2 //type is inferred
/* Without declaring an initial value */
var a string // set to default value => ""
var b int // set to default value => 0
var c bool // set to default value => false
c = true // values can be assigned after initialization
var ay, by, cy, dy int = 1, 3, 5, 7 // Multiple variable declaration (all must be an int type)
ca, da := 7, "World!"
}
Constants
A variable with a fixed value that cannot be changed
Syntax: const CONSTNAME type = value | Note: value must be assigned
Example
package main
import ("fmt")
const PI = 3.14 // Creating a constant w/o type
const A int = 1 // Creating a constant w/ type
const ( // Creating multiple constants
X int = 1
G = 9.81
Z = "Hi!"
)
func main() {
fmt.Println(PI)
}
Printing
package main
import ("fmt")
func main() {
var i,j string = "Hello","World"
fmt.Print(i, " ", j) // Hello World // space must be manually added
var k,m = 10,20
fmt.Print(k,m) // 10 20 // space automatically added since neither are strings
var g,h string = "Hello","World"
fmt.Println(g,h) // Hello World // white space gets automatically added with Println and new line is added at the end
// Formatting
var a string = "Hello"
var b int = 15
fmt.Printf("i has value: %v and type: %T\n", a, a) // i has value: Hello and type: string
fmt.Printf("j has value: %v and type: %T", b, b) // j has value: 15 and type: int
}
package main
import ("fmt")
func main() {
var i,j string = "Hello","World"
fmt.Print(i, " ", j) // Hello World // space must be manually added
var k,m = 10,20
fmt.Print(k,m) // 10 20 // space automatically added since neither are strings
var g,h string = "Hello","World"
fmt.Println(g,h) // Hello World // white space gets automatically added with Println and new line is added at the end
// Formatting
var a string = "Hello"
var b int = 15
fmt.Printf("i has value: %v and type: %T\n", a, a) // i has value: Hello and type: string
fmt.Printf("j has value: %v and type: %T", b, b) // j has value: 15 and type: int
}
Data Types
package main
import ("fmt")
func main() {
var c float32 = 3.14 // 32-bit Floating point number
var y uint = 4500 // unsigned integers can only store non-negative values [0 to 18446744073709551615]
var z int8 = 9 //int8 is an 8-bit integer [-128 to 127]
}
package main
import ("fmt")
func main() {
var c float32 = 3.14 // 32-bit Floating point number
var y uint = 4500 // unsigned integers can only store non-negative values [0 to 18446744073709551615]
var z int8 = 9 //int8 is an 8-bit integer [-128 to 127]
}
Arrays
Arrays are used to store multiple values of the same type in a single variable
Syntax: var array_name = [length]datatype{values} // here length is defined
OR: var array_name = [...]datatype{values} // here length is inferred
Example
package main
import ("fmt")
func main() {
var arr1 = [3]int{1,2,3}
arr2 := [5]int{4,5,6,7,8}
var arr3 = [...]int{1,2,3} // inferred length
fmt.Println(arr3[2]) // 3 // accessing elements of an array
arr3[2] = 50 // change elements of an array
fmt.Println(arr3) // 50
/* Array Initialization */
arr4 := [5]int{} // [0 0 0 0 0] //not initialized
arr5 := [5]int{1,2} // [1 2 0 0 0] //partially initialized
arr6 := [5]int{1,2,3,4,5} // [1 2 3 4 5] //fully initialized
arr7 := [5]int{1:10,2:40} // [0 10 40 0 0] //initialize only the specified index
fmt.Println(len(arr6)) // 5
}
/* Slicing an array - Syntax only */
var myarray = [length]datatype{values} // An array
myslice := myarray[start:end] // A slice made from the array
slice_name = append(slice_name, element1, element2, ...) // Appending elements to a slice
slice3 = append(slice1, slice2...) // Appending 2 slices | Note: The '...' after slice2 is necessary when appending the elements of one slice to another.
Arrays are used to store multiple values of the same type in a single variable
Syntax: var array_name = [length]datatype{values} // here length is defined
OR: var array_name = [...]datatype{values} // here length is inferred
Example
package main
import ("fmt")
func main() {
var arr1 = [3]int{1,2,3}
arr2 := [5]int{4,5,6,7,8}
var arr3 = [...]int{1,2,3} // inferred length
fmt.Println(arr3[2]) // 3 // accessing elements of an array
arr3[2] = 50 // change elements of an array
fmt.Println(arr3) // 50
/* Array Initialization */
arr4 := [5]int{} // [0 0 0 0 0] //not initialized
arr5 := [5]int{1,2} // [1 2 0 0 0] //partially initialized
arr6 := [5]int{1,2,3,4,5} // [1 2 3 4 5] //fully initialized
arr7 := [5]int{1:10,2:40} // [0 10 40 0 0] //initialize only the specified index
fmt.Println(len(arr6)) // 5
}
/* Slicing an array - Syntax only */
var myarray = [length]datatype{values} // An array
myslice := myarray[start:end] // A slice made from the array
slice_name = append(slice_name, element1, element2, ...) // Appending elements to a slice
slice3 = append(slice1, slice2...) // Appending 2 slices | Note: The '...' after slice2 is necessary when appending the elements of one slice to another.
Operators
AND = && ; Bitwise AND = &
OR = || ; Bitwise OR = |
NOT = !
XOR = ^
Conditions
package main
import ("fmt")
func main() {
time := 22
if time < 10 {
fmt.Println("Good morning.")
} else if time < 20 {
fmt.Println("Good day.")
} else {
fmt.Println("Good evening.")
}
}
Switch
// No break statements necessary - once a match, it will stop
// All case value should have same data type
package main
import ("fmt")
func main() {
day := 8
switch day {
case 1:
fmt.Println("Monday")
case 2:
fmt.Println("Tuesday")
case 3:
fmt.Println("Wednesday")
case 4:
fmt.Println("Thursday")
case 5:
fmt.Println("Friday")
case 6:
fmt.Println("Saturday")
case 7:
fmt.Println("Sunday")
default:
fmt.Println("Not a weekday")
}
}
// Multi-case Switch statement
package main
import ("fmt")
func main() {
day := 5
switch day {
case 1,3,5:
fmt.Println("Odd weekday")
case 2,4:
fmt.Println("Even weekday")
case 6,7:
fmt.Println("Weekend")
default:
fmt.Println("Invalid day of day number")
}
}
For loop - the only kind of loop in Go
package main
import ("fmt")
func main() {
for i:=0; i < 110; i+=10 {
if i == 70 {
continue
}
fmt.Println(i)
if i == 90 {
break
}
}
}
// Looping over an array
package main
import ("fmt")
func main() {
fruits := [3]string{"apple", "orange", "banana"}
for idx, val := range fruits {
fmt.Printf("%v\t%v\n", idx, val)
}
}
/* Output
0 apple
1 orange
2 banana
*/
AND = && ; Bitwise AND = &
OR = || ; Bitwise OR = |
NOT = !
XOR = ^
Conditions
package main
import ("fmt")
func main() {
time := 22
if time < 10 {
fmt.Println("Good morning.")
} else if time < 20 {
fmt.Println("Good day.")
} else {
fmt.Println("Good evening.")
}
}
Switch
// No break statements necessary - once a match, it will stop
// All case value should have same data type
package main
import ("fmt")
func main() {
day := 8
switch day {
case 1:
fmt.Println("Monday")
case 2:
fmt.Println("Tuesday")
case 3:
fmt.Println("Wednesday")
case 4:
fmt.Println("Thursday")
case 5:
fmt.Println("Friday")
case 6:
fmt.Println("Saturday")
case 7:
fmt.Println("Sunday")
default:
fmt.Println("Not a weekday")
}
}
// Multi-case Switch statement
package main
import ("fmt")
func main() {
day := 5
switch day {
case 1,3,5:
fmt.Println("Odd weekday")
case 2,4:
fmt.Println("Even weekday")
case 6,7:
fmt.Println("Weekend")
default:
fmt.Println("Invalid day of day number")
}
}
For loop - the only kind of loop in Go
package main
import ("fmt")
func main() {
for i:=0; i < 110; i+=10 {
if i == 70 {
continue
}
fmt.Println(i)
if i == 90 {
break
}
}
}
// Looping over an array
package main
import ("fmt")
func main() {
fruits := [3]string{"apple", "orange", "banana"}
for idx, val := range fruits {
fmt.Printf("%v\t%v\n", idx, val)
}
}
/* Output
0 apple
1 orange
2 banana
*/
Functions
/* Syntax
func FunctionName(param1 type, param2 type) return_type {
// code to be executed
return output
}
*/
// Example 1: simple
package main
import ("fmt")
func myFunction(x int, y int) int {
return x + y
}
func main() {
fmt.Println(myFunction(1, 2))
}
// Example 2: Naming the return values
package main
import ("fmt")
func myFunction(x int, y string) (result int, txt1 string) {
result = x + x
txt1 = y + " World!"
return
}
func main() {
a, _ := myFunction(5, "Hello") // the 2nd return value is omitted by using an '_'
fmt.Println(a)
}
// Example 3: recursion
package main
import ("fmt")
func factorial_recursion(x float64) (y float64) {
if x > 0 {
y = x * factorial_recursion(x-1)
} else {
y = 1
}
return
}
func main() {
fmt.Println(factorial_recursion(4))
}
/* Syntax
func FunctionName(param1 type, param2 type) return_type {
// code to be executed
return output
}
*/
// Example 1: simple
package main
import ("fmt")
func myFunction(x int, y int) int {
return x + y
}
func main() {
fmt.Println(myFunction(1, 2))
}
// Example 2: Naming the return values
package main
import ("fmt")
func myFunction(x int, y string) (result int, txt1 string) {
result = x + x
txt1 = y + " World!"
return
}
func main() {
a, _ := myFunction(5, "Hello") // the 2nd return value is omitted by using an '_'
fmt.Println(a)
}
// Example 3: recursion
package main
import ("fmt")
func factorial_recursion(x float64) (y float64) {
if x > 0 {
y = x * factorial_recursion(x-1)
} else {
y = 1
}
return
}
func main() {
fmt.Println(factorial_recursion(4))
}
Struct
package main
import ("fmt")
type Person struct {
name string
age int
job string
salary int
}
func main() {
var pers1 Person
var pers2 Person
// Pers1 specification
pers1.name = "Nina"
pers1.age = 24
pers1.job = "Secretary"
pers1.salary = 120000
// Pers2 specification
pers2.name = "Julia"
pers2.age = 20
pers2.job = "Archeologist"
pers2.salary = 30000
// Print Pers1 info by calling a function
printPerson(pers1)
// Print Pers2 info by calling a function
printPerson(pers2)
}
func printPerson(pers Person) {
fmt.Println("Name: ", pers.name)
fmt.Println("Age: ", pers.age)
fmt.Println("Job: ", pers.job)
fmt.Println("Salary: ", pers.salary)
}
package main
import ("fmt")
type Person struct {
name string
age int
job string
salary int
}
func main() {
var pers1 Person
var pers2 Person
// Pers1 specification
pers1.name = "Nina"
pers1.age = 24
pers1.job = "Secretary"
pers1.salary = 120000
// Pers2 specification
pers2.name = "Julia"
pers2.age = 20
pers2.job = "Archeologist"
pers2.salary = 30000
// Print Pers1 info by calling a function
printPerson(pers1)
// Print Pers2 info by calling a function
printPerson(pers2)
}
func printPerson(pers Person) {
fmt.Println("Name: ", pers.name)
fmt.Println("Age: ", pers.age)
fmt.Println("Job: ", pers.job)
fmt.Println("Salary: ", pers.salary)
}
Maps
Syntax
var a = map[KeyType]ValueType{key1:value1, key2:value2,...}
b := map[KeyType]ValueType{key1:value1, key2:value2,...}
var a = make(map[KeyType]ValueType) // using make function
// Example 1: simple
package main
import ("fmt")
func main() {
var a = map[string]string{"brand": "Ford", "model": "Mustang", "year": "1964"}
a["year"] = "1970" // Updating an element
a["color"] = "red" // Adding an element
delete(a,"year") // Deleting an element
val2, ok2 := a["day"] // Checking for non-existing key and its value => val2 = "", ok2 = false
b := make(map[string]int) //make is the right way to create an empty map because this b == nil is false
b["Oslo"] = 1
b["Bergen"] = 2
b["Trondheim"] = 3
b["Stavanger"] = 4
fmt.Printf("a\t%v\n", a)
fmt.Printf(a["brand"]) // accessing a single element
fmt.Printf("b\t%v\n", b)
}
/* Maps are references to hash tables. If two map variables refer to the same hash table, changing the content of one variable affect the content of the other.
Sample output
a = map[brand:Ford model:Mustang year:1964]
b = map[brand:Ford model:Mustang year:1964]
After change to b:
a = map[brand:Ford model:Mustang year:1970]
b = map[brand:Ford model:Mustang year:1970]
*/
// Example 2: Looping through maps
package main
import ("fmt")
func main() {
a := map[string]int{"one": 1, "two": 2, "three": 3, "four": 4}
var b = []string // defining the order
b = append(b, "one", "two", "three", "four")
for k, v := range a { // loop with no order
fmt.Printf("%v : %v, ", k, v)
}
fmt.Println()
for _, element := range b { // loop with the defined order
fmt.Printf("%v : %v, ", element, a[element])
}
}
/* Output
two : 2, three : 3, four : 4, one : 1,
one : 1, two : 2, three : 3, four : 4,
*/
Syntax
var a = map[KeyType]ValueType{key1:value1, key2:value2,...}
b := map[KeyType]ValueType{key1:value1, key2:value2,...}
var a = make(map[KeyType]ValueType) // using make function
// Example 1: simple
package main
import ("fmt")
func main() {
var a = map[string]string{"brand": "Ford", "model": "Mustang", "year": "1964"}
a["year"] = "1970" // Updating an element
a["color"] = "red" // Adding an element
delete(a,"year") // Deleting an element
val2, ok2 := a["day"] // Checking for non-existing key and its value => val2 = "", ok2 = false
b := make(map[string]int) //make is the right way to create an empty map because this b == nil is false
b["Oslo"] = 1
b["Bergen"] = 2
b["Trondheim"] = 3
b["Stavanger"] = 4
fmt.Printf("a\t%v\n", a)
fmt.Printf(a["brand"]) // accessing a single element
fmt.Printf("b\t%v\n", b)
}
/* Maps are references to hash tables. If two map variables refer to the same hash table, changing the content of one variable affect the content of the other.
Sample output
a = map[brand:Ford model:Mustang year:1964]
b = map[brand:Ford model:Mustang year:1964]
After change to b:
a = map[brand:Ford model:Mustang year:1970]
b = map[brand:Ford model:Mustang year:1970]
*/
// Example 2: Looping through maps
package main
import ("fmt")
func main() {
a := map[string]int{"one": 1, "two": 2, "three": 3, "four": 4}
var b = []string // defining the order
b = append(b, "one", "two", "three", "four")
for k, v := range a { // loop with no order
fmt.Printf("%v : %v, ", k, v)
}
fmt.Println()
for _, element := range b { // loop with the defined order
fmt.Printf("%v : %v, ", element, a[element])
}
}
/* Output
two : 2, three : 3, four : 4, one : 1,
one : 1, two : 2, three : 3, four : 4,
*/
C++
Intro
C++ is an OOP language and it can be used to create high-performance applications. It gives programmers a high level of control over system resources and memory. It is used when working with OS, GUI, and embedded systems.
C++ and C have almost the same syntax - the main difference between C and C++ is that C++ supports classes and objects, while C does not. To work with C++, we would need GCC as a compiler.
C++ and C have almost the same syntax - the main difference between C and C++ is that C++ supports classes and objects, while C does not. To work with C++, we would need GCC as a compiler.
Basics
- myfirst.cpp
using namespace std;
int main() {
cout << "Hello World!";
// std::cout << "Hello World!"; // if using namespace line was not written
int x, y;
int sum;
cout << "Type a number: ";
cin >> x; // getting user input
cout << "Type another number: ";
cin >> y;
sum = x + y;
cout << "Sum is: " << sum;
return 0;
}
Variables, strings, math, arrays
Variables and constant work exactly the same way they do in C and C#
Data Types and operator are the same as C and C#.
The return value of a comparison is either 1 or 0, which means true (1) or false (0).
int x = 5, y = 3;
cout << (x > y); // returns 1 (true) because 5 is greater than 3
Some String Notes
string txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
cout << "The length of the txt string is: " << txt.size();
cout << "The length of the txt string is: " << txt.length(); // same as above line
string z = txt + 10; // causes an error, numbers cannot be concatenated with strings
Accessing characters of a string is same as C#
cin can only take in 1 number or string with no spaces or tabs => use getline
string fullName; // without namespace line, this would be: std::string fullName;
cout << "Type your full name: ";
getline (cin, fullName);
cout << "Your name is: " << fullName; // your name is: Kannika Kabilar
Math
#include <cmath>
cout << sqrt(64);
cout << round(2.6);
cout << log(2);
cout << max(2, 9);
if ... else if ... else ... and shorthand if ... ? then : else and switch is the same as C and C#
for loop and for each loop, and break & continue is the same as Java, C, and C#
Arrays
string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"};
// string cars[] = {"Volvo", "BMW", "Ford"}; // Three array elements - omitting array size
cars[0] = "Opel";
cout << cars[0];
// Now outputs Opel instead of Volvo
int myNumbers[5] = {10, 20, 30, 40, 50};
int getArrayLength = sizeof(myNumbers) / sizeof(int);
cout << getArrayLength;
// Multi-dimensional array
string letters[2][4] = {
{ "A", "B", "C", "D" },
{ "E", "F", "G", "H" }
};
cout << letters[0][2]; // Outputs "C"
Data Types and operator are the same as C and C#.
The return value of a comparison is either 1 or 0, which means true (1) or false (0).
int x = 5, y = 3;
cout << (x > y); // returns 1 (true) because 5 is greater than 3
Some String Notes
string txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
cout << "The length of the txt string is: " << txt.size();
cout << "The length of the txt string is: " << txt.length(); // same as above line
string z = txt + 10; // causes an error, numbers cannot be concatenated with strings
Accessing characters of a string is same as C#
cin can only take in 1 number or string with no spaces or tabs => use getline
string fullName; // without namespace line, this would be: std::string fullName;
cout << "Type your full name: ";
getline (cin, fullName);
cout << "Your name is: " << fullName; // your name is: Kannika Kabilar
Math
#include <cmath>
cout << sqrt(64);
cout << round(2.6);
cout << log(2);
cout << max(2, 9);
if ... else if ... else ... and shorthand if ... ? then : else and switch is the same as C and C#
for loop and for each loop, and break & continue is the same as Java, C, and C#
Arrays
string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"};
// string cars[] = {"Volvo", "BMW", "Ford"}; // Three array elements - omitting array size
cars[0] = "Opel";
cout << cars[0];
// Now outputs Opel instead of Volvo
int myNumbers[5] = {10, 20, 30, 40, 50};
int getArrayLength = sizeof(myNumbers) / sizeof(int);
cout << getArrayLength;
// Multi-dimensional array
string letters[2][4] = {
{ "A", "B", "C", "D" },
{ "E", "F", "G", "H" }
};
cout << letters[0][2]; // Outputs "C"
Struct
// Declare a structure named "car"
struct car {
string brand;
string model;
int year;
};
int main() {
// Create a car structure and store it in myCar1;
car myCar1;
myCar1.brand = "BMW";
myCar1.model = "X5";
myCar1.year = 1999;
// Create another car structure and store it in myCar2;
car myCar2;
myCar2.brand = "Ford";
myCar2.model = "Focus";
myCar2.year = 2001;
// Print the structure members
cout << myCar1.brand << " " << myCar1.model << " " << myCar1.year << "\n";
cout << myCar2.brand << " " << myCar2.model << " " << myCar2.year << "\n";
return 0;
}
struct car {
string brand;
string model;
int year;
};
int main() {
// Create a car structure and store it in myCar1;
car myCar1;
myCar1.brand = "BMW";
myCar1.model = "X5";
myCar1.year = 1999;
// Create another car structure and store it in myCar2;
car myCar2;
myCar2.brand = "Ford";
myCar2.model = "Focus";
myCar2.year = 2001;
// Print the structure members
cout << myCar1.brand << " " << myCar1.model << " " << myCar1.year << "\n";
cout << myCar2.brand << " " << myCar2.model << " " << myCar2.year << "\n";
return 0;
}
References & Pointers
string food = "Pizza";
string &meal = food;
cout << food << "\n"; // Outputs Pizza
cout << meal << "\n"; // Outputs Pizza
cout << &food; // Outputs 0x6dfed4
string* ptr = &food; // A pointer variable, with the name ptr, that stores the address of food
// Output the value of food (Pizza)
cout << food << "\n";
// Output the memory address of food (0x6dfed4)
cout << &food << "\n";
// Output the memory address of food with the pointer (0x6dfed4)
cout << ptr << "\n";
// Dereference: Output the value of food with the pointer (Pizza)
cout << *ptr << "\n";
// Change the value of the pointer
*ptr = "Hamburger";
// Output the new value of the pointer (Hamburger)
cout << *ptr << "\n";
// Output the new value of the food variable (Hamburger)
cout << food << "\n";
string &meal = food;
cout << food << "\n"; // Outputs Pizza
cout << meal << "\n"; // Outputs Pizza
cout << &food; // Outputs 0x6dfed4
string* ptr = &food; // A pointer variable, with the name ptr, that stores the address of food
// Output the value of food (Pizza)
cout << food << "\n";
// Output the memory address of food (0x6dfed4)
cout << &food << "\n";
// Output the memory address of food with the pointer (0x6dfed4)
cout << ptr << "\n";
// Dereference: Output the value of food with the pointer (Pizza)
cout << *ptr << "\n";
// Change the value of the pointer
*ptr = "Hamburger";
// Output the new value of the pointer (Hamburger)
cout << *ptr << "\n";
// Output the new value of the food variable (Hamburger)
cout << food << "\n";
Functions
// Default parameter value
void myFunction(string country = "Canada") {
cout << country << "\n";
}
int main() {
myFunction("India"); // India
myFunction(); // Canada
myFunction("USA"); // USA
return 0;
}
// Passing vals by reference
void swapNums(int &x, int &y) {
int z = x;
x = y;
y = z;
}
int main() {
int firstNum = 10;
int secondNum = 20;
cout << "Before swap: " << "\n";
cout << firstNum << secondNum << "\n";
// Call the function, which will change the values of firstNum and secondNum
swapNums(firstNum, secondNum);
cout << "After swap: " << "\n";
cout << firstNum << secondNum << "\n";
return 0;
}
// Passing Arrays - sent through reference, so values of arr can be changed
void myFunction(int myNumbers[5]) {
for (int i = 0; i < 5; i++) {
cout << myNumbers[i] << "\n";
}
}
int main() {
int myNumbers[5] = {10, 20, 30, 40, 50};
myFunction(myNumbers);
return 0;
}
Function overloading and recursion work as expected
void myFunction(string country = "Canada") {
cout << country << "\n";
}
int main() {
myFunction("India"); // India
myFunction(); // Canada
myFunction("USA"); // USA
return 0;
}
// Passing vals by reference
void swapNums(int &x, int &y) {
int z = x;
x = y;
y = z;
}
int main() {
int firstNum = 10;
int secondNum = 20;
cout << "Before swap: " << "\n";
cout << firstNum << secondNum << "\n";
// Call the function, which will change the values of firstNum and secondNum
swapNums(firstNum, secondNum);
cout << "After swap: " << "\n";
cout << firstNum << secondNum << "\n";
return 0;
}
// Passing Arrays - sent through reference, so values of arr can be changed
void myFunction(int myNumbers[5]) {
for (int i = 0; i < 5; i++) {
cout << myNumbers[i] << "\n";
}
}
int main() {
int myNumbers[5] = {10, 20, 30, 40, 50};
myFunction(myNumbers);
return 0;
}
Function overloading and recursion work as expected
Classes
class MyClass { // The class
public: // Access specifier (private, protected - by default it is private)
int myNum; // Attribute (int variable)
string myString; // Attribute (string variable)
void myMethod() { // Method/function defined inside the class
cout << "Hello World!";
}
void myMethod2(); // Method/function declaration
MyClass() { // Constructor (constructors can also be created outside of the class like myMethod2
cout << "I just created an instance of MyClass!";
}
};
// Method/function definition outside the class
void MyClass::myMethod2() {
cout << "Hello World 2.0!";
}
int main() {
MyClass myObj; // Create an object of MyClass
// Access attributes and set values
myObj.myNum = 15;
myObj.myString = "Some text";
// Print attribute values
cout << myObj.myNum << "\n";
cout << myObj.myString;
myObj.myMethod(); // Call the method
myObj.myMethod2(); // Call the method
return 0;
}
public: // Access specifier (private, protected - by default it is private)
int myNum; // Attribute (int variable)
string myString; // Attribute (string variable)
void myMethod() { // Method/function defined inside the class
cout << "Hello World!";
}
void myMethod2(); // Method/function declaration
MyClass() { // Constructor (constructors can also be created outside of the class like myMethod2
cout << "I just created an instance of MyClass!";
}
};
// Method/function definition outside the class
void MyClass::myMethod2() {
cout << "Hello World 2.0!";
}
int main() {
MyClass myObj; // Create an object of MyClass
// Access attributes and set values
myObj.myNum = 15;
myObj.myString = "Some text";
// Print attribute values
cout << myObj.myNum << "\n";
cout << myObj.myString;
myObj.myMethod(); // Call the method
myObj.myMethod2(); // Call the method
return 0;
}
Encapsulation
Encapsulation
#include <iostream>
using namespace std;
class Employee {
private:
// Private attribute
int salary;
public:
// Setter
void setSalary(int s) {
salary = s;
}
// Getter
int getSalary() {
return salary;
}
};
int main() {
Employee myObj;
myObj.setSalary(50000);
cout << myObj.getSalary();
return 0;
}
#include <iostream>
using namespace std;
class Employee {
private:
// Private attribute
int salary;
public:
// Setter
void setSalary(int s) {
salary = s;
}
// Getter
int getSalary() {
return salary;
}
};
int main() {
Employee myObj;
myObj.setSalary(50000);
cout << myObj.getSalary();
return 0;
}
INHERITANCE
Inheritance
// MULTI-LEVEL INHERITANCE
// Base class (parent)
class MyClass {
public:
void myFunction() {
cout << "Some content in parent class." ;
}
};
// Derived class (child)
class MyChild: public MyClass {
};
// Derived class (grandchild)
class MyGrandChild: public MyChild {
};
int main() {
MyGrandChild myObj;
myObj.myFunction();
return 0;
}
// MULTIPLE INHERITANCE
// Base class
class MyClass {
public:
void myFunction() {
cout << "Some content in parent class." ;
}
};
// Another base class
class MyOtherClass {
public:
void myOtherFunction() {
cout << "Some content in another class." ;
}
};
// Derived class
class MyChildClass: public MyClass, public MyOtherClass {
};
int main() {
MyChildClass myObj;
myObj.myFunction();
myObj.myOtherFunction();
return 0;
}
// MULTI-LEVEL INHERITANCE
// Base class (parent)
class MyClass {
public:
void myFunction() {
cout << "Some content in parent class." ;
}
};
// Derived class (child)
class MyChild: public MyClass {
};
// Derived class (grandchild)
class MyGrandChild: public MyChild {
};
int main() {
MyGrandChild myObj;
myObj.myFunction();
return 0;
}
// MULTIPLE INHERITANCE
// Base class
class MyClass {
public:
void myFunction() {
cout << "Some content in parent class." ;
}
};
// Another base class
class MyOtherClass {
public:
void myOtherFunction() {
cout << "Some content in another class." ;
}
};
// Derived class
class MyChildClass: public MyClass, public MyOtherClass {
};
int main() {
MyChildClass myObj;
myObj.myFunction();
myObj.myOtherFunction();
return 0;
}
Polymorphism
Polymorphism
#include <iostream>
#include <string>
using namespace std;
// Base class
class Animal {
public:
void animalSound() {
cout << "The animal makes a sound \n";
}
};
// Derived class
class Pig : public Animal {
public:
void animalSound() {
cout << "The pig says: wee wee \n";
}
};
// Derived class
class Dog : public Animal {
public:
void animalSound() {
cout << "The dog says: bow wow \n";
}
};
int main() {
Animal myAnimal;
Pig myPig;
Dog myDog;
myAnimal.animalSound();
myPig.animalSound();
myDog.animalSound();
return 0;
}
#include <iostream>
#include <string>
using namespace std;
// Base class
class Animal {
public:
void animalSound() {
cout << "The animal makes a sound \n";
}
};
// Derived class
class Pig : public Animal {
public:
void animalSound() {
cout << "The pig says: wee wee \n";
}
};
// Derived class
class Dog : public Animal {
public:
void animalSound() {
cout << "The dog says: bow wow \n";
}
};
int main() {
Animal myAnimal;
Pig myPig;
Dog myDog;
myAnimal.animalSound();
myPig.animalSound();
myDog.animalSound();
return 0;
}
Files
#include <iostream>
#include <fstream>
using namespace std;
/* Note: fstream can be used for both reading and writing */
int main() {
// CREATING AND WRITING TO FILES
// Create and open a text file
ofstream MyFile("filename.txt");
// Write to the file
MyFile << "Files can be tricky, but it is fun enough!";
// Close the file
MyFile.close();
// READING FILES
// Create a text string, which is used to output the text file
string myText;
// Read from the text file
ifstream MyReadFile("filename.txt");
// Use a while loop together with the getline() function to read the file line by line
while (getline (MyReadFile, myText)) {
// Output the text from the file
cout << myText;
}
// Close the file
MyReadFile.close();
}
#include <fstream>
using namespace std;
/* Note: fstream can be used for both reading and writing */
int main() {
// CREATING AND WRITING TO FILES
// Create and open a text file
ofstream MyFile("filename.txt");
// Write to the file
MyFile << "Files can be tricky, but it is fun enough!";
// Close the file
MyFile.close();
// READING FILES
// Create a text string, which is used to output the text file
string myText;
// Read from the text file
ifstream MyReadFile("filename.txt");
// Use a while loop together with the getline() function to read the file line by line
while (getline (MyReadFile, myText)) {
// Output the text from the file
cout << myText;
}
// Close the file
MyReadFile.close();
}
Exceptions
try {
int age = 15;
if (age >= 18) {
cout << "Access granted - you are old enough.";
} else if (age == 0) {
throw "zero exception";
}else {
throw 505;
}
}
catch (int myNum) {
cout << "Access denied - You must be at least 18 years old.\n";
cout << "Error number: " << myNum;
}
catch (...) { // Catches any exception
cout << "Something went wrong\n";
}
int age = 15;
if (age >= 18) {
cout << "Access granted - you are old enough.";
} else if (age == 0) {
throw "zero exception";
}else {
throw 505;
}
}
catch (int myNum) {
cout << "Access denied - You must be at least 18 years old.\n";
cout << "Error number: " << myNum;
}
catch (...) { // Catches any exception
cout << "Something went wrong\n";
}