Learning C++

C++Image

Part 2 – Arrays, Pointers and Byte Memory

Part 3 – Functions, Structures and Memory

Part 4 – File I/O and Linked Data

Part 5 – Classes

Part 6 – Inheritance

Part 7 – Polymorphism (Inheritance)

Part 8 – Data Structures


Part 1 – Table of Contents

Macros, Basics and Functions


Imperative Paradigm

The Imperative Paradigm is focused on “how” to program and algorithms

This is fully specified, fully controlled manipulation of data, which happens in a stepwise fashion

What is a paradigm?

A program is the application of an algorithm to a set of data

Different paradigms give different focus to each of these parts

Data

In the imperative paradigm data is represented by states

Variables can be snapped to see the state

FSM/Turing

Data - Key Concepts

  1. Type: What values and operations are allowed
  2. Location: Where data is stored in the memory
  3. Address: An integer associated with location
  4. Reference/pointer: a name associated with the variable that holds an address of the location
  5. Value: Data that is stored in this location
  6. Scope: (lifetime) and visibility

Functions

Functions are the primary unit of Abstraction in C and C++ They are largely like Java methods…

In C/C++ we follow a patter called “Forward Declaration” for most things we create

Forward Declaration and Prototyping

The forward declaration gives

So when forward declaring a function it would look like:

{

    float distance(int, int, int, int);

}

All of this would go before the main function

  1. We use forward declaration to prevent issues with mutual function calling
  2. C/C++ will not know that something exists
  3. If they are forward declared, C/C++ knows they exists and allows this to work

Macros

Program Pre-Processing

Many programming languages allow the programmer to create Macros or inline procedures

References to Macros and inline procedures are replaced by their actual code which is compiled with the rest of the code

These macros become a text replacement. When using these in BASH or our Linux command line we can think of alias One that I use a lot of the time is alias gc="git commit " which allows me to commit a file quickly to git.

git commit ./ -m "comment" now becomes gc ./ -m "comment"

These are not used in all programming languages. More specifically this can be defined in C and C++

Java does not support macros

{

    #define MAXVAL 100
    #define QUADFN(a,b) a*sqrt(b)+b*b- 2*a*a*t++
    x = MAXVAL + QUADFN(5,16);

}

How do these macros work?

Out-line - simulating a function call

Two separate statements that contradict each other Statement [1] and statement [2]

We have two conflict opinions on using pictures in writing. Confucius gave a statement [1], while Dijkstra gave a different statement [2]….

Do you believe the statement [1] or [2]? [1] Confucius : “A picture is worth a thousand words”. [2] Dijkstra: “Pictures are a crutch for weak minds”.

In-line

Use within the same sentence and keep the line going We have two conflict opinions on using pictures in writing. Confucius gave a statement “A picture is worth a thousand words”, while Dijkstra gave a different statement “Pictures are a crutch for weak minds”. Do you believe the statement “A picture is worth a thousand words” or “Pictures are a crutch for weak minds”?

In vs Out

using input inline directly is most likely the best way to go

Risks of Macros

Macros vs Inline

The programmer and compiler may choose to ‘in-line’ a function/method

In-Lining (in C/C++):

Macro

Anatomy: C vs Java

C is the “grand parent” of many programming languages C’s syntax structure informs:

Makes going back and forth quite easy, these above are all C derived languages

Anatomy of C

C’s primary component structure revolves around functions

Functions are essentially sub-routines that can be called on at any time through name and a parameters list There are two kinds of functions:

{

    #include<stdio.h>

    main()
    {

        printf("Hello World!");

    }

}

We have statements to bring in our basic output function

stdio.h gives us access to Standard Input and Ouput functions

The Main Function

This function can be void but some compilers won’t allow for this

The main function can take command line args, passed into the params

printf()

printf() allows us to format out our output to a greater extent

Compilation

gcc -g -Wall helloW.c -o hello

gcc - what are we compiling g - include all debugging info Wall - Show us all of the warnings helloW.c - filename that we are compiling o - redirect ouput to this filename

Declaring Variables

At the machine level data is stored in a memory location as a sequence of bits. A variable declaration binds a name, attributes and a value to a location in memory allowing the programmer easy access to data stored. Attributes:

Follows the following syntax

You can separate multiple declarations with commas

Initializations can also be separated

Scope

The scope of a var begins at the point of declaration

Declaration-before-use: All variables must be declared before they are used

