2024-05-23    2024-07-12     1595 字  8 分钟
cpp

Reference

Introduction

  • What are computer programs

    • The elements working in computers
    • Also known as software
    • A Structured combination of data and instructions used to operate a computer to produce a specific result
  • Programming languages

    • People and computers talk in programming languages.
    • A programming language may be a machine language, and assembly language, or a high-level language (or something else)
      • Machine and assembly languages: Control the hardware directly, but hard to read and program.
      • High-level languages: Easy to read and program, but need a “translator”.
  • A complier translates C++ programs into assembly programs.

    • For other high-level programs, an interpreter may be used instead.
  • C++ programming language

    • C++ originates from another programming language C.
      • C is a procedural programming language.
      • C++ is an object-oriented programming (OOP) language.
      • Roughly speaking, C++ is created by adding object-oriented functionalities to C.

Basic structure and cout

// preprocessor and namespace
#include <iostream>
using namespace std;

// main function
int main()
{
	cout << "Hello World!\n";
	return 0;
}
  • The program can be decomposed into four parts

    • The preprocessor
    • The namespace
    • The main function block
    • The statements
  • cout is a pre-defined object for “console output”

    • It sends whatever data passed to it to the standard display device.
    • Typically this is a computer screen in the console mode.
  • The insertion operator << marks the direction of data flow.

    • Data “flow” like streams.
  • "Hello World!\n" is a string.

    • Characters within a pair of double quotation marks form a string.
  • The escape sequence \n

    • In C++, the slash symbol \ starts an escape sequence.
      • An escape sequence represents a “special character” that does not exist on the keyboard.
      • The newline character \n in C++ means “changing to new line”
  • Some common escape sequences are lists below:

    Escape sequence Effect Escape sequence Effect
    \n A new line \\ A slash: \
    \t A horizontal tab \' A single quotation: '
    \b A backspace \" A double quotation: "
    \a A sound of alert
  • Concatenated data streams

    • The insertion operator << can be used to concatenate multiple data streams in one single statement
      • The two statements:
        • cout << "Hello World! \n";
        • cout << "I love C++ \n so much";
      • and this statement
        • cout << "Hello World! \n" << "I love C++ \n so much";
      • display the same thing.

Variable declaration and cin

  • cin accepts data input (by the user or other programs) from the console input (typically the keyboard)
  • In order to use the cin object, we need to first prepare a “container” for the input data. The thing we need is a variable.
  • When we use a single variable to receive the data, the syntax is
int var;
cin >> var;
  • Variable and data types

    • A variable is a container that stores a value.
      • Once we declare a variable, the system allocates a memory space for it.
      • A value may then be stored in that space.
    • In C++, each variable must be specified a data type.
      • It tells the system how to allocate memory spaces.
      • It tells the system how to interpret those 0s and 1s stored there.
    • The data type will also determine how operations are performed on the variable.
    • Four attributes of a (typical) variable:
      • Type
      • Name: identifier
      • Value
      • Address
  • Basic data Types (Built-in or Primitive):

    Category Type Bytes Type Bytes
    Integers bool 1 long 4
    char 1 unsigned int 4
    int 4 unsigned short 2
    short 2 unsigned long 4
    Fractional numbers floats 4 double 8
    • The number of bytes is compiler-dependent.
  • Variable declaration

    • Before we use a variable, we must first declare it.
      • We need to specify its name and data type.
    • The syntax of a variable declaration statement is: type variable-name;
      • For example, int myInt; declares an integer variable called myInt.
    • A variable name is an identifier.
      • We do not need to memorize the memory address (which is a sequence of numbers)
      • We access the space through the variable name.
  • Assignment

    • Beside declaring a variable, we may also assign values to a variable.
      • int myInt; declares an integer variable.
      • myInt = 10; assigns 10 to myInt.
    • We may do these together:
      • type variable-name = inital-value;
      • int yourInt = 5; declares an integer variable yourInt and assign 5 to it.
      • The assignment is called initialization if it is done with declaration.
    • Without initialization, the variable may be of any value (depending on what was left since the last time this space is used!)
  • The assignment operator

    • In the satement myInt = 10;, we use the assignment operator = to assign 10 to myInt.
    • This is an assignment operation.
    • In general, an operation has operators and operands involved:
      • An operator (1) takes one or a few operands as inputs, (2) make some things happen to them, and then (3) return a value.
    • For the assignment operation:
      • The two operands are a variable (the “l-value”) and a value (the “r-value”).
      • The variable’s value will become the given value.
      • The assigned value will be returned (but ignored in this example).
  • More about variable declaration

    • We may declare multiple variable in the same type together:
      • int a, b, c; declares three integers a, b, and c.
    • We may initialize all of them also in a single statement:
      • int a = 1, b = 2, c = 3;
    • A variable’s name consists fo a consecutive sequence of letters, digits, and the underline symbol “__”.
      • It cannot begin with a number.
      • It cannot be the same as a C++ keywords
      • It (and the whole c++ world) is case-sensitive.
    • Always initialize your variable.
    • Use meaningful names.
    • Capitalize the first character of each word, but not the very first one:
      • int yardToInch = 12, avgGrade = 0, maxGrade = 100;
