[go: up one dir, main page]

0% found this document useful (0 votes)
27 views74 pages

Fund Ofprog In-C++chp 2 3

C and C++ were originally developed in the 1970s at Bell Labs. C++ builds on C by adding object-oriented programming features like classes, inheritance, and polymorphism. A basic C++ program structure includes comments, preprocessor directives like #include, a main function enclosed in curly braces, and statements that end with semicolons. The main function is where program execution begins. Standard C++ libraries provide common functions and objects like cout for output.

Uploaded by

kemal Beriso
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views74 pages

Fund Ofprog In-C++chp 2 3

C and C++ were originally developed in the 1970s at Bell Labs. C++ builds on C by adding object-oriented programming features like classes, inheritance, and polymorphism. A basic C++ program structure includes comments, preprocessor directives like #include, a main function enclosed in curly braces, and statements that end with semicolons. The main function is where program execution begins. Standard C++ libraries provide common functions and objects like cout for output.

Uploaded by

kemal Beriso
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 74

Fundamentals of the C/C++ Programming

Language
InTc 212
Lecture Note
A brief history of C/C++
• The Origins of C and C++:
• The 'C' programming language was originally developed
for and implemented on the UNIX operating system.
One of the best features of C is that it is not tied to any
particular hardware or system. This makes it easy for a
user to write programs that will run without any
changes on practically all machines.
• C is often called a middle-level computer language as it
combines the elements of high-level languages with the
functionalism of assembly language.
• C allows the manipulation of bits, bytes and addresses-
the basic elements with which the computer functions.
• Another good point about C is its portability.
A brief history of C/C++..
• C++ is an enhanced version of the C language.
• C++ includes everything that is part of C and adds
support for object-oriented programming (OOP).
• In addition, C++ also contains many improvements
and features that make it a "better C", independent of
object-oriented programming.
• C++ is actually an extendible language since we can
define new types in such a way that they act just like
the predefined types which are part of the standard
language.
• Some of the new features include encapsulation,
inline function calls, overloading operators,
inheritance and polymorphism for more information.
Introduction to C++ programming
 C++ was developed by Bjarne Stroustrup starting in 1979 at
Bell Labs in Murray Hill, New Jersey, as an enhancement to the
C language and originally named C with Classes but later it was
renamed C++ in 1983.

• C++ is a superset of C, the idea of c++ comes from c


increment operator ++; thereby suggesting that c++ is
an incremented version of c.
• Based up on C and simula, it was become the most
popular language for object-oriented programming.
• The most common versions of C++:
– DevC++
– Microsoft VC++2008
– Eclipse
– g++ (for Unix machines)
IT Dep't Fundamental of programming I
What is C++?
• C++ is a programming language.
• A computer program performs a specific task, and
may interact with the user and the computer
hardware.
• Human work model:

– Computer work model:


First program in C++
1. // the first C++ program
2. #include <iostream.h>
3. using namespace std;
4. int main()
5. {
6. cout << "Hello World!\n";
7. return 0;
8. }

6
C++ program structure
• Any types of c++ program have at least the following
components or structures:
Comments
Compiler directive
Using namespace std;
main function
Braces
Statement
7
Comments
 Comment will not compiled and also will not part of program,
means not executed.
 Comments are an additional information used for different
purpose.
– // symbols indicate a line comment
• apply to just the rest of the line
– Block comments start with /* and end with */
• apply to as many lines as you like
 The main purpose of comments are:
1. To remember what a given program does after let say, a month
or so.
2. To make our program easily understandable by any one when
read it.
 Generally comments are usually placed at the top of the
program
IT Dep't Fundamental of
programming I
C++ program structure
Compiler directives

Are instructions to the compiler rather than a C++


instructions that instruct the C++ compiler to load a
file from disk into the current program.

Begin with #
Eg. #include <iostream.h>

 Tells preprocessor to include the input/output stream


