L02 Introduction to C++
Big picture: Basic Computer Structure
C++ Program -> Compilation -> Machine Code
- saved in storage device (.cpp file and the compiled file, i.e. executable file)
- when running the program, we take the compiled file (executable) and put it in RAM
- CPU fetches data from RAM, executes the executable (performs operations) and then saves output data to RAM
- if needed, communicates interacts with IO before saving output to RAM
OS
- provides an interface between applications and hardware (e.g., web browser, vs code, video game, C++ program, etc.)
simple C++ program
#include <iostream>
using namespace std;
int main(void) {
int num1, num2;
cout << "Enter two numbers" << endl; // string INTO cout, hence <<
cin >> num1 >> num2; //operator INTO variable, hence >>
cout << "The sum is " << num1 + num2 << "!" << endl;
return 0;
}
data types in C++
- Integers: numbers without decimal places
- int = 4 bytes (32 bits) for this course we will use int
- long >= 32 bits
- sizeof(long) should be 64 bits usually
- Real numbers numbers that may contain decimal places
- double = 64 bits for this course we will use double
- float = 32 bits
- long double >= 64 bits
- Characters: 'A', 'a', '$', '\n'
- char = 1 byte (8 bits)
- boolean
- bool = 1 byte
- Arrays to store multiple data elements of the same data type:
int arr[7] = {70, 2, 3, 4, 5, 6, 7};
arr[0] = 1
strings in C
no particular data type; array of characters
char h[] = "hello"; is stored as 'h', 'e', 'l', 'l', 'o', '\0'
In C, we had to #include <string.h> to get access to functions like strlen, strcpy, strcat, etc.
strings in C++
In C++, we have a string "class" that allows you to create a string type variable.
You can use operations on these strings like +, ==, and !=.
// sees if entered course department and code are ECE244
#include <string>
#include <iostream>
using namespace std;
int main(void) {
string courseDep, courseCode;
cout << "Enter course code " << endl;
cin >> courseDep >> courseCode;
string combined = courseDep + courseCode;
if (combined == "ECE244") {
cout << "This is programming fundamentals" << endl;
} else {
cout << "This course is not programming fundamentals" << endl;
}
return 0;
}
Expressions that still apply in C++:
if () {}for () {},while () {}, do while- Operations
- arithmetic
- relational
- logical