Slide 1

Slide 1 text

Learning to Code in C++ Arnav Gupta, Coding Blocks

Slide 2

Slide 2 text

The basic program structure #include int main () { cout << “Hello world”; }

Slide 3

Slide 3 text

Preprocessor Directives #include #ifdef #define ● Tells the compiler to do certain tasks ● Are not part of the program logic ● #include = include libraries/header files

Slide 4

Slide 4 text

The main function int main () { return 0; } ● The function that runs when we execute the program ● “0” return means successful execution ● Should return “int”, but compilers accept “void” returns too

Slide 5

Slide 5 text

Comments // Single line comment /* Multi line comment */ ● Comments are parts of code that are not compiled or run. ● Used to document programs, and make human-readable

Slide 6

Slide 6 text

Variables int a; a = 10; int b = 10; int c; c = a; ● “int” is data type ● “a” is variable name ● b = 10, means assignment

Slide 7

Slide 7 text

Data types int a = 10; bool b = true; b = false; char c = ‘A’; double d = 10.4; float f = 11.5; Primitive data types are integer, boolean, character, float and double. These can be modified with long, unsigned, and short modifiers.

Slide 8

Slide 8 text

Arrays int a[3] = {1,2,3}; char c[] = {‘a’, ‘b’, ‘c’}; a[2] = 5; ● An array is a sequence, of finite size, of a particular data size. ● int a[3] means “a” is an ordered set of 3 integers. ● These can be accessed as a[0], a[1], a[2].

Slide 9

Slide 9 text

Strings char c[4] = “cat”; char d[] = {‘d’, ‘o’, ‘g’, ‘\0’}; ● In C++ there is no real “string” data type. ● A string is an array of char ● String needs to be terminated with “\0” char.

Slide 10

Slide 10 text

Printing to console cout << 10; cout << ‘a’; cout << “string”; int a = 10; char c = ‘C’; cout << a << c << endl; cout << “new \n line”; ● “cout” which means console output, can be used to print to console. ● The “<<” operator shifts data into the cout. ● We can print data directly, or data variables.

Slide 11

Slide 11 text

Reading from console int a; cin >> a; char c; cin >> c; char str[10]; cin >> str; ● Like “cout”, “cin” means console input. ● We use the “>>” operator to shift data from the cin into our variable. ● We can use cin for any primitive data type, as well as string.

Slide 12

Slide 12 text

Pointers ● Pointers are location on the memory (RAM) where the data is stored. ● We use the “ * ” (dereference operator) and “ & ” (address operator) to work with pointers ● pointers are also a kind of data type. ● address of variable is a pointer ● dereference of a pointer gives data stored there