#include <iostream>
using namespace std;

int main()
{
  int num1 = 13, num2 = 4;
  cout << num1 + num2;
  
  return 0;
}
  • We first declare and initialize two integers.
  • Then, we do cout << num1 + num2;
  • There are two operations here:
    • num1 + num2 is an addition operation. The sum will be returned to the program.
    • That returned value is then sent to cout through <<.
#include <iostream>
using namespace std;

int main()
{
  int num1 = 13, num2 = 4;
  cout << num1 + num2 << endl;  // result: 17
  cout << num1 - num2 << endl;  // result: 9
  cout << num1 * num2 << endl;  // result: 52
  cout << num1 / num2 << endl;  // result: 3 \a
  cout << num1 % num2 << endl;  // result: 1
  
  return 0;
}
  • Data types matter!

    • If the inputs of the division operation are both integers, the output will be trancated to an integer.
  • The cin object

    • The extraction operator >> is used with the cin object.
    • The input stream is split into multiple pieces by “enter” and white spaces.
      • Different pieces are sent to different variables.
      • If the number of variables is fewer than the input pieces, pieces will be put in an input buffer waiting for future cin operations.
      • Try to run the following program by entering “4 13”.
#include <iostream>
using namespace std;

int main()
{
    int num1 = 0, num2 = 0;

    cout << "Enter first number: ";
    cin >> num1;
    cout << "Enter second number: ";
    cin >> num2;
    cout << "The sum of " << num1 << " and " << num2 << " is " << num1 + num2 << endl;

    return 0;
}
// Revised version of above program
#include <iostream>
using namespace std;

int main()
{
    int num1 = 0, num2 = 0;

    cout << "Please enter two numbers, seperated by a white space: ";
    cin >> num1 >> num2;
    cout << "The sum of " << num1 << " and " << num2 << " is " << num1 + num2 << endl;

    return 0;
}

The if and while statements

#include <iostream>
using namespace std;

int main()
{
    int num1 = 0, num2 = 0;

    cout << "Please enter two numbers, seperated by a white space: ";
    cin >> num1 >> num2;

    if (num1 > num2)
    {
        cout << num1 << " is greater than " << num2 << endl;
    }
    else if (num1 < num2)
    {
        cout << num1 << " is less than " << num2 << endl;
    }
    else
    {
        cout << num1 << " is equal to " << num2 << endl;
    }
}
  • The comparison operators
    • == checks whether the two sides of it are equal.
    • Returns a Boolean value: true (non-zero) or false (zero).
    • What happens to the following three program?
// First one
int a = 0;
if (a == 1)
{
  cout << "Ha!" << endl;
}

// second one
int a = 0;
if (a = 1)
{
  cout << "Ha!" << endl;
}

// last one 
int a = 0;
if (a = 0)
{
  cout << "HA!" << endl;
}
  • All the following comparison operators return a Boolean value.
    • >: bigger than
    • <: smaller than
    • >=: not smaller than
    • <=: not bigger than
    • ==: equals
    • !=: not equals

Syntax errors vs. logic errors

Formating a C++ program

  • In a C++ program, semicolons are marks of the end of statements.
  • White spaces, tabs, and new lines do not affect the compilation and execution of a C++ program.
    • Except strings and preprocessor commands.
  • Maintaining the program in a good format is very helpful.
  • While each programmer may have her own programming style. there are some general guidelines.
    • Start a new line after each semicolon.
    • Align paired braces vertically.
    • Indent blocks according to their levels.
    • Give variables understandable names.
    • Declare related variables in the same line.
    • Add proper white spaces and empty lines.
    • Write comments.