際際滷

際際滷Share a Scribd company logo
Elementary C
Elementary C+
+
+
+ Programming
Programming
panupong@kku.ac.th
panupong@kku.ac.th
2
// Sample program
// Reads values for the length and width of a rectangle
// and returns the perimeter and area of the rectangle.
#include <iostream.h>
void main()
{
int length, width;
int perimeter, area; // declarations
cout << "Length = "; // prompt user
cin >> length; // enter length
cout << "Width = "; // prompt user
cin >> width; // input width
perimeter = 2*(length+width); // compute perimeter
area = length*width; // compute area
cout << endl
<< "Perimeter is " << perimeter;
cout << endl
<< "Area is " << area
<< endl; // output results
} // end of main program
3
The following points should be
The following points should be
noted in the above program:
noted in the above program:
 Any text from the symbols // until
the end of the line is ignored by the
compiler.
 The line #include <iostream.h>
This statement is a compiler directive
-- that is it gives information to the
compiler but does not cause any
executable code to be produced.
4
The following points should be
The following points should be
noted in the above program:
noted in the above program:
 The actual program consists of the
function main which commences at
the line void main() All programs
must have a function main.
 The body of the function main
contains the actual code which is
executed by the computer and is
enclosed, as noted above, in braces
{}.
5
The following points should be
The following points should be
noted in the above program:
noted in the above program:
 Every statement which instructs the
computer to do something is
terminated by a semi-colon ;.
 Sequences of characters enclosed in
double quotes are literal strings.
Thus instructions such as
cout << "Length = "
send the quoted characters to the output stream cout.
6
The following points should be
The following points should be
noted in the above program:
noted in the above program:
 All variables that are used in a program
must be declared and given a type. In this
case all the variables are of type int, i.e.
whole numbers. Thus the statement
int length, width;
 Values can be given to variables by the
assignment statement, e.g. the statement
area = length*width;
7
The following points should be
The following points should be
noted in the above program:
noted in the above program:
 Layout of the program is quite
arbitrary, i.e. new lines, spaces etc.
can be inserted wherever desired
and will be ignored by the compiler.
8
Variables
Variables
 A variable is the name used for the
quantities which are manipulated by
a computer program.
 In order to distinguish between
different variables, they must be
given identifiers, names which
distinguish them from all other
variables.
9
The rules of C++ for
The rules of C++ for
valid identifiers
valid identifiers
 An identifier must:
 start with a letter
 consist only of letters, the digits 0-9, or
the underscore symbol _
 not be a reserved word
Reserved words are otherwise valid identifiers that
have special significance to C++.
 use of two consecutive underscore
symbols, __, is forbidden.
10
Identifiers
Identifiers
 The following are valid identifiers
Length days_in_year DataSet1
Profit95 Int_Pressure
first_one first_1
 although using _Pressure is not
recommended.
 The following are invalid:
days-in-year 1data
int first.val throw
11
Identifiers
Identifiers
 Identifiers should be meaningful
 C++ is case-sensitive. That is lower-
case letters are treated as distinct
from upper-case letters.
 Thus the word main in a program is
quite different from the word Main or
the word MAIN.
12
Reserved words
Reserved words
and and_eq asm auto bitand
bitor bool break case catch
char class const const_cast continue
default delete do double dynamic_cast
else enum explicit export extern
false float for friend goto
if inline int long mutable
namespace new not not_eq operator
or or_eq private protected public
register reinterpret_cast return short signed
sizeof static static_cast struct switch
template this throw true try
typedef typeid typename union unsigned
using virtual void volatile wchar_t
while xor xor_eq
13
Declaration of variables
Declaration of variables
 In C++ all the variables that a program is
going to use must be declared prior to
use.
 Declaration of a variable serves two
purposes:
 It associates a type and an identifier (or name)
with the variable. The type allows the compiler
to interpret statements correctly.
 It allows the compiler to decide how much
storage space to allocate for storage of the
value associated with the identifier and to
assign an address for each variable which can
be used in code generation.
14
Variable Types
Variable Types
 int
 float
 bool
 char
15
int
int
 int variables can represent negative and positive
integer values (whole numbers).
 There is a limit on the size of value that can be
represented, which depends on the number of
bytes of storage allocated to an int variable by
the computer system and compiler being used.
 On a PC most compilers allocate two bytes for
each int which gives a range of -32768 to
+32767.
 On workstations, four bytes are usually allocated,
giving a range of -2147483648 to 2147483647.
 It is important to note that integers are
represented exactly in computer memory.
16
float
float
 float variables can represent any real numeric
value, that is both whole numbers and numbers
that require digits after the decimal point.
 The accuracy and the range of numbers
represented is dependent on the computer
system.
 Usually four bytes are allocated for float
variables, this gives an accuracy of about six
significant figures and a range of about -1038
to
+1038
.
 It is important to note that float values are only
represented approximately.
17
bool
bool
 bool variables can only hold the
values true or false.
 These variables are known as
boolean variables in honour of
George Boole, an Irish
mathematician who invented boolean
algebra.
18
char
char
 char variables represent a single
character -- a letter, a digit or a
punctuation character.
 They usually occupy one byte, giving
256 different possible characters.
 The bit patterns for characters
usually conform to the American
Standard Code for Information
Interchange (ASCII).
19
Examples of values for such
Examples of values for such
variables are:
variables are:
 int 123 -56 0 5645
 float 16.315 -0.67 31.567
 char '+' 'A' 'a' '*' '7'
20
Variable Declarations
Variable Declarations
 A typical set of variable declarations that
might appear at the beginning of a
program could be as follows:
int i, j, count;
float sum, product;
char ch;
bool passed_exam;
 which declares integer variables i, j and
count, real variables sum and product, a
character variable ch, and a boolean
variable pass_exam.
21
A variable declaration has
A variable declaration has
the form:
the form:
type identifier-list;
 Type specifies the type of the variables
being declared.
 The identifier-list is a list of the identifiers
of the variables being declared, separated
by commas
 Variables may be initialized at the time of
declaration by assigning a value to them
22
Examples
Examples
int i, j, count = 0;
float sum = 0.0, product;
char ch = '7';
bool passed_exam = false;
23
Constants and the
Constants and the
declaration of constants
declaration of constants
 Often in programming numerical constants
are used, e.g. the value of 其.
 It is well worthwhile to associate
meaningful names with constants.
 These names can be associated with the
appropriate numerical value in a constant
declaration.
 The names given to constants must
conform to the rules for the formation of
identifiers as defined above.
24
Constants and the
Constants and the
declaration of constants
declaration of constants
const int days_in_year = 365;
 defines an integer constant days_in_year which has the
value 365.
 Later in the program the identifier days_in_year can be
