EEET2482/COSC2082
Software Engineering Design,
Advanced Programming Techniques
Week 1 – c++ basics
Lecturer: linh tran
RMIT Classification: Trusted
What is C++ ?
▪ A cross-platform language that can be used to create high-performance
applications, such as game development, database system software, operating
systems, etc. It is also widely used for electronic embedded systems and robotics.
▪ C++ is one of the world's most popular programming languages.
▪ C++ supports object-oriented programming, an extension of C.
▪ C/C++ powers the world. Most OS kernels (Windows, Linux, Mac, iOS, Android),
web browsers, game engines use C/C++ in their development (ref: link).
RMIT University School of Science, Engineering and Technology (SSET) 2
RMIT Classification: Trusted
Example Student Projects with C/C++
RMIT University School of Science, Engineering and Technology (SSET) 3
RMIT Classification: Trusted
First “HelloWorld” Program
include libraries (iostream is standard input/output
library in C++, provides input/ouput connected objects
#include <iostream> such as std::cout, std::cin...)
using std::cout; tells the compiler to use cout object from the standard
library std (avoid typing its full name std::cout later)
int main() { main function (first code to execute)
/* My first program in C */ block comment (use // for line comments)
cout << "meow meow! \n"; statement (cout is console output)
(<< is insertion operator)
return 0; returns exit status of the program
} 0: exit success
1 (or other values): exit failure
Note: we should NOT do “using namespace std;” since it is considered as a BAD PRACTICE (ref: 1 2)
RMIT University School of Science, Engineering and Technology (SSET) 4
RMIT Classification: Trusted
Variables, Datatypes and Literals
▪ Variables are containers for storing data values.
o Declaration Syntax:
data_type var1_name, var2_name;
data_type var_name = initial_value;
o Example: int x, y = 10;
▪ A literal is a fixed constant value in the code
o Numeric literal (aka constant) e.g: 123, 1.234
o Character literal e.g: 'a', 'B', '#', '\n', '\t'
o String literal e.g: "This is a string literal"
RMIT University School of Science, Engineering and Technology (SSET) 5
RMIT Classification: Trusted
Basic data types in a 64-bit architecture
Data type Size Typical Usage & Range
(bytes)
void 0 empty (valueless)
bool 1 logic values: true (1)/ false (0).
note: non-zero value will be typecast to true (value 1) for bool variable.
char 1 -128 to 127. Typical usage: ASCII encoding values for characters.
short 2 -32,768 to 32,767
int 4 -2,147,483,648 to 2,147,483,647
long 8 −9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
unsigned char 1 0 to 255.
unsigned short 2 0 to 65,535
unsigned int 4 0 to 4,294,967,295
unsigned long 8 0 to 18,446,744,073,709,551,615
float 4 -3.4E38 to 3.4E38 (floating point with precision up to 6 decimal places, e.g., -9.123456)
double 8 -1.7E308 to 1.7E308 (floating point with precision up to 15 decimal places)
Note: check this link for all built-in datatypes in C++
RMIT University School of Science, Engineering and Technology (SSET) 6
RMIT Classification: Trusted
Naming Conventions and Constants
▪ Naming Conventions
• Names must begin with a letter or underscore ‘_’
• Names are case sensitive
o Example: These are different variables:
int AVar = 0;
int aVar = 0;
• Names must NOT be a reserved keyword in C or C++ (e.g string, short, float).
▪ Named Constants (avoid using magic numbers)
• Define using #define (work as text replacement)
o Example: #define ARRAY_SIZE 100
• Or define using const (variable with unmodifiable value)
o Example: const int ARRAY_SIZE = 100;
7
RMIT Classification: Trusted
Operators
• Arithmetic: +, -, /, *, % (modulo), ++ (increment), -- (decrement)
• Relational: a == b, a != b, a > b, a < b, a >= b, a <= b
• Logical: !a, a && b, a || b
• Bitwise: ~a, a & b, a | b, a ^ b, a << b, a >> b
• Assignment Operators: +=, -=, /=, *=, %= ….
• Conditional Expression: (condition) ? value if true : value if false;
e.g. x = (1 > 0) ? 10 : 9; result: x = 10
• Member and Pointer: a[], *a, &a, a‐>b, a.b
• Others: sizeof (type_casting) e.g. int a = (int) 9.7; result: a = 9
Note: check this link1 link2 for all operators in C++
8
RMIT Classification: Trusted
Basic Input and Output
#include <iostream>
The standard library iostream provide two objects using std::cout;
using std::cin;
connected with input/ouput screen:
int main() {
▪ cout: console output char a;
int num;
Ouput: use insertion operator << to insert data to cout
cout << "Enter a character and an integer: ";
cin >> a >> num;
▪ cin: console input
cout << "Character: " << a << "\n";
Input: use extraction operator >> to extract data from cin cout << "Number: " << num << "\n";
return 0;
}
Note: we can use endl instead of newline character ‘\n’ in C++
RMIT University School of Science, Engineering and Technology (SSET) 9
RMIT Classification: Trusted
Conditional Statements
▪ Conditinal operator: (condition) ? value if true : value if false;
▪ if-else ▪ switch-case
if (exp1) { switch (exp) {
stmt1; case value1:
} else if (exp2) { stmt1;
break;
stmt2;
case value2:
… stmt2;
} else { break;
stmt; …
} default:
stmt;
}
Note:
• exp, value1, value2 must be integer or char values
• The break statement terminates the switch block. Without it, all
cases presented after the matched case will be also executed.
10
RMIT Classification: Trusted
Loop Statements
while (cond) { do { for (init; cond; update){
stmt; stmt; stmt;
} } while (cond); }
• while is a pre-test loop • do-while is a post-test loop • init: initialize a start value
• stmt will run whenever • stmt runs first then the • cond: condition for executing
cond is non-zero cond is checked • update: update the value
init, exp, update are optional
Note: within a loop, we can use break and continue statements
• break : terminate the loop
• continue : skip the remaining code of the current iteration (and move to the next iteration)
11
RMIT Classification: Trusted
Example - Loop
#include <iostream> #include <iostream> #include <iostream>
using std::cout; using std::cout; using std::cout;
int main() { int main() { int main() {
int i = 1; int i = 1; for (int i = 1; i < 10; i++) {
while (i <= 10){ do { if (i == 5)
cout << i << ' '; cout << i << ' '; continue;
i++; i++; else if (i == 9)
} } while (i <= 10); break;
return 0; return 0; cout << i << ' ';
} } }
return 0;
}
Result: 1 2 3 4 5 6 7 8 9 10 Result: 1 2 3 4 5 6 7 8 9 10
Result: 1 2 3 4 6 7 8
RMIT University School of Science, Engineering and Technology (SSET) 12
RMIT Classification: Trusted
Arrays
▪ Arrays hold items of the same data type
▪ One-dimensional array
• Syntax: data_type array_name[array_size];
• Elements are accessed with indexes 0, 1, … size-1.
int marks[3]; // first element marks[0], last is marks[2]
float avg = (marks[0] + marks[1] + marks[2]) / 3.0;
• Initialization can be done in a number of ways:
int data [25] = {}; // all set to 0;
int data [25] = {1,2,3,4,5}; // everything else will be set to 0
▪ Multi-dimensional array
• int matrix[5][2] = { {1, 1}, {2, 8}, {3, 27}, {4, 64}, {5,125} };
13
RMIT Classification: Trusted
C-type Strings
#include <iostream>
#include <cstring>
▪ A C-type string is one-dimensional array of using std::cout;
characters terminated by a null character ‘\0’ int main() {
char s1[100] = {'H', 'e', 'l', 'l', 'o', '\0'}; // strcmp() example code:
char str1[100] = "ABC";
char s2[] = "Hello"; // '\0' is auto inserted char str2[100] = "DEF";
cout << "strlen of str1 = " << strlen(str1) << endl;
▪ Character handling functions from <cctype> library: cout << "strcmp = " << strcmp(str1, str2) << endl;
isdigit() isspace() isalpha() isupper() islower() tolower()
strcat(str1, str2);
toupper(), etc… cout << "str1 after strcat = " << str1 << endl;
strcpy(str1, str2);
▪ String handling functions from <cstring> library: cout << "str1 after strcpy = " << str1 << endl;
• strlen() // length
return 0;
• strcpy(), strncpy() // string copy }
• strcat(), strncat()// concatenate (append)
• strcmp(), strncat()// compare Value Compare string1 with string2
• ………………… the first character that does not match
<0 has a lower value in string1 than in
Important standard libraries to use: string2
1. https://www.asciitable.com/ (ASCII code of characters) 0 string1 is identical to string2
2. https://cplusplus.com/reference/cctype/ (character handling functions) the first character that does not match
3. http://www.cplusplus.com/reference/cstring (string handling functions) >0
has a greater value in ptr1 than in ptr2
14 14