C++: Complete Developers Guide: Part — 3

Syed Khizaruddin
13 min readMar 6, 2022

C++ Programming language

This blog is a continuation of part 1 and part 2, so if you haven’t read pls go through then you can continue reading this.

You can check part 1 and part 2 from my profile , here

C++: Complete Developers Guide, khizaruddins, khizaruddins.medium.com
Photo by Alejandro Luengo on Unsplash

Arrays:

Arrays are data types which are used to store multiple values, there is an index through which we can access array elements, index is just the position of an element inside an array, indices plural form of index, index starts from 0 and till the length of array -1.

C++: Complete Developers Guide Part 3, Arrays, khizaruddins, khizaruddins.medium.com

In above image each index can hold a value, it can hold integer float string char double data type or any,

How to initialise and declare an array?

element_type name_of_array [number of items];

int days_in_week [7]; // eg. 1const int days_in_year [356]; // eg. 2int test_scores [5] {1,2,3,4,5}; // eg. 3const double high_score [10] {20,40}; // eg. 4int dynamic_array [] {1,93,4,53,23}; // eg. 5

Here, in e.g. 1, the days of week will have 7 items in array, in e.g. 2, the items will be 365 days, here you can see we have declared it as a constant variable, in e.g. 3, we declared 5 items of integer data type, in e.g. 4, we have declared 10 items but only 2 are declared so rest 3rd 4th 5th and so on values will be initialised to zero, in e.g. 5, the array items are not declared hence it allocates items dynamically.

In case of dynamic array, we can initialise values, depending on that, compiler notices the array has let say 5 items, so if we access 6th element then the program will crash.

C++: Complete Developers Guide Part 3, Access arrays, khizaruddins, khizaruddins.medium.com
Photo by Katerina Pavlyuchkova on Unsplash

Accessing array elements:

An array has its first value starting form index 0 and so on.., to access the first element or item of an array we use name of that variable holding array elements followed by square bracket passing index of the element to be found.

name_of_array[index];

For eg,

const string odd_numbers [5] {1, 3, 5, 7, 9};cout << odd_number[2] << endl; 

Output: 5

Explanation: As, 0th value is 1, 1st value is 3, 2nd value is 5, hence the result.

If we try to print array name only without square brackets it will give memory location of that variable.

Multi-dimensional Array:

As far as we have discussed arrays above all of them are one dimensional arrays. Two dimensional Arrays are those having array inside as an array element, Three dimensional arrays are those having array with depth as 3, i.e array within array within array.

element_type array_name [dimension1_size][dimension2_size];

Let’s see a 2 dimensional array declaration:

const int rows {3};
const int cols {4};
int movie_rating[rows][cols];
C++: Complete Developers Guide Part 3, Multi dimensional Arrays, khizaruddins, khizaruddins.medium.com

Accessing a multi-dimensional array is pretty easy, the basic formula is as

name_of_array[row_index][column_index];

So, to access first row value 4, we have,

cout << movie_rating[0][1]; // this will print 4 from first row

Below image, we can see how value 5 is read, we can also change the value of specific index of a two dimensional array,

C++: Complete Developers Guide Part 3, Multi Dimensional Array, accessing array, khizaruddins, khizaruddins.medium.com

Vectors:

Arrays are fixed in size, there are many real use cases where we need dynamic arrays, for such cases we need Vectors, Vectors are dynamic arrays, they are containers in C++ Standard Template Library which can grow or shrink in size at execution time, they provide similar syntax and semantics as that of an array, they are efficient than arrays, they have same indexing like arrays, example as below for declaration of vector.

#include <vector>
using namespace std;
int main () { vector <int> test_scores; vector <char> vowels; return 0;}

Note- Vector is a part of Standard Template Library, so it is important to declare namespace std, or to use scope resolution operator to get it from Standard template library,

We can also initialise vectors with a number of items like

vector <int> scores (5);

Note that we have passed 5 in parenthesis (), that means it will take 5 elements, not to be confused with initialization, as we have not initialised it, their values are automatically set to 0. We can initialise vectors like below.

vector <int> scores { 20, 60, 70, 90, 45 };
vector <double> temperatures (365, 80.3);