used instead of the integer 365, making the program far
more readable.
The general form of a constant declaration is:
const type constant-identifier = value ;
25
General form of a C++
General form of a C++
Program
Program
// Introductory comments
// file name, programmer, when written or modified
// what program does
#include <iostream.h>
void main()
{
constant declarations
variable declarations
executable statements
}
26
Input and Output
Input and Output
 Input and output use the input
stream cin and the output stream
cout.
 The input stream cin is usually
associated with the keyboard
 The output stream cout is usually
associated with the monitor.
27
cin
cin
The following statement waits for a number to be
entered from the keyboard and assigns it to the
variable number:
cin >> number;
The general form of a statement to perform input
using the input stream cin is:
cin input-list;
where input-list is a list of identifiers, each identifier
preceded by the input operator >>.
28
cin
cin
cin >> n1 >> n2;
would take the next two values entered by the user and
assign the value of the first one to the variable n1 and the
second to the variable n2.
User enter
10 20 <ENTER>
10 <ENTER>
20<ENTER>
10 20 30 <ENTER>
29
cout
cout
 The following statement outputs the current value
of the variable count to the output stream cout
cout << count;
 The general form of a statement to perform
output using the output stream cout is:
cout output-list;
where output-list is a list of variables, constants, or
character strings in quotation marks, each
preceded by the output operator <<.
30
cout
cout
cout << "Hello there" << endl;
 will print Hello there on the current
output line and then take a new line
for the next output.
31
Example
Example
float length, breadth;
cout << "Enter the length and breadth: ";
cin >> length >> breadth;
cout << endl << "The length is " << length;
cout << endl << "The breadth is " << breadth << endl;
will display, if the user enters 6.51 and 3.24 at the
prompt, the following output:
The length is 6.51
The breadth is 3.24
32
Example
Example
 Note that a value written to cout will be printed
immediately after any previous value with no
space between.
 In the above program the character strings
written to cout each end with a space character.
The statement
cout << length << breadth;
would print out the results as 6.513.24
 which is obviously impossible to interpret
correctly. If printing several values on the same
line remember to separate them with spaces by
printing a string in between them as follows:
cout << length << " " << breadth;
33
Programming Style
Programming Style
 any number of spaces and or new
lines can be used to separate the
different symbols in a C++ program.
 The identifiers chosen for variables
mean nothing to the compiler either,
but using identifiers which have
some significance to the programmer
is good practice.
34
Programming Style
Programming Style
 The program below is identical to the
original example in this Lesson,
except for its layout and the
identifiers chosen. Which program
would you rather be given to modify?
35
Programming Style
Programming Style
#include <iostream.h>
void main(
) { int a,b,
c,d; cout << "Length = "; cin >> a;
cout<<"Width = "
;cin >> b; c = 2*(a+
b); d = a*b; cout
<< endl << "Perimeter is " <<
c << endl << "Area is " << d
<< endl;}
36
Summary
Summary
 All C++ programs must include a function main().
 All executable statements in C++ are terminated
by a semi-colon.
 Comments are ignored by the compiler but are
there for the information of someone reading the
program. All characters between // and the end of
the line are ignored by the compiler.
 All variables and constants that are used in a C++
program must be declared before use. Declaration
associates a type and an identifier with a variable.
 The type int is used for whole numbers which are
represented exactly within the computer.
37
Summary
Summary
 The type float is used for real (decimal) numbers. They are
held to a limited accuracy within the computer.
 The type char is used to represent single characters. A char
constant is enclosed in single quotation marks.
 Literal strings can be used in output statements and are
represented by enclosing the characters of the string in
double quotation marks ".
 Variables names (identifiers) can only include letters of the
alphabet, digits and the underscore character. They must
commence with a letter.
 Variables take values from input when included in input
statements using cin >> variable-identifier.
 The value of a variable or constant can be output by
including the identifier in the output list cout << output-
list. Items in the output list are separated by <<.
38
Hello World
Hello World
#include <iostream.h>
// This program prints
// Hello World.
int main()
{
cout << "Hello World.n";
return 0;
}
39
Exercises
Exercises 1
1
Using literal character strings and cout print
out a large letter E as below:
XXXXX
X
X
XXX
X
X
XXXXX
40
Exercises
Exercises 2
2
Write a program to read in four
characters and to print them out,
each one on a separate line,
enclosed in single quotation marks.
41
Exercises
Exercises 3
3
Write a program which prompts the
user to enter two integer values and
a float value and then prints out the
three numbers that are entered with
a suitable message.
The Assignment
The Assignment
statement
statement
43
The Assignment statement
The Assignment statement
 The main statement in C++ for
carrying out computation and
assigning values to variables is the
assignment statement.
 For example the following
average = (a + b)/2;
 assigns half the sum of a and b to
the variable average.
44
The Assignment statement
The Assignment statement
 The general form of an assignment
statement is:
result = expression ;
 The expression is evaluated and then
the value is assigned to the variable
result.
 It is important to note that the value
assigned to result must be of the
same type as result.
45
The expression
The expression
 can be a single variable,
 a single constant
 variables and constants combined by
the arithmetic operators.
 Rounded brackets () may also be
used in matched pairs in expressions
to indicate the order of evaluation.
46
Arithmetic Operators
Arithmetic Operators
+ addition
- subtraction
* multiplication
/ division
% remainder after division (modulus)
i = 3;
sum = 0.0;
perimeter = 2.0 * (length + breadth);
ratio = (a + b)/(c + d);
47
The type of the operands of
The type of the operands of
an arithmetic operator
an arithmetic operator
The following rules apply:
 if both operands are of type int then the result is
of type int.
 if either operand, or both, are of type float then
the result is of type float.
 if the expression evaluates to type int and the
result variable is of type float then the int will be
converted to an equivalent float before
assignment to the result variable.
 if the expression evaluates to type float and the
result variable is of type int then the float will be
converted to an int, usually by rounding towards
zero, before assignment to the result variable.
48
Priority of Operators
Priority of Operators
a + b * c
 be evaluated by performing the
multiplication first, or by performing
the addition first? i.e. as
 (a + b) * c or as a + (b * c) ?
49
Priority of Operators
Priority of Operators
 C++ solves this problem by
assigning priorities to operators
 Operators with high priority are then
evaluated before operators with low
priority.
 Operators with equal priority are
evaluated in left to right order.
50
Priority of Operators
Priority of Operators
 The priorities of the operators seen
so far are, in high to low priority
order:
( )
* / %
+ -
=
51
Priority of Operators
Priority of Operators
 Thus a + b * c is evaluated as if it
had been written as a + (b * c)
 because the * has a higher priority
than the +.
 If in any doubt use extra brackets to
ensure the correct order of
evaluation.
52
Type Conversions
Type Conversions
 Division of integers will always give an
integer result.
 If the correct float result is required, then
the compiler must be forced to generate
code that evaluates the expression as a
float.
 If either of the operands is a constant,
