C++
C++ characteristics
- vector
- list, forward_list(singly-linked list), …
- map, unordered_map(hash table), …
- set, multi_set, …
- string
- thread
- memory management
C++
- compilation + linking
- OOP
- safe programming
- superset of C
- case sensitive
1 Hello world! print
#include<iostream.h> // header file: input and output stream
int main() // main function, machine's function
{
cout << "Hello World!\n"; // not c++ output: statement cout << is included in #include<iostream.h>
// cout = console out, cout is an object for output to screen, << is operator
// "Hello World!\n" is operands
return 0; // output of machine (main), return 0 means function success, can be other integer
// this line optional
}
2 Variables
#include<iostream.h>
int main() // main function
{
int a; // declaration
a = 5; // initialization
int b = a; // get the value of b
a = 4; // another valur of a assigned
cout << a; // output a
cout << "\n"; // new line
cout << b; // output b
cout << "\n";
return 0;
}
3 Better output
#include<iostream.h>
int main() // main function
{
int a; // declaration
a = 5; // initialization
int b = a; // get the value of b
a = 4; // another valur of a assigned
cout << "a = " << a << "\n" << "b = " << b << endl; // output a and b, need only one cout,
//endl = end line = "\n", not like c
// don't need %d to represent number
return 0;
}
4 input
#include<iostream.h>
int main() // main function
{
int a; // declaration
cin >> a; // console in, 45 is the input of a
cout << "a = " << a << endl; // console out
return 0;
}
5 functions used in Library
#include<iostream.h>
#include<cmath>
int main() // main function
{
cout << pow(10, 2) << endl;
return 0;
}
#include<iostream.h>
#include<cmath>
int main() // main function
{
int base, exponent;
cout << "What is the base?: ";
cin >> base;
cout << "What is the exponent?: ";
cin >> exponent;
cout << pow(base, exponent) << endl;
return 0;
}
#include<iostream.h>
#include<cmath>
int main() // main function
{
int base, exponent;
cout << "What is the base?: ";
cin >> base;
cout << "What is the exponent?: ";
cin >> exponent;
double power = pow(base, exponent); // if use the value returned in function
cout << power << endl;
return 0;
}
6 creating custom functions
#include<iostream.h>
double power(double base, int exponent) // declaring and defining
{
double result = 1;
for(int i = 0; i < exponent; i++)
{
result = result * base;
}
return result;
}
int main() // main function
{
int base, exponent;
cout << "What is the base?: ";
cin >> base;
cout << "What is the exponent?: ";
cin >> exponent;
double my_power = power(base, exponent); // if use the value returned in function
cout << my_power << endl;
return 0;
}