In second vector temperature we have 365 and 80.3 inside parenthesis the first value i.e 365 is item count, which vector temperature will hold, the second value i.e. 80.3 is the default value of all 365 elements that means all 365 items will be initialised to the value 80.3 .

Accessing vector items, are as same as arrays, there is another method vector_name.at(index) which gives the value at index position, we can use it to assign different value at particular index.

scores.at(3) = 78;

To add a new element (vector item) inside a vector, we use, vector_name.push_back(element) to push element at end of vector, which automatically allocates size of vector,

Vector does bound checking, so accessing index position which was not declared or initialised will throw ‘out of bound’ error, Array never does bound checking. For eg.

vector <int> scores {100,44}; cout << scores.at(3);

This will give out of bound error, vector has ‘.size’ function which is used to print the size of a vector, cout << scores.size();

Multi Dimensional Vector: Same as array,

// for eg.
vector <vector<int>> scores { {1,2,3,4}, {4,5,3,2} };

Accessing a value is also the same as an array,
For eg.

cout << scores[0][1]; // this will print out 2

This is called array syntax for accessing values from vector

Vector syntax,

cout << scores.at(0).at(1); // this will print out 2

If we push a vector say ‘A’ inside a vector say B, we are pushing the copy of that vector i.e. A, inside another vector B, so, if vector A is changed at a later point of time the inserted vector in B is not changed, as it was just the copy of vector A.

Expressions, Statement and Operators

Expressions are building blocks of statements and statements are building blocks of programming, we have already seen I/O statements, variable declaration statements, return statements, assignment statements.

Expressions are sequence of operands and operators that compute a value,

34 // literalsscore_number = 32 // variable1.5 + 1.8 // add2 * 5 // multiplya < b // comparea = b // assignment

These are all expressions, and we have many more.

C++: Complete Developers Guide Part 3, Statements, khizaruddins, khizaruddins.medium.com
Photo by Ian Schneider on Unsplash

Statements are complete lines of code which perform some action, usually terminated with semi colon (;) it contains expressions, C++ has many types of statements, expression, null, declaration, compound, selection, iteration, jump, try blocks and others.

Some of the example of statements are given below:

int x; // declaration statementscore_point = 90;  // assignment statement1.5 + 1.8 // expressionx = 2 * 5; // assignment statement if (a < b) cout << "a greater than b" << endl; // if statement; // null statement

Operators

C++ has unary operator binary and ternary operator,

Unary operator operates on a single operand, eg unary minus operator that negates the value of the operand.

A binary operator operates on two operands, eg. a multiplication operator that multiplies two operands.

Ternary operator operates on three operands, eg. comparison operator which compares three operands.

There are several operators which are grouped as follows:

  1. Assignment operator : Assigns value to operands. (=)
  2. Arithmetic operator: Does arithmetic operations on operands. for eg (+,- *, /)
  3. Increment / Decrement operator: Increases or decreases value of operands.
  4. Relational operator (comparison): Compares two values.
  5. Logical operator: tests for logical or boolean conditions. eg ‘and’ or ‘or’ operator
  6. Member access operator: as we have seen to access array in specific index for eg. scores[2]
C++: Complete Developers Guide Part 3, Arithmetic operators, khizaruddins, khizaruddins.medium.com
Photo by Dan-Cristian Pădureț on Unsplash

Arithmetic operator:

These operators perform arithmetic operations, Normally it includes addition (+), subtraction (-), multiplication(*), division (/) and modulo (%).

Addition, subtraction, multiplication and division are done on integers floats and double data types, when two values say int and float are added and stored in an integer variable the decimal part gets stripped off, as the variable holding the value only holds the integer part.

For eg,

5/10 = 0 // in case of integer data type.

But, 5.0 / 10.0 = 0.5 // in case of float and double data type.

Modulo operator or remainder operator: If two numbers are divided we get the quotient and not the remainder, so to get the remainder we use modulo operator, so, if 10/3 gives 3, then, 10%3 will give 1.

we can use multiple operators on multiple variables like,

SI = (P*n*R)/100;

Where, SI is simple interest p is principle amount n is no of years and R is rate of interest, in this case we follow PEMDAS rule i.e. Parenthesis, Exponent, Multiplication, Division Addition and Subtraction. So we first operate parenthesis i.e. (P*n*R), then exponent, as we don’t have, so we will skip it, Multiplication so, numbers will get multiplied, lets say it is result is the value after multiplication, then Division so, result/100.

