You are on page 1of 24

1.

Introduction to C++ programming


Plan
1. Introduction
2. Data types
3. Operators and expressions
4. Control structures : selection and repetition
5. Arrays(one and two dimensional)
6. Strings
7. Functions

2
References
• C++ How to program, Deitel & Deitel, Prentice Hall
• Apprendre le C++, Claude Delannoy; Eyrolles

Site Web : www.deitel.com

3
Introduction
• What is a program?
– A list of instructions that a computer executes
• Why programming ?
– To solve a problem
– To automate a task
• How to program?
– First step - algorithm
• Analyse the problem( program’s objective, inputs, outputs)
• Propose a solution- algorithm: series of steps that solve the problem
• Verify the solution by following the steps defined previously
– Second phase - implementation:
• Traduce the algorithm into a programming language - coding
• Test the program and correct errors - debugging

4
Introduction
• Example of algorithms:
– Sum of two numbers
Enter 2 numbers
Calculate the sum
Output the result on the screen
– Sorting an array
– Find a value in a list
– Modify a file
– Solve a mathematic equation
– …

5
Programming languages
A set of rules , symbols and special keywords used to
construct a program.
Three types of programming languages
1. Machine languages
– Instructions written in binary codes directly
used by the computer
– Binary system
• A bit is the unit used by the computer. It can be 0 or 1
– Corresponds to electricity ‘s being ON/OFF
E.g. : bit 1  5V, bit 0  0V
• A byte = 8bits
– 1Kb is equal to 1000 bits
– 1KB is equal to 1024 bytes
• A word is a group of 16, 32 or 64 bits that a computer processes at
the same time

6
Programming languages
2. Assembly languages
– Use abbreviations or mnemonics from the english language that are
automatically converted to the appropriate sequence of 1s and 0s
– Translation programs that convert Assembly languages to machine
language are called assemblers
Example:
Assembly language: ADD, SUB
Machine language: 00100101, 00010011
3. High-level languages
– Enable programmers to write instructions that look almost like everyday
English and contain common mathematical notations
– Translation programs that convert high-level languages to machine
language are called compiler
– Example of languages: C, C++, Java, Pascal, FORTRAN…
– Example: Totalgrade=finalgrade +midtermgrade

7
Creating a C++ program
1. Editor Editor Disk
Program is created in
the editor and stored


on disk.
Simple text editor:
• wordpad, emacs… Preprocessor Disk
Preprocessor program
processes the code.

– Source code with extension: Compiler creates


• .cpp, .cxx, .C Compiler Disk object code and stores
it on disk.

– Editor + compiler : Microsoft Visual Linker links the object


code with the libraries,
Linker Disk
C++, Borland C++, Dev-C++ creates a.out and
stores it on disk

2. Compilation Primary
Memory
Loader
– Precompilation
Loader puts program
• Execute directives preceded by # in memory.
Disk ..
– To complete the code ..
..

– E.g.: including files Primary


Memory
CPU CPU takes each
instruction and
executes it, possibly
storing new data
values as the program
.. executes.
..
..
8
Creating a C++ program
– Compilation: The compiler traduces Editor Disk
Program is created in
the editor and stored
the C++ program in laguage machine on disk.

(called also object code , with Preprocessor Disk


Preprocessor program
processes the code.
extension .o)
Compiler creates
3. Linker Compiler Disk object code and stores
it on disk.

– Builds links between different object Linker links the object


code with the libraries,
Linker
codes (main and functions) Disk creates a.exe and
stores it on disk

– Produces an executable Primary


Memory
Loader
4. Start the executable
Loader puts program
– loader in memory.
Disk ..
• Loads the executable in memory ..
..

– Execution Primary
Memory
• CPU executes the program one CPU CPU takes each
instruction at a time instruction and
executes it, possibly
storing new data
values as the program
.. executes.
..
..
9
Creatting a C++ program
Enter the program

Compile the program

Yes •Fix the problem


Compilation error ?
No

Execute the program

Yes •Fix the problem


Logic error ?
No

Succes
10
Debugger
• Program integrated in C++ to help error
detection
– Executes the program slowly instruction by
instruction
– Displays the variables of the program while
program is running

11
A simple program:output a text
Program structure:
1. // A first program in C++ 1. Comments
2. #include <iostream>
2. Include iostream
3. Using namespace std;
4. int main() 4. Function main
5. { 6. Print "Welcome to
6. cout << "Welcome to C++!"; C++"
7. return 0; 7. Exit (return 0)
8. }

Program output
Welcome to C++!

12
The body of every function should begin with a left brace {
and terminates with a right brace }. 4 Comments 1
Written between /* et */ or
1. // A first program in C++ after //.
2. #include <iostream>
Clarify the code written.
3. Using namespace std; Computer does not perform
4. int main() any action.
5. {
6. cout << "Welcome to C++!";
7. return 0; 6
return 0 indicates that
8. } the program has terminated
successfully
Welcome to C++! Program output 7
Print the string in quotations.
Compiler directive
A C++ program contains 2 Line 6 that includes cout, the 5
many functions. Main is the Lines that begin with # are compiler operator << and the string
main function directives. "Welcome to C++!" and
The parentheses imply that #include <iostream> notifies the semicolon is
main is a function. the preprocessor to include in the called instruction.
program the content of the
int implies that main input/output stream header file Every instruction must end with
returns an integer value. <iostream> (e.g. print to screen) a semicolon.
3
A simple program: output a text
• cout
– Output object stream
– Associated to the screen
• << (Operator of stream insertion) – "put to"
– Sends information to an output stream
– The value present at the right of the operator is sent to an output
stream
– cout << “Welcome to C++!”;
• \
– Indicates that a special character is output