{

    int height = 6;
    int width = 6;
    int area  = height * width;

}

In the example above, if we change the declaration of height and place int area = height * width; we would get a compile time error

Everything in C is declaration before use

Data Types and C

C defines five basic types:

C++ further Adds

NOTE: BOOLEAN does not exist as a data type in C

Modifications

Short - short - reduces the size of an int to 2 bytes Long - long - increases the size of an int to 8 bytes Unsigned and Signed integers

Printf

printf means - “print formatted data” This is our primary output statement in C Comes form and workds similar to other printf commands Java also has printf() and almost works identically

Anatomy of printf

printf() has two primary parts

printf == printf(, (value), (value), ...)

The output string is the primary output. Anything here will be output to standard output stream

The output string can also put in specifier tags similar to a macro

printf() specifiers

  1. %d - decimal integer
  2. %f - floating point number
  3. %s - String
  4. %c - character
  5. %p - pointer address

Examples.

{

    float myFloat = 3.1415926;
    int myInt = 12345;

    printf("My integer value: %10\n", myInt);
    printf("My float value: %10.2f\n", myFloat);


}

Output –> My integer value: 12345 My float value: 3.14

printf variants

fprintf(, , )

sprintf(, , )

snprintf(, , , )

Input

scanf

Oddity with Strings

This is due to Strings not being a data type within C char str [80] printf ("Enter your family name: "); scanf ("%79s", str); –> limit this input to 79 characters

We can also get multiple inputs from scanf scanf("%i %i %i", %minx, %maxx, %miny);

Variants

fscanf(, , )

sscanf(, , )

C++ Style

More Libraries

C/C++ revolves around using the right libraries

Output

This is the basic output statement of C++. Each item that you want to output is separarted by the insertion operator ‘«’. These items are inserted into the standards output stream as it is typed

cout << "Hello World! << endl;

cout is fast and simple at a base level, however, it doesn’t format output. To do this we have to use another library #include <iomanip> … or … #include <iomanip.h> This brings in the output stream manipulation functions: We can control

iomanip

TODO

File Input and Output

Pointers

To work with files we need to manipulate file pointers. The pipeline for working with files:

File Pointer

When working with C files we need a file pointer

What is the FILE * ?

What is the ‘*’?

{

    FILE* infile; //creates the file pointer

}

Opening the File

Once we have the FILE* we need to point at, we open a file with the fopen() function

The path is a string and consequently needs to follow string rules

The directives are also a string, but it is a string of key letters that tell the compiler what we want to do for the file

Common uses:

fopen()

These directives can be combined

Examples:

{

    #include <stdio.h>
    #include <stdlib.h>

    int main(int argc, char** argv)
    {

        FILE* outfile; //file pointer
        outfile = fopen("data.t", "w"); //open data.t for writing

        int i;

        //loop through file to fprinf information
        for (i = 0; i < 100; i++)
        {

            fprintf(outfile, "%d\n", i);

        }

        fclose(outfile);

        infile = fopen("data.t" , "r"); //open data.t for reading

        int read;
        int result;

        while (result != EOF) //EOF stands for end of file
        {

            result = fscanf(infile, "%d", read);
            printf("read: %d\n", read);

        }
        
        fclose(infile);

        return 0;


    }

}

fscanf() input

Input and output work much the same as we would expect from the console. The File pointer must be used

{

    FILE * infile;
    char buffer[30];
    infile = fopen("C:\\data\\names.txt","r");

    int i = 0;
    for (i = 0; i < 15; i++)
    {

        fscanf(infile, "%s", buffer);

    }

    fclose(infile); //close the file

}

fprintf() - output

Similar to printf and how fscanf works, we are no redirecting our printf to a file with the file pointer

NOTE: like printf() there isn’t any automatic new line characters. A new line needs to be added explicitly

Closing a File

If you open a file, don’t forget to close it

If files are not closed it can cause corruption or other errors

File Input and Output with C++

{

    #include <iostream>
    #include <fstream>

    using std::cout;
    using std::endl;

    int main(int argc, char** argv)
    {

        std::ofstream outfile;
        std::ifstream infile;
        int input;

        outfile.open("info.dat");

        for (int i = 0; i < 100; i++)
        {

            outfile << i << endl;

        }
        outfile.close();

        infile.open("info.dat");

        for (int i = 0; i < 100; i++ )
        {

            infile >> input;
            cout << "Read: " << input << endl;

        }
        infile.close();

        return 0;

    }

}