FINM 326: Computing for Finance
Lecture 1: C++ Fundamentals
Programming Environment
The C++ Standard Library: A First Look
Data Types and Operators
Functions
Week 1 Summary
Programming Environment
I We use Visual Studio on Windows as our primary programming environment:
I Most students are familiar with Windows O/S
I Windows can be installed easily on MacBook
I Visual Studio is user friendly and feature rich programming environment
I Free access
I We will also use gcc on Linux as a secondary platform:
I some employers value programming experience on Linux
I another option for those who do not want to use Windows
I You can use one or the other, or both.
I I will use Windows and Visual Studio most of the time.
I I will show how to use gcc and Linux.
I Visual Studio is installed on lab computers. Report issues to Minsik Yu (minsik@uchicago.edu)
Obtaining Software
I Installing Visual Studio (on Windows):
I Instructions are posted on course site
I Mac users:
I may download and install Windows as a second O/S using bootcamp (https://support.apple.com/en-us/HT201468)
I use VMWare (instructions posted on course site)
I Linux access:
I Request a CS account at: https: //account-request.cs.uchicago.edu/account/requests
I Need help? Contact the TAs.
Getting Started with Visual Studio Integrated Development
Environment (IDE)
Getting Started
I Goal is to learn how how to use Visual Studio IDE, to:
1. create a project (application).
2. use the editor to write code.
3. build the application.
4. run the application.
Getting Started: Hello World Program
I We will create a very simple project to illustrate how to use Visual Studio IDE.
I The program shown below writes a message, "Hello, World!", to console (screen):
#include
int main()
{
std::cout << "Hello, World!" << std::endl;
return 0;
}
Our First C++ Project
I Let's code, build and run this program in Visual Studio.
I First, we will learn the steps we need to follow to create a project.
I After that, we will explain this program step by step and learn some C++.
Step by Step
I Step by step instructions used to create an application are illustrated next.
I Start Visual Studio. Select new project.
I Select "Visual C++" -> "Windows Desktop"
I Select "Windows Desktop Wizard"
Enter:
1. (project) name
2. directory location
3. solution name for the project.
I Change Additional Options as follows:
I uncheck Precompiled Header box.
I check Empty Project box.
I We have a new project!
I Now we can to add source les to our project.
I Go to Source Files folder on the Solutions Explorer.
I Right click, and select, Add -> New Item
I Select C++ File
I Name the le appropriately.
I Now you have a blank cpp le.
I Type code.
I Build the project.
I Make sure the project builds successfully.
I Run it.
I You'll see the greeting message on the screen.
Exercise
1. Use the steps shown above to create an application/project.
2. Code Hello World example. NOTE: C++ is case sensitive
3. Build the application.
4. Run it.
5. Change the program to print a di erent message on the screen.
Hello, World Program: Line by Line
int main()
I main is a special function.
I It is the program entry point.
I Every console application we create should have a main function.
I This function returns an integer (int) value.
I We do not pass any arguments to this function.
I Note: We can have two di erent function signatures for main function:
1. int main()
2. int main(int argc, char* argv[]). We will discuss the use of the second function signature later.
I The line below shows the body of our main function.
{
std::cout << "Hello, World!" << std::endl;
return 0;
}
I A function body starts with { and ends with }.
I Body has 2 statements; each statement ends with a semicolon (";").
I First line writes a message, "Hello, World!", to console.
I Here we use some functionality from the C++ Standard Library.
I After that, the function returns 0 (an integer value)1.
1We don't have to return a value in main function. Return 0 (zero) is implied.
The C++ Standard Library: A First Look
The C++ Standard Library
I Here, we brie y look at the feature (i.e. to write a message to console) used in the Hello World example.
I The C++ Standard Library implements some very useful features we need.
I The Standard Library is divided into several sections (more precisely headers), based on functionality.
I Each header has a name.
I We need to include the appropriate header in order to have access to its components.
I The functionality to handle output to console is de ned in the iostream header.
I To include it: #include
The Standard Input and Output
I Terminology:
I input: a sequence of byte ow coming into the computer memory from a device (e.g. keyboard, le).
I output: a sequence of byte ow from the memory to an output device (e.g. console, le).
I stream: a sequence of characters (bytes) read from an input device or written to an output device.
I The iostream section of de nes objects to read and write a stream to Standard I/O channels:
I cin
I cout
I and more..
Standard Output
cout (pronounced as see-out):
I known as the standard output
I attached to the standard output device, which usually is the console
I uses the stream insertion operator, << cout << "Hello, World";
Standard Input
cin (we pronounce it as see-in):
I known as the standard input
I attached to the standard input device, which usually is the keyboard
I uses the stream extraction operator ( >>), to read a stream from the standard input
int x; cin >> x;
Namespace
I Namespaces allow us to group classes and functions using a name.
I Functions and classes in the C++ Standard Library are de ned in the std namespace.
I To use them (classes/functions), we have to use the fully quali ed name.
I Example: We saw the use of std::cout.
I std is the namespace.
I :: is the scope resolution operator in C++.
I cout is the object in this case.
I We will see the use of namespaces later, when we discuss classes.
Using Namespaces
I Having to write the namespace every time we use a function is a bit cumbersome.
I There are di erent ways to overcome this problem.
I Technique 1:
using std::cout;
using std::endl;
int main()
{
cout << "Hello, World!" << endl;
}
I Technique 2:
using namespace std;
int main()
{
cout << "Hello, World!" << endl;
}
I If we're not careful, the second technique can lead to subtle problems in large programs.
I I encourage you to use the rst technique.
I I may not show every namespace in subsequent slides after they are introduced.
I E.g. I may show cout without showing using std::cout; but you should assume it is there.
Data Types
I We write programs to handle/manipulate data.
I We use variables to store data.
I Programs need to store di erent kinds/types of data:
I a letter or sequence of letters: e.g. your name
I numbers: e.g. your age
I In C++ every variable has to have a type.
I The type of the variable has to be declared before it is used.
I Once a type is assigned to a variable, it cannot be changed.
I Data types in C++ belong to two main categories:
1. fundamental data types
2. user de ned data types
I Fundamental data types are de ned in the C++ language.
I C++ also allows the user to de ne types (classes).
Fundamental Data Types: Numerical Types
I Numerical values can be whole or real numbers: e.g. 1 or 1.2
I For real numbers we have two types (in C++):
I oat : uses 4 bytes
I double : uses 8 bytes
I As a result, max and min values each can store are di erent.
Type |
Size (Bytes) |
Value Range |
|
oat |
4 |
3.4 |
E 38 |
double |
8 |
1.7 |
E 308 |
I We can use them to store both negative and positive real numbers.
I For whole numbers we have several types:
I short: uses 2 bytes
I int: uses 4 bytes
I long: at least 4 bytes
I They have signed and unsigned versions:
I unsigned version can store positive numbers only
I signed version can store both positive and negative numbers
Type |
Size (Bytes) |
Value Range |
unsigned short |
2 |
0 to 65,535 |
short |
2 |
-32,768 to 32,767 |
unsigned int |
4 |
0 to 4,294,967,295 |
int |
4 |
-2,147,483,648 to 2,147,483,647 |
More Types
I Type to hold a ag (true/false)
I bool
I Type to hold a single character
I char
I Reference: https: //msdn.microsoft.com/en-us/library/cc953fe1.aspx
I Type to hold a string of characters
I std::string
I std::string is NOT a fundamental data type
I de ned in the C++ Standard Library
I de ned in the string header le
C++ Operators
Operators for Fundamental Data Types
Listed below are some operators de ned for fundamental types:
I Assignment operator (=) :
a = 5; |
//a is an int |
|
b = 1.5f; |
//b is a float |
|
c = 1.4; |
//c is a |
double |
d = 'a'; |
//d s a char |
|
e = true; |
//e is a |
bool |
I Arithmetic operators (+; ; ; =) :
a = a + 1; b = b – 1.2f; c = c * 2.1 ; c = c / 2.2;
I Comparison operators ():
a > 3; a < 3; a >= 3; a <= 3;
Comparison operators return a bool (true/false) value.
I Equality (==): a == 3;
I Non Equality (! =) : a != 3;
I Logical AND (&&) : returns true if both operands are true; returns false otherwise
a == 3 && d == 'a';
I Logical OR (jj) : return true if either or both operands is true; returns false otherwise
a == 3 || d == 'a';
I Modulo % (to nd the remainder from integer division): int x = 7 % 3;
Operators: Short-cuts
We have some short-cuts; e.g. For an int value i:
I Increment:
i++; // same as, i = i+1;
i += 17; // same as, i = i+17;
I Decrement:
i–; // same as, i = i – 1;
i -= 21; // same as, i = i – 21;
I Multiplication:
i *= 13; // same as, i = i*13;
I Division:
i /= 42; // same as, i = i / 42;
Pre x and Post x
I Post x:
I increment x and return old x:
int x = 3; int y = x++;
I now, y == 3 and x == 4
I Pre x:
I increment x and return new value
int x = 3; int y = ++x;
I now, y == 4 and x == 4
Functions
C++ Functions
I We saw the main() function { every application has to have a main().
I We do NOT write the entire program in the main function.
I We use functions and classes.
I It is easier to solve a complex problem by breaking it up into smaller parts.
I And, combine them to solve the problem.
I We write a function to do a certain task or a sub task.
I Combine one/more functions to solve a problem.
I Using functions have several advantages.
I First, let's learn how to write functions in C++.
I Example: we can write a function to display a greeting message on the screen:
void DisplayGreeting()
{
std::cout << "Hello World!" << std::endl;
}
I A C++ function:
I has a name2
I takes zero or more arguments
I usually does something in the function body
I returns some value of a certain type
I if a function does not return anything, its return type is void
2We can also write a function without name
Functions: Example 1
I Our rst function writes the greeting, "Hello World!" to the screen:
#include
void DisplayGreeting()
{
std::cout << "Hello World!" << std::endl;
}
I We can now call this function from the main function:
int main()
{
DisplayGreeting();
return 0;
}
Functions: Example 2
I How would you write a function to add two integers?
int Add(int a, int b)
{
return a+b;
}
int main()
{
int result = Add(2, 3);
cout << " Result :" << result << endl;
}
Functions: Advantages
1. Better/simpler solution: divide the problem into smaller tasks.
2. Better code structure: improve readability/clarity.
3. Reuse: once a function is written, we can use it any number of times.
4. Maintainability: we write a function once, if we want to make a chance, x a bug, we can do it just in one place.
5. Type safety:
I arguments passed to a function should match the types in the function declaration
I program will not compile if there's a mismatch
Parameter Overloading
I Overloading allows 2 or more functions to have the same name:
I they must have di erent input argument types
I they cannot di er by the return type only
I Allows us to write more than one method to do some task in di erent ways, using di erent inputs.
I For example, we can write another Add() function as:
double Add(double a, double b)
{
return a+b;
}
In-Class Exercises
I Write functions to add:
1. two oat values
2. 3 integer values
3. 3 double values
Implicit Type Conversions
I Suppose we have the following function:
double Add(double a, double b)
{
return a+b;
}
I What happens if we use it to add two integer values:
int main()
{
int a = 2; int b = 3;
cout << Add(a, b) << endl;
}
I Question: does this program build?
I Yes, this program builds just ne:
I arguments are passed to the function as doubles
I size of int is 4 bytes; double is 8 bytes
I we can safely store any int value in a double
I C++ (compiler) converts the int to double (implicitly) in this case.
I This is a conversion from a smaller (4 byte) to a larger (8 byte) type.
I It is called a widening, or, promotion
I Promotions are safe implicit conversions.
I Suppose we have the following function:
int Add(int a, int b)
{
return a+b;
}
I What happens if we use it to add two double values:
int main()
{
double a = 2.2; double b = 3.3;
cout << Add(a, b) << endl;
}
I Will this program build?
I Yes, this program also builds:
I arguments are passed as ints
I size of double is 8 bytes; int is 4 bytes
I we cannot safely convert every double value to an int
I C++ (compiler) converts the double do int values implicitly in this case.
I Results in a conversion from a larger (8 byte) to a smaller (4 byte) type.
I It is called a narrowing.
I Narrowing can be dangerous, and results in a build Warning.
I Why is this not an error?
I C++ expects us to know what we're doing
I C++ will let you shoot yourself in the foot if we're not careful
I Lesson: Pay Attention to Build Warnings!
Casting
I What's the result from integer divsion below:
int a = 3, b = 2;
cout << a / b << endl;
I To get the correct (real) number, we must convert at least one operand to real.
I Explicit type conversions are known as casting.
I Casts are not encouraged, sometimes they are necessary.
I C++ supports 4 types of casts (known as named casts).
I We'll look at static_cast now:
I static_cast:
I Used to force conversions, e.g. int->double
int a = 3; int b = 2;
cout << static_cast
I static_cast returns a double value in this case.
Demos
I Implicit type conversions:
I widening
I narrowing
I static cast
I Handling syntax errors:
1. build logs: errors and warnings
2. IntelliSense3: makes coding covenient
I Debugging
3 https://msdn.microsoft.com/en-us/library/dn957937.aspx
C++ and Header Files
I We wrote all code in the same le.
I In practice we never write all code in the same le:
I di cult to read a very large le (with thousands of lines of code)
I doesn't promote reusability
I di cult for multiple programmers to work on the same project
I makes build process longer
I Solution is to use separate les for functions/classes etc.
I This requires using:
I C++ les
I Header les
I Let's illustrate how to implement a function(or related functions) in a separate C++ le.
I Let's use the add functions as an example:
I We will implement the Add() functions in a separate Add.cpp le.
I When we move the add functions to a new le our program won't build.
I The main() function doesn't know about the Add() functions.
I We need to declare a function before we can use it in a separate le.
I We could add the following two declarations before we use them in main:
int Add(int, int);
double Add(double, double);
I This solution is not ideal: it requires us to have these declarations in every le we use them.
I Proper C++ way:
I Write the function declarations in a header le (e.g. Add.h):
int Add(int, int);
double Add(double, double);
I Include it in source les, using #include preprocessor directive:
#include "Add.h"
In-Class Exercise
I Using one (or more) Add() function/functions from the previous exercise, write:
1. function de nition in the header le.
2. function implementation in the cpp source le.
3. call the Add() function from main().
C++ Build Process
C++ build process uses several steps:
1. Preprocessing:
I uses the preprocessor
I the preprocessor handles the preprocessor directives (e.g. #include)
I the output of this step is a C++ le without preprocessor directives
1. Compiling:
I uses the compiler
I checks syntax
I makes sure the data types are compatible with the operations
I each .cpp le is compiled to create an object le (.obj)
2. Linking :
I uses the linker
I creates an executable (.exe) le using the object les
Demo: Build Errors
I We can have build errors in each stage.
I We need to have an idea about each stage to x build problems.
Type Alias
I Type aliasing can help make code:
1. more readable
2. less error prone
I Consider the function declaration below which calculates the
Black Scholes price of an Option.
double BSPrice(double, double, double, double, double);
I Error prone: it is not clear what the arguments are
I We can use typedefs here:
typedef double OptionPrice;
typedef double StockPrice;
typedef double Strike;
typedef double Expiration;
typedef double Rate;
typedef double Volatility;
OptionPrice BSPrice(StockPrice, Strike, Expiration, Rate, Volatility);
The const keyword
I The const keyword is used to de ne a constant value.
I If you try to change the value of a const member, the compiler catches it.
const int MaxValue = 10;
MaxValue = 20; // <= This is an error
I This is another example of the bene ts of type safety in C++.
I We will discuss other uses of the const keyword later in the course.
Comments
I We can write comments using C style or C++ style.
I C style:
/* This is a C style comment */
I C++ style:
// This is a C++ style comment
Assignment 0 (Not Graded)
1. Write a function to add two integers.
2. Read two integer values from the keyboard.
3. Add them using the function you wrote.
4. Write the result to console.
I Individual Assignment.
I Due: January 13, 2018 by midnight (CST).
I Total points: 0 (Zero)
I Submission (Optional):
Clean the solution using Clean Solution under Build tab in Visual Studio.
Compress (zip) the folder containing the project.
Submit on Canvas: follow Assignments -> Assignment 0 link and attach the zip le.
Week 1 Summary
Visual Studio IDE
I We created our rst application:
I we create a project
I solution is a placeholder for one or more projects
I Tools in Visual Studio IDE:
I editor to write code
I intellisense support
I build tools
I debugger
I Build uses 3 steps:
I preprocessing, compiling and linking
I brie y discussed each step
Data Types
I Categories:
1. fundamental
2. user de ned
I We discussed fundamental types and operators
I Compiler can do implicit type conversions:
3. widening/promotion (e.g. int to double)
4. narrowing (e.g. double to int)
I We can force type conversions via casting
Functions
I main(): program entry point
I Write a function to do a certain task or a sub task.
I Combine them to write a large program.
I Functions promote:
I readability
I reusability
I maintainability
I type safety
I You will understand these advantages when we write more code.
C++ Standard Library
I Collection of useful classes/functions.
I Brie y looked at some features in the iostream header:
I streams
I cout
I cin
I Introduced the std::string type in std::string header.
代写计算机编程类/金融/高数/论文/英文
本网站支持淘宝 支付宝 微信支付 paypal等等交易。如果不放心可以用淘宝或者Upwork交易!
E-mail:850190831@qq.com 微信:BadGeniuscs 工作时间:无休息工作日-早上8点到凌晨3点
如果您用的手机请先保存二维码到手机里面,识别图中二维码。如果用电脑,直接掏出手机果断扫描。