14
1. include <iostream>
3. main
1 #include <iostream> 5.1 Output "Welcome"
2 using namespace std; 5.2 New line
3 int main() 5.3 Output "to"
4 { 5.4 New line
5 cout << "Welcome\nto\n\nc++!" 5.5 New line
6 return 0; 5.6 Output C++!
7 } 6 Exit (return 0)

Welcome
To
Begins a new line after "\n"
C++

15
Special characters
EscapeSequence Description

\n Newline. Positionthescreencursor tothe


beginningof thenext line.
\t Horizontal tab. Movethescreencursor tothenext
tabstop.
\r Carriagereturn. Positionthescreencursor tothe
beginningof thecurrent line; donot advancetothe
next line.
\a Alert. Soundthesystembell.
\\ Backslash. Usedtoprint abackslashcharacter.
\" Doublequote. Usedtoprint adoublequote
character.

16
Another simple program: addition of
• cin
two numbers
• Input object stream
• >> (operator of stream extraction) - "get from"
– Used with cin, it waits until the user enters a value and stores it in
memory
– The use enters a value and Press « Enter » to send data to the computer
– Example:
int myVariable; // declaration
cin >> myVariable;
• Waits until the user enters a value and stores it in myvariable
• = (assignment operator)
– Attributes a value to a variable
– Binary operators (has two operanads)
– Example:
sum = variable1 + variable2;

17
Program structure
1// Addition program 2. loading <iostream>
2#include <iostream> 4. main
3 using namespace std; 6 variables declaration integer1,
u integer2, and sum
4 int main() 7 Printing "Enter first
5{ integer"
6 int integer1,integer2, sum; 7.1 Enter
7 cout << "Enter first integer:"; 8 Printing"Enter second
prompt
8 cin >> integer1; integer"
9 cout << "Enter second integer:"; 8.1 Enter
// 11 Adding the variables and put the
10 prompt
cin >> integer2; result in sum
11 sum=integer1+ integer2; 12 Printing"Sum is«
12 cout<<« Sum is:« <<endl <<sum; 12.1 Put sum
13 return 0; 13 End (return 0)
14 }
Enter first integer :45
Enter second integer: 72
Sum is
117
1//
2// Addition program
3#include <iostream>
4using namespace std;
5int main()
6{
7 int integer1, integer2, sum; //declaration
8 cout << "Enter first integer"; // prompt
9 cin >> integer1; // read an integer
10 cout << "Enter second integer"; // prompt
11 cin >> integer2; // read an integer
12 sum = integer1 + integer2;// assignment of sum
13 cout << "Sum is " << endl<<sum ; // print sum
14
15 return 0;
16} Output the variable using cout <<
variableName.
Enter first integer: 45
Enter second integer: 72 endl produces a newline and
Sum is empties the buffer
117
Notice how cin is used to get a value from the
user.
Variables and constants
• Variables
– Location in memory whose value can change
• Constant
– Location in memory whose value cannot
change
Variables and constants should be declared before they can
be used in a program by defining their name and their type
Example of declaration of a variable of type
integer : Trace:
int x=2 ; x Output:
x=x+1; 2 6
x=x*2; 3
cout << x ; 6

20
Variables and constants
Example of declaration of a constant of type float:
Write a program that reads the radius of a circle and display the perimeter and
the area of the circle. Use the constant π number 3.14159
# include<iostream>
using namespace std;
int main(){
const float pi=3.14159;
float perim, area,rad;
cout<<"Enter the circle radius:" ;
cin>>rad;
perim=2*pi*rad;
area=pi*rad*rad;
cout<<"The perimeter is:" <<perim;
cout<<" \nThe area is:" <<area;
Return 0;
}

Remark: PI = PI + 1 ;// False

21
Remark on constants
• We cannot modify a constant
– E.g.: const float PI=3.14159; // True
PI = PI + 1 ;// False
E.g. : const int W=15; // True
W=8 ; // False
– E.g.: const int C; // False
C=10; // False

22
Identifier and declaration
• An identifier is the name associated to a
variable, a constant or a function
• C++ has reservered keywords that cannot be
used as identifier
– E.g. : int and return are 2 keywords
• C++ distinguishes between lower-case
letters and upper-case letters:
– variable x is different than X
• A declaration is the association of an
identifier to a data type
– E.g. : int x ;
• Declare x as type integer
Identifiers recommendation
Invalid Identifier Explanation

var int spaces are not allowed

x-2 the "–" symbol is a mathematic operator

cost$ special characters like $ are not allowed

integer the keyword "integer" is a reserved keyword


Note that a variable can contain the underline "_" symbol
•E.g. : x_1 is a valid identifier

You might also like