header file <iostream.h>
9
C++ program structure
• Pre-processor Directive
• # (hash) symbol is a signal to the processor, each time you start your
compiler the processor is run. Lines beginning with a hash ('#')
communicate to the preprocessor and are called "Preprocessor Directives“.
The preprocessor performs macro substitution, inclusion of named files
and conditional compilation.
– Things to do before compiling
– The preprocessor performs very minimal error checking of the
preprocessing instructions. Because it operates at a text level, it is
unable to check for any sort of language-level syntax errors. This
function is performed by the compiler.
• The following are preprocessor directives:
• #define #elif #else #endif #if #ifdef #ifndef #include
#line
#undef
• Libraries allow for code reuse
IT Dep't Fundamental of
programming I
C++ program structure
 The #include directive
• #include “adds” the contents of a given include file to another file.
• #include <iostream> tells the preprocessor to copy the standard I/O
stream library header file into the program.
• <iostream> declares the cout, cin and endl objects
– If you do not include it you cannot use these objects or anything else
"declared" in this file
• Note that the angle brackets < and > are not part of the file name;
they are used to indicate that this is a Standard C++ Library file.

• What about <iostream.h>?


• Very similar to <iostream>
• Also declares cin, cout and endl
– In the global namespace not in the std namespace
• This is for compatibility with older versions of C++.
IT Dep't Fundamental of
programming I
C++ program structure
• Using namespace std;
• Indicates to compiler that this program uses objects
defined by a standard namespace called std.
• “using”-indicates that a program is using elements from a
particular namespace.
• “Namespace”-Region where program elements are
defined.
Ends with a semicolon (;)
Follows #include directives in the code
Must appear in all programs

IT Dep't Fundamental of
programming I
C++ program structure
• Function main()
• Exactly one main function per program.
• A function is a collection of related statements int main ( )
that perform a specific operation.
• int indicates the return type of the function {
• ( ) indicates no special information passed to // function
the function by the operating system.The body
actual program execution starts from the main }
function.
• No main function means:
– nothing to run
– cannot build the program
• Link time error – file compiles OK but cannot
make
IT Dep't Fundamental of
programming II
C++ program structure
Braces { }
Are used to mark the beginning and the end of a
block of code.
Every opening brace must have a corresponding
closing brace.
Statements
Are instructions and commands that make the computer
work.
Each statement must end in semicolon (;).
The semicolon tells the compiler that the statement is
completed.
There are different types of statements
14
Types of Statements
• Declaration statements: describe the data the function
needs:
const float KM_PER_MILE = 1.609;
float miles, kms;
• Executable statements: specify the actions the
program will take:
cout << “Enter the distance in miles: “;
cin >> miles;

IT Dep't Fundamental of
programming II
Executable Statements
–Assignment statements
–Input statements
–Output statements
–The return statement

• Assignment statements
– variable = expression;
E.g.: kms = KM_PER_MILE * miles;

IT Dep't Fundamental of
programming II
Input Statements
• Obtain data for a program to use - different each time a
program executes
• Standard stream library iostream
• cin - name of stream associated with standard input
device (keyboard by default)
• Uses extraction operator (>>)
E.g.:
cin >> miles;
cin >> age >> firstInitial;

IT Dep't Fundamental of
programming II
Output Statements
• Used to display results of a program
• Uses standard stream library iostream
• cout - name of stream associated with standard output
device (monitor by default)
• Uses Insertion operator (<<) for each element
• Can prompt messages that is used to inform program
user to enter data
• endl (or ‘\n’) causes a new line in output
e.g.
cout << “The distance in kilometers is“
<< kms << endl;
If variable kms has value 16.09, the output becomes:
The distance in kilometers is 16.09
IT Dep't Fundamental of
programming II
The return Statement
• Last line of main function is typically
return 0;
• When a function returns a value it is given to the function that
calls it
• When main returns a value it is given to the operating system
(Windows)
• main (should) always return an int
• number is usually ignored by windows
– 0 means success
– greater than 0 means an error maybe a different number for
a different error
• This transfers control from the program to the operating system,
indicating that no error has occurred

IT Dep't Fundamental of
programming II
C++ program structure ..
 C++ is case sensitive because it interprets uppercase and
lowercase letters differently

For example

Cow and cow are two different combination of letters.

White space
 Blank lines, space characters and tabs

 Used to make programs easier to read

 Ignored by the compiler


20
Good Programming Practice
 Many programmers make the last character printed by a function a
newline (\n).

 This ensures that the function will leave the screen cursor
