0% found this document useful (0 votes)
21 views

03 IntroductionToC++

1. A C++ program goes through several steps including compilation, where the syntax is checked for errors, and execution. 2. C++ evolved from C and was standardized to ensure consistency across compilers. 3. A C++ program structure typically includes preprocessing directives, namespaces, a main function, statements and expressions using variables, data types, operators, and control structures.

Uploaded by

ZHEN-HONG LEE
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views

03 IntroductionToC++

1. A C++ program goes through several steps including compilation, where the syntax is checked for errors, and execution. 2. C++ evolved from C and was standardized to ensure consistency across compilers. 3. A C++ program structure typically includes preprocessing directives, namespaces, a main function, statements and expressions using variables, data types, operators, and control structures.

Uploaded by

ZHEN-HONG LEE
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 52

INTRODUCTION

TO C++
UCCD1004 Programming Concepts and Practices
Life of a C++ Program
Step 1 – 3

Important source file


which the compiler
knows where to start to
run the program

Checking the syntax


error to ensure the
programmer obey the
programming rules in
order to give clear
instruction
Step 4 – 6
ANSI/ISO Standard C++
• C++ evolved from C and was
designed by Bjarne Stroustrup at
Bell Laboratories in early 1980s.

• There are many C++ compiler


available. Unfortunately, things
started to evolve in different ways
in different compilers.

• Therefore, a standard is needed.


ANSI/ISO Standard C++
#include <iostream>
using namespace std;

auto functionA(int x) { //Since C++14


    return x * x;
}

int main(void) {
    auto answer = 1 + 3;
    cout << answer << endl; //Since C++11
    cout << functionA(4) << endl;
    return 0;
}
Programming Steps
It is a problem solving process.

Potentially 3 types of errors:-

Syntax errors: when the program is not


written according to the rules of the
language.

Runtime errors: even though they are


syntactically correct, the instructions may
violate some other rules of the language or
some other set condition. (e.g. division by
zero)

Semantic errors: Syntactically correct but


it is not doing the right thing. These are
generally the most difficult to figure out.
Content Overview
Structure of C++ Programs

Statements Control Control


String and
and Structures Structures Functions Structs Pointers
Array
Expressions (Selection) (Iteration)

Input & Pass-by-


Data Types FileIO Classes
Output reference
Content Overview
Structure of C++ Programs

Statements Control Control


String and
and Structures Structures Functions Structs Pointers
Array
Expressions (Selection) (Iteration)

Input & Pass-by-


Data Types FileIO Classes
Output reference
Structure of C++ Program
#include <iostream> //Preprocessor
using namespace std; //Namespace

int main(void) { //Application entry point


    cout << "Hello World" << endl;
//Statements
    return 0; //Statements
}
Preprocessor
• It is used to provide commands before the code is compiled.

• Preprocessor directives and the names of the header files are


used to tell the computer the locations of the code provided in
libraries.

• There are many other usages (we will see them along the way).
Namespace
• Namespaces are used to organize code into logical groups and
to prevent name collisions that can occur especially when your
code base includes multiple libraries.

• For now just live with it. =)


Application Entry Point

• A point where control is transferred from the OS to an


application.

• In C/C++ this point is a function called main.

• It returns zero, meaning the execution is successful.


Main

There are 2 proper ways to write a main in C++

int main(void) { /* ... */ }

int main(int argc, char *argv[]) { /* ... */ }

The main function must return int.


Main
Question: Can I write “void main()” or just “main()”?
Answer: NO !

Bjarne Stroustrup says it is not and never has been C++, nor has it
even been C.  Even if your compiler accepts "void main()" avoid
it, or risk being considered ignorant by C and C++ programmers.

http://www.stroustrup.com/bs_faq2.html#void-main
Statements vs. Expressions
• Every single line of code can be considered as a statement,
often end with “;”

• Expression statement is “a sequence of operators and operands


that specifies a computation”.

• For example:- int main(void) {


    int x; //statement
    x = 3 + 5; //expression
    return 0;
}
Statements vs. Expressions