then it can be expressed as a floating
point constant by appending a .0 to it, as
we have seen.
53
Type Conversions
Type Conversions
 To force an expression involving two
int variables to be evaluated as a
float expression, at least one of the
variables must be converted to float.
This can be done by using the cast
operation:
f = float(i)/float(n);
54
Exercise
Exercise
 Write a program to converts an input
value in degrees Fahrenheit to the
corresponding value in degrees
Centigrade
C = 5/9 * (F-32)
55
Exercise
Exercise
 Write a program to converts an input
value in pence to the equivalent
value in pounds and pence.
56
Exercise
Exercise
 Write a C++ program which reads
values for two floats and outputs
their sum, product and quotient.
Include a sensible input prompt and
informative output.
57
Summary
Summary
 Expressions are combinations of operands and
operators.
 The order of evaluation of an expression is
determined by the precedence of the operators.
 In an assignment statement, the expression on
the right hand side of the assignment is
evaluated and, if necessary, converted to the
type of the variable on the left hand side before
the assignment takes place.
 When float expressions are assigned to int
variables there may be loss of accuracy.
Further
Further
Assignment
Assignment
Statements &
Statements &
Control of Output
Control of Output
59
Increment and Decrement
Increment and Decrement
Operators
Operators
 Some operations that occur so
frequently in writing assignment
statements that C++ has shorthand
methods for writing them.
 One common situation is that of
incrementing or decrementing an
integer variable. For example:
n = n + 1;
n = n - 1;
60
Increment and Decrement
Increment and Decrement
Operators
Operators
 C++ has an increment operator ++
and a decrement operator --. Thus
n++; can be used instead of n = n + 1;
n--; can be used instead of n = n - 1;
++n; can be used instead of n = n + 1;
--n; can be used instead of n = n - 1;
61
Increment and Decrement
Increment and Decrement
Operators
Operators
 For example if n has the value 5 then
i = n++;
would set i to the original value of n i.e. 5
and would then increment n to 6.
i = ++n;
would increment n to 6 and then set i to 6.
62
Specialised Assignment
Specialised Assignment
Statements
Statements
 Another common situation that occurs is
assignments such as the follows:
sum = sum + x;
 in which a variable is increased by some
amount and the result assigned back to
the original variable.
 This type of assignment can be
represented in C++ by:
sum += x;
63
Specialised Assignment
Specialised Assignment
Statements
Statements
 This notation can be used with the
arithmetic operators +, -, *, / and %.
 The general form of such compound
assignment operators is:
variable op= expression
which is interpreted as being equivalent to:
variable = variable op ( expression )
64
Specialised Assignment
Specialised Assignment
Statements
Statements
total += value;
total = total + value;
prod *= 10;
prod = prod * 10;
x /= y + 1;
x = x/(y + 1);
n %= 2;
n = n % 2;

More Related Content

Similar to Elementary_Of_C++_Programming_Language.ppt (20)

BCP_u2.pptxBCP_u2.pptxBCP_u2.pptxBCP_u2.pptx
BCP_u2.pptxBCP_u2.pptxBCP_u2.pptxBCP_u2.pptxBCP_u2.pptxBCP_u2.pptxBCP_u2.pptxBCP_u2.pptx
BCP_u2.pptxBCP_u2.pptxBCP_u2.pptxBCP_u2.pptx
RutviBaraiya
Declaration of variables
Declaration of variablesDeclaration of variables
Declaration of variables
Maria Stella Solon
Unit No 2.pptx Basic s of C Programming
Unit No 2.pptx   Basic s of C ProgrammingUnit No 2.pptx   Basic s of C Programming
Unit No 2.pptx Basic s of C Programming
Vaibhav Parjane
CPLUSPLUS UET PESHAWAR BS ELECTRICAL 2ND SEMSTER Lecture02.ppt
CPLUSPLUS UET PESHAWAR BS ELECTRICAL 2ND SEMSTER Lecture02.pptCPLUSPLUS UET PESHAWAR BS ELECTRICAL 2ND SEMSTER Lecture02.ppt
CPLUSPLUS UET PESHAWAR BS ELECTRICAL 2ND SEMSTER Lecture02.ppt
abdurrahimk182
Lesson 4 Basic Programming Constructs.pptx
Lesson 4 Basic Programming Constructs.pptxLesson 4 Basic Programming Constructs.pptx
Lesson 4 Basic Programming Constructs.pptx
John Burca
L03vars
L03varsL03vars
L03vars
Ramasamyvelambaal Acadamy
Basics of c++ Programming Language
Basics of c++ Programming LanguageBasics of c++ Programming Language
Basics of c++ Programming Language
Ahmad Idrees
4 Introduction to C.pptxSSSSSSSSSSSSSSSS
4 Introduction to C.pptxSSSSSSSSSSSSSSSS4 Introduction to C.pptxSSSSSSSSSSSSSSSS
4 Introduction to C.pptxSSSSSSSSSSSSSSSS
EG20910848921ISAACDU
C Programming Language Introduction and C Tokens.pdf
C Programming Language Introduction and C Tokens.pdfC Programming Language Introduction and C Tokens.pdf
C Programming Language Introduction and C Tokens.pdf
poongothai11
INTRODUCTION TO C++.pptx
INTRODUCTION TO C++.pptxINTRODUCTION TO C++.pptx
INTRODUCTION TO C++.pptx
MamataAnilgod
keyword
keywordkeyword
keyword
teach4uin
keyword
keywordkeyword
keyword
teach4uin
#Code2 create c++ for beginners
#Code2 create  c++ for beginners #Code2 create  c++ for beginners
#Code2 create c++ for beginners
GDGKuwaitGoogleDevel
basics of c programming for naiver.pptx
basics of c programming  for naiver.pptxbasics of c programming  for naiver.pptx
basics of c programming for naiver.pptx
ssuser96ba7e1
MCA 101-Programming in C with Data Structure UNIT I by Prof. Rohit Dubey
MCA 101-Programming in C with Data Structure UNIT I by Prof. Rohit DubeyMCA 101-Programming in C with Data Structure UNIT I by Prof. Rohit Dubey
MCA 101-Programming in C with Data Structure UNIT I by Prof. Rohit Dubey
kiranrajat
Introduction%20C.pptx
Introduction%20C.pptxIntroduction%20C.pptx
Introduction%20C.pptx
20EUEE018DEEPAKM
C Language Part 1
C Language Part 1C Language Part 1
C Language Part 1
Thapar Institute
FUNDAMENTAL OF C
FUNDAMENTAL OF CFUNDAMENTAL OF C
FUNDAMENTAL OF C
KRUNAL RAVAL
Chapter2
Chapter2Chapter2
Chapter2
Anees999
Fundamentals of computers - C Programming
Fundamentals of computers - C ProgrammingFundamentals of computers - C Programming
Fundamentals of computers - C Programming
MSridhar18
BCP_u2.pptxBCP_u2.pptxBCP_u2.pptxBCP_u2.pptx
BCP_u2.pptxBCP_u2.pptxBCP_u2.pptxBCP_u2.pptxBCP_u2.pptxBCP_u2.pptxBCP_u2.pptxBCP_u2.pptx
BCP_u2.pptxBCP_u2.pptxBCP_u2.pptxBCP_u2.pptx
RutviBaraiya
Unit No 2.pptx Basic s of C Programming
Unit No 2.pptx   Basic s of C ProgrammingUnit No 2.pptx   Basic s of C Programming
Unit No 2.pptx Basic s of C Programming
Vaibhav Parjane
CPLUSPLUS UET PESHAWAR BS ELECTRICAL 2ND SEMSTER Lecture02.ppt
CPLUSPLUS UET PESHAWAR BS ELECTRICAL 2ND SEMSTER Lecture02.pptCPLUSPLUS UET PESHAWAR BS ELECTRICAL 2ND SEMSTER Lecture02.ppt
CPLUSPLUS UET PESHAWAR BS ELECTRICAL 2ND SEMSTER Lecture02.ppt
abdurrahimk182
Lesson 4 Basic Programming Constructs.pptx
Lesson 4 Basic Programming Constructs.pptxLesson 4 Basic Programming Constructs.pptx
Lesson 4 Basic Programming Constructs.pptx
John Burca
Basics of c++ Programming Language
Basics of c++ Programming LanguageBasics of c++ Programming Language
Basics of c++ Programming Language
Ahmad Idrees
4 Introduction to C.pptxSSSSSSSSSSSSSSSS
4 Introduction to C.pptxSSSSSSSSSSSSSSSS4 Introduction to C.pptxSSSSSSSSSSSSSSSS
4 Introduction to C.pptxSSSSSSSSSSSSSSSS
EG20910848921ISAACDU
C Programming Language Introduction and C Tokens.pdf
C Programming Language Introduction and C Tokens.pdfC Programming Language Introduction and C Tokens.pdf
C Programming Language Introduction and C Tokens.pdf
poongothai11
INTRODUCTION TO C++.pptx
INTRODUCTION TO C++.pptxINTRODUCTION TO C++.pptx
INTRODUCTION TO C++.pptx
MamataAnilgod
#Code2 create c++ for beginners
#Code2 create  c++ for beginners #Code2 create  c++ for beginners
#Code2 create c++ for beginners
GDGKuwaitGoogleDevel
basics of c programming for naiver.pptx
basics of c programming  for naiver.pptxbasics of c programming  for naiver.pptx
basics of c programming for naiver.pptx
ssuser96ba7e1
MCA 101-Programming in C with Data Structure UNIT I by Prof. Rohit Dubey
MCA 101-Programming in C with Data Structure UNIT I by Prof. Rohit DubeyMCA 101-Programming in C with Data Structure UNIT I by Prof. Rohit Dubey
MCA 101-Programming in C with Data Structure UNIT I by Prof. Rohit Dubey
kiranrajat
FUNDAMENTAL OF C
FUNDAMENTAL OF CFUNDAMENTAL OF C
FUNDAMENTAL OF C
KRUNAL RAVAL
Chapter2
Chapter2Chapter2
Chapter2
Anees999
Fundamentals of computers - C Programming
Fundamentals of computers - C ProgrammingFundamentals of computers - C Programming
Fundamentals of computers - C Programming
MSridhar18

