Vous êtes sur la page 1sur 34

C++ PROGRAMMING SKILLS

Part 1
Basics of C++
• C++ Overview
• Elements
• I/O
• Assignment and Comments
• Formatted Output
++History of C and C
BCPL 1967 B :By Ken Thompson
By Martin Richards Used to create early UNIX
Lang. to write OS @ Bell lab's 1970
NO Data Type + NO Data Type

C :By Dennis Ritchie @ Bell OO Features


lab’s
UNIX written in C- +
HW Independent-
many versions in late 1970’s-

C++: By Bjarne Stroustrap


Standard ANSI C
+ Early 1980s @ Bell lab’sُ
In 1980 was approved
Provides OO programming
OO Features +

Java: In 1995 by
Sun Microsystems
Arithmetic
• Arithmetic calculations
– Use * for multiplication and / for division
– Integer division truncates remainder
• 7 / 5 evaluates to 1
– Modulus operator returns the remainder
• 7 % 5 evaluates to 2
• Operator precedence
– Some arithmetic operators act before others (i.e., multiplication before
addition)
• Be sure to use parenthesis when needed
– Example: Find the average of three variables a, b and c
• Do not use: a + b + c / 3
• Use: (a + b + c ) / 3
Arithmetic
• Arithmetic operators:
C ++ o p e ra tio n Arith m e tic Alg e b ra ic C ++ e xp re ssio n
o p e ra to r e xp re ssio n
Addition + f+7 f + 7
Subtraction - p–c p - c
Multiplication * bm b * m
Division / x/y x / y

Modulus % r mod s r % s

• Rules of operator precedence:


Operator(s) Operation(s) Order of evaluation (precedence)

() Parentheses Evaluated first. If the parentheses are nested, the


expression in the innermost pair is evaluated first. If
there are several pairs of parentheses “on the same level”
(i.e., not nested), they are evaluated left to right.
*, /, or % Multiplication Division Evaluated second. If there are several, they re
Modulus evaluated left to right.
+ or - Addition Evaluated last. If there are several, they are
Subtraction evaluated left to right.
Equality and Relational Operators

Sta n d a rd a lg e b ra ic C ++ e q u a lity Exa m p le Me a n in g o f


e q u a lity o p e ra to r o r o r re la tio n a l o f C ++ C ++ c o n d itio n
re la tio n a l o p e ra to r o p e ra to r c o n d itio n

Relational operators
> > x > y x is greater than y
< < x < y x is less than y

 >= x >= y x is greater than or equal to y

 <= x <= y x is less than or equal to y

Equality operators
= == x == y x is equal to y

 != x != y x is not equal to y
Logical Operators
Truth Table Meaning Operator in C++

OUTPUT INPUT
Exp1 Exp2
F F F
F F T Logical AND
F T F
&&
T T T
F F F
T F T Logical OR
T T F
||
T T T
T F Logical NOT !
F T
Operators Precedence update
Operator(s) Operation(s) Order of evaluation (precedence)

() Parentheses Evaluated first. If the parentheses are nested, the expression


in the innermost pair is evaluated first. If there are several
pairs of parentheses “on the same level” (i.e., not nested),
they are evaluated left to right.
!, +, - Logical NOT, signs Evaluated second. If there are several, they re
evaluated right to left.
*, /, or % Multiplication Division Evaluated third. If there are several, they re
Modulus evaluated left to right.
+ or - Addition Evaluated fourth. If there are several, they are
Subtraction evaluated left to right.
>, <, >=, <= Relational Operators Evaluated fifth. If there are several, they are
evaluated left to right.
==, != Equality Operators Evaluated sixth. If there are several, they are
evaluated left to right.
&& Logical AND Evaluated seventh. If there are several, they are
evaluated left to right.
|| Logical OR Evaluated eighth. If there are several, they are
evaluated left to right.
Memory Concepts

• Variable names
– Correspond to locations in the computer's memory
– Every variable has a name, a type, a size and a value
– Whenever a new value is placed into a variable, it replaces
the previous value - it is destroyed
– Reading variables from memory does not change them
• A visual representation