• Example:
Please plus 1 with 2 then multiply with 3. Later divide the
answer with 3.
Comments
• Comments are portions of the code ignored by
the compiler which allow the user to make
simple notes in the relevant areas of the source
code. 

• Comments come either in block form or as


single lines. int main(void) {
    // this is a
comment
    /*
     this is a
     multi-line
     comment
     */
    return 0;
}
Whitespace, Newline and Indentation

• C++ doesn’t care much about Whitespace, Newline and


Indentation.

• Programmers follow certain programming convention to make


sure that their codes are readable.
Special Symbols
• Token is the smallest individual unit of a program written in
any programming language.

• Tokens can be special symbols, keywords and identifier.


Variable
• Variables are the names given to computer memory locations
which are used to store values in a computer program.

• C++ is a strongly typed (debatable). Therefore, the type of the


variable need to be specified explicitly.

int main(void) {
    int x;
    double y;
    char z;
}
Defining Variables
• Variables of the same type can be defined
In separate statements
• int length;
• int width;

In the same statement


• int length, width;

• Variables of different types must be defined in separate statements

2-22
Named Constants
• Also called constant variables

• Variables whose content cannot be changed during program


execution

• Used for representing constant values with descriptive names


• const double TAX_RATE = 0.0675;
• const int NUM_STATES = 50;

• Often named in uppercase letters

3-23
Data Types
• In computing, data type is a particular kind of data item, as
defined by the values it can take, the programming language
used, or the operations that can be performed on it.

• In C++, data type can be of the followings:-


• Primitive Data Type
• Custom Data Type
• Pointers
Primitive Data Type
• A built-in type provided by a programming language as a basic
building block. For example:-
Primitive Data Type
• Different compilers may allow different ranges of values. It also
depends on the particular system (type of computer).
Primitive Data Type

*https://www.geeksforgeeks.org/data-type-ranges-and-their-macros-in-c/
Primitive Data Type
• A float is a single precision, 32-bit floating-point data type that
accommodates seven digits.

• A double is a double-precision, 64-bit floating-point data type.


It accommodates 15 to 16 digits.

• It includes those before and after the decimal point. 


Arithmetic Operators
There are five arithmetic operators:
+ (addition)
- (subtraction or negation)
* (multiplication),
/ (division)
% (mod, (modulus or remainder))
/ Operator
• C++ division operator (/)performs integer division if both
operands are integers
cout << 13 / 5;    // displays 2
cout << 2 / 4;    // displays 0

• If either operand is floating-point, the result is floating-point

cout << 13 / 5.0;  // displays 2.6


cout << 2.0 / 4;   // displays 0.5

2-30
% Operator
• C++ modulus operator (%) computes the remainder resulting
from integer division
cout << 9 % 2;   // displays 1

• % requires integers for both operands


cout << 9 % 2.0; // error

2-31
HELLO WORLD

#include <iostream>
using namespace std;

int main(void) {
    cout << "Hello World" << endl;
    return 0;
}
Unary operator
• C++ also supports unary operators for example:-

i++
++i
--j
j--
Combined Assignment operators

• Applies an arithmetic operation to a variable and assigns the


result as the new value of that variable

• Operators: += -= *= /= %=

• Example:
sum += amt; is short for sum = sum + amt;

3-34
More Examples

x += 5; means x = x + 5;
x -= 5; means x = x – 5;
x *= 5; means x = x * 5;
x /= 5; means x = x / 5;
x %= 5; means x = x % 5;
The right hand side is evaluated before the
combined assignment operation is done.
x *= a + b; means x = x * (a + b);

3-35
Precedence

Warning: This is not exhaustive, there are more operators.


Mathematical Expressions
• An expression can be a constant, a variable, or a combination of
constants and variables combined with operators

• Can create complex expressions using multiple mathematical operators

• Examples of mathematical expressions:


• 2
• height
• a + b / c
• sum = 21 + 3;

3-37
Using Mathematical Expressions
■ Can be used in assignment statements, with cout, and
in other types of statements

■ Examples: This is an
expression