More from GordanaJovanoska1 (6)

Scratch programming and Numeracy in Senior Primary Classes.pptx
Scratch programming and Numeracy in Senior Primary Classes.pptxScratch programming and Numeracy in Senior Primary Classes.pptx
Scratch programming and Numeracy in Senior Primary Classes.pptx
GordanaJovanoska1
Elementary_Variables_And_Data123456.pptx
Elementary_Variables_And_Data123456.pptxElementary_Variables_And_Data123456.pptx
Elementary_Variables_And_Data123456.pptx
GordanaJovanoska1
chap2_Variables_In_Proraming_Introduction.ppt
chap2_Variables_In_Proraming_Introduction.pptchap2_Variables_In_Proraming_Introduction.ppt
chap2_Variables_In_Proraming_Introduction.ppt
GordanaJovanoska1
1 从仂仄于亳 - 亠仆舒仂亟亠仆 亟亠仆 仆舒 舒亳亠 仍亳舒.ppsx
1 从仂仄于亳 - 亠仆舒仂亟亠仆 亟亠仆 仆舒 舒亳亠 仍亳舒.ppsx1 从仂仄于亳 - 亠仆舒仂亟亠仆 亟亠仆 仆舒 舒亳亠 仍亳舒.ppsx
1 从仂仄于亳 - 亠仆舒仂亟亠仆 亟亠仆 仆舒 舒亳亠 仍亳舒.ppsx
GordanaJovanoska1
Osnovi na programiranje i na programski jazik
Osnovi na programiranje i na programski jazikOsnovi na programiranje i na programski jazik
Osnovi na programiranje i na programski jazik
GordanaJovanoska1
Vmetnuvanje i formatiranje na tabeli vo Word
Vmetnuvanje i formatiranje na tabeli vo WordVmetnuvanje i formatiranje na tabeli vo Word
Vmetnuvanje i formatiranje na tabeli vo Word
GordanaJovanoska1
Scratch programming and Numeracy in Senior Primary Classes.pptx
Scratch programming and Numeracy in Senior Primary Classes.pptxScratch programming and Numeracy in Senior Primary Classes.pptx
Scratch programming and Numeracy in Senior Primary Classes.pptx
GordanaJovanoska1
Elementary_Variables_And_Data123456.pptx
Elementary_Variables_And_Data123456.pptxElementary_Variables_And_Data123456.pptx
Elementary_Variables_And_Data123456.pptx
GordanaJovanoska1
chap2_Variables_In_Proraming_Introduction.ppt
chap2_Variables_In_Proraming_Introduction.pptchap2_Variables_In_Proraming_Introduction.ppt
chap2_Variables_In_Proraming_Introduction.ppt
GordanaJovanoska1
1 从仂仄于亳 - 亠仆舒仂亟亠仆 亟亠仆 仆舒 舒亳亠 仍亳舒.ppsx
1 从仂仄于亳 - 亠仆舒仂亟亠仆 亟亠仆 仆舒 舒亳亠 仍亳舒.ppsx1 从仂仄于亳 - 亠仆舒仂亟亠仆 亟亠仆 仆舒 舒亳亠 仍亳舒.ppsx
1 从仂仄于亳 - 亠仆舒仂亟亠仆 亟亠仆 仆舒 舒亳亠 仍亳舒.ppsx
GordanaJovanoska1
Osnovi na programiranje i na programski jazik
Osnovi na programiranje i na programski jazikOsnovi na programiranje i na programski jazik
Osnovi na programiranje i na programski jazik
GordanaJovanoska1
Vmetnuvanje i formatiranje na tabeli vo Word
Vmetnuvanje i formatiranje na tabeli vo WordVmetnuvanje i formatiranje na tabeli vo Word
Vmetnuvanje i formatiranje na tabeli vo Word
GordanaJovanoska1

