C++ Basics

chapter1 Overview of C++

Computer Programming

Computer Components

image-20210402203000479

Programming Language

It is a language with strict grammar rules, symbols, and special words used to construct a computer program.

Machine Language

  • is not portable
  • Runs only on specific type of computer
  • is made up of binary-coded instructions
  • is the language that can be directly used by the computer

High Level Languages

  • are portable
  • user writes program in language similar to natural language
  • most are standardized by ISO/ANSI to provide an official description of the language

C++ History

image-20210402203847317

Program Construction

image-20210402203940234

#include <iostream>

int Square(int);
int Cube(int);

int main(){
    cout<<"The square of 2 is "<<Square(2)<<endl;
    cout<<"The cube of 2 is "<<Cube(2)<<endl;
    return 0;
}
int Square(int n){
    return n*n;
}
int Cube(int n){
    return n*n*n;
}

Compilation and Execution Processes

image-20210402204513344

chapter2 Numeric Type and Expressions

Overview of C++ Data Types

image-20210402205113848

C++ Data Type:String

  • a string is a sequence of characters enclosed in double quotes

  • string sample values: “Hello”,”1234”

  • the empty string(null string) contains no characters and is written as “”

  • string is not a built-in (standard) type

    • it is a programmer-defined data type
    • it is provided in the C++ standard library
  • string operations include

    • comparing 2 string values
    • searching a string for a particular character
    • joining one string to another

C++ Identifiers

an identifier must start with a letter or underscore, and be followed by zero or more letters(A-Z,a-z), digits(0-9), or underscores(字母,数字,下划线,首字母只能是字母或下划线)

  • some C++ compilers recognize only the first 32 characters of the identifier as significant
  • case-sensitive

Declarations for Numeric Types

A Variable

  • A variable is a location in memory which we can refer to by an identifier, and in which a data value that can be changed is stored.
  • declaring a variable means specifying both its name and its data type

image-20210402212714852

Named Constant

A named constant is a location in memory that we can refer to by an identifier, and in which a data value that cannot be changed is stored.

// VALID CONSTANT DECLARATIONS
const string STARS = "****";
const float NORMAL_TEMP = 98.6;
const char BLANK = ' ';
const int VOTING_AGE = 18;

image-20210402213120355

Arithmetic Expressions

  • An expression is a valid arrangement of variables, constants, and operators.

  • in C++ each expression can be evaluated to compute a value of a given type

Operators can be

binary involving 2 operands +

unary involving 1 operands ++

ternary involving 3 operands ? :

image-20210402213840310

Precedence

  • Higher Precedence determines which operator is applied first in an expression having several operators
  • Paranthesese()can be used to change the usual order

image-20210402214235110

Assignment Operator

image-20210402214319016

chapter3 Introduction to Programming

Simple Input and Output Operations

image-20210402214736481

Input Statements

cin >> length;
cin >> width;

cin >> length >> width;

Output Statements

cout << "The answer is";
cout << 3*4;

cout << "The answer is" << 3*4;

Manipulators

  • manipulators are used only in input and output statements
  • endl, fixed, setprecision, and setw are manipulators that can be used to control output format
  • endl is used to terminate the current output line, and create blank lines in output

image-20210402215157715

image-20210402215229047

#include <iomanip>   // for setprecision
#include <iostream>

using namespace std;

int main(){
    float myNumber = 123.4567;
    cout << fixed;  // use decimal format
    
    cout << "Number is" << setprecision(3)
        << myNumber << endl;  // Number is 123.459
    return 0;
}

image-20210402215530772

#include <iomanip>  // for setw
#include <iostream>

int main(){
    int myNumber = 123;
    int yourNumber = 5;
    cout << setw(10) << "Mine"
         << setw(10) << "Yours"    << endl;
    cout << setw(10) << myNumber
         << setw(10) << yourNumber << endl;
    return 0;
}

Output:

​ Mine Yours

​ 123 5

image-20210402215959221

Control Structures

Basic Control Structures

  • a sequence is a series of statements that execute one after another
  • selection(branch) is used to execute different statements depending on certain conditions
  • looping(repetition) is used to repeat statements while certain conditions are met

image-20210402220232296

Selection Control Structures

image-20210402220335628

int carDoors, driverAge;
float premium, monthlyPayment;
...
if((carDoors == 4) && (driverAge>24)){
    premium = 650.00;
    cout << "LOW RISK";
}else{
    premium = 1200.00;
    cout << "HIGH RISK";
}

image-20210402220601530

Loop Control Structures

image-20210402220640396

