CS计算机代考程序代写 compiler c++ LT2: Language Syntax, Variable and Basic I/O

LT2: Language Syntax, Variable and Basic I/O

Computer Programming

Computer Program

2

Logic Flow

Computer
Program

Instructions Data

A program is somewhat similar to the recipes used in cooking!

Ingredients ?

Volume ?

Variables ?

Data Size ?

Add / Sub… Mix / Heat…

if (i<0) cout<<“Negative”; Flip the egg if it is browned conditional while (i>0) { x=x+i; i–; }

Keep stirring until dissolved

repetition

check
something

I

a
While week 5

week2

Outlines

3

! C++ Language Syntax

! Constant and Variable Declaration

! Data types (integers, real numbers, true/false, string…)

! Operators (e.g. + – * / %)

! cin and cout from library

operators
X 3

operators

4
operand operand operand

int float

4

Outcomes

! Describe the basic syntax and data types of C++ language.

! Explain the concepts of constant, variable and their scope.

! Declare variable and constant under different scopes.

! Perform update on variables via different operators.

! Able to output variables’ values to screen with different formats.

! Able to read value from keyboard and assign to variable.

Syntax of C++

5

! Like real-life languages, C++ has grammatical rules for
putting together words and punctuation to make legal
program; that is called syntax of the language

! C++ compilers detect any violation of the syntactic rule
within the program

! In C++, vocabularies (keywords) are separated by space
and punctuations

! Most C++ commands end with semi-colon ;

Template (just like “to whom this may concern” in English)

6

#include
using namespace std;
int main(){

return 0;
}

/* Place your code here! */

Important!: no semi-colon here

Syntax – Tokens

7

! Tokens in C++ can be categorized into:

! keywords, e.g., return, int, float, double…etc.

! identifiers, e.g., user-defined names for variable/functions…

! data constants, e.g., (string) “Hello”, (number) 123…etc.

! operators, e.g., + – * / %

! punctuations, e.g., ; and ,

I
string constants

operand

constant
variable is not unknown I

Xt1 4
ft shxt le update constant

I
no

Keywords

8

it

Keywords (reserved words)
-covered in this course-

Data type char double float int bool

long short signed unsigned void

Flow control if else switch case

break default for do

while continue

Others using namespace true false sizeof

return const class new delete

operator public protected private friend

this try catch throw struct

typedef enum union
9

Keywords (cont’d)

10

! Each keyword in C++ has a reserved meaning.

! When a programmer needs to give name to variables or
functions, the name should NOT be the same as those
reserved keywords.

! Just like in English… If you give yourself a name “Happy”,
then the meaning of “I am Happy” would be ambiguous.

! Most of the keywords given in the previous page will be
covered in this course; No need to be hurry in memorizing
them all NOW, you’ll learn them over weeks

! The list in last page is partial, some keywords are
deliberately omitted

11

Identifiers
! Identifiers are unique names given to various items in a program, like

functions (command block) and variable (data storage)

! Similar to keywords, identifiers are also case sensitive
(i.e. SALARY and Salary are considered different)

! As mentioned in the previous page, reserved keywords like float and
int cannot be used as identifiers

! An identifier is composed of a sequence of letters, digits and
underscore (e.g. myRecord, point3D, last_file…)

! Avoid foreign characters (Chinese/Japanese…etc)

To get a good name…
! Variable names in C++ are case sensitive

(so abc, ABC, Abc are three different and unrelated variables)

! It may contains alphabet (a-z A-Z), digits (0-9), underscore ( _ ),
but… NO SPACE, NO HYPHEN !
(finalResult, final_result and result0_9 are ok, but final result is not!)

! First character must be non-digit (i.e. not 0-9)
(result_1A is ok, but 1A_result is not!)

! The Rule is: assign a name which is self-explanatory & just enough!
! Names like x, y, z are too simple to understand what they’re for

(it is considered worldwide that it’s a bad programming habit,
some lecturers deduce mark for that!)

! A name like total_sales_in_year_2020_to_2021 is self-explanatory…but..

K treater as I i

IIA result is ok

hard to know it Y Z

too long