Recently uploaded (20)

Sulfonamides by Mrs. Manjushri P. Dabhade
Sulfonamides by Mrs. Manjushri P. DabhadeSulfonamides by Mrs. Manjushri P. Dabhade
Sulfonamides by Mrs. Manjushri P. Dabhade
Dabhade madam Dabhade
compiler design BCS613C question bank 2022 scheme
compiler design BCS613C question bank 2022 schemecompiler design BCS613C question bank 2022 scheme
compiler design BCS613C question bank 2022 scheme
Suvarna Hiremath
Viceroys of India & Their Tenure Key Events During British Rule
Viceroys of India & Their Tenure  Key Events During British RuleViceroys of India & Their Tenure  Key Events During British Rule
Viceroys of India & Their Tenure Key Events During British Rule
DeeptiKumari61
The basics of sentences session 10pptx.pptx
The basics of sentences session 10pptx.pptxThe basics of sentences session 10pptx.pptx
The basics of sentences session 10pptx.pptx
heathfieldcps1
Enhancing SoTL through Generative AI -- Opportunities and Ethical Considerati...
Enhancing SoTL through Generative AI -- Opportunities and Ethical Considerati...Enhancing SoTL through Generative AI -- Opportunities and Ethical Considerati...
Enhancing SoTL through Generative AI -- Opportunities and Ethical Considerati...
Sue Beckingham
Unit 3: Combustion in Spark Ignition Engines
Unit 3: Combustion in Spark Ignition EnginesUnit 3: Combustion in Spark Ignition Engines
Unit 3: Combustion in Spark Ignition Engines
NileshKumbhar21
Yale VMOC Special Report - Measles Outbreak Southwest US 3-30-2025 FINAL v2...
Yale VMOC Special Report - Measles Outbreak  Southwest US 3-30-2025  FINAL v2...Yale VMOC Special Report - Measles Outbreak  Southwest US 3-30-2025  FINAL v2...
Yale VMOC Special Report - Measles Outbreak Southwest US 3-30-2025 FINAL v2...
Yale School of Public Health - The Virtual Medical Operations Center (VMOC)
Different perspectives on dugout canoe heritage of Soomaa.pdf
Different perspectives on dugout canoe heritage of Soomaa.pdfDifferent perspectives on dugout canoe heritage of Soomaa.pdf
Different perspectives on dugout canoe heritage of Soomaa.pdf
Aivar Ruukel
Knownsense 2025 prelims- U-25 General Quiz.pdf
Knownsense 2025 prelims- U-25 General Quiz.pdfKnownsense 2025 prelims- U-25 General Quiz.pdf
Knownsense 2025 prelims- U-25 General Quiz.pdf
Pragya - UEM Kolkata Quiz Club
Quizzitch Cup_Sports Quiz 2025_Prelims.pptx
Quizzitch Cup_Sports Quiz 2025_Prelims.pptxQuizzitch Cup_Sports Quiz 2025_Prelims.pptx
Quizzitch Cup_Sports Quiz 2025_Prelims.pptx
Anand Kumar
Different Facets of Knowledge on different View.pptx
Different Facets of Knowledge on different View.pptxDifferent Facets of Knowledge on different View.pptx
Different Facets of Knowledge on different View.pptx
NrapendraVirSingh
Antifungal agents by Mrs. Manjushri Dabhade
Antifungal agents by Mrs. Manjushri DabhadeAntifungal agents by Mrs. Manjushri Dabhade
Antifungal agents by Mrs. Manjushri Dabhade
Dabhade madam Dabhade
MIPLM subject matter expert Dr Alihan Kaya
MIPLM subject matter expert Dr Alihan KayaMIPLM subject matter expert Dr Alihan Kaya
MIPLM subject matter expert Dr Alihan Kaya
MIPLM
General Quiz at ChakraView 2025 | Amlan Sarkar | Ashoka Univeristy | Prelims ...
General Quiz at ChakraView 2025 | Amlan Sarkar | Ashoka Univeristy | Prelims ...General Quiz at ChakraView 2025 | Amlan Sarkar | Ashoka Univeristy | Prelims ...
General Quiz at ChakraView 2025 | Amlan Sarkar | Ashoka Univeristy | Prelims ...
Amlan Sarkar
NURSING PROCESS AND ITS STEPS .pptx
NURSING PROCESS AND ITS STEPS                 .pptxNURSING PROCESS AND ITS STEPS                 .pptx
NURSING PROCESS AND ITS STEPS .pptx
PoojaSen20
CLEFT LIP AND PALATE: NURSING MANAGEMENT.pptx
CLEFT LIP AND PALATE: NURSING MANAGEMENT.pptxCLEFT LIP AND PALATE: NURSING MANAGEMENT.pptx
CLEFT LIP AND PALATE: NURSING MANAGEMENT.pptx
PRADEEP ABOTHU
Unit No 4- Chemotherapy of Malignancy.pptx
Unit No  4- Chemotherapy of Malignancy.pptxUnit No  4- Chemotherapy of Malignancy.pptx
Unit No 4- Chemotherapy of Malignancy.pptx
Ashish Umale
How to Install Odoo 18 with Pycharm - Odoo 18 際際滷s
How to Install Odoo 18 with Pycharm - Odoo 18 際際滷sHow to Install Odoo 18 with Pycharm - Odoo 18 際際滷s
How to Install Odoo 18 with Pycharm - Odoo 18 際際滷s
Celine George
Pass SAP C_C4H47_2503 in 2025 | Latest Exam Questions & Study Material
Pass SAP C_C4H47_2503 in 2025 | Latest Exam Questions & Study MaterialPass SAP C_C4H47_2503 in 2025 | Latest Exam Questions & Study Material
Pass SAP C_C4H47_2503 in 2025 | Latest Exam Questions & Study Material
Jenny408767
Chapter 6. Business and Corporate Strategy Formulation.pdf
Chapter 6. Business and Corporate Strategy Formulation.pdfChapter 6. Business and Corporate Strategy Formulation.pdf
Chapter 6. Business and Corporate Strategy Formulation.pdf
Rommel Regala
Sulfonamides by Mrs. Manjushri P. Dabhade
Sulfonamides by Mrs. Manjushri P. DabhadeSulfonamides by Mrs. Manjushri P. Dabhade
Sulfonamides by Mrs. Manjushri P. Dabhade
Dabhade madam Dabhade
compiler design BCS613C question bank 2022 scheme
compiler design BCS613C question bank 2022 schemecompiler design BCS613C question bank 2022 scheme
compiler design BCS613C question bank 2022 scheme
Suvarna Hiremath
Viceroys of India & Their Tenure Key Events During British Rule
Viceroys of India & Their Tenure  Key Events During British RuleViceroys of India & Their Tenure  Key Events During British Rule
Viceroys of India & Their Tenure Key Events During British Rule
DeeptiKumari61
The basics of sentences session 10pptx.pptx
The basics of sentences session 10pptx.pptxThe basics of sentences session 10pptx.pptx
The basics of sentences session 10pptx.pptx
heathfieldcps1
Enhancing SoTL through Generative AI -- Opportunities and Ethical Considerati...
Enhancing SoTL through Generative AI -- Opportunities and Ethical Considerati...Enhancing SoTL through Generative AI -- Opportunities and Ethical Considerati...
Enhancing SoTL through Generative AI -- Opportunities and Ethical Considerati...
Sue Beckingham
Unit 3: Combustion in Spark Ignition Engines
Unit 3: Combustion in Spark Ignition EnginesUnit 3: Combustion in Spark Ignition Engines
Unit 3: Combustion in Spark Ignition Engines
NileshKumbhar21
Different perspectives on dugout canoe heritage of Soomaa.pdf
Different perspectives on dugout canoe heritage of Soomaa.pdfDifferent perspectives on dugout canoe heritage of Soomaa.pdf
Different perspectives on dugout canoe heritage of Soomaa.pdf
Aivar Ruukel
Quizzitch Cup_Sports Quiz 2025_Prelims.pptx
Quizzitch Cup_Sports Quiz 2025_Prelims.pptxQuizzitch Cup_Sports Quiz 2025_Prelims.pptx
Quizzitch Cup_Sports Quiz 2025_Prelims.pptx
Anand Kumar
Different Facets of Knowledge on different View.pptx
Different Facets of Knowledge on different View.pptxDifferent Facets of Knowledge on different View.pptx
Different Facets of Knowledge on different View.pptx
NrapendraVirSingh
Antifungal agents by Mrs. Manjushri Dabhade
Antifungal agents by Mrs. Manjushri DabhadeAntifungal agents by Mrs. Manjushri Dabhade
Antifungal agents by Mrs. Manjushri Dabhade
Dabhade madam Dabhade
MIPLM subject matter expert Dr Alihan Kaya
MIPLM subject matter expert Dr Alihan KayaMIPLM subject matter expert Dr Alihan Kaya
MIPLM subject matter expert Dr Alihan Kaya
MIPLM
General Quiz at ChakraView 2025 | Amlan Sarkar | Ashoka Univeristy | Prelims ...
General Quiz at ChakraView 2025 | Amlan Sarkar | Ashoka Univeristy | Prelims ...General Quiz at ChakraView 2025 | Amlan Sarkar | Ashoka Univeristy | Prelims ...
General Quiz at ChakraView 2025 | Amlan Sarkar | Ashoka Univeristy | Prelims ...
Amlan Sarkar
NURSING PROCESS AND ITS STEPS .pptx
NURSING PROCESS AND ITS STEPS                 .pptxNURSING PROCESS AND ITS STEPS                 .pptx
NURSING PROCESS AND ITS STEPS .pptx
PoojaSen20
CLEFT LIP AND PALATE: NURSING MANAGEMENT.pptx
CLEFT LIP AND PALATE: NURSING MANAGEMENT.pptxCLEFT LIP AND PALATE: NURSING MANAGEMENT.pptx
CLEFT LIP AND PALATE: NURSING MANAGEMENT.pptx
PRADEEP ABOTHU
Unit No 4- Chemotherapy of Malignancy.pptx
Unit No  4- Chemotherapy of Malignancy.pptxUnit No  4- Chemotherapy of Malignancy.pptx
Unit No 4- Chemotherapy of Malignancy.pptx
Ashish Umale
How to Install Odoo 18 with Pycharm - Odoo 18 際際滷s
How to Install Odoo 18 with Pycharm - Odoo 18 際際滷sHow to Install Odoo 18 with Pycharm - Odoo 18 際際滷s
How to Install Odoo 18 with Pycharm - Odoo 18 際際滷s
Celine George
Pass SAP C_C4H47_2503 in 2025 | Latest Exam Questions & Study Material
Pass SAP C_C4H47_2503 in 2025 | Latest Exam Questions & Study MaterialPass SAP C_C4H47_2503 in 2025 | Latest Exam Questions & Study Material
Pass SAP C_C4H47_2503 in 2025 | Latest Exam Questions & Study Material
Jenny408767
Chapter 6. Business and Corporate Strategy Formulation.pdf
Chapter 6. Business and Corporate Strategy Formulation.pdfChapter 6. Business and Corporate Strategy Formulation.pdf
Chapter 6. Business and Corporate Strategy Formulation.pdf
Rommel Regala