positioned at the beginning of a new line.

 Conventions of this nature encourage software reusability—a key


goal in software development.

 Indent the entire body of each function one level within the braces
that delimit the body of the function.

 This makes a program’s functional structure stand out and helps


make the program easier to read.
21
Compiling and Running a C++ Program
• Before we run C++ program, it must be compiled and then linked.
• Compile: - the process of converting a C++ program to an
equivalent object code (machine code) (done by compiler)
• Linking: - the process of combining the object code with library
functions to form a complete executable program.
Testing and Debugging

• In a complex program it is likely to occur a


mistake.

• A mistake in a program is usually called bug.


The process of eliminating bugs is called
debugging.
Types of Program errors
1. Syntax error: -
• Syntax: - is the general format of writing a command
(statement)
• Syntax error is an error due to violation of syntax (the
grammar rules of the programming language). Syntax
errors are usually detected by the compiler.
2. Run – time errors: - Errors that the computer detects while
the program runs. Eg-division by zero, square root to
negative numbers.
3. Logical errors: - this type of error is due to a mistake in the
underlying algorithm. The compiler does not detect these
types of errors. The program runs without any error
message but it gives a wrong out put.
//Example; this program prints Welcome to C++ Programming
#include <iostream> /* pre-processor directive */
using namespace std; // tells to compiler std
int main() // main function, start of program
{
int year = 2015; // an integer variable declaration
char entry; // a character variable
cout << "Welcome to C++ Programming" << year << '\n';
cout << "Enter 'x' to quit: ";
cin >> entry; // read input from user
cout << "Goodbye!\n";
return 0; // return value to operating system
}

IT Dep't Fundamental of programming II


//Write a program which displays the weeklyPay of an employee
and print out the result
#include <iostream> /* pre-processor directive */
using namespace std; // tells to compiler std
int main() // main function, start of program
{
int workDays = 5;
float workHours = 7.5;
float payRate = 38.55;
float weeklyPay = workDays * workHours * payRate;

cout << "Weekly Pay = ";


cout << weeklyPay;
cout << '\n';
}
//this program prints Named Constant
#include <iostream>
using namespace std;
int main( )
{
const double RATE = 6.9;
double deposit
cout << "Enter the amount of your deposit $";
cin >> deposit;
double newBalance;
newBalance = deposit + deposit*(RATE/100);
cout << "In one year, that deposit will grow to\n"
<< "$" << newBalance << " an amount worth waiting for.\n";
return 0;
}
Constants, Variables, data Types and
Operators
Lecture Note
Data types, Variables, and Constants
What is a Variables?
A variable is a named memory address or location in
computers’ memory that is used to store a value. It is possible
to retrieve a stored value by using its address in memory.
Your computer's memory can be viewed as a series of
storeroom.
Each storeroom or memory location is numbered sequentially.
These numbers are known as memory addresses.
A variable reserves one or more storeroom in which you
may store a value.
Variables have:
•Names
•Type (of data to store) and
•value (content of the address)
Constants
• Like variables, constants are data storage locations. Unlike
variables, and as the name implies, constants don't
change.
• You must initialize a constant when you create it, and you
cannot assign a new value later.
• C++ has two types of constants:
A. symbolic and
B. literal constant

A. A symbolic constant- is a constant that is represented


by a name, just as a variable is represented.
• Example Pi =3.1416, maximum=100;
IT Dep't Fundamental of
programming II
Con’t
B. A literal constant- is a value typed directly into your
program wherever it is needed.
• There are three types of literal constant:
• a) Value constants: are the values themselves
Numeric constant
• Example integers and decimals (2, 1.5, 3.1416,100...)
• b) Character constant: Any character within a single
quote.
‘A’, ‘ Z’, ‘a’, ‘s’, ‘2’, ‘0’, '$'
• c) String constant: a sequence of characters within
a double quote
• “Ethiopia “, “ Zero”, “ Selam”, "1234"
IT Dep't Fundamental of
programming I
Naming Variables
• The name that you choose for a variable is called an
identifier
• An identifier can be of any length, but must start with:

- a letter (a – z or A-Z)
- an underscore ( _ )
• Identifiers are case sensitive. In other words, uppercase
and lowercase letters are considered to be different. The
identifier “name” is different from “Name”, which is
different from “NAME”.

