C++ Basics Data Processing Course, I. Hrivnacova, IPN Orsay The First Program Comments Function main() Input and Output Namespaces Variables Fundamental Types Operators Control constructs 1
C++ Programming language Features: C++ is C. C++ supports (almost) all the features of C. Like C, C++ allows programmers to manage the memory directly, so as to develop efficient programs. C++ is OO. C++ enhances the procedural-oriented C language with the objectoriented extension. The OO extension facilitates design, reuse and maintenance for complex software. Template C++. C++ introduces generic programming, via the so-called template. You can apply the same algorithm to different data types. STL. C++ provides a huge set of reusable standard libraries, in particular, the Standard Template Library (STL). 2
C++ Standards C++ is standardized as ISO/IEC 14882. Currently, there are two versions: C++98 (ISO/IEC 14882:1998): 1st standard version of C++. C++03 (ISO/IEC 14882:2003): minor "bug-fix" to C++98 with no change to the language. Commonly refer to as C++98/C++03 or First C++ standard. C++11 (ISO/IEC 14882:2011): 2nd standard version of C++. Formerly called C++0x, as it was expected to finalize in 200x. It adds some new features to the language; more significantly, it greatly extends the C++ standard library and standard template library (STL). We will use some features introduced in C++11 in our course, too 3
C++ Program /* The first C++ program * - just outputs 'Hello, World!' */ #include <iostream> int main() { // print Hello, World! on the screen std::cout << Hello, World! << std::endl; 4
C++ Program /* The first C++ program * - just outputs 'Hello, World!' */ #include <iostream> int main() { // print Hello, World! on the screen std::cout << Hello, World! << std::endl; Comments: /* */ - can span over several lines or be inserted in the code on one line // - lasts to the end of the line 5
C++ Program /* The first C++ program * - just outputs 'Hello, World!' */ #include <iostream> int main() { // print Hello, World! on the screen std::cout << Hello, World! << std::endl; Include statement(s): Including all necessary declarations for input and output 6
C++ Program /* The first C++ program * - just outputs 'Hello, World!' */ #include <iostream> int main() { // print Hello, World! on the screen std::cout << Hello, World! << std::endl; The main function called at the program startup, leaving main() ends the program 7
C++ Program /* The first C++ program * - just outputs 'Hello, World!' */ #include <iostream> int main() { // print Hello, World! on the screen std::cout << Hello, World! << std::endl; A statement ending with a semicolon; It writes the string Hello, World! followed by std::endl symbol, to the standard output 8
Function main() The function main is called at the program startup, leaving main() ends the program The function head: int the return type main the function name () the parameter list The function main() returns integer value If return statement is not present, the zero value is returned implicitly You can also write the statement explicitly: return 0; In C programs the return statement cannot be omitted 9
Input and Output (IO) Chua Hock-Chuan: Programming Notes C/C++ IO are based on streams, which are sequence of bytes flowing in and out of the programs (just like water and oil flowing through a pipe). In input operations, data bytes flow from an input source (such as keyboard, file, network or another program) into the program. In output operations, data bytes flow from the program to an output sink (such as console, file, network or another program). 10
Input and Output The input/output (I/O) functionality is provided in components of standard library Generally assigned to the keyboard (input) and the screen (output) Can be redirected by the operating system to a file std::cin - input channel (the keyboard) std::cout - output channel (the screen) #include <iostream> Standard channels to provide input/output: Symbols To get these components known to the program: << operator : std::endl - line break (new line) Send data to the output channel >> operator : Read data from an input channel 11
Namespaces The prefix std:: is used for all symbols of the standard library Using the namespace concept, symbols can be grouped logically within a package (or a component) Avoids names clashes in large program using namespace directive can be used to make all symbols from a namespace available without std:: prefix #include <iostream> using namespace std; cout << Hello, World! << std; 12
Four digits program We will discuss the Four digits program (from the C++ book) line by line to learn the basic language concepts: Variables, Types, Operators and Control Constructs The program will list all four digits numbers that fulfill the following condition If you split a four digits number into two parts each having two digits and add the squares of these numbers, you get the original four digit number: Eg. 1233 = 12*12 + 33*33 13
Code #include <iostream> // C++ header file for I/O using namespace std; int main() { int counter = 0; // current number of found four-digit numbers // for every number from 1000 to 9999 for (int number=1000; number<10000; ++number) { // separate the first and last two digits int front = number / 100; // the first two digits int back = number % 100; // the last two digits // if the sum of the squares produce the original number, // output number and increment counter if (front*front + back*back == number) { cout << number << " == " << front << "*" << front << " + " << back << "*" << back << endl; ++counter; // output number of four-digit numbers found cout << counter << " numbers found" << endl; 14
Variables #include <iostream> // C++ header file for I/O using namespace std; int main() { int counter = 0; // current number of found four-digit numbers // for every number from 1000 to 9999 for (int number=1000; number<10000; ++number) { A variable counter is defined to count how many four-digit numbers were found: int ~ type counter ~ name = 0 ~ initialized to the value 0 // separate the first and last two digits int front = number / 100; // the first two digits int back = number % 100; // the last two digits // if the sum of the squares produce the original number, // output number and increment counter if (front*front + back*back == number) { cout << number << " == " << front << "*" << front << " + " << back << "*" << back << endl; ++counter; // output number of four-digit numbers found cout << counter << " numbers found" << endl; 15
Variable NAME VALUE TYPE counter 0 int number pi 1556 3.141592 int double It allocates memory The current memory content is its value counter has the value 0 The size of memory allocated and the operations we can do with a variable are defined by its type A variable has a name, stores a value of the declared type 16
Variable Declaration Variable declaration = the instruction that creates the variable We can declare a variable without giving it an initial value; its value is undefined int counter; We can also declare a variable with giving it its initial value: int counter = 0; Other ways of initialization: int counter(0); int counter = { 0 ; We prefer to declare variables just before their use The const declaration of a variable - creates a variable that can not be changed later const double PI = 3.14; PI = 5.4; // error: cannot assign to variable 'PI' // with const-qualified type 'const double' 17
Variable Type Defines how the object (its binary configuration in memory) can be manipulated Fundamental types Numeric: integer (int), floating point numbers (float, double) Characters: char Enclosed in single quotes: 'a', '0' Special characters must be masked with a backslash: \', \ Boolean: bool: can have only two values: true, false Object types Defined in the C++ standard library and by the programmer Have their own defined functions; can also have their own defined operators enum: for enumeration types (names that represent integral value) void: nothing (for functions without a return value) 18
Loop For loop: iterates over certain values composed of 3 statements: 1)int number=1000; 2)number<10000; 3)++number 1) Initialize loop variable: executed once 2) Condition: loop continues as long as the condition is true 3) Increment loop variable: in each iteration #include <iostream> // C++ header file for I/O using namespace std; int main() { int counter = 0; // current number of found four-digit numbers // for every number from 1000 to 9999 for (int number=1000; number<10000; ++number) { // separate the first and last two digits int front = number / 100; // the first two digits int back = number % 100; // the last two digits // if the sum of the squares produce the original number, // output number and increment counter if (front*front + back*back == number) { cout << number << " == " << front << "*" << front << " + " << back << "*" << back << endl; ++counter; // output number of four-digit numbers found cout << counter << " numbers found" << endl; 19
Loops for (int i = 10; i < 10; ++i ) {... int counter = 10; while ( counter < 10 ) {... int counter = 10; do {... while ( counter < 10 ); For loop While loop = pre-test loop preferred when it is possible that the block of code will not be executed Do loop = post-test loop preferred when the block must always be executed (at least once) 20
Loops: break, continue for ( if if // int i = 0; i < 10; i++ ) { ( i == j ) continue; ( i > k ) break; do something break - allows to quit the loop earlier continue - allows to skip one iteration But be careful - it should not be abused (sign of bad programming style) 21
Operators #include <iostream> // C++ header file for I/O using namespace std; int main() { int counter = 0; // current number of found four-digit numbers // for every number from 1000 to 9999 for (int number=1000; number<10000; ++number) { Using operators to separate first two and last two digits: Operator '/' ~ division Operator '%' ~ modulo // separate the first and last two digits int front = number / 100; int back = number % 100; // the first two digits // the last two digits // if the sum of the squares produce the original number, // output number and increment counter if (front*front + back*back == number) { cout << number << " == " << front << "*" << front << " + " << back << "*" << back << endl; ++counter; // output number of four-digit numbers found cout << counter << " numbers found" << endl; 22
Operators Basic operators Basic operators + * / % addition, positive sign subtraction, negative sign multiplication division modulo operator < <= > >= ==!= less than less than or equal to greater than greater than or equal to equal to not equal to && logical AND logical OR! logical negation Increment and Decrement Operators a++ a-++a Assignment Operators: --a = simple assignment += addition -= subtraction *= multiplication /= division... postfix increment postfix decrement prefix increment prefix decrement Bit operators Special operators 23
Tests An if statement checks whether the sum of the squares of two-digits numbers produces the original number Inside if using multiplication (*), addition (+) and equal to (==) operators Note == is different from = #include <iostream> // C++ header file for I/O using namespace std; int main() { int counter = 0; // current number of found four-digit numbers // for every number from 1000 to 9999 for (int number=1000; number<10000; ++number) { // separate the first and last two digits int front = number / 100; // the first two digits int back = number % 100; // the last two digits // if the sum of the squares produce the original number, // output number and increment counter if (front*front + back*back == number) { cout << number << " == " << front << "*" << front << " + " << back << "*" << back << endl; ++counter; // output number of four-digit numbers found cout << counter << " numbers found" << endl; 24
Tests if ( x < 7 ) { cout << x is less than 7 << endl; if ( x < 7 ) { cout << x is less than 7 << endl; else { cout << x is greater than or equal to 7 << endl; The { are not necessary if the expression does not exceed one line But we prefer to include always braces in order to avoid a possible problems when extending the code on more lines 25
Flow Control Chua Hock-Chuan: Programming Notes 26
Code If the condition inside loop is satisfied: An appropriate message is written to the standard output channel: 1233 == 12*12 + 33*33 The counter is increased by one using increment operator: ++counter #include <iostream> // C++ header file for I/O using namespace std; int main() { int counter = 0; // current number of found four-digit numbers // for every number from 1000 to 9999 for (int number=1000; number<10000; ++number) { // separate the first and last two digits int front = number / 100; // the first two digits int back = number % 100; // the last two digits // if the sum of the squares produce the original number, // output number and increment counter if (front*front + back*back == number) { cout << number << " == " << front << "*" << front << " + " << back << "*" << back << endl; ++counter; // output number of four-digit numbers found cout << counter << " numbers found" << endl; 27
Code The result (the value of all numbers found) is then printed at the end of program: X numbers found #include <iostream> // C++ header file for I/O using namespace std; int main() { int counter = 0; // current number of found four-digit numbers // for every number from 1000 to 9999 for (int number=1000; number<10000; ++number) { // separate the first and last two digits int front = number / 100; // the first two digits int back = number % 100; // the last two digits // if the sum of the squares produce the original number, // output number and increment counter if (front*front + back*back == number) { cout << number << " == " << front << "*" << front << " + " << back << "*" << back << endl; ++counter; // output number of four-digit numbers found cout << counter << " numbers found" << endl; 28