! Variable is a named place to store information. It is similar to the
unknowns (e.g. x) in your Math lessons, but…
! Variables could have longer names (e.g. finalResult )
! could change value as program runs (at first it was 1, but then it became 10)
! could store something other than number (e.g. user name, address…etc)

! To create a variable, write:
! ; (e.g. int a; ) or

= ; (e.g. int a = 5; )

! Note, however, that variable is NOT the unknowns in Math…
! You may write cout<<-a; (which gives -5), but writing cout<<2a; is WRONG! ! The equal sign (=) means ASSIGN (i.e. copy value from right to left), but not EQUALITY, therefore writing 5 = a; is WRONG! ! IMPORTANT: Don’t quote the variables. cout<<“a”; will show just the a character, but not the internal value 5 What is a variable? Data int mustint FEETello t ERR ta Declaration - Variable 14 ! Variable and constant must be declared before use. ! Declaration actually asks compiler to reserve memory space for you. ! Examples: ! int age ; ! float volume ; ! char initial ; ! char student_name[30]; ! Optionally, the initial value of a variable can be set with declaration. ! int age=18; ! float volume=15.4; ! Do NOT try to read from a variable before its value is set! ! Declarations could be written in: ! Beginning of program, outside all functions (i.e. outside main() {..} ) ! Beginning of a function (i.e. inside the { } of main ) havactor 15 Declaration – Global vs. Local ! Variables actually have life-span. There are restrictions on when and where it could be read… ! Scope of a variable refers to the accessibility of a variable: ! Two major types: Global vs. Local ! Global variable ! A variable defined in the global declaration sections of a program, i.e. defined outside functions. ! can be accessed anywhere by all functions ! Local variable ! Declare in a block and can be only accessed within the block. ! Try to access a local variable outside the block will produce error. Declaration – Variable (Local) 16 #include
using namespace std;
int main() {

int number1=12;
int number2=3;
int result;

result=number1+number2;

return 0;
}

We consider the variables local as they’re

enclosed by the brackets { } of main

1

2
The variables could be read / written

from here… (open brackets)

Up to here… (close brackets)3

4
If you put cout<
using namespace std;

int number1=12;
int number2=3;

int main(){

int result;

result=number1+number2;

return 0;
}

We consider the variables global as they

are NOT enclosed by the brackets { }

1

Global variables could also be accessed

inside functions (like main() ), as
long as their names are different from

that of local variables!

(FYI: If their name crash with the local
vars, then you always read the local vars,
global vars will be inaccessible)

2

3 Of course, number1 can also be accessed

after here ! (by some other functions) since it
does not belongs to main()

usually avoid global variable

18

Scope of function variables

int number1=12;
int number2=3;

int min( int x , int y ){
if (x>y){

return y;
}else{

return x;
}

}

int main(){
int result;
result=min(number1,number2);
return 0;

}

x and y are alive only in function
min(), between the brackets { }

x and y not accessible

outside brackets { }

main() could not read x and y

as well since they’re dead after
the execution of function

(We’ll re-visit the detail syntax of function in later weeks…)

19

C++ Predefined Data type

! Numerical
! Integer (+/- number without decimal place)- 1, -999, 123456

! int (most common)

! short, long, unsigned (less common)

! Floating point (+/- num wit dot, or scientific notation) – 0.25, 3.01e-5

! double (more accurate), float (less accurate)

! Character – ‘a’, ‘e’, ‘o’, ‘\n’
! char (actually char can be used to store small integer (rare))

! Boolean – true, false

! bool

Account balance X

20

Constants (i.e. give the value directly)

! Constants can be numeric-, character- or string-based, e.g.,
13, 7.11, ‘\n’, “Tuesday”

! Numbers are represented in decimal system. Although NOT
COMMON, but octal (base-8)(preceded by 0) or hexadecimal
(base-16) integers (preceded by 0x) are also possible.

e.g., the following number are equal to a decimal 26
032 /* octal integer, Important ! It is not 32 (thirty two) */
0x1a /* hexadecimal integer */

! Character constant is enclosed by single quotation marks,
e.g., ‘a’, ‘\n’, ‘\t’

21

Declaration – Named constants

! Allow us to give a name to special value. (easier to understand..)