IT Dep't Fundamental of
programming I
The Identifiers rule in c++ are:
o It should start with letters or underscores.
o Consists only from letters, digits(0-9) or an underscore.
o Couldn’t contain special characters $,#,&…
o There couldn’t have embedded blank
 Eg, int my age; //incorrect
o Key words can’t be taken as variable
Eg. Int; char;
Upper and lower case significant
Examples, from the previous sample program
cin C++ name for standard input stream
cout C++ name for standard output stream
kms Data elementfor storing distance in kilometers
KM_PER_MILE Conversion constant
miles Data element for storing distance in miles
std C++ name for the standard namespace
IT Dep't Fundamental of
programming II
Reserved Words (Keywords)
• Have special meaning in C++
• Cannot be used for other purposes
Examples

bool, break, case, char, const,


continue, do, default, double,
else, extern, false, float, for,
if, int, long, namespace, return,
short, static, struct, switch,
typedef, true, unsigned, void,
while

IT Dep't Fundamental of
programming II
POP QUIZ

• Which of the following are valid variable names?


1)Amount5
2)6tally
3)my&Name
4)salary
5)_score
6)first Name
7)total#

IT Dep't Fundamental of
programming II
C++ Data Types & Variables Declaration

• Data types
– Defines a set of values and operations that can be
performed on those values
– C++ contains the following standard data types:
int Bool and
Float-point void
 char

IT Dep't Fundamental of
programming II
Basic Data types
• There are different types of data that our program
works on.
• The type of data stored in memory that is reserved by
a variable. Basic data types are found in c++ library
– Eg. int, char, float, double…

• When we specify data types we are specifying the


type of data and size of data that we want to store.
• Two types of basic data types:
• 1. numeric float-point(real nuber) and integer
• 2. character char=contains 1byte(i.e 256 character
value)
IT Dep't Fundamental of
programming II
Integer
 An integer type is a number without a
fractional part.
 It is also known as an integral number.
 C++ supports three different sizes of the
integer data type: short int, int and long int.
sizeof(short int)<= sizeof(int)<= sizeof(long int)

short int

int

long int

IT Dep't Fundamental of
programming II
Integer …
• Represented internally in binary
• Although the size is machine dependent, most PCs use the
integer sizes shown below.
Type Sign Byte Number Min Value Max Value
Size of Bits

short int Signed 2 16 -32768 32767


unsigned 0 65535

int Signed 4 32 -2,147,483,648 2,147,483,647


unsigned
0
4,294,967,295
long int Signed 4 32 -2,147,483,648 2,147,483,647
unsigned
0 4,294,967,295

IT Dep't Fundamental of
programming II
Floating Point
 A floating-point type is a number with a
fractional part, such as 43.32, 5.0, 3.66666666, -
0.000034.
 The C++ language supports three different sizes
of floating-point: float, double and long
double.

sizeof(float)<=sizeof(double)<=sizeof(long double)

float
double
long double

IT Dep't Fundamental of
programming II
Floating Point …
• stored internally in binary as mantissa and exponent
• Although the physical size of floating-point types is
machine dependent, many computers support the sizes
shown below.

type Byte size Number of Bits

float 4 32
double 8 64

long double 10 80

IT Dep't Fundamental of
programming II
Boolean & Character
• Boolean
– named for George Boole
– bool: used to represent conditional values
– values: true and false
• Characters
– represent individual character values
E.g. ‟A‟ ‟a‟ ‟2‟ ‟*‟ ‟”‟ ‟ ‟
– stored in 1 byte of memory
– special characters: escape sequences
E.g. ‟\n‟ ‟\b‟ ‟\r‟ ‟\t‟ „\‟‟
IT Dep't Fundamental of
programming II
String
• String is not built-in, but come from library
• String literal enclosed in double quotes
E.g.: “Enter speed: “ “ABC” “B” “true” “1234”
• #include <string.h>
– for using string identifiers, but not needed for literals

• void:
– It has no values and no operations.
– it is a very useful data type that we will discuss later.

