To get a sum of all elements from an array of integers, we will use simple incremental addition with a help of a for loop.
Starting point for loop will be zero, ending point will be number of elements.
While jumping from one element to another, we will incrementaly add previous elements until we reach top level, in this case number 5.
We must not skip any of elements, thus increment must x = x + 1.
Run this code:
#include <iostream>
using namespace std;
int main() {
int numbers[5] = {23, 34, 56, 5000, 2};
int total = 0;
for (int x = 0; x < 5; x = x + 1) {
total = total + numbers[x];
cout << "Result of addition at this pass: " << x << " -> " << total << endl;
}
return 0;
}
Result:
Result of addition at this pass: 0 -> 23
Result of addition at this pass: 1 -> 57
Result of addition at this pass: 2 -> 113
Result of addition at this pass: 3 -> 5113
Result of addition at this pass: 4 -> 5115
Process returned 0 (0x0) execution time : 0.065 s
Press any key to continue.
In this example we will find number of elements in an array so we don't need to count them manually.
Solution is a little bit weird because we get size of whole array and than divide it by size of an individual element (in bytes).
Please note, when calculating array size we are not using an integer as data type, butsize_t data type in combination with sizeof() function:
#include <iostream>
using namespace std;
int main() {
int numbers[] = {45, 234, 5000, 0, 567};
size_t n = sizeof(numbers) / sizeof(numbers[0]);
for (size_t x = 0; x < n; x++) {
cout << "Element at position: " << x << " -> " << numbers[x] << endl;
}
return 0;
}
Result:
Element at position: 0 -> 45
Element at position: 1 -> 234
Element at position: 2 -> 5000
Element at position: 3 -> 0
Element at position: 4 -> 567
Process returned 0 (0x0) execution time : 0.053 s
Press any key to continue.
We will use the same approach when working with individual characters.
Don't forget to use single quotes for elements when data type is char:
#include <iostream>
using namespace std;
int main() {
char characters[] = {'A', 'C', 'D'};
size_t n = sizeof(characters) / sizeof(characters[0]);
for (size_t x = 0; x < n; x++) {
cout << "Element at position: " << x << " -> " << characters[x] << endl;
}
return 0;
}
Result:
Element at position: 0 -> A
Element at position: 1 -> C
Element at position: 2 -> D
Process returned 0 (0x0) execution time : 0.021 s
Press any key to continue.
It's easy to list/use elements from array in C++. We will use simple for loop to do that. Our starting point will be zero, and ending point will be total number of elements in an array.
This is case when we know how many elements will array store, or array is small enough to count them visually.
Of course, positions will be used here and abstract "x" will represent any of those elements while a loop is working until it reaches top level:
#include <iostream>
using namespace std;
int main() {
int numbers[5] = {45, 234, 5000, 0, 567};
int x = 0;
for (x; x < 5; x = x + 1) {
cout << "Element at position: " << x << " -> " << numbers[x] << endl;
}
return 0;
}
Result:
Element at position: 0 -> 45
Element at position: 1 -> 234
Element at position: 2 -> 5000
Element at position: 3 -> 0
Element at position: 4 -> 567
Process returned 0 (0x0) execution time : 0.284 s
Press any key to continue.
An array is collection of elements. But in C++ and some low level languages we must state what will be data type of those elements.
To create array, we must state specify data tupe, name for array and number of elements array will receive.
In this example our array "numbers" will be filled with 5 integers.
To print individual intefers positions/indexes are used. First element will be at position 0. It's a little bit weird to start from 0, but most of programming languages use that approach.
You will get used to it.
Run this code:
#include <iostream>
using namespace std;
int main() {
int numbers[5] = {45, 234, 5000, 0, 567};
cout << "Number at position 0: " << numbers[0] << endl;
cout << "Number at position 1: " << numbers[1] << endl;
cout << "Number at position 2: " << numbers[2] << endl;
cout << "Number at position 3: " << numbers[3] << endl;
cout << "Number at position 4: " << numbers[4] << endl;
return 0;
}
Result:
Number at position 0: 45
Number at position 1: 234
Number at position 2: 5000
Number at position 3: 0
Number at position 4: 567
Process returned 0 (0x0) execution time : 0.285 s
Press any key to continue.
In next example we have an array of characters. Sometimes when we don't know how much elements will end up in specific array we can just use empty square brackets.
Please note, when working with individual characters single quotes must be used around elements.
To get each of them individually, we will use positions/indexes just as with any other array:
#include <iostream>
using namespace std;
int main() {
char characters[] = {'B', 'A', 'T'};
cout << "Character at position 0: " << characters[0] << endl;
cout << "Character at position 1: " << characters[1] << endl;
cout << "Character at position 2: " << characters[2] << endl;
return 0;
}
Result:
Character at position 0: B
Character at position 1: A
Character at position 2: T
Process returned 0 (0x0) execution time : 0.184 s
Press any key to continue.
To generate random number, we will use rand() function.
Please note, cstdlib must be imported for rand() function to work.
Inside main() section we will establish variable r that is result of rand() function.
To use for loop to generate a list of random numbers, there must be starting point established. In this case initial integer x will have value 0. That's our starting point while looping.
This code will work to some degree, but problem arises when we realize that every time when we run our program random numbers will be same. We will fix our code.
But first run this code multiple times to see what is happening:
#include <iostream>
#include <cstdlib>
using namespace std;
int main() {
int r = rand();
int x = 0;
for (x; x <=20; x = x + 1) {
cout << rand() << endl;
}
return 0;
}
Result:
18467
6334
26500
19169
15724
11478
29358
26962
24464
5705
28145
23281
16827
9961
491
2995
11942
4827
5436
32391
14604
Process returned 0 (0x0) execution time : 0.217 s
Press any key to continue.
Now we will fix things. First thing to do is import of ctime.
Then we will call srand() function and pass to it time() function with argument 0.
Rest of program is the same as in the first example:
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main() {
srand(time(0));
int r = rand();
int x = 0;
for (x; x <=20; x = x + 1) {
cout << rand() << endl;
}
return 0;
}
Result after first run:
23852
19756
6004
7158
3533
32224
20942
19137
7716
21498
8810
10097
18113
8021
27907
19690
9425
32508
12488
26795
28319
Process returned 0 (0x0) execution time : 0.163 s
Press any key to continue.
Result after second run:
15488
25268
14163
10738
28176
17782
11505
25261
7521
14398
10925
24188
25905
24669
8168
29001
9100
22079
27560
17683
17740
Process returned 0 (0x0) execution time : 0.063 s
Press any key to continue.
Think about function overloading as a case where we have multiple function with same name but individually they grab as parameters different data types.
Now, when we use those functions, and we pass specific values as inputs/arguments, function that must be activated will be automatically called.
It's basically automatic recognition.
In this case we have two function with same name printStuff() but they demand different parameters. Operations are same, but inputs must be different:
#include <iostream>
#include <cstdlib>
using namespace std;
void printStuff(int container) {
cout << container << endl;
}
void printStuff(char container) {
cout << container << endl;
}
int main() {
int x = 50;
char c = 'A';
printStuff(x);
printStuff(c);
return 0;
}
Result:
50
A
Process returned 0 (0x0) execution time : 0.326 s
Press any key to continue.
Use of Unary Scope Operator means use of double colon symbol to access something that is not immediately reachable from main() section of our programs.
For example, we have two variables temp here with same name.Values in those variables are different.
If we use just temp in main() section, we will have 20 as result.
But to access temp outside main() section, we will use same name of variable but with double colons as prefix. In this case value of an external temp is 50:
Outside Temp Value: 50
Inside Temp Value: 20
Process returned 0 (0x0) execution time : 0.062 s
Press any key to continue.
This is interesting situation when we have three temp variables. One is external, one is internal in main() section, and one is internal in printTemp() function.
All of them have same name, but they are used in different ways:
#include <iostream>
#include <cstdlib>
using namespace std;
int temp = 50;
void printTemp() {
int temp = 10000;
cout << "In Function Temp Value: " << temp << endl;
}
int main() {
int temp = 20;
cout << "Inside Temp Value: " << temp << endl;
cout << "With Unary Scope Temp Value: " << ::temp << endl;
printTemp();
return 0;
}
Result:
Inside Temp Value: 20
With Unary Scope Temp Value: 50
In Function Temp Value: 10000
Process returned 0 (0x0) execution time : 0.161 s
Press any key to continue.
Return from function means that function will produce some result and export it to rest of the program so other parts of program can grab it and use it as input values.
In an example down below our function addNumbers() will have 2 mandatory integers as parameters. We are stating that while declaring function above main() part of our program.
Below main() part of the program, we have function definition where operations are stated. In this case it's just simple addition.
Once we have result as product of operation, then we are returning it to the rest of the program. Note, we are not doing anything more inside addNumbers(), just exporting it to outside world:
#include <iostream>
#include <cstdlib>
using namespace std;
int addNumbers(int x, int y);
int main() {
cout << "Result of add: " << addNumbers(5, 10) << endl;
return 0;
}
int addNumbers(int x, int y) {
int result = x + y;
return result;
}
Result:
Result of add: 15
Process returned 0 (0x0) execution time : 0.059 s
Press any key to continue.
Inside main() part of our program we can have a variable (container) that will receive what is returned when we call function addNumbers().
Then, that result (container that hold value) will be used in future operations, multiple times even, if we need that:
#include <iostream>
#include <cstdlib>
using namespace std;
int addNumbers(int x, int y);
int main() {
int container = addNumbers(5, 10);
cout << "Result of add: " << container << endl;
return 0;
}
int addNumbers(int x, int y) {
int result = x + y;
return result;
}
Result:
Result of add: 15
Process returned 0 (0x0) execution time : 0.053 s
Press any key to continue.
Sure, we can have function full detailed above main() section, and combination of direct call and indirect call (using a variable - container) will work too.
Run this code:
#include <iostream>
#include <cstdlib>
using namespace std;
int addNumbers(int x, int y) {
int result = x + y;
return result;
}
int main() {
int container = addNumbers(10, 90);
cout << "Result for 10 and 90: " << container << endl;
cout << "Result for 5 and 15: " << addNumbers(5, 15) << endl;
return 0;
}
Result:
Result for 10 and 90: 100
Result for 5 and 15: 20
Process returned 0 (0x0) execution time : 0.072 s
Press any key to continue.
Default arguments are used when while calling functions we forget to enter arguments or there's no need for them.
It's easy, while creating parameters just state name, data type and initial (default) value, just as in this example where we have 2 default parameters, y with value 5000 and z with value 1000.
But we always must pass value for x, otherwise compiler will complain:
#include <iostream>
#include <cstdlib>
using namespace std;
void defaultArgs(int x, int y = 5000, int z = 1000);
int main() {
defaultArgs(4);
return 0;
}
void defaultArgs(int x, int y, int z) {
cout << "X: " << x << endl;
cout << "Y: " << y << endl;
cout << "Z: " << z << endl;
}
Result:
X: 4
Y: 5000
Z: 1000
Process returned 0 (0x0) execution time : 0.059 s
Press any key to continue.
When we don't provide values while calling function, default arguments will step in.
Otherwise, if all of them have default value, forgetting one/more of them will not be a problem for a compiler:
#include <iostream>
#include <cstdlib>
using namespace std;
void defaultArgs(int x = 3000, int y = 5000, int z = 1000);
int main() {
defaultArgs();
defaultArgs(2);
defaultArgs(3, 4);
defaultArgs(1, 2, 3);
return 0;
}
void defaultArgs(int x, int y, int z) {
cout << "X: " << x << endl;
cout << "Y: " << y << endl;
cout << "Z: " << z << endl;
cout << "---------------------------" << endl;
}
Result:
X: 3000
Y: 5000
Z: 1000
---------------------------
X: 2
Y: 5000
Z: 1000
---------------------------
X: 3
Y: 4
Z: 1000
---------------------------
X: 1
Y: 2
Z: 3
---------------------------
Process returned 0 (0x0) execution time : 0.057 s
Press any key to continue.
Functions can take multiple parameters/arguments. Every time when we declare function we must state name and data type for those arguments.
When passing values to function, there's no need to prefix them with data type because we already did that while declaring function.
Function down below will just demand 3 individual characters, so we can print them on screen.
Run this code:
#include <iostream>
#include <cstdlib>
using namespace std;
void printMultiChars(char x, char y, char z) {
cout << x << " " << y << " " << z << endl;
}
int main() {
printMultiChars('A', 'R', 'B');
return 0;
}
Result:
A R B
Process returned 0 (0x0) execution time : 0.057 s
Press any key to continue.
We can improve our function to have left parts as custom report so we can concatenate it with real values:
#include <iostream>
#include <cstdlib>
using namespace std;
void printMultiChars(char x, char y, char z) {
cout << "Value of x: " << x << endl;
cout << "Value of y: " << y << endl;
cout << "Value of z: " << z << endl;
}
int main() {
printMultiChars('A', 'R', 'B');
return 0;
}
Result:
Value of x: A
Value of y: R
Value of z: B
Process returned 0 (0x0) execution time : 0.171 s
Press any key to continue.
In this example we are taking values using keyboard, run it:
#include <iostream>
#include <cstdlib>
using namespace std;
void printMultiChars(char x, char y, char z) {
cout << "Value of x: " << x << endl;
cout << "Value of y: " << y << endl;
cout << "Value of z: " << z << endl;
}
int main() {
char x, y, z;
cout << "Enter char in container x: " << endl;
cin >> x;
cout << "Enter char in container y: " << endl;
cin >> y;
cout << "Enter char in container z: " << endl;
cin >> z;
printMultiChars(x, y, z);
return 0;
}
Result:
Enter char in container x:
a
Enter char in container y:
b
Enter char in container z:
c
Value of x: a
Value of y: b
Value of z: c
Process returned 0 (0x0) execution time : 6.807 s
Press any key to continue.
It's easy to create a simple calculator. Function will demand two parameters, integers. Inside function theres result variable (integer). That is simple multiplication operation.
Function will print results on screen, when called with real values.
In this example, we are passing values 5 and 10 as inputs:
#include <iostream>
#include <cstdlib>
using namespace std;
void calculator(int x, int y) {
int result = x * y;
cout << "Multiplication: " << result << endl;
}
int main() {
calculator(5, 10);
return 0;
}
Result:
Multiplication: 50
Process returned 0 (0x0) execution time : 0.068 s
Press any key to continue.
We can pass values to function so function can grab them and use for some operations.
When we declare or define functions, in between parentheses, we will state type and name for parameters/arguments.
For example, we have function here funcName(int x) that will demand some integer as input.
Lowercase "x" will represent any number that we will pass. You can use any character here, just use something abstract for simple stuff, or some word that will describe what is happening.
A task for function is simple here, it will just print that value on screen.
Down in main() section of program, we are calling function funcName() with input 40.
Run this code:
#include <iostream>
#include <cstdlib>
using namespace std;
void funcName(int x) {
cout << "x at this moment of time: " << x << endl;
}
int main() {
funcName(40);
return 0;
}
Result:
x at this moment of time: 40
Process returned 0 (0x0) execution time : 0.144 s
Press any key to continue.
Naturally, we can call same function multiple times with same or different arguments:
#include <iostream>
#include <cstdlib>
using namespace std;
void funcName(int x) {
cout << "x at this moment of time: " << x << endl;
}
int main() {
funcName(40);
funcName(424654);
funcName(1231321);
return 0;
}
Result:
x at this moment of time: 40
x at this moment of time: 424654
x at this moment of time: 1231321
Process returned 0 (0x0) execution time : 0.056 s
Press any key to continue.
Inside main() program section we will create a container that will hold value from a keyboard so we can pass it to function.
Because x must be an integer while calling function, container must be of same data type:
#include <iostream>
#include <cstdlib>
using namespace std;
void funcName(int x) {
cout << "x at this moment of time: " << x << endl;
}
int main() {
int container;
cout << "Please, enter just integer: " << endl;
cin >> container;
funcName(container);
return 0;
}
Result when we enter integer 50:
Please, enter just integer:
50
x at this moment of time: 50
Process returned 0 (0x0) execution time : 1.807 s
Press any key to continue.
While learning programming you will often run into this two terms: function declaration and function definition.
To declare function we need to state function name, number and type of parameters and function return type. Function declaration must happen above main() function.
Then, below main function we will define function. That means we will write that dedicated source about what job function will achieve. It's like going into great detail what and how function will do something.
In the example below we are declaring function printStuff() with void (function will do simple printing), and she has no parameters. Parameters are inputs for function. This is simple printing, so no need for them at the moment.
Then, below main() program function we have source code what that function will actually do. In this case it will just print "Hack The Planet" on our screens. Simple as that.
Run this code:
#include <iostream>
#include <cstdlib>
using namespace std;
void printStuff();
int main() {
printStuff();
return 0;
}
void printStuff() {
cout << "Hack The Planet" << endl;
}
Result:
Hack The Planet
Process returned 0 (0x0) execution time : 0.021 s
Press any key to continue.
Now, in the example below, we can have full function source before main() part of the program. Function function_1() will print one line on screen.
But also we have declaration of function_2(). That function will also do simple printing, but it will be defined below main() part of the program.
We can combine these two approaches if we need that:
#include <iostream>
#include <cstdlib>
using namespace std;
void function_1() {
cout << "I am from function_1" << endl;
}
void function_2();
int main() {
function_1();
function_2();
return 0;
}
void function_2() {
cout << "But, I am from function_2" << endl;
}
Result:
I am from function_1
But, I am from function_2
Process returned 0 (0x0) execution time : 0.223 s
Press any key to continue.
Functions are peaces of code dedicated to getting some specific job done. They can produce imiddiate results as product (printing on screen, for example), or they can return values so other parts of program, other functions can grab those values and do something more with that.
Think about functions as dedicated workers in some firm that will do just one job perfectly and nothing else. They are like specialists.
In this case we will create function someFunction() that will just print one line "I am from someFunction". It's not enough to have function, we also need to use it in main section of our program.
In C++ functions we can create functions outside main() part of the program, just like in this example:
#include <iostream>
#include <cstdlib>
using namespace std;
void someFunction() {
cout << "I am from someFunction" << endl;
}
int main() {
someFunction();
return 0;
}
Result:
I am from someFunction
Process returned 0 (0x0) execution time : 0.200 s
Press any key to continue.
We can have multiple functions that will do specific jobs, in this case secondFunction() will run Calculator on Windows machines.
Run this code:
#include <iostream>
#include <cstdlib>
using namespace std;
void someFunction() {
cout << "I am from someFunction" << endl;
}
void secondFunction() {
system("calc");
}
int main() {
someFunction();
secondFunction();
return 0;
}
Many times it's useful to create functions that will call other functions, even multiple times. Don't forget semicolons after the end of function call:
#include <iostream>
#include <cstdlib>
using namespace std;
void someFunction() {
cout << "I am from someFunction" << endl;
}
void multiple_run() {
someFunction();
someFunction();
someFunction();
}
int main() {
multiple_run();
return 0;
}
Result:
I am from someFunction
I am from someFunction
I am from someFunction
Process returned 0 (0x0) execution time : 0.021 s
Press any key to continue.
Functions that will do some direct operations will have void before their name, and functions that will return values to rest of the program will have data types as return types like int, char and so on.
To run already existing programs on your computer header cstdlib (C Standard General Utilities Library) must be imported:
#include <iostream>
#include <cstdlib>
Now it's easy to run, for example Windows calculator using system() function. This function help us to execute system commands:
system("calc");
And this is full source:
#include <iostream>
#include <cstdlib>
using namespace std;
int main() {
system("calc");
return 0;
}
Result:
It's easy to execute multiple programs with C++. Run this code and play around with other apps you have on windows.
#include <iostream>
#include <cstdlib>
using namespace std;
int main() {
system("calc");
system("notepad");
system("calc");
return 0;
}
Run External Programs with Switch Statement
In this simple example we have information what end users need to type:
int menu = 0;
cout<< "0 for string, 1 for calc, 2 for notepad" << endl;
cout << "Please enter option: " << endl;
Then we get value with cin:
cin >> menu;
Then switch statement with 3 options and default one:
switch(menu) {
case 0:
cout << "This is just a string" << endl;
break;
case 1:
system("calc");
break;
case 2:
system("notepad");
break;
default:
cout << "Check your input" << endl;
break;
}
This is full working source:
#include <iostream>
#include <cstdlib>
using namespace std;
int main() {
int menu = 0;
cout<< "0 for string, 1 for calc, 2 for notepad" << endl;
cout << "Please enter option: " << endl;
cin >> menu;
switch(menu) {
case 0:
cout << "This is just a string" << endl;
break;
case 1:
system("calc");
break;
case 2:
system("notepad");
break;
default:
cout << "Check your input" << endl;
break;
}
return 0;
}
Result when input value is 0:
0 for string, 1 for calc, 2 for notepad
Please enter option:
0
This is just a string
Process returned 0 (0x0) execution time : 5.448 s
Press any key to continue.
Simple as that.
Now you know a lot of useful things in C++, but we will learn a lot more.