0% found this document useful (0 votes)
8 views14 pages

C++ Basics: Variables, Operators, Loops

The document provides an overview of C++ programming, detailing its significance as a cross-platform language used in various high-performance applications. It covers fundamental concepts such as variables, data types, operators, conditional statements, loops, arrays, and C-type strings, along with examples and syntax. The content is structured as a lecture series from RMIT University, aimed at teaching advanced programming techniques.

Uploaded by

Khoa Hua anh
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views14 pages

C++ Basics: Variables, Operators, Loops

The document provides an overview of C++ programming, detailing its significance as a cross-platform language used in various high-performance applications. It covers fundamental concepts such as variables, data types, operators, conditional statements, loops, arrays, and C-type strings, along with examples and syntax. The content is structured as a lecture series from RMIT University, aimed at teaching advanced programming techniques.

Uploaded by

Khoa Hua anh
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Software

EEET2482 Engineering Design Design


Software Engineering
Advanced
COSC2082Programming TechniquesTechniques
Advanced Programming

M o d u l e 1 - C++ b a s i c s
L e c t u r e r : Dr V i n h T r u o n g
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.

RMIT University School of Science, Engineering and Technology (SSET) 2


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 (instead of typing its full name std::cout)

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

RMIT University School of Science, Engineering and Technology (SSET) 3


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) 4


RMIT Classification: Trusted

Basic data types in a 64-bit architecture


Data type Size (bytes) Range
void 0 empty (valueless)
bool 1 true (1)/ false (0).
note: non-zero value will be typecased to true (value 1) for bool variable.
char 1 -128 to 127
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 (precision up to 6 decimal places)
double 8 -1.7E308 to 1.7E308 (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) 5


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 A_var = 0;
int a_var = 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;

RMIT University School of Science, Engineering and Technology (SSET) 6


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++

RMIT University School of Science, Engineering and Technology (SSET) 7


RMIT Classification: Trusted

Basic Input and Output


#include <iostream>
The standard library iostream provide two objects using std::cout;
connected with input/ouput screen: using std::cin;

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) 8


RMIT Classification: Trusted

Conditional Statements
▪ Conditional 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.

RMIT University School of Science, Engineering and Technology (SSET) 9


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, cond, 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)

RMIT University School of Science, Engineering and Technology (SSET) 10


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) 11


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} };

RMIT University School of Science, Engineering and Technology (SSET) 12


RMIT Classification: Trusted

C-type Strings
#include <iostream>
▪ A C-type string is one-dimensional array of #include <cstring>
using std::cout;
characters terminated by a null character ‘\0’ using std::endl;

char s1[100] = {'H', 'e', 'l', 'l', 'o', '\0'}; int main() {
// strcmp() example code:
char s2[] = "Hello"; // '\0' is auto inserted char str1[100] = "ABC";
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() toupper() strcat(str1, str2);
cout << "str1 after strcat = " << str1 << endl;

▪ String library functions: strcpy(str1, str2);


cout << "str1 after strcpy = " << str1 << endl;
• strlen() // length
• strcpy(), strncpy() // string copy return 0;
• strcat(), strncat()// concatenate (append) }

• strcmp(), strncmp()// 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. [Link] (ASCII code of characters) 0 string1 is identical to string2
2. [Link] (character handling functions)
the first character that does not match
3. [Link] (string handling functions) >0
has a greater value in ptr1 than in ptr2
RMIT University School of Science, Engineering
14 and Technology (SSET) 13
RMIT Classification: Trusted

Summary
• Functions
• Variables
• Operators
• Conditional statement
• Loop
• Array
• String

You might also like