integer1 45
Variable Names (Identifiers)
• Letter + {Letters and/or Digits and/or ( _ ) Naming Convention(Style)

• _ +Letter+{Letters and/or Digits and/or ( _ ) Variables LengthInYard , hours


Functions CalcAverage , Cube(27)
Constant MAX_HOUR , LIMIT
Underscore character ( _ )

Correction Explanation ? Invalid


forty_Hours , hours40 Begin with a digit 40Hours

get_Date , getDate Blanks not allowed Get Date

box_22 , box22 The hyphen(-) is minus Box-22

costInUSDollar Special symbols not cost_in_$


allowed
int_1 Reserved word in C++ int
Data Types
• short int :Range of values ( ±32,767 ).
• long int :Range of values ( ±2,147,483,647 ).
• int : Integer numbers
• float: floating point used for working with real numbers.
• double: is a floating point type much like float , but it can store a value of
much greater magnitude with greater precision.
• Bool*: is a boolean data type can take two value TRUE or FALSE.
*Note:- bool data type is provided by ANSI/ISO C++ standard. It is undefined in Borland Turbo C++.

• char: character data type (alpha,digit,special-symbol or space).


A single character with its value quoted with single-quotation
egs. ‘A’ , ‘a’ , ‘$’ , ‘ ‘ , ‘8’

Letter S.Symbol Space Digit

• string: for working with multiple characters including letters, numbers ,


special symbols and spaces its value quoted with double- quotation.
egs. “C++” , “Computer Science” , “ “.
Declaration of Variables Constant Variables

Data Type Identifier1, Identifier2,…; const Data Type Identifier=value;

:Examples and preference :Examples

char Letter, middleInt , ch; const string STARS=“*****”;


const char ch=‘$‘;
char Letter; const float MAX_Hour=40.0
char middleInt;
char ch;
Assignment Statement
Variable = Expression ;

 Store the value of the Expression into the variable, any previous value of the variable
is destroyed.
Example:Giving the declarations
string firstname;
;”firstname=“Sara
char letter; ;num = 5 Valid Assignment
int num; ;num=5*5-3
’letter=‘S

;firstname=Sara
;=firstname Invalid Assignment
letter=S

Remark :Double or more assignment allowed and precedence from Right-to-Left


eg. N1=n2=n3=5;
Output statement
cout << Constant | Variable | Expression <<Expr2…; | means or

Example: Given ch=‘2’ and firstname=“Ali”


and lastname=“Ahmad” The Output
cout<<ch; 2
cout<<“ch=“<<2; ch=2
cout<<firstname<<” “<<lastname; Ali Ahmad
cout<<“Erorr#”<<ch; Error#2
cout<<“\”Hello!\” ”; “Hello!”
To print 2 words on separate lines use <<endl
Example:
cout<<“He ”;
cout<<“There”; Hi There

cout<<“Hi”<<endl;
cout<<“There”<<endl; Hi
There
Comments
..……Text..………… */
For Multiple Lines
/* ……… Text .……………

………… Text ………… // For Single Line

The compiler ignores comments (Not executable)

• C++ Preprocessor
 #include<iostream> :- This line known as Preprocessor Directive its not
handled by C++ compiler but by a program known as Preprocessor.
 iostream :- Header file contains declarations of I/O facilities.
 Preprocessor program acts as a filter before compilation.

Source program Expanded Source


Preprocessor C++ Compiler
program
Input statement
;… cin >> variable1 >> variable2
It needs #include<iostream> preprocessor directive that contain istream cin
.ostream cout
Example:-
-:1
;cin>>Length>>width
;cin>>Length The Same
;cin>>width
-:2
Statement Data Contents after input
cin>>i>>ch>>x; 25 A 16.9 i=25 ch=‘A’ x=16.9

-:3
cin>>i>>j>>x; 12 8 i=12 j=8 (computer wait for the third number)
-:4
cin>>i>>x; 46 32.4 15 i=46 j=32.4 (15 is held for later input)
New line character ‘\n’ is considered one character
eg. cout<<“Hello!\n”; The Same
cout<<“Hello!”<<endl;
Input statement(cont.)
• Note :- can’t input SPACE character , the >> skips white space
(blank) character.

• cin.get() FUNCTION READS ONE CHARACTER FROM THE


KEYBOARD (Does not skips space characters)

eg.
ch1=cin.get() R cin>>ch1
ch2= cin.get() ch2=cin.get()
ch3=cin.get() 1 cin>>ch3

Given input: R 1
Operators Precedence update
Operator(s) Operation(s) Order of evaluation (precedence)

() Parentheses Evaluated first. If the parentheses are nested, the expression in the
innermost pair is evaluated first. If there are several pairs of
parentheses “on the same level” (i.e., not nested), they are evaluated
left to right.
!, +, - Logical NOT, signs Evaluated second. If there are several, they are evaluated right to left.

*, /, or % Multiplication Division Evaluated third. If there are several, they are evaluated left to right.
Modulus
+ or - Addition Evaluated fourth. If there are several, they are evaluated left to right.
Subtraction
>>, << Input steam extraction and Evaluated fifth. If there are several, they are evaluated left to right.
output stream insertion
>, <, >=, <= Relational Operators Evaluated sixth. If there are several, they are evaluated left to right.

==, != Equality Operators Evaluated seventh. If there are several, they are evaluated left to right.
&& Logical AND Evaluated eighth. If there are several, they are evaluated left to right.
|| Logical OR Evaluated nineth. If there are several, they are evaluated left to right.
= Assignment Evaluated tenth. If there are several, they are evaluated right to left.
Phases of C++ Programs
:C++ program development goes through six steps
• Step1: Edit (using text editor to type, correct and save the program
file).
• Step2: preprocessor, automatically before compile, executes to
include other text files in the file to be compiled.
• Step3: Compile , the compiler translates the C++ code into
machine language (also called object-code).
• Step4: Link , it is linking any used functions that are defined
elsewhere such as standard library functions, or private library for a
group of programmers, linker, links the object code with the code
for the missing functions to provide full code
• Step5: Load, a program before executing , must be loaded into the
main memory, loader does this task , loading code from disk.
• Step6: Execute, the computer under the control of its CPU
executes the program. Instruction by instruction.
illustration of C++ Program Phases

Phases of C++ Programs: Editor Disk


Program is created in
the editor and stored
on disk.

1. Edit Preprocessor Disk


Preprocessor program
processes the code.

Compiler creates
2. Preprocess Compiler Disk object code and stores
it on disk.
Linker links the object
code with the libraries,
3. Compile Linker Disk creates a.out and
stores it on disk
main

4. Link
Memory
Loader

Loader puts program


in memory.
5. Load Disk ..
..
..

6. Execute main
Memory
CPU CPU takes each
  instruction and
executes it, possibly
storing new data
..
values as the program
.. executes.
..
Structure of C++ program
• Every C++ program must have a function named main. The programmer can choose to
decompose the program into several parts (user-defined functions). Think of main as the
master and the other functions are the servants.
• The execution always starts with main.

Preprocessor Directive Header file facilitate


#include <iostream.h>
I/O
int main( )
Type of returned value { Declarations ;

Executable Statement_1 ;
Marks the start of the Executable Statement_2 ;
main function (program) :
Executable Statement_n ;

return 0;
}
Returning 0 means
Marks the end of the every things is OK
main function (program) else(1,2,..) something
went wrong (Exit Status)
C++ Programming Examples

• C++ language
– Facilitates a structured and disciplined
approach to computer program design

• Following are several examples


– The examples illustrate many important
features of C++
– Each example is analyzed one statement at a
time.
1 // Fig. 1.2: fig01_02.cpp Comments

2 // A first program in C++ Written between /* and */ or following a //.

3 #include <iostream.h>
Improve program readability and do not cause the computer to
perform any action.
4
preprocessor directive
5 int main() Message to the C++ preprocessor.
6 { Lines beginning with # are preprocessor directives.
7 cout << "Welcome to C++!\n"; #include <iostream.h> tells the preprocessor to include
the contents of the file <iostream.h>, which includes
8 input/output operations (such as printing to the screen).
9 return 0; // indicate that program ended successfully
C++ programs contain one or more functions, one of which must
10 }
be main
Parenthesis are used to indicate a function
Welcome to C++! int means that main "returns" an integer value.

return is a way to exit a function from a


function. Prints the string of characters contained between the quotation
marks.
return 0, in this case, means that the The entire line, including cout, the << operator, the string
program terminated normally. "Welcome to C++!\n" and the semicolon (;), is called a
1. Comments statement.
2. Load <iostream.h> All statements must end with a semicolon.
3. main A left brace { begins the body of every function
3.1 Print "Welcome to C++\n" and a right brace } ends it.
3.2 exit (return 0)
A Simple Program: Printing a Line of Text
• cout
– Standard output stream object
– “Connected” to the screen
• <<
– Stream insertion operator
– Value to the right of the operator (right operand) inserted
into output stream (which is connected to the screen)
– cout << “Welcome to C++!\n”;
• \
– Escape character
– Indicates that a “special” character is to be output
A Simple Program: Printing a Line of Text

Escape Sequence Description

\n Newline. Position the screen cursor to the


beginning of the next line.
\t Horizontal tab. Move the screen cursor to the next
tab stop.
\r Carriage return. Position the screen cursor to the
beginning of the current line; do not advance to the
next line.
\a Alert. Sound the system bell.
\\ Backslash. Used to print a backslash character.
\" Double quote. Used to print a double quote
character.

• There are multiple ways to print text


– Following are more examples
1 // Fig. 1.4: fig01_04.cpp

2 // Printing a line with multiple statements


1. Load
<iostream.h>
3 #include <iostream.h>

4 2. main
5 int main()

6 { 2.1 Print "Welcome"


7 cout << "Welcome ";

8 cout << "to C++!\n";


2.2 Print "to C++!"

9
2.3 newline
10 return 0; // indicate that program ended successfully

11 }
2.4 exit (return 0)

Welcome to C++! Program Output

Unless new line '\n' is specified, the text continues


on the same line.
1 // Fig. 1.5: fig01_05.cpp

2 // Printing multiple lines with a single statement 1. Load <iostream.h>

3 #include <iostream.h>
2. main
4

5 int main() 2.1 Print "Welcome"


6 {
2.2 newline
7 cout << "Welcome\nto\n\nC++!\n";

8
2.3 Print "to"
9 return 0; // indicate that program ended successfully

10 } 2.4 newline

2.5 newline
Welcome
to
  2.6 Print "C++!"
C++!

Multiple lines can be printed with one 2.7 newline


statement.
2.8 exit (return 0)

Program Output
Another Program: Adding Two Integers
• >> (stream extraction operator)
– When used with cin, waits for the user to input a value and
stores the value in the variable to the right of the operator
– The user types a value, then presses the Enter (Return) key to
send the data to the computer
– Example:
int myVariable;
cin >> myVariable;
• Waits for user input, then stores input in myVariable
• = (assignment operator)
– Assigns value to a variable
– Binary operator (has two operands)
– Example:
sum = variable1 + variable2;
1 // Fig. 1.6: fig01_06.cpp
2 // Addition program
1. Load <iostream>
3 #include <iostream.h>
Notice how cin is used to get user input. 2. main
4
5 int main()
2.1 Initialize variables
6 { integer1,
7 int integer1, integer2, sum; // declaration integer2, and sum
8
9 cout << "Enter first integer\n"; // prompt 2.2 Print "Enter first
10 cin >> integer1; // read an integer integer"
11 cout << "Enter second integer\n"; // prompt 2.2.1 Get input
12 cin >> integer2; // read an integer
13 sum = integer1 + integer2; // assignment of sum 2.3 Print "Enter
14 cout << "Sum is " << sum << endl; // print sum second integer"
15 2.3.1 Get input
16 return 0; // indicate that program ended successfully 2.4 Add variables and put
result into sum
17 }
endl flushes the buffer and prints a 2.5 Print "Sum is"
newline. 2.5.1 Output sum
Enter first integer
45
Enter second integer 2.6 exit (return 0)
72 Variables can be output using
Sum is 117
cout << variableName. Program Output
Built-in (Library) Function
Function Exponentiation
pow (x, y) x is raised to power y; (xy )
sqrt (x) Square-root of x
sin (x) Sine of x ‫جا‬
cos (x) Cosine of x ‫جت```ا‬
tan (x) Tangent of x ‫ظا‬
exp (x) Exponentiation of x, ( ex)
fabs (x) Absolute Value of x, | x |
log (x) Logarithm of x (base e)
log10 (x) Logarithm of x (base 10)
floor (x) Rounding-down x
ceil (x) Rounding-up x
______etc. {there are more}_______________________
Eg.1. floor (9.2) = 9.0
Eg.2. floor (-9.8) = -10.0
 Remark:you need to include <math.h> to be able to use these
functions. In newer versions it is #include<cmath>
Good Programming practices
 Keep it simple do not “stretch” the language.
 Read C++ manual.
 Experiment a feature by writing a simple program and test it.
 Start your program with a comment to indicate what the program
does?
 Use new line \n to make output more organized.
 Indent the body of each function one level, more indents for nesting.
 Choose meaningful variables, constants and function names.
 Use spaces after commas, operators and new lines between
declaration and executable statement.
 One statement per line.
Note: The function time(0) returns the current calendar time in seconds
calculated from 1970.
It needs: #include<time.h> // turbo C++
#include<ctime> // Visual C++
Common programming Errors
 Divide by zero.
 Not including iostream for input/output operations.
 Forgetting the (;) at end of each statement.
 Using % with non-integer.
 If a space found between the pair-of-symbols for the
relational operators. (i.e., > = instead of >= ).
 Confusing the equality == with the assignment =.
 Reversing the order of the relational operators
(i.e., => isntead of >=).
Formatted Output
• setw can be used to specify the width of the field that the next value of output
will be printed in. To use it, you must include <iomanip.h> header file.
eg1:-
int num=12;
cout<< setw(4) << num; //num will be printed in a field width of 4 character.
1 2
eg2:-
int n1=12;
int n2=197;
cout<<setw(5)<< n1 << setw(6) << n2;
1 2 1 9 7
eg3:- (if the value is more than the specified setw value the compiler ignores the setw
effect and print it with the minimum number of positions required.)
int num=1977;
cout<<setw(3)<<num;

1 9 7 7
Formatted Output(cont…1)
precision and setprecision for printing formatted floating point values
You may set the Number of Digits that appear on the right of the decimal-point the way
you like it to be.
 it can be done by either setprecision stream manipulator, or precision member function.
eg. Using both to output the square root of 2

#include<iostream.h>
#include<iomanip.h>
#include<math.h>
int main( )
{
double root2=sqrt(2.0);
int places;
cout<<"square root of 2 with precision 0-9\n";
cout<<" using precision member function:\n";
for(places=0;places<=9;places++)
{
cout.precision(places);
cout << root2<<"\n";
}
cout<<"Using setprecision manipulator:\n";
for(places=0;places<=9;places++)
cout<<setprecision(places)<<root2<<"\n";
return 0;
}
Formatted Output(cont…2)
Output
Square root of 2 with precision 0-9 using precision member function
1
1.4
1.41
1.414
1.4142
1.41421
1.414214
1.4142136
1.41421356
1.414213562
Using setprecision manipulator
1
1.4
1.41
1.414
1.4142
1.41421
1.414214
1.4142136
1.41421356
1.414213562

Vous aimerez peut-être aussi