IT Dep't Fundamental of
programming II
Declarations
• Constants and variables must be declared before they can
be used.
• A constant declaration specifies the type, the name and the
value of the constant.
• A variable declaration specifies the type, the name and
possibly the initial value of the variable.
• When you declare a constant or a variable, the compiler:
1.Reserves a memory location in which to store the value
of the constant or variable.
2.Associates the name of the constant or variable with the
memory location. (You will use this name for referring to
the constant or variable.)

IT Dep't Fundamental of
programming II
Constant declarations
• Constants are used to store values that never change
during the program execution.
• Using constants makes programs more readable and
maintainable.
Syntax:
const <type> <identifier> = <expression>;
Examples:
const double DOLLAR2BIRR = 19.25;
//Exchange rate of US $ to ETH Birr
const double EURO2BIRR = 25.60;
//Exchange rate of Euro to ETH Birr
const double POUND2BIRR = 1.51 * DOLLAR2BIRR;
//Exchange rate of Pound to ETH Birr
const float KM_PER_MILE = 1.609;
//mile is 1.609 KMs
IT Dep't Fundamental of
programming II
//for example...
Syntax: : const type var=Value;
• const- is a key word that tells the compiler that the
variable cannot change its value throughout the program.
• var: is the name of the variable.

• Value is: - any constant that matches the type in the


declaration.
• Note: The data type is optional, that is, it is implicitly
known from the value assigned
Examples:
const double US2HK = 7.8;
//Exchange rate of US$ to HK$
IT Dep't Fundamental of
programming II
Variable declarations
• Variables are used to store values that can be changed during
the program execution.
• A variable is best thought of as a container for a value.
3445 y -3.14
Syntax:
<type> <identifier>;
<type> <identifier> = <expression>;

Examples:
int sum;
int total = 3445;
char answer = 'y';
double temperature = -3.14;

IT Dep't Fundamental of
programming II
POP QUIZ

• What data types would you use to store the


following types of information?:

1)The number of students in the room


2)Location of a point on screen
3)Speed of light
4)Open/Closed status of a file
5)The first letter of your name
6)237.66

IT Dep't Fundamental of
programming II
What are Operators?
• Operators are the most basic units of a program. They
perform operations on primitive data types.
• Operators are special symbols used for mathematical
functions, assignment statements, and logical
comparisons

• As you know, expressions are statements that produce a


value. Some of the most common expressions are
mathematical and make use of operators

IT Dep't Fundamental of
programming II
• Today we will go over 5 different groups of operators:
– Arithmetic operators
– Assignment operator
– Relational operators
– Logical operators
– Increment/Decrement operators

As you learn more about C++ or Java, you


will learn additional operators

IT Dep't Fundamental of
programming II
Arithmetic Operators
• C++ has 4 basic arithmetic operators:
+,-,*, and /, which have the usual meanings – add,
subtract, multiply, and divide.
• The order of operations or precedence that applies
when an expression using these operators is
evaluated is the same as you learned at school.
• For example:
1. int number = 20 – 3*3 – 9/3 ;
will produce the value 8

2. int number = (20 – 3)*(3 – 9)/3;


is equivalent to 17*(-6)/3 will produce the
value -34
IT Dep't Fundamental of
programming II
• Modulus (%)

– Used only with integers


– Yields remainder - the result is integer
Examples:
5 % 7 = 5, 299 % 100 = 99, 49 % 5 = 4
15 % 0 undefined

IT Dep't Fundamental of
programming II
Rules for Division
• C++ treats integers differently from decimal numbers.
• 100 is an int type.
• 100.0 , 100.0000, and 100. are double type.
• The general rule for division of int and double types is:
– double/double -> double (normal)
– double/int -> double (normal)
– int/double -> double (normal)
– int/int -> int (note: the decimal part is discarded)
Examples:
– 220. / 100.0 double/double -> doublen result is 2.2
– 220. / 100 double/int -> double result is 2.2
– 220 / 100.0 int/double -> double result is 2.2
– 220 / 100 int/int -> int result is 2
IT Dep't Fundamental of
programming II
Assignment Operator
• Assignment operators include = as well as the
arithmetic operators (+,-,/,*, and %) used in
conjunction with it.
• For example:
1.
count += 5;
is equivalent to
count = count + 5;

2.
result /= a % b/(a+b);
is equivalent to
result = result / (a % b/(a+b));

