NSWI170, 2025, Labs 01
Jáchym Bártík
int a = 1;
if (someExpression) // Parentheses, no colon
doSomething(); // Mandatory semicolon
else { // Again, no colon
doSomethingElse();
doMoreElse(); // Braces are used to create a block
} // of code (instead of indentation)
for (int i = 0; i < 10; i++) { // For-loop is entirely different
doSomething();
}
Hello World!
#include <iostream>
using namespace std;
int main() {
cout << "Hello World!" << endl;
return 0;
}
g++ helloWorld.cpp -o helloWorld
./helloWorld
*
na jednom řádkuvoid printStars(int amount) {
...
}
int main() {
printStars(5);
return 0;
}
/*
*****
*/
*
void printTriangle(int levels) { ... }
printTriangle(4);
/*
*
**
***
****
*/
*
void printTree(int levels, int skipped = 0) { ... }
printTree(3);
/*
*
***
*****
*/
printTree(3, 1);
/*
***
*****
*/
*
void printChristmasTree(int segments, int segmentHeight, int ornaments) { ... }
printChristmasTree(5, 3, 4);
/*
*
***
*****
@***@
*****
*******
*****
@*******@
*********
*******
*********
@***********@
*********
***********
*************
*/
int a[32]; // Array with 32 elements (from a[0] to a[31])
int b[] = { 1, 2, 3, 4, 5 }; // Array with 5 elements
int c[3][4]; // Matrix of 3 times 4 elements
int d[][2] = { { 1, 0 }, { 0, 1 } }; // Unit matrix 2 times 2
int b[] = { 1, 2, 3, 4, 5 };
int bSize = sizeof(b) / sizeof(b[0]); // bSize = 5
void foo(int array[], int size) {
int computedSize = sizeof(array) ... // Does not work!
}
*
void printChart(int values[], int count) { ... }
int values[] = { 3, 4, 4, 5, 6, 8, 11, 10, 5, 2, 0 };
printChart(values, count);
/*
| ***
| ****
| ****
| *****
| ******
| ********
| ***********
| **********
| *****
| **
|
*/
int size = rand() % 100; // Random size from 0 to 99
int* array = new int[size]; // Dynamic allocation
... // Some computations
delete [] array; // Deallocation
int* computeMovingAverage(int values[], int count, int windowSize) { ... }
int values[] = { 3, 4, 4, 5, 6, 8, 11, 11, 10, 5, 2, 0 };
computeMovingAverage(values, 12, 3);
/*
initial: [ 3, 4, 4, 5, 6, 8, 11, 11, 10, 5, 2, 0 ]
output: [ 4, 4, 5, 6, 8, 10, 10, 8, 5, 2, 0, 0 ]
*/
|
no_value
)
temperatures
a konstanta no_value
jsou poskytnuty v souboru temps.h
int temperatures[] = { 4, 2, no_value, 0, -1, -3 };
/*
|****
|**
|**
|
*|
***|
*/