You are on page 1of 38

1

Basic Elements of C++


IT11103/ IT12103 – Introduction to Computer Programming
Faculty of Computing & Informatics (FCI) UMS
2 Content
 The Basic of a C++ Program
 Data Types
 String Types
 Identifiers, Variables & Constants
 C++ Expression
 Assignment operator & statement
 Arithmetic Operators & Operator Precedence
 Type Conversion
 Decision Making: Equality & Relational operators
 Increment & Decrement Operators
 Preprocessor Directives
 Creating a C++ program
 Syntax, Semantics & Errors
3 The Basic of a C++ Program

 Preparing to program
 Determine the objectives of the program
 Determine the methods you want to use in writing the program
 Create the program to solve the program
 Run the program to see the result
4 The Basic of a C++ Program

 Basic Structure

#include <iostream> <- info about I/O to be included


int main () <- main function
{ <- brace begins a block of code
cout<<“ hello”; <- to print out on screen
} <- end of code
5 The Basic of a C++ Program
 1 // Fig. 1.2: fig01_02.cpp // Single-line comments
 2 // A first program in C++.
Preprocessor directive to include input/output stream header
 3 #include <iostream>
file <iostream>
 4
 5 // function main begins program execution
Function main returns Function main appears exactly once in every C++ program
an integer value  6 int main()
Left brace { begin function body Statement end with a semicolon ;
 7 {
 8 std::cout << "Welcome to C++!\n"; \n Escape sequence – C++ special character
Name cout belongs tonamespace
9 std << Stream insertion operator
 10 return 0; // indicate that program ended successfully
 11 Keyword return is one of several means to exit function; value 0 indicates program terminated successfully

 12
 13 } // end function main
Right brace } end function body
6 The Basic of a C++ Program

Escape sequences
7 Data Types
C++ Data Type

Simple Address Derived/Structured

Integral Floating array


pointer
struct
references
union
class
char float
short double
int long double
long
bool
8 Data Types

 General syntax of declaration of data type:


Data_type variable_name;
 e. g. : int pelajar;
9 String Type
 A string is a sequence of characters enclosed in double quotes
 string sample values
“Hello” “Year 2000” “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
 Need to include the following two lines:
#include <string>
using namespace std;
10 Arithmetic operators and Operator Precedence

Arithmetic operators
11 Arithmetic operators and Operator Precedence

Operators precedence
12 Identifier
 An identifier is the name to denote labels, types, variables, constants or functions,
in a C++ program.
 C++ is a case-sensitive language. (Work is not work )
 Identifiers should be descriptive (Using meaningful identifiers is a good
programming practice)
 Identifiers must be unique
 Identifiers cannot be reserved words (keywords)
i.e.: double main return
 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