//Count-controlled Loop
int count = 4;
while(count>0){
    cout << count << endl;
    count--;
}
cout << "Done" << endl;
//Event-controlled Loop
do{
    cin >> response;
    if((response!='y')&&(reponse!='\n'))
        cout << "Please type y or n:";
}while((response!='y')&&(response!='n'));

chapter4 functions

Function Declaration

Function Definition

image-20210403125608837

Function Prototype

  • A prototype looks like a heading but must end with a semicolon(😉
  • and its parameter list just needs to contain the type of each parameter.

SYNTAX

DataType FunctionName (Parameter List);

before a function is called in your program, the compiler must previously process either the function’s prototype, or the function’s definition(heading and body)

Function Call

  • One function calls another by using the name of the called function next to () enclosing an argument list.
  • A function call temporarily transfers control from the calling function to the called function.

Function Call Syntax:FunctionName(Argument List)

  • the argument list is a way for functions to communicate with each other by passing information
  • The argument list can contain 0, or more arguments, separated by commas(,).

Value-returning Function

in its identifier at most 1 values of the type which was specified (called the return type) in its heading and prototype. But, a void-function cannot return any value in its identifier

#include <iostream>

int Square(int); //prototypes
int Cube(int);
using namespace std;

int main()
{
    cout << "The square of 2 is" << Square(2) << endl;
    cout << "The cube of 2 is" << Cube(2) << endl;
    return 0;
}
// Rest of program
int Square(int n){
    return n*n;
}
int Cube(int n){
    return n*n*n;
}

void Function

#include <iostream>
void DisplayMessage(int);  // prototype
using namespace std;

int main(){
    DisplayMessage(15);
    cout << "Good Bye" << endl;;
    return 0;
}
void DisplayMessage(int n){
    cout << "I have liked math for " << n << "years" << endl;
}

Parameters

Parameters is the means used for a function to share information with the block containing the call.

image-20210403131333230

image-20210403131522547

  • (of simple types like int, cahr, float, double) are always value parameters, unless you do something to change that
  • To get a reference parameter you need to place & after the type in the function heading and prototype.

Reference parameters should be used when you want your function to give a value to, or change the value of , a variable from the calling block without an assignment statement in the calling block.

pass-by-value(值传递)

image-20210403135807514

pass-by-reference(引用传递)

image-20210403135841190

image-20210403135928108

#include <iostream>
using namespace std;

// one parameter has default value 0
int sum(int a, int b, int c=0) {
    return a+b+c;
}

int main(){
    int i=10,j=20,k=30;
    // sum up three int numbers
    cout<<i<<'+'<<j<<'+'<<k<<'='<<sum(i,j,k)<<endl;
    //sum up two int numbers
    cout<<i<<'+'<<j<<'='<<sum(i,j)<<endl;
    reutrn 0;
}

Scope of an Identifier

the scope of an identifier(or named constant) means the region of program code where it is legal to use that identifier for any purpose

image-20210403140502265

const float TAX_RATE = 0.05;  //global constant
global tipRate;    // global variable
void handle(int, float);   // function prototype

using namespace std;

int main(){
    int age;  // age and bill local to this block
    float bill;
    
    ...    //a,b,and tax cannot be here
           // TAX_RATE and tipRate can be used
    handle(age,bill);
    return 0;
}
void handle(int a, float b){
    float tax;   // a,b and tax local to this block
    ...
}

Detailed Scope Rules

  1. Function name has global scopre
  2. Function parameter scope is identical to scope of a local variable declared in the outermost block of the function body
  3. Global variable (or constant) scope extends from declaration to the end of the file, except as noted in rule 5.
  4. Local variable(or constant) scope extends from declaration to the end of the block where declared. This scope includes any nested blocks, excpet as noted in rule 5.
  5. An identifier’s scope does not include any nested block that contains a locally declared identifier with the same name (local identifier have name precedence)

When a function declares a local identifier with the same name as a global identifier, the local identifier takes precedence within that function

Name Precedence Implemented by Compiler Determines Scope

  • When an expression refers to an identifier, the compiler first checks the local declarations
  • If the identifier isn’t local, compiler works outward through each level of nesting until it finds an identifier with same name. There it stops.
  • Any identifier with the same name declared at a level further out is never reached
  • If compiler reaches global declarations and still can’t find the identifier, an error message results.

Lifetime of a Variable

  • the lifetime of a variable is the time during program execution when an identifier actually has memory allocated to it
// These allocate memory
int someInt;  // for the global variable

int Square(int n){  // for instructions in body
    int result;  // for the local variable
    result = n*n;
    return result;
}

// These do NOT allocate memory
int Square(int n);  // function prototype
extern int someInt; // someInt is a global variable defined in another file

Lifetime of Local Automatic Variables

  • local variables are “alive” while function is executing
  • Their storage is created(allocated) when control enters the function
  • Theri storage is destroyed when function exits;

Lifetime of Global Variables

  • Their lifetime is the lifetime of the entire program
  • their memory is allocated when program begins execution
  • Their memory is destroyed when the entire program terminated

By default

  • local variables are automatic
  • To obtain a static local variable, you must use the reserved word static in its declaration.

image-20210403142950787

Static and Automatic Local Variables

int popularSquare(int n){
    static int timesCalled = 0; // initialized only once
    it result = n*n;  //initialized each time
    
    timesCalled = timesCalled + 1;
    cout << "Call #" << timesCalled << endl;
    return result;
}

More on Functions

Inline Function

#include <iostream>
using namespace std;
inline int max(int,int,int); // function prototype

int main(){
    int i=10,j=20,k=30,m;
    m = max(i,j,k); // repalced by the body block of max when compiling
    cout << "max="<<m<<endl;
    return 0;
}

inline int max(int a, int b, int c)  // define the inline function 
{
    if(b>a) a = b;
    if(c>a) a= c;
    return a;
}

Function Overloading

#include <iostream>
using namespace std;

int sum(int a, int b){return a+b;}  // two int parameters
int sum(int a, int b, int c){return a+b+c;} // three int parameters
double sum(double a, double b){reurn a+b;} // two double parameters

int main(){
    int i=10,j=20,k=30;
    double m=2.1,n=3.5;
    cout<<i<<'+'<<j<<'='<<sum(i,j)<<endl;  //two int arguments
    cout<<i<<'+'<<j<<'+'<<k<<'='<<sum(i,j,k)<<endl; 
    cout<<m<<'+'<<n<<'='<<sum(m,n)<<endl;
    return 0;
}

Function Template

#include <iostream>
using namespace std;

template <class T>  //declare a template with type parameter T
T sum(T a, T b) {return a+b;}

int main(){
    int i=10,j=20;
    double m=2.1,n=3.5;
    cout<<i<<'+'<<j<<'='<<sum(i,j)<<endl; //replace T by int
    cout<<m<<'+'<<n<<'='<<sum(m,n)<<endl; //replace T by double 
    return 0;
}

chapter5 Arrays

An Array is a structured collection of components (called array elements), all of the same data type, given a single name, and stored in adjacent memory locations.

Declaring and Using an One-Dimensional Array

SYNTAX

DataType ArrayName[ConstIntExpression];
  • The index is also called the subscript
  • the base address of an array is its begining address in memory
// allocated memory for array
float temps[5];
int m = 4;
temps[2] = 98.6;
temps[3] = 101.2;
temps[0] = 99.4;
temps[m] = temps[3]/2.0;
temps[1] = temps[3] - 1.2;

int ages[5] = {40,13,20,19,36};
for(int m=0;m<5;m++){
    cout<<"ages["<<m<<"]="<<ages[m]<<endl;
}

image-20210403145129963

Passing Arrays as Arguments to Functions

  • in C++, arrays are always passed by reference
  • whenever an array is passed as an argument, its base address is sent to the called function.

example:

#include <iomanip>
#include <iostream>

void Obtain(int [], int); 
void FindWarmest(const int[], int, int &);
void FindAverage(const int[], int, int &);
void Print(const int[], int);

using namespace std;

int main(){
	int temp[31];
    int numDays;
    int average;
    int hottest;
    int m;
    cout<<"How many daily temperatures?";
    cin>>numDays;
    
    Obtain(temp, numDays); // passes value of numDays and address of the array temp to function
    cout<<numDays<<"temperatures"<<endl;
    Print(temp,numDays);
    
    FindAverage(temp, numDays, average);
    FindWarmest(temp, numDays, hottest);
    cout<<endl<<"Average was: "<<average<<endl;
    cout<<"Highest was:"<<hottest<<endl;
    return 0;
}

Declaring and Using a Two-Dimensional Array

image-20210403145930197

//Example
const int NUM_STATES = 50;
const int NUM_MONTHS = 12;
int stateHighs[NUM_STATES][NUM_MONTHS];

image-20210403150049769

example:

int total = 0;
int month;
int average;
for(month=0;month<NUM_MONTHS;month++)
    total = total + stateHighs[2][month];
average = int(total/12.0+0.5);

image-20210403150258937

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值