IT Dep't Fundamental of
programming II
Assignment, Initialization
• You can assign a value to a variable by using the assignment
operator(=). The process of storing value (data) into a variable is
called assignment. If we write a=b; means take the value of b and
put inside a.
• Thus, you would assign 20 to width by writing
– int width ;
width=20;
You can combine these steps and initialize width when you define
it by writing:
int width=20;
 Initialization- looks very much like assignment, and with integer
variable, the difference is minor. The essential difference is that
initialization takes place at the moment you create the variable.
Just as you can define more than one variable at a time, you can
initialize more than one variable at creation.

 Exercise: create two int variables and assign, initialize them


Relational Operators
Operator Description

> Produces the value true if the left operand is greater


than the right operand, and false otherwise
>= Produces the value true if the left operand is greater
than or equal to the right operand, and false otherwise
== Produces the value true if the left operand is equal to
the right operand, and false otherwise
!= Produces the value true if the left operand is not equal
to the right operand, and false otherwise
<= Produces the value true if the left operand is less than
or equal to the right operand, and false otherwise

< Produces the value true if the left operand is less than
the right operand, and false otherwise
IT Dep't Fundamental of programming II
• For example:
int x = 3;
int y = 5;
boolean state;
1.
state = (x > y);
now state is assigned the value false because x is not greater
than y
2.
state = (15 == x*y);
now state is assigned the value true because the product of x
and y equals 15
3.
state = (x != x*y);
now state is assigned the value true because the product of x
and y is not equal to x

IT Dep't Fundamental of
programming II
Logical Operators
Symbol Long Name Examples
& Logical AND (5<6)&(5<7) T=1
&& Conditional AND (6<6)&&(5<6) f=0
| Logical OR (5<6)|(6<6) T=1
|| Conditional OR (5<6)||(6<6) T=1
! Logical negation !(5==5) f=0
(NOT)

Logical operators are only used to combine expressions


that have a value of true or false. Because they
operate on boolean values they are also referred to
as boolean operators.
IT Dep't Fundamental of programming II
Truth Table for Logical Operators
x y x&y x|y !x
x && y x || y
True True True True False

True False False True False

False True False True True

False False False False True

IT Dep't Fundamental of programming II


• For example:
boolean x = true;
boolean y = false;
boolean state;

1. Let state = (x & y);


now state is assigned the value false (see truth table!)

1. Let state = ((x | y) & x);


now state is assigned the value true (x | y) gives true
(see truth table!) and then (true & x) gives true

IT Dep't Fundamental of
programming II
• boolean x = true;
boolean y = false;
boolean state;

1. Let state = (((x || y) | (!x)) & ((! y)


& x))
now state is assigned the value true
(x II y) gives true; (! x) gives false;
so ((x || y) | (! x)) is equivalent to (true | false) which
gives true.
(! y) gives true;
so ((! y) & x) is equivalent to (true & x) which gives true.
So the whole expression for state is equivalent to (true
& true), that state is true.
IT Dep't Fundamental of
programming II
&& versus &
• The difference between && and & is that the
conditional && will not bother to evaluate the right-
hand operator if the left-hand operator is false,
since the result is already determined in this case to
be false. The logical & operator will evaluate both
terms of the expression.

|| versus |
• The difference between || and | is that the
conditional || will not bother to evaluate the right-
hand operator if the left-hand operator is true,
since the result is already determined in this case to
be true. The logical | operator will evaluate both
terms of the expression.
IT Dep't Fundamental of
programming II
We will come back to this example after we learn about
control structures.
• As we saw in the previous examples in most cases the
two operators are interchangeable. Here are examples
of where it matters which operator we use.
• if (++value%2 == 0 & ++ count < limit) {
// Do something
}
Here the variable count will be incremented in any
event. If you use && instead of &, count will only be
incremented if the left operand of the AND operator is
true. You get a different result depending on which
operator is used.

IT Dep't Fundamental of
programming II
• if (count > 0 && total/ count > 5) {
// Do something
}
In this case the right operand for the &&
operation will only be executed if the left
operand is True – that is, when count is
positive. Clearly, if we were to use & here, and
count happened to be zero, we will be
attempting to divide the value of total by 0,
which will terminate the program.

