c++ basics - ipn orsayipn€¦ · · 2018-01-04i. hrivnacova @ data processing course 2018 2 c++...
TRANSCRIPT
I. Hrivnacova @ Data Processing Course 2018 1
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
I. Hrivnacova @ Data Processing Course 2018 2
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 object-oriented extension. The OO extension facilitates design, reuse and maintenancefor 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, theStandard Template Library (STL).
I. Hrivnacova @ Data Processing Course 2018 3
C++ Standards
● C++ is standardized as ISO/IEC 14882. Currently, there are twoversions:– 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 tothe language. Commonly refer to as C++98/C++03 or First C++ standard.
– C++11 (ISO/IEC 14882:2011): 2nd standard version of C++. Formerlycalled C++0x, as it was expected to finalize in 200x. It adds somenew features to the language; more significantly, it greatly extendsthe C++ standard library and standard template library (STL).
● We will use some features introduced in C++11 in our course, too
I. Hrivnacova @ Data Processing Course 2018 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; }
I. Hrivnacova @ Data Processing Course 2018 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; }
Comments: ● /* */ - can span over several lines or be inserted in the code on one line● // - lasts to the end of the line
I. Hrivnacova @ Data Processing Course 2018 6
C++ Program
Include statement(s): ● Including all necessary declarations for input and output
/* The first C++ program * - just outputs 'Hello, World !' */
#include <iostream>
int main() { // print “Hello, World !” on the screen std::cout << “Hello, World !” << std::endl; }
I. Hrivnacova @ Data Processing Course 2018 7
C++ Program
The main function● called at the program startup, leaving main() ends the 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; }
I. Hrivnacova @ Data Processing Course 2018 8
C++ Program
A statement ending with a semicolon;● It writes the string “Hello, World !” followed by std::endl symbol,
to the standard output
/* The first C++ program * - just outputs 'Hello, World !' */
#include <iostream>
int main() { // print “Hello, World !” on the screen std::cout << “Hello, World !” << std::endl; }
I. Hrivnacova @ Data Processing Course 2018 9
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
I. Hrivnacova @ Data Processing Course 2018 10
Input and Output (IO)
● C/C++ IO are based on streams,which are sequence of bytesflowing in and out of the programs(just like water and oil flowingthrough a pipe).– In input operations, data bytes flow
from an input source (such askeyboard, file, network or anotherprogram) into the program.
– In output operations, data bytesflow from the program to an outputsink (such as console, file, networkor another program).
Chua Hock-Chuan: Programming Notes
I. Hrivnacova @ Data Processing Course 2018 11
Input and Output
● The input/output (I/O) functionality isprovided in components of standardlibrary
● To get these components known tothe program:– #include <iostream>
● Standard channels to provideinput/output:– Generally assigned to the keyboard
(input) and the screen (output)
– Can be redirected by the operatingsystem to a file
● Symbols– std::cin - input channel (the
keyboard)
– std::cout - output channel (thescreen)
– std::endl - line break (new line)
● << operator :– Send data to the output channel
● >> operator :– Read data from an input channel
I. Hrivnacova @ Data Processing Course 2018 12
Namespaces
● The prefix std:: is used for all symbols of the standardlibrary
● Using the namespace concept, symbols can be groupedlogically within a package (or a component)
● Avoids names clashes in large program
● using namespace directive can be used to make all symbolsfrom a namespace available without std:: prefix
#include <iostream>
using namespace std;
cout << “Hello, World !” << std;
I. Hrivnacova @ Data Processing Course 2018 13
“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 thefollowing condition
● If you split a four digits number into two parts each having twodigits and add the squares of these numbers, you get theoriginal four digit number:– Eg. 1233 = 12*12 + 33*33
I. Hrivnacova @ Data Processing Course 2018 14
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;}
I. Hrivnacova @ Data Processing Course 2018 15
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) {
// 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;}
A variable counter is defined to counthow many four-digitnumbers were found:● int ~ type● counter ~ name● = 0 ~ initialized to
the value 0
I. Hrivnacova @ Data Processing Course 2018 16
Variable
● It allocates memory● The current memory content
is its value ● counter has the value 0● The size of memory
allocated and the operationswe can do with a variableare defined by its type
counter 0 int
NAME VALUE TYPE
number 1556 int
pi 3.141592 double
A variable has a name, stores a value of the declared type
I. Hrivnacova @ Data Processing Course 2018 17
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'
I. Hrivnacova @ Data Processing Course 2018 18
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)
I. Hrivnacova @ Data Processing Course 2018 19
Loop#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;}
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: loopcontinues as long asthe condition is true
3) Increment loopvariable: in eachiteration
I. Hrivnacova @ Data Processing Course 2018 20
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 thatthe block of code will not beexecuted
● “Do” loop = post-test loop
– preferred when the block mustalways be executed (at leastonce)
I. Hrivnacova @ Data Processing Course 2018 21
Loops: break, continue
● break - allows to quit theloop earlier
● continue - allows to skipone iteration
● But be careful - it should notbe abused (sign of “bad”programming style)
for ( int i = 0; i < 10; i++ ) { if ( i == j ) continue; if ( i > k ) break; // do something }
I. Hrivnacova @ Data Processing Course 2018 22
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) {
// 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;}
Using operators toseparate first two andlast two digits:● Operator '/'
~ division● Operator '%'
~ modulo
I. Hrivnacova @ Data Processing Course 2018 23
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
Basic operators
&& logical AND|| logical OR! logical negation
Assignment Operators:
= simple assignment+= addition-= subtraction*= multiplication/= division ...
Increment andDecrement Operators
a++ postfix incrementa-- postfix decrement++a prefix increment--a prefix decrement
Bit operators
Special operators
I. Hrivnacova @ Data Processing Course 2018 24
Tests#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;}
An if statement checks whether thesum of the squares oftwo-digits numbersproduces the originalnumber● Inside if using
multiplication (*),addition (+) andequal to (==) operators
● Note == is differentfrom =
I. Hrivnacova @ Data Processing Course 2018 25
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
I. Hrivnacova @ Data Processing Course 2018 27
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;}
If the condition insideloop is satisfied:● An appropriate
message is writtento the standardoutput channel:
1233 == 12*12 +33*33
● The counter isincreased by oneusing incrementoperator:
++counter
I. Hrivnacova @ Data Processing Course 2018 28
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;}
The result (the valueof all numbers found) isthen printed at the endof program: X numbers found