lets convert inr to ‘usd’ using c++,

#include<iostream>
using namespace std;
int main () {
const double usd_rate {75.89}; // 1 USD is 75.89INR today,3/3/2022

double usd {0.0};
double inr {0.0};

cout << "Enter the value in USD" << endl;

cin >> usd;
inr = usd * usd_rate; // arithmetic expression

cout << "$" << usd << " is equivalent to ₹"<< inr << endl;
return 0;
}

Increment and Decrement operator:

Basically it is a plus plus (++) increment operator or minus minus (- -) decrement operator, which means increment operand by one or decrement operand by one, it is also used to move pointers will talk about pointers in later sections. These operators have two variants depending on their placement, prefix notation and postfix notation, that means before operand or after operand.

postfix: operand++, prefix: ++operand

Important: Never use this operator twice for same operand on same statement. meaning for eg. don’t use like this ++operand- -

#include <iostream>using namespace std;int main () {  int incr {0};
int result {0};
// example 1 result = incr + 1; // result becomes 0 + 1 ~ 1
incr++; // short version of incr = incr + 1; incr ~ 1;
++incr; // works same as incr++, hence incr ~ 2

result = result + incr; // 1 + 2 ~ 3
cout << "Eg1. Result: " << result << endl;
// example 2 result = 0; // resetting values
incr = 0;
result = ++incr; // increment 1 and then store in result cout << "Eg.2 Result: " << result << endl;

result = incr++;
cout << "Eg.2 Result: " << result << " Incr: " << incr << endl; return 0;}

Output:

Eg1. Result: 3
Eg.2 Result: 1
Eg.2 Result: 1 Incr: 2

Explanation:

In example 1, when we use ++incr or incr++ no matter where we use in one line statement it will add one to the existing value, this is not the case when we are handling expressions.

In example 2, we can see, result = ++incr; here, we have used prefix notation inside of an expression so, if ++ is before variable we will increment it by one and then we will assign it to the result variable, if ++ would have been after ‘incr’ variable, then assignment occurs before increment, hence result will get ‘incr’ value without incrementing it, but at later point of time we will use increased value of ‘incr‘ variable, Decrement operator works same as increment just we will subtract one existing.

Mixed Type expression:

C++ operation occurs for same type of operands, if operands are of different types C++ converts one the type of operand and if it can’t then compiler throws error, conversion of this type automatically by C++ is called type coercion.

Higher types are those which holds higher values and Lower types are those which holds lower values, hence lower type can be converted into higher type as lower type values can be fit into higher type values, but the reverse is not possible, converting lower type to higher type is called promotion, and reverse is called demotion,

2 * 3.5 ~ 7.0 // 2 is promoted to 2.0int num {0};
num = 100.2;
// 100.2 is demoted to 100 and num will hold 100

However this is done automatically, we can tell C++ compiler to type coerce explicitly, by using static_cast<type> in front of the variable of which type needs to be changed.

For example below,

#include <iostream>
using namespace std;
int main () { int total_amt {100};
int total_num {10};
double avg {0.0};
avg = total_amt / total_num; cout << "Average: " << avg << endl; // output Average: 12 avg = static_cast<double>(total_amt) / total_num; cout << "Average: " << avg << endl; // output Average: 12.5 return 0;
}

Equality or Comparison operators:

Equality operator determines whether two variable holds same values or not if it is same it results to true if not same it results false, whereas comparison operator, compares variable value with some number or two different variable to be greater or less than each other, we can also test for expressions having two variables not being equal, or password match etc.