IT Dep't Fundamental of
programming II
Increment/Decrement Operators
• Let int count;
count = count + 1;
The statement above can be written as
++count; //This operator is called the increment
operator.

• The decrement operator has the same effect on


count for subtracting 1.
count = count - 1;
--count;

IT Dep't Fundamental of
programming II
• The increment/decrement operator has two forms:
I. The prefix form ++count, --count
first adds 1 to the variable and then continues to any other operator in
the expression
int numOrange = 5;
int numApple = 10;
int numFruit;
numFruit = ++numOrange + numApple;
numFruit has value 16
numOrange has value 6
II. The postfix form count++, count--
first evaluates the expression and then adds 1 to the variable
int numOrange = 5;
int numApple = 10;
int numFruit;
numFruit = numOrange++ + numApple;
numFruit has value 15
numOrange has value 6
IT Dep't Fundamental of
programming II
Precedence of operators
Precedence of Operators
• Precedence specifies the order in which an operation is
performed
• Consider the expression: a + b * c
The multiplication is carried out first, then the value of
b * c is added to a


Note: Some of these operators will not be familiar to you,
you will learn more about them in following lectures

IT Dep't Fundamental of programming I


Order of Operator Precedence
Highest
( ) nested expressions evaluated inside
out

unary: ++, --, !, -

Binary: *, /, %

Binary: +, -
Lowest

Warning: watch out for the types of operands and the type
of the result from evaluating each operand!
IT Dep't Fundamental of
programming II
Continued..
• But if there is a parentheses() then compiler
evaluates that first.
– eg. (5+2)*3+6/2
7*3+6/2
21+3=24
• Operator precedence
• Arithmetic has usual precedence
– parentheses
– Unary minus
– *, /, and %
– + and -
– operators on same level associate left to right
• N.B. The order in which the operators will be
process is called precedence.
POP QUIZ
• 1)What is the value of number?
int number = 5*3–3/6–9*3;
2) What is the value of state?
int x = 8;
int y = 2;
boolean state;
state = (15 == x*y);
3) What is the value of state?
boolean x = false;
boolean y = true;
boolean state;
state = (((x && y) & (!x)) || ((! y) | x))
4) What is the value of numCar?
What is the value of numGreeenCars?
int numBlueCars = 5;
int numGreenCars = 10;
int numCar;
numCar=numGreenCars++ + numBlueCars + ++numGreeenCars;

IT Dep't Fundamental of
programming II
// Demonstrate the features of output format manipulators
// Input: cost of lunch, number of people attending lunch
// Output: lunch cost per person
#include <iomanip> // Use IO manipulators
#include <iostream>
using namespace std;
int main()
{
double cost_of_lunch, cost_per_person;
int number_of_people;
cout << "Press return after entering a number.\n";
cout << "Enter the cost of lunch:\n";
cin >> cost_of_lunch;
cout << "Enter the number of people attending”
<< “ lunch:\n";
cin >> number_of_people;
cost_per_person = cost_of_lunch / number_of_people;
//cout << setiosflags(ios::fixed) << setprecision(2);
cout << "If the lunch cost is Birr ";
cout << cost_of_lunch;
cout << ", and you have " << number_of_people
<< " persons attending, then \n"; IT Dep't Fundamental of
programming II
// Demonstrate the features of output format manipulators

cout << "the cost per person is Birr "
<< cost_per_person << ".\n";
/*
cout << "the cost per person is $";
cout<<setprecision(4)<<cost_per_person << ".\n";
*/
return 0;
}
Output of example program:
Press return after entering a number.
Enter the cost of lunch:
800.75
Enter the number of people attending lunch:
9
If the lunch cost Birr 800.75, and you have 9
attending, then the cost is 88.9722.
Using setprecision(4) in the last cout statement can change the final result to
Birr 88.97.

IT Dep't Fundamental of
programming II
C++ Lab Assignments
1. Write a program which displays the sum of any
two numbers and print out the result
2. Write a program that calculates
a) The area of a triangle
b) The area of a circle
c) The area of a trapezium
3. Write a program which read three numbers u,a
and t and then calculate function S where
S=u*t +1/2 *a *t*t

You might also like