GithubHelp home page GithubHelp logo

cpp-in-21-days-part1's Introduction

C++ in 21 days Part 1

My note for learning C++ in 21 days (Day 1 - 5)

Reference: Liberty, J., & Jones, B. L. (2004). Sams teach yourself C++ in 21 days. Sams Publishing.

Created by Komsun Tamanakijprasart

Table of contents

About C++

C++ is a compiled languages, meaning you can distribute the executable program (.exe) to people who don’t have the compiler. C++ fully supports object-oriented programming (OOP), including encapsulation, inheritance, and polymorphism.

Encapsulation is the property of being a self-contained unit. You can accomplish data hiding with encapsulation. Changes can be made to workings of program without affecting the operation of the program. With inheritance, you can declare a new type that is an extension of an existing type and add additional capabilities. The program may respond differently than the original one but a user does not have to know about these differences. This is Polymorphism, the same name taking many forms.

The Process of Creating the Program

  1. Create a source code file with a .cpp extension
  2. Compile the source code to create an object file (.obj or .o extension) with the Compiler
  3. Link the object file with any needed libraries to produce an executable program (.exe)

The Anatomy of a C++ Program

  • The # symbol signals the preprocessor
  • #include is a preprocessor instruction meaning that “What follows is a file-name. Find that file, read it, and place it right here”
  • iostream is a file in the directory that holds all the include files for your compiler
  • main() is a special function that’s called automatically when your program starts. Every C++ program has a main() function
  • For best practice, main() should be specified to return integer value 0

Using the Standard Namespace

  • Declare to use the standard namespace (std)
  • std::endl is used to enter a new line to the console
  • std::endl is preferable to the use of \n because endl is adapted to the operating system in use.

// Listing 2.3 - using the using keyword (P.31)
#include <iostream>
int main()
{
using std::cout;
using std::endl;
cout << "Hello there! \n";
cout << "Here is 5: " << 5 << "\n";
cout << "The manipulator std::endl ";
cout << "writes a new line to the screen.";
cout << endl;
cout << "Here is a very big number:\t" << 70000;
cout << endl;
cout << "Here is the sum of 8 and 5:\t";
cout << 8+5 << endl;
cout << "Here's a fraction:\t\t";
cout << (float) 5/8 << endl;
cout << "And a very very big number:\t";
cout << (double) 7000 * 7000 << endl;
cout << "Komsun T. is a C++ programmer! \n";
return 0;
}

Variables and Constants

  • You must tell the compiler what type of variable it is: integer, floating-point number, character, etc.
  • signed integers can be negative or positive. unsigned integers are always positive
  • You define a variable by stating its type, followed by spaces, followed by the variable name and a semicolon
  • C++ is case sensitive, meaning uppercase and lowercase letters are different!

image

Assigning Values to Variables

  • You can initialize more than one variable at creation with mix definitions and initializations:
int myAge = 39, yourAge, hisAge = 40;

Creating Aliases with type definition (typedef)

  • typedef is used to create a synonym of the phrase (not creating a new type)
typedef unsigned short int USHORT

int main()
{
  USHORT Width = 5;
  USHORT Length;
  Length = 10;
  return 0;
}

Constants

  • When a constant is initialized, you cannot assign a new value later!
  • C++ has two types of constants: literal and symbolic
  • A literal constant is a value typed directly into your program (the number is a constant)
  • A symbolic constant is a constant that is represented by a name
  • Symbolic constant can be declared with 1) #define (NOT recommended), or 2) const
// Literal constant
int myAge = 39; // 39 is a literal constant

// Symbolic constant
const unsigned short int numObj = 15; // numObj is a symbolic constant

Enumerated Constant

  • Enumerated constants enable you to create new types and then define variables of those types whose values are restricted to a set of possible values
  • Enumerated constants have the advantages of being self-documenting
enum COLOR {RED, BLUE, GREEN, WHITE, BLACK};

The above example performs two tasks:

  1. It makes COLOR the name of an enumeration; that is, a new type
  2. It makes RED a symbolic constant with the value 0, BLUE = 1, GREEN = 2, WHITE = 3, BLACK = 4
  • Every enumerated constant has an integer value. If not specified, the first constant has the value 0, then 1, 2, ...
  • Any one of the constants can be initialized with a particular value, but those that are not initialized count upward from the ones before
enum Color {RED=100, BLUE, GREEN=500, WHITE, BLACK=700};

// Define a new variable of type 'Color'
Color thisFlower;
thisFlower = RED;   // This creates a constant thisFlower with the value 100

In this example, RED = 100, BLUE = 101, GREEN = 500, WHITE = 501, BLACK = 700

!!! Enumerator variables are generally of type unsigned int !!!

