From the above table, it is easy to see that comma operator has the lowest precedence, and postfix operators such as the function call operator, the subscript operator, the structure pointer operator, the post-increment operator, and the post-decrement operator have the highest precedence. You may come to check this table for precedence when you are using them in your expressions.
Let's work on a lab to better understand operator precedence in C++.
Hands-on:
Please enter the following program in the online C compiler, run and observe the results.
#include <iostream>
using namespace std;
main() {
int a = 20;
int b = 10;
int c = 15;
int d = 5;
int e;
e = (a + b) * c / d; // 30 * 15 / 5
cout << "Value of (a + b) * c / d is : " << e << endl;
e = ((a + b) * c) / d; // (30 * 15 ) / 5
cout << "Value of ((a + b) * c) / d is :" << e << endl;
e = (a + b) * (c / d); // 30 * (15/5)
cout << "Value of (a + b) * (c / d) is : " << e << endl;
e = a + (b * c) / d; // 20 + 150/5
cout << "Value of a + (b * c) / d is : " << e << endl;
return 0;
}
If there is nothing going wrong, the result should look like:
Value of (a + b) * c / d is : 90
Value of ((a + b) * c) / d is :90
Value of (a + b) * (c / d) is : 90
Value of a + (b * c) / d is : 50
You may construct more formula with various operators and observe their precedence in execution.
In C++ programming language, an expression is anything that gives a value, such as an operand, or a combination of operand(s) and operator(s) that can be evaluated to a value. The operand can be a literal value, variable, constant, function, or another expression. The operator can be any of the operators as discussed above.
Expressions may be categorized into a few types such as primary expressions, arithmetic expressions, logical expressions, conditional expressions, relational expressions, pointer expressions, and bitwise expressions.
A primary expression is a building block of more complex expressions. It may be a literal value, named constant, variable, function, generic selection, keywords, or an expression in parentheses.
A postfix expression is a primary expression followed by an operator — for example, the array subscript or postfix increment operator. For example, myArray[5] is an array element expression, a++ is an increment expression. similarly, there are prefix expressions that have an operator before a primary expression such as ++a. These are expressions with unary operators.
An arithmetic expression consists of arithmetic operators (+, -, *, /, %) and computes values of int, float, or double type.
A relational expression consists of comparison operators (==, >, <, >=, <=) and computes the answer in the bool type, i.e., true (1) or false (0).
A logical expression consists of logical operators (&&, ||, !) and combines relational expressions to compute answers in the bool type.
A conditional expression consists of conditional statements (?:) that return true if the condition is met and false otherwise.
Note: Generally, any expression that result in true or false is called a conditional expression.
A pointer expression may consist of an address operator (&) and returns address values.
A bitwise expression consists of bitwise operators (>>, <<, ~, &, |, ^) and performs operations at the bit level.
Let's work on a lab to better understand the types of expressions.
Hands-on:
Please enter the program below in the online C++ compiler (IDE). Run and observe the results.
#include <iostream>
using namespace std;
int main(){
//Arithmetic expression
int a = (6 * 2) + 7 - 9;
cout << "The arithmetic expression returns: " << a << endl;
//Relational Expression
int b = 10;
cout << "The relational expression returns: " << (b % 2 == 0) << endl;
//Logical Expression
int c = (7 > 9) && ( 5 <= 9);
cout << "The logical expression returns: " << c << endl;
//Conditional Expression
int d = (34 > 7) ? 1 : 0;
cout << "The conditional expression returns: " << d << endl;
//Pointer Expression
int e = 20;
int *addr = &e;
cout << "The pointer expression returns:" << addr << endl;
//Bitwise Expression
int f = 10;
int shift = 10 >> 1;
cout << "The bitwise expression returns: " << shift << endl;
return 0;
}
If nothing goes wrong, the output should look like:
The arithmetic expression returns: 10
The relational expression returns: 1
The logical expression returns: 0
The conditional expression returns: 1
The pointer expression returns:0x7ffd1b50210c
The bitwise expression returns: 5
You may construct your own expressions and test in a program like this one.
A statement in a program is like a sentence in English. It is the smallest complete executable unit. A statement consists of expressions and /or keywords and ends with a semicolon (;).
There are five basic types of statements plus their combinations to from compound statements in C++ programming language:
i. Declaration statements
ii. Expression statements
iii. Jump statements
iv. Selection statements
v. Iteration statements
vi. Compound statements
Some references may have labeled statements, which are statements with labels.
a. Declaration statements
In C++ programming language, a declaration statement is a statement formed from a primary expression of declaration that introduces one or more identifiers into the program and specifies their meaning and properties.
In C++ programming language, a declaration statement is used to declare a variable (include named constant) or function. The syntax of a declaration statement looks like:
type variable_name; //declare a variable
or
type variable_name = initial_value; //declare a variable with initial value
or
type function_name(parameter_list); //declare a function prototype
In the above declaration statements, type is a data type discussed earlier.
For example,
int my_var = 0; //declare variable my_var with initial value 0
int my_fun(); //declare function my_fun();
In C++ programming language, an expression statement is a statement that consists of an expression followed by a semicolon. The execution of such a statement will get an evaluated result of the expression. Most C++ programs' statements are expression statements.
Here are some examples of expression statements in C++:
a = 5; // assignment statement formed from assignment expression
printf("Hello World!"); // function call statement from a function call primary expression
x++; // arithmetic (increment) statement from arithmetic expression
In C++ programming language, a jump statement is a statement that causes the program to transfer control to another part of the program.
The four types of jump statements in C++ are:
goto statement
It is generally considered bad practice to use goto statements because they can make code difficult to read and understand. You may simply skip this section for goto statement. The use of goto can be simply avoided by using break and continue statements.
The goto statement in C++ is a jump statement that is used to jump from one part of the code to any other part of the code in C. It helps in altering the normal flow of the program according to our needs. The goto statement can be used to jump from anywhere to a specified place in a function. When the C++ compiler reaches the goto statement, it will jump unconditionally (both forward and backward) to the location specified in it (we called it as a label). However, it is highly discouraged as the goto statement makes the program logic very complex and makes tracing the flow of the program very difficult. The use of goto can be simply avoided by using break and continue statements.
The goto statement is formed from goto primary expression. For example,
#include <iostream>
using namespace std;
int main() {
int i = 0;
loop: //label
cout << i << endl;
i++;
if (i < 10) {
goto loop; //goto statement
}
return 0;
}
In this example, the goto statement transfers control back to the beginning of the statement labeled “loop”.
break statement
The break statement is formed from break primary expression and used to exit a loop body or switch body. For example (please test it in the online C++ compiler (IDE),
#include <iostream>
using namespace std;
int main() {
int i;
for (i = 0; i < 10; i++) {
if (i == 5) {
break; //break statement
}
cout << i <<endl;
}
return 0;
}
In this example, the break statement is used to exit the loop when the value of “i” is equal to 5.
The example below is usingn the break statements to exit a switch body:
switch (expression) {
case constant1:
// code to be executed if expression is equal to constant1;
break;
case constant2:
// code to be executed if expression is equal to constant2;
break;
default:
// code to be executed if expression doesn't match any of the above cases;
}
In this example, each case of the switch statement has a break statement that is used to exit the switch block once the code for the case has been executed.
continue statement
The continue statement is used to skip the current iteration of a loop and move on to the next iteration. It is formed from continue primary expression. For example (please test in the online C++ compiler (IDE):
#include <iostream>
using namespace std;
int main() {
int i;
for (i = 0; i < 10; i++) {
if (i == 5) {
continue; //continue statement
}
cout << i << endl;
}
return 0; //return statement
}
In this example, a continue statement is to skip the loop when i is 5 and start the next cycle of the loop.
Note: please compare the output from this program and the one for break statement. You should see the difference between continue and break: continue shall skip the current cycle and work on the following cycles in the loop, while break shall stop working in the loop.
return statement
the return statement is used to return a value from a function. The return statement is formed from a return primary expression. Here is an example of a function that returns an integer value:
int add(int x, int y) {
int sum = x + y;
return sum; //return statement
}
To summarize, the goto statement is considered a harmful construct and a bad programming practice. The other three jump statements are used in loops and functions to control the flow of execution. We will see more of their usage and examples when we discuss loops and functions.
d. Selection or conditional statements
In C++ programming language, selection statements are based on relational and / or logical expressions and used to control the flow of execution based on the value of an expression.
The two types of selection statements in C++ are below:
i. if statement
An if statement is a selection statement that allows for conditional execution of code based on the value of an expression. For example (please test in the online C++ compiler (IDE)),
#include <iostream>
using namespace std;
int main() {
int x = 5;
//the statement below is an example of if-statement
if (x == 5) {
cout << "x is equal to 5" << endl;
}
return 0;
}
As shown in the example, if statement consists of three parts:
1) the if keyword.
2) the conditional expression enclosed in a pair of parentheses.
3) the if statement body enclosed in a pair of curly brackets. When the if statement body consists of only a single statement, the curly brackets can be omitted such as
if(x==5) cout << "x is equal to 5" << endl;
Often, the keywords if and else combine to form multiple branches or nested if statements. For example,
int x = 10;
if (x > 5) {
cout << "x is greater than 5";
} else {
cout << "x is less than or equal to 5";
}
In this example, if x is greater than 5, then the program will output “x is greater than 5”. Otherwise, it will output “x is less than or equal to 5”.
ii. switch statement
In C programming language, switch statements are used to control the flow of execution based on the value of an expression. For example (please test in the online C++ compiler (IDE)),
#include <iostream>
using namespace std;
int main() {
int x = 2;
//Example of a switch statement
switch (x) {
case 1:
cout << "x is equal to 1" << endl;
break;
case 2:
cout << "x is equal to 2" << endl;
break;
default:
cout << "x is not equal to 1 or 2" << endl;
}
return 0;
}
As shown in the example, the switch statement consists of three parts:
1) the switch keyword.
2) the conditional expression enclosed in a pair of parentheses.
3) the switch statement body enclosed in a pair of curly brackets. The switch statement body consists of one or more case branches and end with a default branch. A case branch consists of a case header and a case body. The case header is in the form of
case value:
it consists of keyword case and a possible value of the conditional expression in the parentheses. In this example, 1 and 2 are the possible values of x. The case header ends with colon (:).
The case body consists of a few statements, which can be any types of statements. In this example, there is only a cout statement in a case. The case body ends with a break statement, which stop continuing to execute the other branches below.
The default branch is the last branch in the switch body, which shall be executed once no case branch meets the condition.
The main difference between if statements and switch statements is that if statements are used when there are only two cases of a condition to check, whereas switch statements are used when there are more than two cases of a condition to check, and the condition gives a value for the cases.
e. Iteration or looping statements
Iteration statements in C++ are used to execute a block of code repeatedly for a specified number of times or until a condition is met. These statements also alter the control flow of the program and thus can also be classified as control statements in C++ Programming Language. There are three types of looping statements in C++: For Loop, While Loop and Do-while loop. A loop consists of three parts: conditional value initialization, test expression of condition, and increment/decrement or update the conditional value. For different types of loops, the conditional expressions might be at various places of the loop.
i. For loop
The For Loop is one of the three types of looping statements in C++. It is the most commonly used loop because it has all the three parts of the loop in the one line. The syntax of a for loop look like:
for(initialization; test expression; update expression) {
//body of loop
}
A for loop consists of three parts:
1) the keyword for.
2) the condition enclosed in a pair of parentheses.
3) the for loop body enclosed in a pair of curly brackets.
The condition consists of three parts: the initialization, the test expression, and the update expression.
The initialization part is executed only once at the beginning of the loop. It is the entry condition to enter the loop.
The test expression is evaluated at the beginning of each iteration. If it evaluates to true, then the body of the loop is executed. otherwise, the program execution moves on to the next statement following this for loop.
After each iteration, the update expression is executed before evaluating the test expression again.
The for-loop body consists of a number of other statements. When there is zero or one statement in the for loop, the curly brackets can be omitted.
Here's an example of a for loop (please test in the online C++ compiler (IDE)):
#include <iostream>
using namespace std;
int main() {
int i;
//for loop
for (i = 1; i <= 5; i++) {
cout << i << endl;
}
return 0;
}
This program initializes the variable i to 1, then tests whether i is less than or equal to 5. If it is, it executes the body of the loop (which prints the value of i), then increments i by 1. It repeats this process until i is no longer less than or equal to 5.
ii. While loop
The while loop is another type of looping statement in C++. It executes the statement(s) in the loop body as long as a given condition is true. The syntax of a while loop in C looks like:
while (condition) {
statement(s);
}
A while loop consists of three parts:
1) the keyword while.
2) the condition enclosed in a pair of parentheses.
3) the while loop body enclosed in a pair of curly brackets.
The condition is of expression that produces a Boolean result, true or false. In C++, false is 0, true is any nonzero value.
The while loop body, statement(s), may be a single statement or a block of statements. Below is an example of while loop (please test in the online C++ compiler (IDE)):
#include <iostream>
int main() {
int i = 1;
//while loop statement
while (i <= 5) {
cout << i << endl;
++i;
}
return 0;
}
This program initializes the variable i to 1, then tests whether i is less than or equal to 5. If it is, it executes the body of the loop (which prints the value of i), then increments i by 1. It repeats this process until i is no longer less than or equal to 5.
iii. Do-while loop
The do-while loop is one of the three loop statements in C++. It is popularly used to traverse arrays, vectors, and some other data structures. The do-while loop is similar to the while loop but the body of do-while loop is executed at least once and then, the test expression is evaluated. The syntax of the do...while loop looks like:
do {
statement(s);
} while (condition);
Do-while loop consists of three parts:
1) the keyword do.
2) the loop body enclosed in the curly brackets.
3) the while condition with the keyword while and condition enclosed in a pair of parentheses.
Please note that the conditional expression is at the end of the loop, so the statement(s) in the loop executes once before the condition is tested.
Here's an example of a do-while loop that prompts the user to enter a number (please test in the online C++ compiler (IDE)):
#include <iostream>
using namespace std;
int main() {
double number, sum = 0.0;
do {// The loop body is executed first
cout << "Enter a number: ";
cin >> number;
sum += number;
} while(number != 0.0); // The test expression is evaluated
cout << "Sum = " << sum << endl;
return 0;
}
This program uses a do-while loop to prompt the user to enter a number. The loop works as long as the input number is not 0. The do-while loop executes at least once i.e. the first iteration runs without checking the condition. The condition is checked only after the first iteration has been executed.
A compound statement is a group of statements that are enclosed in curly braces `{}`. It is used where multiple statements are required. The compound statement is treated as a single statement by the compiler. The syntax of a compound statement is:
{
statement1;
statement2;
.
.
.
statementN;
}
That is, a group of statements enclosed in a pair of curly brackets. Here, statement1, statement2, ..., statementN are any valid C++ statements as discussed above. The compound statements can be nested in another compound statements.
The compound statements are usually used as a structure body, function body, loop body, selection statement body, and so on.
A block in C++ is a set of statements written within a pair of curly braces ({}). A block may contain other blocks within itself, that is, nested blocks. A variable declared inside a block has a block scope and is accessible inside the block and its inner blocks.
A compound statement is actually a block.
An array in C++ is a collection of similar data items stored in contiguous memory locations. The data items in an array can be of primitive data types such as int, char, float, etc., and also derived and user-defined data types such as pointers, structures, and so on. The elements of an array are accessed by their index number. The index number starts from 0 and goes up to (size of the array - 1). The size of an array must be specified at the time of declaration.
Arrays are used in C++ for a variety of reasons. They are used to store a collection of similar data items. They are also used to store the collection of derived and user-defined data types such as pointers, structures, etc. Arrays are also used to pass a large number of arguments to functions. They are also used to implement other data structures such as stacks, queues, and trees.
The syntax of declaring an array in C++ is:
Type arrayName[arraySize];
Here, the Type is the type of data that the array will hold. arrayName is the name of the array, and arraySize is the number of elements that the array can hold. For example,
int numbers[5];
This declares an array named numbers that can hold 5 integers.
Once an array is declared, its elements are accessed by their index numbers. The index number starts from 0 and goes up to (size of the array - 1). For example,
int numbers[7] = {1, 2, 3, 4, 5, 6, 7};// An array of 7 int items is declared and initialized
cout << numbers[2] << endl;
This prints the third element of the array numbers, which is `3`.
We can easily loop through an array with a for loop. For example,
int numbers[7] = {1, 2, 3, 4, 5, 6, 7};
for (int i = 0; i < 5; i++) {
cout << numbers[i] << endl;
}
This prints all the elements of the array numbers.
Arrays are popularly used in processing a group of same type of data. For example, we want to sum up a group of integers, we can use array to easily implement it.
#include <iostream>
using namespace std;
int main() {
int numbers[7] = {1, 2, 3, 4, 5, 6, 7};
int sum = 0;
for(int i = 0; i < 5; i++) {
sum += numbers[i];
}
cout << "The sum of the array is " << sum;
}
This program creates an array of integers called numbers with five elements and initializes them with values from 1 to 7. It then uses a for loop to iterate over the array and add up all the values. Finally, it prints out the sum of the array.
In C++ programming, we can create an array of arrays. These arrays are known as multidimensional arrays. For example,
float x[3][4];
Here, x is a two-dimensional (2d) array. The array can hold 12 elements. You can think the array as a table with 3 rows and each row has 4 columns.
To access an element from the multidimensional array, add the index for the element you want. For example, x[1][2] will access the element at row 1 and column 2 of the array. You can also use a for loop or for each loop to access multiple elements in a multidimensional array.
We can use a nested for loops (one for loop inside another for loop) to access elements of a multidimensional array in C++. Here is an example of how to use a for loop to initialize each member of a 2D array one by one:
int x[3][4];
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 4; j++) {
x [i] [j] = i + j;
}
}
This method is useful when the value of each element has some sequential relation.
Strings are used in C++ programming language to represent text such as words and sentences. They are also used to manipulate text data. For example, you can use strings to store user input or read data from a file.
In C++ programming language, a string variable contains a collection of characters surrounded by double quotes. To create and use strings, you must include the header file <string>, and declare a string like:
#include <string> //include the string library header file
string name = "John Doe"; //Create a string variable with initial value
C++ allows you to concatenate strings with the plus '+' operator. For example (please test it in the online C++ compiler (IDE)),
#include <iostream>
#include <string>
using namespace std;
int main() {
string firstName = "John";
string lastName = "Doe";
string fullName = firstName + " " + lastName;
cout << fullName << endl;
return 0;
}
This program declares two string variables named firstName and lastName, concatenates them using the + operator, and stores the result in a third string variable named fullName. It then prints the full name to the console.
The + operator is overloaded to automatically identify numbers and strings. If you add two numbers, the result will be a number. If you add two strings, the result will be a string concatenation as the above example shows. If you add a number to a string, however, an error occurs. For example (please test it in the online C++ compiler (IDE),
#include <iostream>
#include <string>
using namespace std;
int main() {
string x = "10";
int y = 20;
string z = x + y;
cout << z << endl;
return 0;
}
This program declares a string type variable x and an int type variable y, then tries to "add" up them and assign the result to variable z. Since x is string, though it contains numeric chars, it cannot be added to int y. If you try to compile (or Run) it, you shall receive an error like "no match for operator +".
C++ allows you to easily obtain the length of a string by using the length() function, or size(), which is an alias of length(). For example (please test it in the online C++ compiler (IDE)),
#include <iostream>
#include <string>
using namespace std;
int main() {
string txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
cout << "The length of the txt string is: " << txt.length();
return 0;
}
The result should be displaying "The length of the txt string is: 26". You may use txt.size() to replace txt.length().
Since a string is essentially an array of characters, C++ allows you to access the characters in a string by referring to its index number inside square brackets [ ]. For example,
string myString = "Hello";
cout << myString[0]; // Outputs H
Note: The subscription of an array starts with 0.
You can update a character in a string by assigning a char to a position. For example,
string myString = "Hello";
myString[0] = 'J';
cout << myString; // Outputs Jello instead of Hello
C++ allows you to easily input a string to a string variable by using the extraction operator >> on cin. For example:
string name;
cout << "Type your first name: ";
cin >> name; // get user input from the keyboard
cout << "Your name is: " << name;
Note: cin considers a space (whitespace, tabs, etc) as a terminating character, which means that it can only store a single word (even if you type many words). Therefore, the above code accepts only one word and assigns it to string variable name. If you enter two words separated by a space, only the first word will be accepted and assigned to variable name.
Tip: because of the issue caused from cin, C++ provides function getline() to read a line of text. It takes cin as the first parameter, and the string variable as the second. For example (please test it in the online C++ compiler (IDE)),
#include <iostream>
#include <string>
using namespace std;
int main() {
string fullName;
cout << "Type your full name: ";
getline (cin, fullName);
cout << "Your name is: " << fullName;
return 0;
}
Tip: Even though getline() allows us to accept a whole line of a string to be stored, it does not identify each of the words in the input string. To recognize each word in the input string, we may use C++ istringstream class, which is used to read input from a string as if it were a stream, and is often used to extract values from a string. istringstream is defined in <sstream> so that we should include this header file to use istringstream. For example (please test it in the online C++ compiler (IDE)),
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main() {
string fullName;
cout << "Type your full name: ";
getline(cin, fullName);
cout << "Your name is: " << fullName << endl;
istringstream iss(fullName);
string word;
cout << "To display each single name: " << endl;
while(iss >> word){
cout << word << endl;
}
return 0;
}
In execution of this program, if we enter multiple words in a string, each of the words will be accessed and displayed. A sample execution looks like:
Type your full name: John Michael Doe
Your name is: John Michael Doe
To display each single name:
John
Michael
Doe
A few characters have special meaning and may cause issues if they are used as normal characters. For example, double quote (") cannot be directly enclosed in a pair of double quotes as a normal character in a string. To reach the goal of using double quote as a normal character, we must use the backslash (\), which is called the escape character, to turns it into a normal character. This kind of characters include single quote ('), double quote ("), and backslash (\). For examples,
string txt = "It is the so-called \"Baozi\" in the country.";
string txt = "It\'s alright.";
string txt = "The character \\ is called backslash.";
A few other characters, when used with the escape character, will change their original meaning such as slash n (\n) is newline, slash r (\r) is carriage return, and slash t (\t) works as a tab. To summarize, let's use them in an example (please test it in the online C++ compiler (IDE)):
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main() {
cout << "It is the so-called \"Baozi\" in the country." << endl;
cout << "It\'s alright." << endl;
cout << "The character \\ is called backslash." << endl;
cout << "This line is ended by a new line character \n" << endl;
cout << "Carriage return is \r" << endl;
cout << "Slash t add a tab \t in the string." <<endl;
return 0;
}
The output should looks like
It is the so-called "Baozi" in the country.
It's alright.
The character \ is called backslash.
This line is ended by a new line character
Carriage return is
Slash t add a tab in the string.
Please observe the output and compare against the strings in the program code, and be sure to understand the meaning of these special characters and the use of the escape character (\).
The advantages of math processing in C++ include the ability to perform complex mathematical calculations and operations quickly and accurately. This is especially useful in scientific and engineering applications where precise calculations are required.
Besides arithmetic operators such as +, -, *, /, %, ++, --, etc. to perform basic math operations, C++ provides a lot of functions in a few library header files.
The <cstdlib> header file in C++ provides a set of general-purpose functions. It also declares several mathematical functions such as abs() to find the absolute value of a number.
The <cmath> header file in C++ declares a set of functions to compute common mathematical operations and transformations such as trigonometric functions, exponential and logarithmic functions, rounding and remainder functions, power functions, error and gamma functions, minimum, maximum and difference functions and other functions. The header file also declares a set of macros/functions such as fpclassify to classify floating-point value.
The table below shows some math functions defined in <cstdlib> and <cmath>. More details can be found at Common mathematical functions - cppreference.com.