area = 2 * PI * radius;
cout << "border is: " << (2*(l+w));

These are
expressions

3-38
Order of Operations
■ In an expression with > 1 operator, evaluate in this order

Do first:- (unary negation) in order, left to right

* / % in order, left to right


Do next:

Do last:+ - in order, left to right

■ In the expression 2 + 2 * 2 – 2 ,

Evaluate Evaluate Evaluate


2nd 1st 3rd
3-39
Associativity of Operators
• - (unary negation) associates right to left

• * / % + - all associate left to right

• parentheses ( ) can be used to override the order of operations


• 2+2 * 2–2 = 4
• (2 + 2) * 2 – 2 = 6
• 2 + 2 * (2 – 2) = 2
• (2 + 2) * (2 – 2) = 0

3-40
Algebraic Expressions
• Multiplication requires an operator
Area = lw is written as Area = l * w;
• There is no exponentiation operator
Area = s2 is written as Area = pow(s, 2);
(note: pow requires the cmath header file)
• Parentheses may be needed to maintain order of operations
y 2  y1
m
x 2  x1
is written as
m = (y2-y1)/(x2-x1);
3-41
Type conversion
• Implicit type coercion – when a value of one data type is
automatically changed to another data type.

int main(void) {
    int x = 100.0/3.0;
    cout << x << endl;
}

• Implicit type coercion can produce hard to debug code for novice
programmer.
Casting
• Explicit type conversion in C++ can be achieved using the
following syntax:-

int main(void) {
    cout << static_cast<int> (7.9) << endl;
    cout << static_cast<double> (7) << endl;
}

• C-like casting is also acceptable for primitives data type. Avoid


using C-like casting on complex data type / object.
E.g. double x = (double)5;
Character
• char is a data type that holds one character (letter, number,
etc.) of data.

• A char is not an integer, meaning arithmetic operations cannot


be applied on them.

int main(void) {
    char one = 'a';
    char two = '2';
    char three = ' ';
}
Casting a Character in Integer
• It is possible to cast a char into an integer, vice-versa.
• The integer is the representation of the char in number. Known as
ASCII.
• UTF8 is currently most popular character encoding method.
int main(void) {
    char one = 'a';
    char two = 'A';
    cout << static_cast<int>(one) << endl; // 97
    cout << static_cast<int>(two) << endl; // 65
}
String
• How about handling a word or a sentence? A word/sentence is an
array of characters.
• Use the string library.
• We will cover more about string library in coming lectures.
#include <iostream>
#include <string>

int main(void) {
    string word1 = "Hello World";
    cout << word1 << endl; //Hello
World
    cout << word1[0] << endl; //H
    cout << word1[1] << endl; //e
    cout << word1[12] << endl;
//runtime error
}
String Constant
• Can be stored a series of characters in consecutive memory
locations
"Hello"
• Stored with the null terminator, \0, at end
• Is comprised of characters between the " "

H e l l o \0
[0] [4]

2-47
A character or a string constant?
• A character constant is a single character, enclosed in single quotes:
'C'
• A string constant is a sequence of characters enclosed in double
quotes:
"Hello, there!"
• A single character in double quotes is a string constant, not a
character constant:
"C"

2-48
Input and Output

• 'Input' is information supplied to a computer or program.

• 'Output' is information provided by a computer or program. 


std::cout
• One of the simplest method to output for C++ is std::cout.

cout << "Hello World" << endl;

• However, bare in mind that output is not necessary only to your


monitor. It can also be others such as speaker, LED and others.

cout << "\a" << endl; //create a beep sound.


std::cin

• In general, inputs are often from keyboard. However, it can


also be from events from sensors and networks.

int main(void) {
    string name;
    cout << "What is your name?" << endl;
    cin >> name; //user enter John
    cout << "Hi " << name << endl; //Hi John
}
What about the whitespace?

int main(void) {
    string name;
    cout << "What is your name?" << endl;
    getline(cin, name); //Enter John
    cout << "Hi " << name << endl; //Hi John
}

You might also like