expr1 == expr2 // true, only if expr1 and expr2 values are same 
expr1 != expr2 // true, only if expr1 and expr2 values are not same
num1 == num2 // for eg, num1 is 100 and num2 is 200,
// hence, 100 == 200, so it results, false
bool result {false};result = (100 == (50 + 50);
result = (num1 != num2);
cout << (num1 == num2)<< endl; // if false prints 0 if true prints 1cout << std::boolalpha;
cout << (num1 == num2) << endl;
// now it will print true or false
cout << std::noboolalpha; // now it will print 0 or 1
cout << num1 <= 10; // compares num1, less than or equal to 10
cout << num2 < 10; // compares num2, less than, 10
cout << num1 > 10; // compares num1 greater than, 10
cout << num1 >= 10; // compares num1 greater than or equal to 10

Here, result = (100 == (50 + 50); in this, 100 == 100 which is true hence result will hold value as 1, as 1 is for true value and 0 is for false value to use true and false we should use std::boolalpha and to disable it we can use std::noboolalpha

Note- In case of comparing integer and float number the integer is promoted to float and it is compared. for eg. 10 == 10.0 ~ 10.0 == 10.0, hence, true.

There is one more comparison operator in C++ (version = 20)

Which is < = > operator, this is called three way comparison operator, this operator compares two expressions and evaluates to zero if they are equal, less than zero if left hand expression is greater than right hand expression, greater than zero if right hand is greater than left hand expression

Formula, expr1 < = > expr2

if expr1 == expr2 , above evaluates 0,

if expr1 > = expr2, above evaluates to -1,

if expr 1 < = expr2, above evaluates to 1

C++: Complete Developers Guide Part 3, Logical operators, khizaruddins, khizaruddins.medium.com
Photo by Lidiia Nemyrova on Unsplash

Logical Operators:

There are mainly three operators, which are ‘not’ (!) operator or ‘negation’ ‘logical and’ (&&) operator and ‘logical or’ (||) operator. It allows us to create complex conditions in programming.

Lets see some truth table,

  1. Logical not truth table (!):
C++: Complete Developers Guide Part 3, Logical not truth table, khizaruddins, khizaruddins.medium.com

This table shows us how logical not operator will work, meaning if variable a holds true value if we use negation operation its value will be changed to false, and vice versa. For eg,

bool a {true}; 
cout << a; // prints 1
cout << !a; // prints false or 0

Note- Logical not operator is a unary operator.

2. Logical and truth table:

C++: Complete Developers Guide Part 3, Logical and truth table, khizaruddins, khizaruddins.medium.com

This table shows if variable a and b holds different values and what its output will be, after using logical and operator,

Simply, only true and true will be true, the rest will be false.

bool a {true};
bool b {false};
cout << a && b;
// prints false as true && false ~ false

3. Logical Or truth table:

C++: Complete Developers Guide Part 3, Logical or truth table, khizaruddins, khizaruddins.medium.com

This table shows if variable a and b holds different values and what its output will be, after using logical or operator,

Simply, at least one expression from both to be true, or else false.

bool a {true};
bool b {false};
cout << a || b;
// prints false as true || false ~ true

Precedence of logical operator:

  1. Logical not, has higher precedence than, Logical and.
  2. Logical and, has higher precedence than, logical or.

Examples,

num1 <= 10 && num1 < 20 // both expression must be true for entire
//
expression to be true
num1 <= 10 || num1 >= 20 // only one or both expression needs be
// true for expression to be true
!is_raining && temp >= 32.0 // here, first logical not will get
// evaluated, then logical and
temp > 100 && is_humid || is_raining // here, first logical and will
// be evaluated, then or

Short Circuit Evaluation:

C++ stops evaluating an expression as soon as it knows the result. For eg, expr1 && expr2 && expr3

Let’s say, expr1 is false, then C++ won’t evaluate expr2 and expr3, because the and needs all to be true, hence result evaluates to false.

expr1 || expr2 || expr3

Let's say, expr1 is true, then entire expression is true, hence compiler won’t evaluate expr2 and expr3. However, if expr1 is false then it will continue to evaluate expr2

This is called short circuit evaluation.

Compound assignment operator:

C++: Complete Developers Guide Part 3, Compound assignment operator, khizaruddins, khizaruddins.medium.com

lhs: left hand side, rhs: right hand side

lhs += rhs, meaning increment lhs with rhs and store value in lhs.

eg. num+=1 same as, num = num + 1;

lhs-=rhs, same as above, but decrement it, with rhs.

eg. num-=1 same as num = num -1;

lhs*=rhs, same as above but multiply it with rhs.

eg. num *= 2 same as, num = num * 2;

Same, for lhs %=rhs and lhs /= rhs, just operation changes.

Complex eg. cost += item * tax; same as, cost = cost + item * tax;

TLDR;

For more tech related blogs please visit:

khizaruddins.medium.com
Follow me on twitter and instagram

Buy me a Coffee

--

--