// Listing 3.8 - Enumerated Constants (P.62)
#include <iostream>
int main()
{
// Define new type 'Days' and its values
enum Days{ Sunday, Monday, Tuesday,
Wednesday, Thurday, Friday, Saturday };
// just like how you define: int x=10; (10 is value of 'int')
Days today;
today = Monday; // (Monday is value of 'Days')
// We can also assign today = (Days) 2; // (=Monday)
if (today == Sunday || today == Saturday) // || is 'or'
std::cout << "\nGotta' love the weekends!\n";
else
std::cout << "\nBack to work...\n";
return 0;
}

Self-assigned operators | Incrementing and Decrementing

x -= 5;  // same as x = x - 5
x += 5;  // same as x = x + 5
x /= 5;  // same as x = x / 5
x *= 5;  // same as x = x * 5
x %= 5;  // same as x = x % 5

x--;  // same as x = x - 1
x++;  // same as x = x + 1

Prefix and Postfix Operators

  • The prefix operator (e.g. ++myAge) is evaluated before the assignment
  • The postfix operator (e.g. myAge) is evaluated after the assignment
int a = ++x;    // same as    x = x+1;
                //            a = x;

int b = x++;    // same as    b = x;
                //            x = x+1;

if Statement

  • Multiple statements are required to be surrounded by braces { }
  • For one statement, the braces { } are not required but should be put for best practice
// Single statement
if (bigNum > smallNum)
  bigNum = smallNum;

// Single statement (good practice)
if (bigNum > smallNum)
{
  bigNum = smallNum;
}

// Multiple statements
if (bigNum > smallNum)
{
  bigNum = smallNum;
  std::cout << "big number: " << bigNum << std::endl;
  std::cout << "small number: " << smallNum << std::endl;
}

// Listing 4.6 - complex nested if statement
// (P.87)
#include <iostream>
int main()
{
/* Ask for 2 numbers
Assign the numbers to bigNumber and littleNumber
If bigNumber is bigger than littleNumber,
see if they are evenly divisible
If they are, see if they are the same number */
using namespace std;
int firstNumber, secondNumber;
cout << "Enter two numbers.\nFirst:\t";
cin >> firstNumber;
cout << "\nSecond:\t";
cin >> secondNumber;
cout << "\n";
if (firstNumber >= secondNumber)
{
if ( (firstNumber % secondNumber) == 0) // evely divisible?
{
if (firstNumber == secondNumber)
cout << "Hey! They are the same!!\n";
else
cout << "They are evenly divisible!\n";
}
else
cout << "They are NOT evenly divisible!\n";
}
else
cout << "Hey! The second on is larger!!\n";
return 0;
}

Logical Operators

  • for best practice, use if(x != 0) instead of if(x), and use if(x == 0) instead of if(!x)
(x == 5) && (y == 5)    // Logical AND
(x == 5) || (y == 5)    // Logical OR
!(x == 5)               // Logical NOT (same as  x !=5 )

Short Circuit Evaluation

**Be careful! **

  • When the compiler is evaluating an AND statement, if the first statement is False then the second statement WILL NOT be evaluated !!!
  • When the compiler is evaluating and OR statement, if the first statement is True then the second statement WILL NOT be evaluated !!!
if ( (x == 5) || (++y == 5) )
// if x is 5 then (++y == 5) is not evaluated. If you are counting on y to be incremented regardless, it will not happen !

The Conditional (Ternary) (?:) Operator

  • The conditional operator (?:) is C++'s only ternary operator, it is the only operator to take 3 terms
(expression1) ? (expression2):(expression3)

This means "If expression1 is true, return the value of expression2; otherwise, return the value of expression3."

// method 1 : if test
if (x > y)
z = x;
else
z = y;
cout << "After if test, \nbigger number = " << z;
cout << "\n\n";
// method 2 : conditional test (shorter expression)
z = (x > y) ? x : y; // if x > y, z = x otherwise, z = y
cout << "After conditional test, \nbigger number = " << z << endl;
cout << "\n\n";

Functions

Basic example:

int myFunction(int someValue, float someFloat);
// This means that myFunction will return an integer, and it will take two values

int theValueReturned = myFunction(5, 6.7);

image

Function Prototype

image
Parts of a function prototype
  • The function prototype is a statement, which means it ends with a semicolon;
  • The function prototype does not need to contain the names of the parameters, just their type, but it is not a good idea!
  • if the return type of function is not stated, its default is int
long Area(int, int);   // ok but bad
long Area2(int length, int width);    // ok and good

Defining the Function

  • Functions consist of a header and a body
  • The value returned MUST be of the same type declared in the function header
  • A function that has nothing to return would be declared to return void
  • If you don't put a return statement into the function, it automatically returns void !!!
  • Global variables are not recommended as they are shared data, and one function can change its value in a way that is invisible to another function!
image
The structure of a function

#include <iostream>
int Area(int len, int wid); // function prototype
// Don't need to name the arguments
int main()
{
using std::cout;
using std::cin;
int legnth_yard;
int width_yard;
int area_yard;
cout << "\nHow wide is your yard? Ans: ";
cin >> width_yard;
cout << "\nHow long is your yard? Ans: ";
cin >> legnth_yard;
area_yard = Area(width_yard, legnth_yard);
cout << "\nYour yard is ";
cout << area_yard << " square feet\n\n";
return 0;
}
int Area(int len, int wid) // function declaration
{
return len*wid; // function definition
}

  • You can have more than one return statement in a single function