! Value MUST be given at the same time it is declared

! Value could not be changed further

! Format:
! const Data_type variable/constant identifier = value;

! Examples:

! const float pi=3.14159;

! const int maxValue=500;

! const char initial=‘D’;

! const char student [] =”Amy Li”;
If you later write maxValue=1;

or cin>>maxValue; it will be

syntax error and Visual Studio

will not compile your code!

Data type int
About 2*109, not
as large as you

think !

22

! Typically, an int is stored in four bytes (or 32bits, as 1 byte = 8 bits).

! 64bit CPU uses 8 bytes. It may be some other sizes in future CPUs

! The length of an int data type restricts the range of number it can
store. A 32-bit int can store numbers in the range of -231 to 231 -1
(i.e. -2147483648 to +2147483647)

! We can optionally put the unsigned keyword before int, by doing so
we will give up the negative range and double the positive range

! e.g. When we write: unsigned int x; x has range 0 to 232 -1

! When an int is assigned a value greater than its maximum bound,
overflow occurs and this ends up with incorrect result

! Note: C++ does not inform you that overflow error occurred!
(Let’s try cout << 90000 * 90000;) same withdy easy maintain us int 23 The floating types ! float, double and long double are floating point types. (i.e. numbers with decimal point or in scientific notation) ! Numeric constants with decimal point (e.g. 3.14) by default is in double type (not float !) ! Scientific notation is also acceptable, e.g., 1.23e3 and 3.367e-4 (means 1.23*103 and 3.367*10-4 respectively) ! A constant is considered floating point if dot or exponent exist! (e.g. 1000.0 and 1e3 are floating point, while 1000 is integer) 32bits 64 double size 80 a 1 103 1000 If EYEcont R default big fig 24 Characters & data type char ! In C++, a char takes one byte or 8 bits of memory to store. ! Although char is considered as character, but just like other variables, it’s just a sequence of binary 0 & 1 in memory (i.e. can also be considered as binary NUMBER) e.g. char x = ‘a’; is (of course) OK char y = ‘A’ + 1; is also OK! (y will store ‘B’) char z = 97; is also OK! (z will store ‘a’) (see next page !) ! The relationship (mapping) of the character against the binary number is listed in the ASCII table (It is international standard used by major PCs!). ! Therefore if you write int w = x; w will store 97 ! ! Conclusion: char and small integers are interchangeable! 25 ASCII Code 26 Conversions ! cout automatically detects data type and prints accordingly ! char x = ‘A’; int y=x; ! cout<>hour; cout<<“Hi”; Those >> and << are also operators 29 Operators and punctuations ! Unary operators (work with ONE value) ! Negation - ! e.g. int x = 5; int y = -x; (y is having a value of -5) ! Besides the – operator, C++ also defines: ++ and -- Which applies only to integers ! ++ is increment by one. ! k++ and ++k are equivalent to k=k+1 (increase the value by 1) ! -- is decrement by one. ! k-- and - -k are equivalent to k=k-1 (decrease the value by 1) 30 Increment & decrement operators ! ++ and - - are special. Unlike addition (+): ! It cannot be applied to constant. (e.g. ++5 is wrong!) ! It can be placed before (++x) or after (x++) a variable. ! Difference between writing in front / after ? ! Post-increment and post-decrement: k++ and k-- ! k’s value is altered AFTER the expression is evaluated ! int k=1, j; ! j=k++; /* result: j==1, k==2 */ ! Pre-increment and pre-decrement: ++k and --k ! k’s value is altered BEFORE evaluating the evaluation ! int k=1, j; ! j=++k; /* result: j==2, k==2 */ 31 Self Test 1 int x=3; cout<< x; cout<< ++x; cout<< x; cout<< x++; cout<< x; What is the output of the following program? (let’s verify with Visual Studio) 3 4 4 4 5 32 Self Test: Solution Old x New x Output int x=3; 3 3 -- cout<< x; 3 3 3 cout<< ++x; 3 4 4 cout<< x; 4 4 4 cout<< x++; 4 5 4 cout<< x; 5 5 5 33 Self Test 2 int a=0,i=0; cout<<"i="< Post navigation