Valid (age_of_student, StudentAge, Age123)
Invalid (age#, Age-of-dog, 2000Age, main)
13 Identifier
C++ Keyword (cannot be used as identifier)
asm do if return typedef
auto double inline short typeid
bool dynamic_cast int signed typename
break delete long sizeof union
case else mutable static unsigned
catch enum namespace static_cast using
char explicit new struct virtual
class extern operator switch void
const false private template volatile
const_cast float protected this wchar_t
continue for public throw while
default friend register true union
delete goto reinterpret_cast try unsigned
14 Class Activity
Explain why the given identifiers are invalid, and please give the valid
identifiers
 2morrow
 Min Time
 Age-70
 Cost_in _$
 int
 Five*two
 Name’s
 short
15 Variable
 A variable is a memory address where data can be stored and
changed.
 Declaring a variable means specifying both its name and its data
type.
 A declaration tells the compiler to allocate enough memory to hold
a value of this data type, and to associate the identifier with this
location.
 All variables must be declared before use.
16 Variable
 Variable declaration:
Example  int age;
Data type Identifier ( variable’s name)
 Commas are used to separate identifiers of the same type.
Example  int number, age;
 Can be initialized to a starting value when the are declared.
Example  int age = 1;
int count, age = 0;
17 Variable

 DO use variable names that are descriptive.


 DO adopt and stick with a style for naming your variables. E.g.
studentName, studentAge.
 DON'T start your variable names with an underscore
unnecessarily.
 DON'T name your variables with all capital letters
unnecessarily.
18 Constant
 Constants are used to store values that never change during the program
execution.
 Using constants makes programs more readable and maintainable.
Syntax:
const <type> <identifier> = <expression>;
Examples:
const double US2HK = 7.8;
//Exchange rate of US$ to HK$
const double HK2TW = 3.98;
//Exchange rate of HK$ to TW$
const double US2TW = US2HK * HK2TW;
//Exchange rate of US$ to TW$
19 C++ Expression
 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.
 In C++, an expression can be:
 A variable or a constant (e.g.: count, 100)
 An operation (e.g.: a + b, a * 2)
 Function call (e.g.: getRectangleArea(2, 4))
20 Assignment Operator & Statement

Age = 27 Assignment Statement

Variable Value

Assignment operator

 The assignment operator is used to change the content of a variable.


21 Type Conversion
 Warning: If you store values of one type in variable of
another type the results can be inconsistent:
 Can store integers in floating point or in char (assumes ASCII
value)
 bool can be stored as int: (true = nonzero, false = 0)
 Implicit promotion: integers are promoted to doubles
double var = 2; // results in var = 2.0
22 Type Conversion (Implicit Conversion)
 The compiler tries to be value-preserving.
 Assigning float to int will truncate the float value;
int_variable = 2.99; // results in 2 being stored in int_variable
 Assigning int to float will promote the int value to double;
double dvar = 2; // results in 2.0 being stored in dvar
23 Type Conversion (Explicit Conversion)
 Casting - forcing conversion by putting (type) in front of variable or expression.
Used to ensure that result is of desired type.
 Example: If you want to divide two integers and get a real result you must cast
one to double so that a real divide occurs and store the result in a double.
int x=5, y=2; double z; z = static_cast <double>(x)/y; // 2.5
int x=5, y=2; double z; z = (double)x/y; // 2.5
int x=5, y=2; double z; z = static_cast <double>(x/y) ; // 2.0

 converts x to double and then does mixed division, not integer division.
 static_cast<int> (z) - will truncate z.
24 Decision Making: Equality & Relational
Operators
 Usually used in “ if statement”, allows a program to take alternative action based
on whether a condition is true or false.
 Condition can be formed using equality operators and relational operators.
 The relational operators all have the same level of precedence and associate left to
right.
 The equality operators both have the same level of precedence, which is lower
than that of the relational operators, and associate left to right.
25 Decision Making: Equality & Relational
Operators
Relational & Equality operators
26 Precedence and associativity of the operators
(as discussed above)
27 Increment & decrement operators
 Always used in repetition structures
 Increment operator  ++
 Post increment  x++;
 Pre increment  ++x;

 Decrement operator  --
 Post decrement  x--;
 Pre decrement  --x;
28 Increment & decrement operators
29 Increment & decrement operators

How the operators work:


30 Preprocessor Directives
 Many functions and symbols are provided as collection of libraries
 Every library has a name and is referred to by a header files.
 The preprocessor directives give instruction to the compiler to process the
information before actual compiler starts
 All preprocessor commands begin with #
 No semicolon(;) at the end of commands.
Example:
#include <iostream>
- Causes the preprocessor to include the header file
iostream in the program
- iostream  input/output stream
31 Preprocessor Directives
32 Creating a C++ Program

 C++ program has two parts:


 Preprocessor directives
 The program
 Processor directives and program statement constitute C++ source code (.cpp)
 Compiler generates object code (.obj)
 Executable code is produced and save in a file with the extension (.exe)
33 Creating a C++ Program
 A C++ program is a collection of functions.
 The first line of function main is called the heading of the function:
e.g.: int main ()
 The statement enclosed between the curly braces ({ and }) form the body of the
function
 Contains two types of statements:
 Declaration statements
 Executable statements
34 Syntax, Semantic and Errors
 Syntax
 The formal rules governing how valid instructions are written in a programming language.

 Semantic
 The meaning of instructions written in programming language.
35 Syntax, Semantic and Errors

 Types of error
 Syntax error
 Occurs when a rule is not followed. Also known as compile time error.
 Examples of syntax error:

 Cannot be run (not executable)


36 Syntax, Semantic and Errors

 Semantic error
 Occurs when a statement written in the program is not meaningful to the compiler.
 Example:

void main(){
int a, b, c;
a+b=c;
}
 Logical error
 Occurs when the desired output is not obtained.

 Run-time error
 Occurs during program execution after successful compilation. E.g. divison by a zero.
37 Class Activity
Case 1 Case 2

int main () int main (){


int a,b: int a=10,b=0;
cin>>a>>b; cout<<“division =”a/b
cout<<a<<b; return 0;
return 0, }
}
Case 3 Case 4

int main (){ int main (){


int a=1,b=2,c=0; int s,u,r,a;
While (c ==1){ (s/u)+a=r;
cout<<“sum =”<< a+b; cout<<r;
} return 0;
return 0, }
}
38 Class Activity

 Answer
 Case 1 – Syntax errors ({ : , )
 Case 2 – Run time error ( a/b = /0 )
 Case 3 – Logical error (while loop cant be executed)
 Case 4 – Semantic error ((s/u)+a=r)

You might also like