return 5;
return (x>5):   // (returning True of False)
return (MyFunction());

Default Parameters

  • A default value is a value to use if none is supplied to a funciton
  • A default value can be declared in the function prototype
  • Since parameter names are not required in a prototype, this declaration could omit the parameter name
long myFunction (int x = 50);    // 50 is the default input to myFunction if no argument is supplied
long myFunction2 (int = 69);     // This statement is also legal
  • If any of the parameters does not have a default value, no previous parameter can have a default value!!!
long myFunction (int Param1, int Param2, int Param3);
// You can assign a default value to Param2 only if you have assigned a default value to Param3
// You can assign a default value to Param1 only if you've assigned a default value to both Param2 and Param3

Overloading Functions (Function Polymorphism)

C++ allows you to create more than one function with the same name so that the function is more flexible. This is called function overloading or function polymorphism

  • The functions must differ in their parameter list with a different type of parameter, a different number of parameters, or both!!
  • The return types can be the same or different on overloaded functions
// Example of function overloading
int myFunction (int, int);
int myFunction (long, long);
int myFunction (long);
  • The right function will be called automatically by matching the parameters used
  • Without function overloading, you would have to create multiple individual function for one task, for example:
// Without function overloading
int AverageInt(int);
float AverageFloat(float);
// With function overloading
int Average(int);
float Average(float);

// Listing 5.8 - Function Polymorphism (function overloading)
// (P.119)
#include <iostream>
int Doubler(int);
long Doubler(long);
float Doubler(float);
double Doubler(double);
using namespace std;
int main()
{
int myInt = 6500;
long myLong = 65000;
float myFloat = 6.5f;
double myDouble = 6.5e20;
int doubledInt;
long doubledLong;
float doubledFloat;
double doubledDouble;
cout << "myInt: " << myInt << endl;
cout << "myLong: " << myLong << endl;
cout << "myFloat: " << myFloat << endl;
cout << "myDouble: " << myDouble << endl;
doubledInt = Doubler(myInt);
doubledLong = Doubler(myLong);
doubledFloat = Doubler(myFloat);
doubledDouble = Doubler(myDouble);
cout << "doubledInt: " << doubledInt << endl;
cout << "doubledLong: " << doubledLong << endl;
cout << "doubledFloat: " << doubledLong << endl;
cout << "doubledDouble: " << doubledDouble << endl;
return 0;
}
int Doubler(int x)
{
cout << "In Doubler(int)\n";
return 2*x;
}
long Doubler(long x)
{
cout << "In Doubler(long)\n";
return 2*x;
}
float Doubler(float x)
{
cout << "In Doubler(float)\n";
return 2*x;
}
double Doubler(double x)
{
cout << "In Doubler(double)\n";
return 2*x;
}

Inline Functions

  • When you call the function, the execution of the program jumps to the instruction, and when the function returns, the execution jumps back
  • Inline functions can generally improve the efficiency of the program
  • Inline functions can be declared with inline at the function prototype
  • When the inline function is called, the compiler copy-paste the code just as if you had written the statements into the calling function

// Listing 5.9 - Inline function (P.123)
#include <iostream>
inline int Doubler(int); // same as copying function definiiton to main
// instead of jumping to function back and forth
int main()
{
int target;
using std::cout;
using std::cin;
using std::endl;
cout << "Enter a number: ";
cin >> target;
cout << endl;
target = Doubler(target);
cout << "Target = " << target << endl;
target = Doubler(target);
cout << "Target = " << target << endl;
target = Doubler(target);
cout << "Target = " << target << endl;
return 0;
}
int Doubler(int x)
{
return 2*x;
}

Recursion

  • Recursion is a function calling itself, which can be direct or indirect
  • Direct recursion = function calls itself, Indirect recursion = function calls another function that calls the first function
  • In recursion, a new copy of the function is run. The local variables in the 2nd version are independent of those in 1st version
  • Recursive functions need a stop condition !!!

image

// Listing 5.10 - Recursion: Fibonacci series (P.125)
#include <iostream>
int fib(int);
int main()
{
int n, answer;
std::cout << "Enter position to find: ";
std::cin >> n;
std::cout << "\n\n";
answer = fib(n);
std::cout << "\nAns. " << answer << " is the " << n;
std::cout << "th Fibonacci number.\n\n";
return 0;
}
int fib(int n)
{
std::cout << "Processing fib(" << n << ")...";
if (n < 3)
{
std::cout << "Returning 1\n";
return 1;
}
else
{
std::cout << "Call fib(" << n-2 << ")";
std::cout << " and fib(" << n-1 << ").\n";
return fib(n-2) + fib(n-1);
}
}

image

cpp-in-21-days-part1's People

Contributors

komxun avatar

Stargazers

 avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.