Elementary_Of_C++_Programming_Language.ppt

  • 1. Elementary C Elementary C+ + + + Programming Programming panupong@kku.ac.th panupong@kku.ac.th
  • 2. 2 // Sample program // Reads values for the length and width of a rectangle // and returns the perimeter and area of the rectangle. #include <iostream.h> void main() { int length, width; int perimeter, area; // declarations cout << "Length = "; // prompt user cin >> length; // enter length cout << "Width = "; // prompt user cin >> width; // input width perimeter = 2*(length+width); // compute perimeter area = length*width; // compute area cout << endl << "Perimeter is " << perimeter; cout << endl << "Area is " << area << endl; // output results } // end of main program
  • 3. 3 The following points should be The following points should be noted in the above program: noted in the above program: Any text from the symbols // until the end of the line is ignored by the compiler. The line #include <iostream.h> This statement is a compiler directive -- that is it gives information to the compiler but does not cause any executable code to be produced.
  • 4. 4 The following points should be The following points should be noted in the above program: noted in the above program: The actual program consists of the function main which commences at the line void main() All programs must have a function main. The body of the function main contains the actual code which is executed by the computer and is enclosed, as noted above, in braces {}.
  • 5. 5 The following points should be The following points should be noted in the above program: noted in the above program: Every statement which instructs the computer to do something is terminated by a semi-colon ;. Sequences of characters enclosed in double quotes are literal strings. Thus instructions such as cout << "Length = " send the quoted characters to the output stream cout.
  • 6. 6 The following points should be The following points should be noted in the above program: noted in the above program: All variables that are used in a program must be declared and given a type. In this case all the variables are of type int, i.e. whole numbers. Thus the statement int length, width; Values can be given to variables by the assignment statement, e.g. the statement area = length*width;
  • 7. 7 The following points should be The following points should be noted in the above program: noted in the above program: Layout of the program is quite arbitrary, i.e. new lines, spaces etc. can be inserted wherever desired and will be ignored by the compiler.
  • 8. 8 Variables Variables A variable is the name used for the quantities which are manipulated by a computer program. In order to distinguish between different variables, they must be given identifiers, names which distinguish them from all other variables.
  • 9. 9 The rules of C++ for The rules of C++ for valid identifiers valid identifiers An identifier must: start with a letter consist only of letters, the digits 0-9, or the underscore symbol _ not be a reserved word Reserved words are otherwise valid identifiers that have special significance to C++. use of two consecutive underscore symbols, __, is forbidden.
  • 10. 10 Identifiers Identifiers The following are valid identifiers Length days_in_year DataSet1 Profit95 Int_Pressure first_one first_1 although using _Pressure is not recommended. The following are invalid: days-in-year 1data int first.val throw
  • 11. 11 Identifiers Identifiers Identifiers should be meaningful C++ is case-sensitive. That is lower- case letters are treated as distinct from upper-case letters. Thus the word main in a program is quite different from the word Main or the word MAIN.
  • 12. 12 Reserved words Reserved words and and_eq asm auto bitand bitor bool break case catch char class const const_cast continue default delete do double dynamic_cast else enum explicit export extern false float for friend goto if inline int long mutable namespace new not not_eq operator or or_eq private protected public register reinterpret_cast return short signed sizeof static static_cast struct switch template this throw true try typedef typeid typename union unsigned using virtual void volatile wchar_t while xor xor_eq
  • 13. 13 Declaration of variables Declaration of variables In C++ all the variables that a program is going to use must be declared prior to use. Declaration of a variable serves two purposes: It associates a type and an identifier (or name) with the variable. The type allows the compiler to interpret statements correctly. It allows the compiler to decide how much storage space to allocate for storage of the value associated with the identifier and to assign an address for each variable which can be used in code generation.
  • 14. 14 Variable Types Variable Types int float bool char
  • 15. 15 int int int variables can represent negative and positive integer values (whole numbers). There is a limit on the size of value that can be represented, which depends on the number of bytes of storage allocated to an int variable by the computer system and compiler being used. On a PC most compilers allocate two bytes for each int which gives a range of -32768 to +32767. On workstations, four bytes are usually allocated, giving a range of -2147483648 to 2147483647. It is important to note that integers are represented exactly in computer memory.
  • 16. 16 float float float variables can represent any real numeric value, that is both whole numbers and numbers that require digits after the decimal point. The accuracy and the range of numbers represented is dependent on the computer system. Usually four bytes are allocated for float variables, this gives an accuracy of about six significant figures and a range of about -1038 to +1038 . It is important to note that float values are only represented approximately.
  • 17. 17 bool bool bool variables can only hold the values true or false. These variables are known as boolean variables in honour of George Boole, an Irish mathematician who invented boolean algebra.
  • 18. 18 char char char variables represent a single character -- a letter, a digit or a punctuation character. They usually occupy one byte, giving 256 different possible characters. The bit patterns for characters usually conform to the American Standard Code for Information Interchange (ASCII).
  • 19. 19 Examples of values for such Examples of values for such variables are: variables are: int 123 -56 0 5645 float 16.315 -0.67 31.567 char '+' 'A' 'a' '*' '7'
  • 20. 20 Variable Declarations Variable Declarations A typical set of variable declarations that might appear at the beginning of a program could be as follows: int i, j, count; float sum, product; char ch; bool passed_exam; which declares integer variables i, j and count, real variables sum and product, a character variable ch, and a boolean variable pass_exam.
  • 21. 21 A variable declaration has A variable declaration has the form: the form: type identifier-list; Type specifies the type of the variables being declared. The identifier-list is a list of the identifiers of the variables being declared, separated by commas Variables may be initialized at the time of declaration by assigning a value to them
  • 22. 22 Examples Examples int i, j, count = 0; float sum = 0.0, product; char ch = '7'; bool passed_exam = false;
  • 23. 23 Constants and the Constants and the declaration of constants declaration of constants Often in programming numerical constants are used, e.g. the value of 其. It is well worthwhile to associate meaningful names with constants. These names can be associated with the appropriate numerical value in a constant declaration. The names given to constants must conform to the rules for the formation of identifiers as defined above.
  • 24. 24 Constants and the Constants and the declaration of constants declaration of constants const int days_in_year = 365; defines an integer constant days_in_year which has the value 365. Later in the program the identifier days_in_year can be used instead of the integer 365, making the program far more readable. The general form of a constant declaration is: const type constant-identifier = value ;
  • 25. 25 General form of a C++ General form of a C++ Program Program // Introductory comments // file name, programmer, when written or modified // what program does #include <iostream.h> void main() { constant declarations variable declarations executable statements }
  • 26. 26 Input and Output Input and Output Input and output use the input stream cin and the output stream cout. The input stream cin is usually associated with the keyboard The output stream cout is usually associated with the monitor.
  • 27. 27 cin cin The following statement waits for a number to be entered from the keyboard and assigns it to the variable number: cin >> number; The general form of a statement to perform input using the input stream cin is: cin input-list; where input-list is a list of identifiers, each identifier preceded by the input operator >>.
  • 28. 28 cin cin cin >> n1 >> n2; would take the next two values entered by the user and assign the value of the first one to the variable n1 and the second to the variable n2. User enter 10 20 <ENTER> 10 <ENTER> 20<ENTER> 10 20 30 <ENTER>
  • 29. 29 cout cout The following statement outputs the current value of the variable count to the output stream cout cout << count; The general form of a statement to perform output using the output stream cout is: cout output-list; where output-list is a list of variables, constants, or character strings in quotation marks, each preceded by the output operator <<.
  • 30. 30 cout cout cout << "Hello there" << endl; will print Hello there on the current output line and then take a new line for the next output.
  • 31. 31 Example Example float length, breadth; cout << "Enter the length and breadth: "; cin >> length >> breadth; cout << endl << "The length is " << length; cout << endl << "The breadth is " << breadth << endl; will display, if the user enters 6.51 and 3.24 at the prompt, the following output: The length is 6.51 The breadth is 3.24
  • 32. 32 Example Example Note that a value written to cout will be printed immediately after any previous value with no space between. In the above program the character strings written to cout each end with a space character. The statement cout << length << breadth; would print out the results as 6.513.24 which is obviously impossible to interpret correctly. If printing several values on the same line remember to separate them with spaces by printing a string in between them as follows: cout << length << " " << breadth;
  • 33. 33 Programming Style Programming Style any number of spaces and or new lines can be used to separate the different symbols in a C++ program. The identifiers chosen for variables mean nothing to the compiler either, but using identifiers which have some significance to the programmer is good practice.
  • 34. 34 Programming Style Programming Style The program below is identical to the original example in this Lesson, except for its layout and the identifiers chosen. Which program would you rather be given to modify?
  • 35. 35 Programming Style Programming Style #include <iostream.h> void main( ) { int a,b, c,d; cout << "Length = "; cin >> a; cout<<"Width = " ;cin >> b; c = 2*(a+ b); d = a*b; cout << endl << "Perimeter is " << c << endl << "Area is " << d << endl;}
  • 36. 36 Summary Summary All C++ programs must include a function main(). All executable statements in C++ are terminated by a semi-colon. Comments are ignored by the compiler but are there for the information of someone reading the program. All characters between // and the end of the line are ignored by the compiler. All variables and constants that are used in a C++ program must be declared before use. Declaration associates a type and an identifier with a variable. The type int is used for whole numbers which are represented exactly within the computer.
  • 37. 37 Summary Summary The type float is used for real (decimal) numbers. They are held to a limited accuracy within the computer. The type char is used to represent single characters. A char constant is enclosed in single quotation marks. Literal strings can be used in output statements and are represented by enclosing the characters of the string in double quotation marks ". Variables names (identifiers) can only include letters of the alphabet, digits and the underscore character. They must commence with a letter. Variables take values from input when included in input statements using cin >> variable-identifier. The value of a variable or constant can be output by including the identifier in the output list cout << output- list. Items in the output list are separated by <<.
  • 38. 38 Hello World Hello World #include <iostream.h> // This program prints // Hello World. int main() { cout << "Hello World.n"; return 0; }
  • 39. 39 Exercises Exercises 1 1 Using literal character strings and cout print out a large letter E as below: XXXXX X X XXX X X XXXXX
  • 40. 40 Exercises Exercises 2 2 Write a program to read in four characters and to print them out, each one on a separate line, enclosed in single quotation marks.
  • 41. 41 Exercises Exercises 3 3 Write a program which prompts the user to enter two integer values and a float value and then prints out the three numbers that are entered with a suitable message.
  • 43. 43 The Assignment statement The Assignment statement The main statement in C++ for carrying out computation and assigning values to variables is the assignment statement. For example the following average = (a + b)/2; assigns half the sum of a and b to the variable average.
  • 44. 44 The Assignment statement The Assignment statement The general form of an assignment statement is: result = expression ; The expression is evaluated and then the value is assigned to the variable result. It is important to note that the value assigned to result must be of the same type as result.
  • 45. 45 The expression The expression can be a single variable, a single constant variables and constants combined by the arithmetic operators. Rounded brackets () may also be used in matched pairs in expressions to indicate the order of evaluation.
  • 46. 46 Arithmetic Operators Arithmetic Operators + addition - subtraction * multiplication / division % remainder after division (modulus) i = 3; sum = 0.0; perimeter = 2.0 * (length + breadth); ratio = (a + b)/(c + d);
  • 47. 47 The type of the operands of The type of the operands of an arithmetic operator an arithmetic operator The following rules apply: if both operands are of type int then the result is of type int. if either operand, or both, are of type float then the result is of type float. if the expression evaluates to type int and the result variable is of type float then the int will be converted to an equivalent float before assignment to the result variable. if the expression evaluates to type float and the result variable is of type int then the float will be converted to an int, usually by rounding towards zero, before assignment to the result variable.
  • 48. 48 Priority of Operators Priority of Operators a + b * c be evaluated by performing the multiplication first, or by performing the addition first? i.e. as (a + b) * c or as a + (b * c) ?
  • 49. 49 Priority of Operators Priority of Operators C++ solves this problem by assigning priorities to operators Operators with high priority are then evaluated before operators with low priority. Operators with equal priority are evaluated in left to right order.
  • 50. 50 Priority of Operators Priority of Operators The priorities of the operators seen so far are, in high to low priority order: ( ) * / % + - =
  • 51. 51 Priority of Operators Priority of Operators Thus a + b * c is evaluated as if it had been written as a + (b * c) because the * has a higher priority than the +. If in any doubt use extra brackets to ensure the correct order of evaluation.
  • 52. 52 Type Conversions Type Conversions Division of integers will always give an integer result. If the correct float result is required, then the compiler must be forced to generate code that evaluates the expression as a float. If either of the operands is a constant, then it can be expressed as a floating point constant by appending a .0 to it, as we have seen.
  • 53. 53 Type Conversions Type Conversions To force an expression involving two int variables to be evaluated as a float expression, at least one of the variables must be converted to float. This can be done by using the cast operation: f = float(i)/float(n);
  • 54. 54 Exercise Exercise Write a program to converts an input value in degrees Fahrenheit to the corresponding value in degrees Centigrade C = 5/9 * (F-32)
  • 55. 55 Exercise Exercise Write a program to converts an input value in pence to the equivalent value in pounds and pence.
  • 56. 56 Exercise Exercise Write a C++ program which reads values for two floats and outputs their sum, product and quotient. Include a sensible input prompt and informative output.
  • 57. 57 Summary Summary Expressions are combinations of operands and operators. The order of evaluation of an expression is determined by the precedence of the operators. In an assignment statement, the expression on the right hand side of the assignment is evaluated and, if necessary, converted to the type of the variable on the left hand side before the assignment takes place. When float expressions are assigned to int variables there may be loss of accuracy.
  • 59. 59 Increment and Decrement Increment and Decrement Operators Operators Some operations that occur so frequently in writing assignment statements that C++ has shorthand methods for writing them. One common situation is that of incrementing or decrementing an integer variable. For example: n = n + 1; n = n - 1;
  • 60. 60 Increment and Decrement Increment and Decrement Operators Operators C++ has an increment operator ++ and a decrement operator --. Thus n++; can be used instead of n = n + 1; n--; can be used instead of n = n - 1; ++n; can be used instead of n = n + 1; --n; can be used instead of n = n - 1;
  • 61. 61 Increment and Decrement Increment and Decrement Operators Operators For example if n has the value 5 then i = n++; would set i to the original value of n i.e. 5 and would then increment n to 6. i = ++n; would increment n to 6 and then set i to 6.
  • 62. 62 Specialised Assignment Specialised Assignment Statements Statements Another common situation that occurs is assignments such as the follows: sum = sum + x; in which a variable is increased by some amount and the result assigned back to the original variable. This type of assignment can be represented in C++ by: sum += x;
  • 63. 63 Specialised Assignment Specialised Assignment Statements Statements This notation can be used with the arithmetic operators +, -, *, / and %. The general form of such compound assignment operators is: variable op= expression which is interpreted as being equivalent to: variable = variable op ( expression )
  • 64. 64 Specialised Assignment Specialised Assignment Statements Statements total += value; total = total + value; prod *= 10; prod = prod * 10; x /= y + 1; x = x/(y + 1); n %= 2; n = n % 2;