#include <iostream>
using std::cout;
using std::endl;
using std::string;
// arrays are similar to vectors but they require the number of elements during declaration
int main()
{
/*
When declaring an array the size must be a constant expression, in other words the
size of the array must be known at compile time. A constant expression is an expression
whose value cannot change and that can be evaluated at compile time. For example,
an integer literal is a constant expression. Declaring a variable with the constexpr
keyword will ask the compiler to verify that the variable is a constant expression.
This also implies that the variable is a constant. Generally, any situation that
requires a constant expression should use a constexpr.
*/
int arr[10]; // array declaration using a literal
constexpr int num = 45;
int arr2[num]; // array declaration using a constexpr
/*
Arrays can also be list initialized as long as the size of the array is greater
than the number of initializers
*/
int listInitNoSize[] = {1, 3, 4}; // compiler can infer the size of the array from the number of initializers
int listInitSize[3] = {7, -1, 3}; // the number of initializers must match the array size
int biggerSize[5] = {12, 17, 19}; // this is OK because the number of initializers is smaller than the array size
for (int i = 0; i < 5; i++) {
cout << biggerSize[i] << endl;
}
//int smallerSize[3] = {7, -9, 10, 12, 13}; // this will generate an error because the number of initializers is more than the array size
/*
Character arrays can be initialized using a string. However, string literals have
a null character at the end so the size of the array required to hold the string
is the number of characters plus one.
*/
char charArr[] = "Vedant"; // using a string literal to initialize a char array
cout << sizeof(charArr) << endl; // check the size of the array
//char charArr2[6] = "Vedant"; // this will generate an error because the string literal has 6 characters plus the null character which requires an array size of 7
// pointers and arrays
string names[] = {"Paul", "Steve", "Richard", "Scott"};
string *pNames = &names[0]; // pointer that points to the first element of the array
string *pNames2 = names; // whenever an array is used the compiler substitutes it with a pointer to the first element of the array
if (pNames == pNames2) {
cout << "They are the same!" << endl;
}
/*
Pointers that point to arrays can be incremented or decremented. They play the same role
as iterators in the context of vectors.
*/
string *begNames = names; // pointer that points to the first element in the names array, equivalent to begNames = &names[0]
string *endNames = &names[4]; // off-the-end pointer that points to the memory location after the last element in the names array
string *begNames2 = begin(names); // begin function returns a pointer to the first element given an array argument
string *endNames2 = end(names); // end function returns the off-the-end pointer given an array argument
if (begNames == begNames2 && endNames == endNames2) {
cout << "They match!" << endl;
}
// adding an interger to a pointer results in another pointer
string *addNames = begNames + 1;
cout << "First element: " << *begNames << endl;
cout << "Second element: " << *addNames << endl;
/* Subtracting an integer from a pointer results in a different data type. The data
type will be unsigned because its possible the subtraction operation will result in
a negative number. It is not necessary to know the data type so just use auto.
*/
auto *subNames = endNames - 1;
cout << "Last element: " << *subNames << endl;
// array of pointers and pointers to arrays
int nums[5] = {2, -1, 5, 6, 9};
int *arrOfPoint[5]; // declares an array of 5 pointers to int
int (*pointToArr)[5]; // declares a pointer that points to an array of ints
pointToArr = &nums;
//arrOfPoint = &nums; // this generates an error because the address of the array is being assigned to an array of pointers
arrOfPoint[0] = &nums[0];
// multidimensional arrays
// two-dimensional arrays can be list initialized, as long as the number of initilizers match the size of the array
int multiDimArr[5][5] = {{1, 1, 1, 1, 1},
{2, 2, 2, 2, 2},
{3, 3, 3, 3, 3},
{4, 4, 4, 4, 4},
{5, 5, 5, 5, 5}};
int smallArr[2][3] = {{-1, 2, 4}}; // this is OK because the number of initializers is less than the size of the array
int i = 0;
while (i < 2) {
int j = 0;
while (j < 3) {
cout << smallArr[i][j] << " ";
j++;
}
i++;
cout << endl;
}
//int largeArr[2][3] = {{-1, 2, 4, 5}, // this generates an error because the number of initializers is more than the size of the array
// {0, 9, 8, 3}};
/*
Multidimensional arrays can be subscripted by using multiple subscript ([]) operators.
If the number of subscript operators is less than the dimension of the array then the
inner array element at the specified index will be retrieved.
*/
cout << multiDimArr[2][3] << endl;
/*
When using a range-for loop to iterate over a multidimensional array it is necessary
to use type aliases for all loop control variables (except for the innermost loop).
This is because 'row' in the outer loop is an array and the compiler converts any instance
of an array to a pointer. This means the inner loop will be iterating over a pointer
which is illegal.
*/
//for (auto row: multiDimArr) { // this generates an error
//for (auto col: row) {
//cout << col << endl;
//}
//}
for (auto &row: multiDimArr) { // this is OK
for (auto col: row) {
cout << col << endl;
}
}
// using pointers with multidimensional arrays
int junkArr[3][2] = {{-1, 2},
{4, -3},
{7, 8}};
/*
The compiler converts any instance of a multidimensional array to a pointer that points
to an array. This is because multidimensional arrays are actually arrays of arrays.
*/
cout << "---------------------------------------------------------------" << endl;
int (*p)[2] = junkArr; // declare a pointer to an array of ints and initialize it using the first row of junkArr
for (int i: *junkArr) { // deference the pointer to get back the array of ints when using the range-for loop
cout << i << endl;
}
return 0;
} Write, Run & Share C++ code online using OneCompiler's C++ online compiler for free. It's one of the robust, feature-rich online compilers for C++ language, running on the latest version 17. Getting started with the OneCompiler's C++ compiler is simple and pretty fast. The editor shows sample boilerplate code when you choose language as C++ and start coding!
OneCompiler's C++ online compiler supports stdin and users can give inputs to programs using the STDIN textbox under the I/O tab. Following is a sample program which takes name as input and print your name with hello.
#include <iostream>
#include <string>
using namespace std;
int main()
{
string name;
cout << "Enter name:";
getline (cin, name);
cout << "Hello " << name;
return 0;
}
C++ is a widely used middle-level programming language.
When ever you want to perform a set of operations based on a condition If-Else is used.
if(conditional-expression) {
//code
}
else {
//code
}
You can also use if-else for nested Ifs and If-Else-If ladder when multiple conditions are to be performed on a single variable.
Switch is an alternative to If-Else-If ladder.
switch(conditional-expression){
case value1:
// code
break; // optional
case value2:
// code
break; // optional
......
default:
code to be executed when all the above cases are not matched;
}
For loop is used to iterate a set of statements based on a condition.
for(Initialization; Condition; Increment/decrement){
//code
}
While is also used to iterate a set of statements based on a condition. Usually while is preferred when number of iterations are not known in advance.
while (condition) {
// code
}
Do-while is also used to iterate a set of statements based on a condition. It is mostly used when you need to execute the statements atleast once.
do {
// code
} while (condition);
Function is a sub-routine which contains set of statements. Usually functions are written when multiple calls are required to same set of statements which increases re-usuability and modularity. Function gets run only when it is called.
return_type function_name(parameters);
function_name (parameters)
return_type function_name(parameters) {
// code
}