Fund Ofprog In-C++chp 2 3
Fund Ofprog In-C++chp 2 3
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.
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
Begin with #
Eg. #include <iostream.h>
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
White space
Blank lines, space characters and tabs
This ensures that the function will leave the screen cursor
positioned at the beginning of a new line.
Indent the entire body of each function one level within the braces
that delimit the body of the function.
- 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
IT Dep't Fundamental of
programming II
POP QUIZ
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…
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
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.
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.
Examples:
int sum;
int total = 3445;
char answer = 'y';
double temperature = -3.14;
IT Dep't Fundamental of
programming II
POP QUIZ
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
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
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
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.
< 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)
IT Dep't Fundamental of
programming II
• boolean x = true;
boolean y = false;
boolean state;
|| 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.
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
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