C

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 50

COM 313

OBJECT ORIENTED PROGRAMMING C++ (COOP)

WEEK ONE

INTRODUCTION
C++ is a statically typed, free-form, multi-paradigm, compiled, general-purpose programming
language. It is regarded as an intermediate-level language, as it comprises a combination of both high-
level and low-level language features. It was developed by Bjarne Stroustrup starting in 1979 at Bell
Labs as an enhancement to the C language and originally named C with Classes. It was renamed C++
in 1983.

C++ is one of the most popular programming languages and its application domains include systems
software, application software, device drivers, embedded software, high-performance server and client
applications, and entertainment software such as video games. Several groups provide both free and
proprietary C++ compiler software, including the GNU Project, Microsoft, Intel and Embarcadero
Technologies. C++ has greatly influenced many other popular programming languages, most notably
C# and Java.

Why C++?
C++ has certain characteristics over other programming languages. The most remarkable are:

Object-oriented programming
It is possible to orient programming to objects allows the programmer to design applications
from a point of view more like a communication between objects rather than on a structured
sequence of code. In addition it allows a greater reusability of code in a more logical and
productive way.
Portability
You can compile the same C++ code in almost any type of computer and operating system
without making any changes. C++ is the most used and ported programming language in the
world.
Brevity
Code written in C++ is very short in comparison with other languages, since the use of special
characters is preferred to key words, saving some effort to the.
Modular programming
An application's body in C++ can be made up of several source code files that are compiled
separately and then linked together. Saving time since it is not necessary to recompile the
complete application when making a single change but only the file that contains it. In addition,
this characteristic allows to link C++ code with code produced in other languages, such as
Assembler or C.
C Compatibility
C++ is backwards compatible with the C language. Any code written in C can easily be included
in a C++ program without making any change.
Speed
The resulting code from a C++ compilation is very efficient, due indeed to its duality as high-
level and low-level language and to the reduced size of the language itself.
OBJECT TECNOLOGY

Is an umbrella term for object-oriented programming, object-oriented databases, object-oriented


analysis and design.

Object technology differs from traditional system design which separates the data from the
processing. Although data and processing are naturally related since software causes the computer to
process data, the traditional approach has been to design the databases separate and apart from the
processing routines, often using different modeling and documentation tools. But in object oriented
database or system data are bind together with the system that process the data.

OBJECT-ORIENTED PROGRAMMING
Object-orientation is a set of tools and methods that enable software engineers to build reliable, user
friendly, maintainable, well documented, and reusable software system that fulfills the requirements
of its users. It is' claimed that object-orientation provides software developers with new mind tools to
use in solving a wide variety of problems. Object-orientation provides a new view of computation. A
software system is seen as a community of objects that cooperate with each other by passing messages
in solving a problem.

An object-oriented programming language provides support for the following object-oriented


concepts:
 Objects and Classes
 Inheritance
 Polymorphism and Dynamic Binding

The two most important concepts OOP are the Class and Object.

OBJECT
In the broad term, an object is anything you can ever imagine, either tangible or intangible. Any
program written in Object-Oriented programming will definitely consists of interacting objects. For a
program maintain student's resident of a college hostel, we may have student, room, and floor objects.
An object comprises of data and operation that manipulate the data.

for example. A student objects may consist of data such as name, gender, birth date, home address,
phone number e.t.c and operations for assigning and changing these data values.

CLASS
Inside a program, we must write instruction to create objects. For a computer to be able to create
Objects, we must provide a definition called a class. A class is a kind of mold or template that dictates
what objects can do and what it cannot do. An Object is called an instance of a class. An object is an
exactly instance of one class. An instance of a class belongs to the class.

SIMPLE C++ PROGRAM


This section will review this program in more detail. The program below shows a very simple program
in C++.

HELLO.CPP demonstrates the parts or a C++ program.


1: #include <iostream>
2: using namespace std;
3: int main()
4: {
5: cout << "Hello World!\n";
6: return 0;
7: }

Hello World!

line 1, the file iostream is included in the file.

The first character is the # symbol, which is a signal to the preprocessor. Each time you start your
compiler, the preprocessor is run. The preprocessor reads through your source code, looking for lines
that begin with the pound symbol (#), and acts on those lines before the compiler runs.

Include is a preprocessor instruction that says, "What follows is a filename. Find that file and read it
in right here." The angle brackets around the filename tell the preprocessor to look in all the usual
places for this file. If your compiler is set up correctly, the angle brackets will cause the preprocessor
to look for the file iostream in the directory that holds all the files for your compiler. The file iostream
(Input-Output-Stream) is used by cout and cin, which assists with writing to the screen. The effect of
line 1 is to include the file iostream into this program as if you had typed it in yourself.

New Term: The preprocessor runs before your compiler each time the compiler is invoked. The
preprocessor translates any line that begins with a pound symbol (#) into a special command, getting
your code file ready for the compiler.

Line 2 (using namespace std;) tells the C++ compiler to apply the prefix std:: to resolve names that
need prefixes. It allows us to use cout in place of std:: cout. This makes larger programs easier to read.

Line 3 begin the actual program with a function named main(). Every C++ program has a main()
function. in general, a function is a block or code that performs one or more actions. Usually functions
are invoked or called by other functions, but main() is special. When your program starts, main() is
called automatically.

Main(), like all functions, must state what kind of value it will return. The return value type for main()
in HELLO.CPP is void, which means that this function will not return any value at all. All functions
begin with an opening brace ({) and end with a closing brace (}). The braces for the main() function
are on lines 4 and 7. Everything between the opening and closing braces is considered a part of the
function.

The meat and potatoes of this program is on line 5. The object cout is used to print a message to the
screen.

These two objects, cout and cin, are used in C++ to print strings values to the screen and input data to
the system respectively. A string is just a set of characters.
Here's how cout is used: type the word cout, followed by the output insertion operator (<<). Whatever
follows the output redirection operator is written to the screen. If you want a string of characters
written, enclose them in double quotes ("), as shown on line 5.

New Term: A text string is a series of printable characters.


All ANSI-compliant programs declare main() to return an int. This value is "returned" to the operating
system when your program completes. Some programmers signal an error by returning the value 1. In
this handout, main() will always return 0.

The main() function ends on line.7 with the closing brace.

Input Using cin


The global object cin is responsible for input and is made available to your program when you include
iostream. Use the extraction operator (>>) to put data into your program's variables. How does
this work? The syntax is as follows:

int someVariable;
cin >> someVariable;

Output using cout


We use cout to print data to the screen. To print a value to the screen, write the word cout, followed
by the insertion operator (<<), which you create by typing the less-than character (<) twice. Even
though this is two characters, C++ treats it as one.

Follow the insertion character with your data. Your lab manual on Output using cout "Example
10"shows how this works.

COMMENTS
When you writing a program, it is always clear and self-evident what you are trying to do. Funny thing,
later, when you return to the program, it can be quite confusing and unclear. I'm not sure how that
confusion creeps into your program, but it always does.

To fight the onset of confusion, and to help others understand your code, you'll want to use comments.
Comments are simply text that is ignored by the compiler, but that may inform the reader of what you
are doing at any particular point in your program. I

Types of Comments
C++ comments come in two flavors: the double-slash (//) comment and the slash-star (/*) comment.
The double-slush comment, which will be referred to as a C++-style comment, tells the compiler to
ignore everything that follows this comment, until the end of the line.
The slash-star comment mark tells the compiler to ignore everything that follows until it finds a star-
slash (*/) comment mark. These marks will be referred: to as C-style. Comments. Every /* must be
matched with a closing */

WEEK TWO
NAMING RULES FOR VARIABLES

C++ has rules that limit the forms of names used for variables. Some of these are:
 Variables have names that start with a letter (uppercase or lowercase), or an underscore
character ( _ ).
 The names contain only letters (abcdefghijklmnopqrstuvwxyzABC...YZ), digits
(0123456789) and underscore characters _.
 You can't use C++ "reserved words",
In addition, you should remember that the libraries define some variables (e.g, the variable cin is
defined in the iostream library). Use of a name that is already been defined in a library that you
have #included will result in an error message.

C++ is case-sensitive. In other words, uppercase and lowercase letters are considered to be different. A
variable named age is different from Age, which is also different from AGE.

DATA TYPE
The various data type in C++ are as follow
 Integer
 Float
 Boolean types
 Character Data type

Integer types: integer number is a whole number. In other way, it is any number without a decimal
point. There are six integer types in standard C++; these types actually have several names. For
example:

Data type Range


 short int -32,768 to 32,767 (28 values – 1 byte)
 Int -2,147,483,647 to 2,147,483,647 (232 values – 4bytes)
 Long -2,147,483,647 to 2,147,483,647 (232 values – 4bytes)
 Unsigned short 0 to 65,535; (28 values – 1 bytes)
 Unsigned int 0 to 4,294,967,295 (232 values – 4 bytes)
 Unsigned long 0 to 4,294,967,295 (232 values – 4 bytes)

You can determine the numerical ranges of the integer types on your system by running this
program.
Example 1
#include<iostream>
#include<limits>
using namespace std;
Int main()
{
Cout<<”minimum short = “<<SHRT_MIN<<endl;
Cout<<”maximum short = “<<SHRT_MAX<<endl;
Cout<<”maximum unsigned short = 0“<<endl;
Cout<<”maximum unsigned short = 0“<<USHRT_MAX<<endl;
Cout<<”minimum int = “<<INT_MIN<<endl;
Cout<<”maximum int = “<<INT_MAX<<endl;
Cout<<”minimum unsigned int = 0“<<endl;
Cout<<”maximum unsigned = “<<UINT_MAX<<endl;
Cout<<”minimum long = “<<LONG_MIN<<endl;
Cout<<”maximum long = “<<LONG_MAX<<endl;
Cout<<”minimum unsigned long = 0“<<endl;
Cout<<”maximum unsigned long = 0“<<ULONG_MAX<<endl;
}

FLOATING-POINT TYPE
C++ supports three (3) real number types: That is, float, double and long double. On most system,
double used twice as many bytes as float. Typically, float uses 4 bytes, double uses 8 bytes and long
double uses 8, 10, 12, or 16 bytes.

Types that are used for real numbers are called "Floating-point" types because of the way they are
stored internally in the computer. On some system, it is converted to binary form.

Example 2
#include <iostream>
Using namespace std;
Int main( )
{ // test the floating-point operators +,-,*, and /;
Double x = 23.2;
Double y = 10.5;
cout<<” x = “ << x << “ and y = “ << y <<endl;
cout << “ x + y = “ << x + y << endl;
cout << “x – y = “ << x – y << endl’
cout << “x*y = “ << x * y <<end;
cout <<” x % y = “ << x % y <<endl;
}

BOOLEAN DATA TYPES


A Boolean type is an integer types whose variable can only have two values: True and False.
These values arc stored as integers 0 and 1. The Boolean type in Standard C++ is named bool.

Example 3
#include<iostream>
using namespace std;
int main( )
{ / / prints the value of a Boolean variable
Bool flag = false;
cout << “ flag = “ << flag << endl;
flag = true;
cout << “ flag = “ << flag << endl;
}
CHARACTER DATA TYPE
A character type is an integer whose variable represent character like the letter ‘A’ or the digit '8'. The
character literals delimited by the apostrophe (‘), Like all integer type values. Character values are
stored as integers.

Example 4
#include<iostream>
using namespace std;
int main()
{ char c = ‘A’;
cout<<”c = “ << c <<”, int(c) = “ << int(c) <<endl;
c = ‘t’;
cout<<”c = “ <<c<<”, int(c) = “ << int(c) <<endl;
cout<<’\t’; // the tab character
cout<<”c = “ << c <<”, int(c) = “ << int(c) <<endl;
c=’!’;
cout<<”c = “ << c << “, int(c) = “ int(c) <<endl;
}

TYPES OF OPERATORS IN C++


Several operations can be performed in C++ just like another programming language. This is achieved
through the use of some of the operators mentioned below. These are
 Relational operator
 Mathematical operator
 Logical operators
 Increment and decrement operator
 Assignment operator

RELATIONAL OPERATORS
The relational operators are used to determine whether two numbers are equal, or if one is greater or
less than the other, Every relational statement evaluates to either 1 (TRUE) or 0 (FALSE). The
relational operators are presented in your lab manual. Example:

If the integer variable myAge has the value 39, and the integer variable yourAge has the value 40, you
can determine whether they are equal by using the relational "equals" operator:

myAge == yourAge; // is the value in myAge the same as in yourAge?

This expression evaluates to 0, or false, because the variables are not equal.

The expression:

myAge> yourAge; // is myAge greater than yourAge? Evaluates to 0 or false,

WARNING: Many novice C++ programmers confuse the assignment operator (=) with the equals
operator (==). This can create a nasty bug in your program.
There are six relational operators. These are:
 Equals (==),
 less than (<),
 greater than (>)
 less than or equal to (<=)
 greater than or equal to (>=)
 and not equals (!=).

The Relational Operators


Name operator Sample Evaluates
Equals ==100 == 50; False
50 == 50; True
Not Equal != 100 != 50; True
50!= 50; False
Greater Than > 100 > 50; True
50 > 50; False
Greater Than >= 100 >= 50; True
Or Equals 50 >= 50; True
Less Than < 100 < 50; False
50 < 50; False
Less Than <= 100 <= 50; False
Or Equals 50 <= 50; True

DO remember that relational operators return the value 1 (true) or 0 (false). DON'T confuse the
assignment operator (=) with the equals relational operator (==). This is one of the most common C++
programming mistakes--be on guard for. Check Example 5 of your lab manual to see a sample program
on relational and logical operators.

WEEK THREE

TYPES OF OPERATORS IN C++


Several operations can be performed in C++ just like another programming language. This is achieved
through the use of some of the operators mentioned below. These are
 Relational operator
 Mathematical operator
 Logical operators
 Increment and decrement operator
 Assignment operator

RELATIONAL OPERATORS
The relational operators are used to determine whether two numbers are equal, or if one is greater or
less than the other, Every relational statement evaluates to either 1 (TRUE) or 0 (FALSE). The
relational operators are presented in your lab manual. Example:

If the integer variable myAge has the value 39, and the integer variable yourAge has the value 40, you
can determine whether they are equal by using the relational "equals" operator:

myAge == yourAge; // is the value in myAge the same as in yourAge?

This expression evaluates to 0, or false, because the variables are not equal.

The expression:

myAge> yourAge; // is myAge greater than yourAge? Evaluates to 0 or false,

WARNING: Many novice C++ programmers confuse the assignment operator (=) with the equals
operator (==). This can create a nasty bug in your program.

There are six relational operators. These are:


 Equals (==),
 less than (<),
 greater than (>)
 less than or equal to (<=)
 greater than or equal to (>=)
 and not equals (!=).

The Relational Operators


Name operator Sample Evaluates
Equals == 100 == 50; False
50 == 50; True
Not Equal != 100 != 50; True
50!= 50; False
Greater Than > 100 > 50; True
50 > 50; False
Greater Than >= 100 >= 50; True
Or Equals 50 >= 50; True
Less Than < 100 < 50; False
50 < 50; False
Less Than <= 100 <= 50; False
Or Equals 50 <= 50; True

DO remember that relational operators return the value 1 (true) or 0 (false). DON'T confuse the
assignment operator (=) with the equals relational operator (==). This is one of the most common C++
programming mistakes--be on guard for. Check Example 5 of your lab manual to see a sample program
on relational and logical operators.

MATHEMATICAL OPERATOR
Computers were invented to perform numerical calculations. Like most programming languages, C++
performs its numerical calculations by means of the five operators named below:
 Addition (+)
 Subtraction (-)
 Multiplication (*)
 Division (/)
 Modulus (%)

Integer Division and Modulus


Integer division is somewhat different from everyday division. When you divide 21 by 4, the result is
a real number (a number with a fraction). Integers don't have fractions, and so the "remainder" is lopped
off. The answer is therefore 5. To get the remainder, you take 21 modulus 4 (21 % 4) and the result is
1. The modulus operator tells you the remainder after an integer division.

Finding the modulus can be very useful. For example, you might want to print a statement on every
10th action. Any number whose value is 0 when you modulus 10 with that number is an exact multiple
of 10. Thus 1 % 10 is 1, 2% 10 is 2 and so forth, until 10 % 10, whose result is O. 11 % 10 is back to 1,
and this pattern continues until the next multiple of 10, which is 20. Check "Example 2" in your Lab
Manual for simple program on this.

LOGICAL OPERATORS
Often you want to ask more than one relational question at a time. "Is it true that x is greater than y,
and also true that y is greater than z?" A program. might need to determine that both of these conditions
are true, or that some other condition is true, in order to take an action.

Imagine a sophisticated alarm system that has this logic: "If the door alarm sounds AND it is after six
p.m. AND it is NOT a holiday, OR if it is a weekend, then call the police." C++'s three logical operators
are used to make this kind of evaluation. These operators are listed in Table below:

The Logical Operators

Operator symbol Example


AND && Expression1 && expression2
OR || Expression1 ||expressinn2
NOT ! !expression
Logical AND
A logical AND statement evaluates two expressions, and if both expressions are true, the logical AND
statement is true as well. if it is true that you are hungry, AND it is true that you have money, THEN it
is true that you can buy lunch. Thus, If ( (x == 5) && (y == 5) )
Would evaluate TRUE since both x and y are equal to 5, and it would evaluate FALSE if either one is
not equal to 5.

Note that both sides must be true for the entire expression to be true.

Logical OR
A logical OR statement evaluates two expressions. If either one is true, the expression is true. If you
have money OR you have a credit card, you can pay the bill. You don't need both money and a credit
card; you need only one, although having both would be fine as well. Thus,
If ( (x == 5) || (y == 5) )
Evaluates TRUE if either x or y is equal to 5, or if both are.

Logical NOT
A logical NOT statement evaluates true if the expression being tested is false. Again, if the expression
being tested is false, the value or the test is TRUE! Thus
If ( !(x == 5) )
is true only if x is not equal to 5. This is exactly the same as writing if (x !==5).

Example 5
#include<iostream>
using namespace Std;
Int main()
{
Int n1, n2, n3;
cout<<”enter three integers” << endl;
cin>> n1 >> n2 >> n3;
if (n1 <= n2 && n1 <= n3) cout <<”Their minimum is “ << n1 << endl;
if (n2 <= n1 && n2 <= n3) cout <<”Their minimum is “ << n2 << endl;
if (n3 <= n1 && n3 <= n2) cout <<”Their minimum is “ << n3 << endl;

Example 5.1 program that computes the grade of a student


#include<iostream>
using namespace std;
Int main()
{
Int score;
Cout<<” Enter the student’s score”<<endl;
cin>>score;
if((score<0) || (score > 100))
cout<<”This is an invalid score! Pls try again”<<endl;
else
if (score <= 39)
cout<<”The student’s grade is F (Failed!) ”<<endl;
else

if (score <= 44)


cout<<”The student’s grade is E (Fair!) ”<<endl;
else
if (score <= 49)
cout<<”The student’s grade is D (Pass!) ”<<endl;
else
if (score <= 59)
cout<<”The student’s grade is C (Credit!) ”<<endl;
else
if (score <= 69)
cout<<”The student’s grade is B (Very Good!) ”<<endl;
else
{cout<<”the student’s garde is A (Excellent!”)<<endl;
Cout<<”Congratulation! You’ve won yourself a scholarship!”<<endl;}
Return 0;
}

INCREMENT AND DECREMENT


The most common value to add (or subtract) and then reassign into a variable is 1. In C++, increasing
a value by 1 is called incrementing, and decreasing by 1 is called decrementing. There are special
operators to perform these actions.

The increment operator (++) increases the value of the variable by 1, and the decrement operator (--)
decrease it by 1. Thus you have a variable. C. and you want to increment it, you would use this
statement:

C++; // Start with C and increment it.


This statement is equivalent to the more verbose statement
C = C + 1;
Which you learned is also equivalent to the moderately verbose statement
C + = 1;
PREFIX AND POSTFIX
Both the increment operator (++) and the decrement operator (--) come in two varieties: prefix and
postfix. The prefix variety is written before the variable name (++myAge); the postfix
Variety is written after (myAge++).'

In a simple statement, it doesn't much matter which you use, but in a complex statement, when you are
incrementing (or decrementing) a variable and then assigning the result to another variable, it matters
very much. The prefix operator is evaluated before the assignment, the postfix is evaluated after.
The semantics of prefix is, this: Increment the value and then fetch it. The semantics of postfix is
different: Fetch the value and then increment the original.

This can be confusing at first, but if x is an integer whose value is 5 and you write

int a = ++x;

You have told the compiler to increment x (making it 6) and then fetch that value and assign it to a.
Thus, a is now 6 and x is now 6.

If, after doing this, you write

int b = x++;

You have now told the compiler to fetch the value in x (6) and assign it to b, and then go back and
increment x. Thus, b now 6, but x is now 7.

Example 6:
//A sample program for pre-increment and post increment demonstrates use of prefix and postfix
increment and decrement operators.

1: #include <iostream>
2: using namespace std;
3:
4: int main()
5: {
6: // initialize two integers
7: int myAge = 39;
8: int yourAge = 39;
9: cout <<”I am: “<<myAge<<” years old.\n”;
10: cout <<”You are: “<<yourAge<<” years old\n”;
11: myAge++; // postfix increment
12: ++yourAge; // prefix increment
13: cout <<”One year passes...\n;
14: cout <<”I am: “<<myAge<< “ years old.\n
15: cout <<”You are: “<<yourAge<< “ years old\n”;
16: cout <<”Another year passes\n”;
17: cout <<”I am: “<<myAge++<< “ years old.\n”;
18: cout <<”You are: “<<++yourAge<<” years old\n”;
19: cout <<”Let’s print it again.\n”;
20: cout <<”I am: “<<myAge<< “ years old.\n”;
21: cout <<”You are: “<<yourAge<< “ years old\n”;
22: return 0;
23: }

Output:
I am 39 years old
You are 39 years old
One year passes
I am 40 years old
You are 40 years old
Another year passes
I am 40 years old
You are 41 years old
Let’s print it again
I am 41 years old
You are 41 years old

Analysis: on lines 7 and 8, two integer variables are declared, and each is initialized with the value 39.
their value are printed on lines 9 and 10.
On line 11, myAge is incremented using the postfix increment operator, and on line 12, yourAge is
increment using the prefix increment operator. The results are printed in line 14 and 15, and they are
identical (both 40).
On line 17, myAge is increment as part of the printing statement, using the postfix increment operator.
Because it is postfix, the increment happens after the print, and so value 40 is printed again, in contrast.
On line 18, yourAge is incremented using the prefix increment operator. Thus it is incremented before
being printed, and the value displays is 41 for yourAge.

Program 6.1
#include<iostream>
using namespace std;
Int main()
{
int m, n;
m=44; n=++m;
cout<<”m = “ << m <<”,n = “ << n << endl;
m = 44; n = m++;
cout<<”m = “ << m <<”, n = “ << n << endl;
return 0;
}
Output
m = 45, n = 45
m = 45, n = 44

ASSIGNMENT OPERATORS
Some standard assignment operators in C++ are as follows:
Operator Example Is The Same As
= x=y x=y
+= x+=y x=x+y
-= x-=y x=x-y
*= x*=y x=x*y
/= x/=y x=x/y
.= x.=y x=x.y
% x%=y x=x%y

Example 7: Sample program of an Assignment operators


#include<iostream.h>
int main()
{
int n = 50;
cout<<” n = “ << n << endl;
n += 10;
cout<<”After n += 10, n = “ << n << endl;
n -= 20;
cout<<”After n -= 20, n = “ << n << endl;
n *= 12;
cout<<”After n *= 12, n = “ << n << endl;
n /= 12;
cout<<”After n /= 10, n = “ << n << endl;
n %= 7;
cout<<”After n %= 7, n = “ << n << endl;
return 0;
}
WEEK FOUR

THE CONDITIONAL ( OR TERNARY) OPERATOR (?:)

The conditional operator is an operator used in C and C++ (as well as other languages, such as C#).
The ?: operator returns one of two values depending on the result of an expression. The syntax is:

(conditional statement ? True “ False);

expression 1 ?expression 2: expression 3

If expression 1 evaluates to true, then expression 2 is evaluated.

If expression 1 evaluates to false, then expression 3 is evaluated instead.

#include<iostream>
Int main()
{
Int a,b;
cout<<”enter any two numbers :”;
cin>>a>>b;
( a < b ? cout<<”the minimum is : “<<a<<endl : cout<<“the minimum is: “<< b <<endl):
}
KEYWORDS
Keywords are reserved to the compiler for use by the language. You cannot define classes, variables,
or functions that have these keywords as their names.
The list is a bit arbitrary, as some of the keywords are specific to a given compiler. Your mileage may
vary slightly:
auto break case catch char
class const continue default delete
do double else enum extern
float for friend goto if
int long mutable new operator
private protected public registerreturn
short signed sizeof static struct
switch template this throw typedef
union unsigned virtual void volatile
while

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: literal and symbolic.

Literal Constants
A literal constant is a value typed directly into your program wherever it is needed. For example int
myAge = 39;
myAge is a variable of type int; 39 is a literal constant. You can't assign a value to 39 and its value can't
be changed.

Symbolic Constants
A symbolic constant is a constant that is represented by a name just as a variable is represented. Unlike
a variable, however, after a constant is initialized, its value can't be changed.
If your program has one integer variable named students and another named class, you could compute
how many students you have, given a known number of Classes, if you knew there were 15 students per class:
Student = classes * 15;

Example 8
A program that uses literal and symbolic constant
#include<iostream>
int main()
{
const pi = 3.142;
double area, r;
cout<<”Enter the radius value”;
cin>>r;
area = pi * r * r;
cout<<:The Area of a circle = :<< area <<endl;
return 0;
}
WEEK FIVE

LOOP STATEMENT
There may be a situation, when you need to execute a block of code several number of times. In
general, statements are executed sequentially: The first statement in a function is executed first,
followed by the second, and so on.

Programming languages provide various control structures that allow more complicated execution
paths.
A loop statement allows us to execute a statement or group of statements multiple times and following
is the general from of a loop statement in most of the programming languages.

C++ programming language provides the following type of loops to handle looping requirements.

 For loop
 While loop
 Do-while loop

1) For loop:
The for-loop is the most commonly used statement in C++. This loop consists of three expressions.
The first expression is used to initialize the index value. The second to check whether or not the loop
is to be continued again and the third to change the index value for further iteration.

The syntax of the loop is:


For (expression 1, expression2, expression3)
Statement;

Where expression1 is the initialization of the condition; expression2 is the checked as long as the given
expression is true; and expression3 is the increment or decrement to change the index value of the for
loop variable.
In other words
For (initial condition, test condition, increment or decrement)
{
Statement1;
Statement2
……
}

Thus, consider a simple program show below

Int main()
{
int n;
cout<< “Enter a positive interger:”;
cin>> n;
long sum=0;
for (int i=1; i <=n; i++)
sum +=i;
cout << “the sum of the first “<< n <<” integers is “ << sum;
}

2) While loop
The while loop is used when we are not certain that the loop will be executed. After checking whether
the initial condition is true or false and finding to be true, only then the while loop will enter into the
loop operations.

The general syntax of the while loop is;


For a single statement:

While (condition)
Statement;

For bock of statements;

While (condition)
{
Statement1;
Statement2;
-------------
-----------
}

The while-loop does not explicitly contain the initialization or incrementing part of the loop. These two
statements are normally provided by the programmers.

Initial condition
While (test condition)
{
Statement1;
Statement2;
Change the initial condition:
}
This program compute the sum 1+2+3+…………………………n, for an input integer n:
Int main()
{
int n, i=1;
cout<< “Enter a positive integer:”;
cin>> n;
long sum=0;
while (i<=n)
sum +=i++;
cout<< “The sum of the first “<< n << ” integers is ”<< sum;
}

Sometimes, the operations carried out by while loop can also be done by using the for loop. However,
it is the programmer whom has to decide which loop to be used in a given situation.

3) Do while loop
The do-while loop is another repetitive loop used in C++ programs. Whenever one is certain about a
test condition, the do-while loop can be used, as it enters into the loop at least once and then check
whether the given condition is true, the loop operations or statements will be repeated again and again.
As in the case of a while loop, here is also three expressions are used to construct this loop. Expression}
is used to initialize the index value that normally appears out of the loop; cxpression2 to change the
index value and the expression3 to check whether or not the loop is to be repeated again.

The syntax of the do-while loop is:

Do {
Statement1;
Stutement2;
…………...
}
While (expression);

In other words, the above do-while loop is equivalent to:

Expression1 Do
{
Statement1;
Statement2;
………….;
Expresion2
}
Whi1e (expression3);

Example this program has the same effect as the one in while loop above.

Int main( )
{
Int n, i=1;
cout << “Enter a positive integer: ”;
cin >> n;
long sum =0;
do
sum +=i++;
while (i<=n);
cout << “the sum of the first ”<< n << “ integers is “<< sum;
}
PRACTICAL

Week one

Activity: Explaining C++ compiler, C++ editor and compilation of a simple Program.
Aims: To identify different component of C++, Compilation of simple C++ program and how to
retrieve C++ Program.
Procedure: installing Visual Studio.
The lecturer introduces the C++ environment to the students.
The lecturer guides the students in using C++ editor.
The lecturer showed the students the various ways of compiling C++ source code after typing.
The lecturer showed the students how a project a can be save and retrieved.
The lecturer writes and compiles the programs below as examples and finally asked students to
solve the exercises that follow:

Elementary C++ programming


0.1 A program that will print “hello, welcome to C++ class” on the screen.
#include<iostream>
Using namespace std;
Int main()
{
cout<<” hello, welcome to C++ class”<<endl;
Return 0;
}

0.2 A C++ program that will print a block letter B in 7x6 grid of stars like this

*****
* *
* *
*****
* *
* *
*****
#include<iostream>
Using namespace std;
Int main()
{
cout<< “*****”<<endl;
cout<<”* *”<<endl;
cout<<”* *”<<endl;
cout<<”*****”<<endl;
cout<<”* *”<<endl;
cout<<”* *”<<endl;
cout<<”*****”<<endl;
}

Exercises:
1. Write a C++ program that print the name of your course code on the screen.
2. Write a C++ program that print block letter ‘D’ in gride of stars on the screen.

PRACTICAL

Week two

Activity: knowing how C++ compiler calls the various in the system memory.
Aims: To enable the student to know the numerical ranges of the integer types on system by running
the program below:
Procedure: writing a single program that will print the various integers’ type in the system.
#include<iostream>
#include<limits>
Using namespace std;
Int main()
{
Cout<<”minimum short = “<<SHRT_MIN<<endl;
Cout<<”maximum short = “<<SHRT_MAX<<endl;
Cout<<”maximum unsigned short = 0“<<endl;
Cout<<”maximum unsigned short = 0“<<USHRT_MAX<<endl;
Cout<<”minimum int = “<<INT_MIN<<endl;
Cout<<”maximum int = “<<INT_MAX<<endl;
Cout<<”minimum unsigned int = 0“<<endl;
Cout<<”maximum unsigned = “<<UINT_MAX<<endl;
Cout<<”minimum long = “<<LONG_MIN<<endl;
Cout<<”maximum long = “<<LONG_MAX<<endl;
Cout<<”minimum unsigned long = 0“<<endl;
Cout<<”maximum unsigned long = 0“<<ULONG_MAX<<endl;
}

Exercise:
1. Write the program above in C++ editor, compile it and write out the output.
2. modify the program above to cater for real numbers like float, double e.t.c

Week 3

Activity: To be able to understand the general format of Arithmetic, Boolean and char expression.
 To assist the student to write simple C++ program that perform all these basi arithmetic
operators
 To enable the student to write simple C++ Boolean program.
Aims: To enable the student to see how a simple C++ can be used to perform all these basic arithmetic
operators, Boolean operation and Character type.
Procedure: Writing a simple program that perform arithmetic operators like (+,-,*,/,%), Boolean
and character type.

Example2: Arithmetic operators sample program


// This sample program illustrate how arithmetic operators works using constant values 23.0 and 10.0
for x and y respectively.
#include <iostream>
Using namespace std;
Int main( )
{ // test the floating-point operators +,-,*, and /;
Double x = 23.2;
Double y = 10.5;
cout<<” x = “ << x << “ and y = “ << y <<endl;
cout << “ x + y = “ << x + y << endl;
cout << “x – y = “ << x – y << endl’
cout << “x*y = “ << x * y <<end;
cout <<” x % y = “ << x % y <<endl;
}
Note: Unlike integer division, floating-point does not truncate the result

Example 3
#include<iostream>
using namespace std;
int main( )
{ / / prints the value of a Boolean variable
Bool flag = false;
cout << “ flag = “ << flag << endl;
flag = true;
cout << “ flag = “ << flag << endl;
}
Example 4
#include<iostream>
using namespace std;
int main()
{ char c = ‘A’;
cout<<”c = “ << c <<”, int(c) = “ << int(c) <<endl;
c = ‘t’;
cout<<”c = “ <<c<<”, int(c) = “ << int(c) <<endl;
cout<<’\t’; // the tab character
cout<<”c = “ << c <<”, int(c) = “ << int(c) <<endl;
c=’!’;
cout<<”c = “ << c << “, int(c) = “ int(c) <<endl;
}

Exercise 2:
1. Write the C++ programs above in your Editor, compile it and write out the output.
2. Write a simple program that will ask user to enter values for two variables and will perform all
arithmetic operators o the variables.

Week 4

Activity: To be able to understand the general format of relational and logical operators.
Aims: To assist the student to write simple C++ program that use relational and logical operators.
Procedure: Writing a simple C++ program that performs relational and logical operations.

Example 5:
A program that returned the minimum number out of three given numbers using Relational and Logical
operators.
#include<iostream>
Using namespace std;
Int main()
{
Int n1, n2, n3;
cout<<”enter three integers” << endl;
cin>> n1 >> n2 >> n3;
if (n1 <= n2 && n1 <= n3) cout <<”Their minimum is “ << n1 << endl;
if (n2 <= n1 && n2 <= n3) cout <<”Their minimum is “ << n2 << endl;
if (n3 <= n2 && n3 <= n2) cout <<”Their minimum is “ << n3 << endl;

}
Example 5.1 program that computes the grade of a student
#include<iostream>
Using namespace Std;
Int main()
{
Int score;
Cout<<” Enter the student’s score”<<endl;
cin>>score;
if((score<0) || (score > 100))
cout<<”This is an invalid score! Pls try again”<<endl;
else
if (score <= 39)
cout<<”The student’s grade is F (Failed!) ”<<endl;
else

if (score <= 44)


cout<<”The student’s grade is E (Fair!) ”<<endl;
else
if (score <= 49)
cout<<”The student’s grade is D (Pass!) ”<<endl;
else
if (score <= 59)
cout<<”The student’s grade is C (Credit!) ”<<endl;
else
if (score <= 69)
cout<<”The student’s grade is B (Very Good!) ”<<endl;
else
{cout<<”the student’s garde is A (Excellent!”<<endl;
Cout<<”Congratulation! You’ve won yourself a scholarship!”<<endl;}
Return 0;
}

//Using ternay operator


The syntax is:
(conditional statement ? True “ False);

#include<iostream.h>
Int main()
{
Int a,b;
cout<<”enter any two numbers :”;
cin>>a>>b;
( a < b ? cout<<:the minimum is : “<<a<<endl : cout<<:the minimum is: “<< b <<endl):
}

Exercise 5:
1. Write a program that returns the maximum and the minimum out of three given numbers using
relational and logical operator.
2. write a C++ program that returns the minimum out of two given numbers using ternary
operators.
3. Write a C++ program that request the user to enter two value and check if one is divisible by
another using ternary operator.
4. Modify Example 5.1 above using switch – case – break
WEEK 5

Activity: A program and analysis on how post increment and pre-increment operator are used in a
program

Aims: To assist the students to know the different between the pre-increment and post-increment
operators even though they are both use to increment by one.

Procedure: Writing a simple C++ program that implements pre-increment and post-increment
operations.

Example 6:
//A sample program for pre-increment and post increment demonstrates use of prefix and postfix
increment and decrement operators.
4: #include <iostream.h>
5: int main()
6: {
7: int myAge = 39; // initialize two integers
8: int yourAge = 39;
9: cout <<”I am: “<<myAge<<” years old.\n”;
10: cout <<”You are: “<<yourAge<<” years old\n”;
11: myAge++; // postfix increment
12: ++yourAge; // prefix increment
13: cout <<”One year passes...\n;
14: cout <<”I am: “<<myAge<< “ years old.\n
15: cout <<”You are: “<<yourAge<< “ years old\n”;
16: cout <<”Another year passes\n”;
17: cout <<”I am: “<<myAge++<< “ years old.\n”;
18: cout <<”You are: “<<++yourAge<<” years old\n”;
19: cout <<”Let’s print it again.\n”;
20: cout <<”I am: “<<myAge<< “ years old.\n”;
21: cout <<”You are: “<<yourAge<< “ years old\n”;
22: return 0;
23: }
Output: I am 39 years old
You are 39 years old
One year passes
I am 40 years old
You are 40 years old
Another year passes
I am 41 years old
You are 41 years old
Let’s print it again
I am 41 years old
You are 41 years old
Analysis: on lines 7 and 8, two integer variables are declared, and each is initialized with the value 39.
their value are printed on lines 9 and 10.
On line 11, myAge is incremented using the postfix increment operator, and on line 12, yourAge is
increment using the prefix increment operator. The results are printed in line 14 and 15, and they are
identical (both 40).
On line 17, myAge is increment as part of the printing statement, using the postfix increment operator.
Because it is postfix, the increment happens after the print, and so value 40 is printed again, in contrast.
On line 18, yourAge is incremented using the prefix increment operator. Thus it is incremented before
being printed, and the value displays as is the value in yourAge.

Program 2
#include<iostream>
using namespace etd;
Int main()
{
int m, n;
m=44;
n=++m;
cout<<”m = “ << m <<”,n = “ << n << endl;
m = 44; n = m++
cout<<”m = “ << m <<”, n = “ << n << endl;
return 0;
}
Output
M = 45, n = 45
M = 45, n = 44

Exercise:
 Modify program 1 above to request for your age as at last year and should use the value to give
your age this year and what your age will be by next year using increment: pre-increment and
post increment.
 Modify program 2 to be user interactive.

WEEK SIX

C++ DECISION MAKING STATEMENTS


Decision making structures require that the programmer specify one or more conditions to be
tested by the program, along with a statement or statements to be executed if the condition is
determined to be true, and optionally, other statements to be executed if the condition is
determined to be false.

C++ programming language provides following types of decision making statements.


 If statement
 If ...else statement
 If...else if...else Statement
 switch statement
 nested if statements
 nested switch statements
If statement
An if statement consists of a Boolean expression followed by one or more statements.

Syntax
The syntax of an if statement in C++ is.

If (boolean expression)
{
//statement(s) will execute if the boolean expression is true
}

If the Boolean expression evaluates to true, then the block of code inside the if statement will
be executed. If Boolean expression evaluates to false, then the first set of code after the end of
the if statement (after the closing curly brace) will be executed.

Example
#include <iostream>
using namespace std;

int main ()
{
int a = 10;
if( a < 20 )
{
cout << "a is less than 20;" << endl;
}
cout << "value of a is : " << a << endl;
return 0;
}

When the above code is compiled and executed, it produces the following result.

a is less than 20;


value of a is : 10

If ...else statement
An if statement can be followed by an optional else statement, which executes when the
boolean expression is false.

Syntax
The syntax of an if...else statement in C++ is
If (boolean_expression)
{
// statement(s) will execute if the boolean expression is true
}
else
{
// statement(s) will execute if the boolean expression is false
}

If the boolean expression evaluates to true, then the if block of code will be executed,
otherwise else block of code will be executed.

Example
#include <iostream>
using namespace std;

int main ()
{
int a = 100;

if ( a < 20 )
{
cout << "a is less than 20;" << endl;
}
Else
{
cout << "a is not less than 20;" << endl;
}
cout << "value of a is : " << a << endl;

return 0; }

When the above code is compiled and executed, it produces the following result.

a is not less than 20;


value of a is : 100

If...else if...else Statement


An if statement can be followed by an optional else if...else statement, which is very useful to
test various conditions using single if...else if statement.

Syntax
The syntax of an if...else if...else statement in C++ is −
If (boolean_expression 1)
{
// Executes when the boolean expression 1 is true
}
else if( boolean_expression 2)
{
// Executes when the boolean expression 2 is true
}
else if( boolean_expression 3)
{
// Executes when the boolean expression 3 is true
}
else
{
// executes when the none of the above condition is true.
}

Example

#include <iostream>
using namespace std;

int main ()
{
int a = 100;

if ( a == 10 )
{
cout << "Value of a is 10" << endl;
}
else if( a == 20 )
{
cout << "Value of a is 20" << endl;
}
else if( a == 30 )
{
cout << "Value of a is 30" << endl;
}
else
{
cout << "Value of a is not matching" << endl;
}
cout << "Exact value of a is : " << a << endl;
return 0;
}

When the above code is compiled and executed, it produces the following result.

Value of a is not matching


Exact value of a is : 100

Switch statement

A switch statement allows a variable to be tested for equality against a list of values. Each
value is called a case, and the variable being switched on is checked for each case.

Syntax
The syntax for a switch statement in C++ is as follows
switch (expression)
{
case constant-expression :
statement(s);
break; //optional
case constant-expression :
statement(s);
break; //optional
// you can have any number of case statements.
default : //Optional
statement (s);
}

Example
#include <iostream>
using namespace std;

int main () {
char grade = 'D';

switch (grade)
{
case 'A' :
cout << "Excellent!" << endl;
break;
case 'B' :
case 'C' :
cout << "Well done" << endl;
break;
case 'D' :
cout << "You passed" << endl;
break;
case 'F' :
cout << "Better try again" << endl;
break;
default :
cout << "Invalid grade" << endl;
}
cout << "Your grade is " << grade << endl;

return 0;
}

You passed
Your grade is D

The following rules apply to a switch statement:


 The expression used in a switch statement must have an integral or enumerated type,
or be of a class.
 You can have any number of case statements within a switch. Each case is followed by
the value to be compared to and a colon.
 The constant-expression for a case must be the same data type as the variable in the
switch, and it must be a constant or a literal.
 When the variable being switched on is equal to a case, the statements following that
case will execute until a break statement is reached.
 When a break statement is reached, the switch terminates, and the flow of control jumps
to the next line following the switch statement.
 Not every case needs to contain a break. If no break appears, the flow of control will fall
through to subsequent cases until a break is reached.
 A switch statement can have an optional default case, which must appear at the end of
the switch. The default case can be used for performing a task when none of the cases
is true. No break is needed in the default case.
Nested if statements
It is always legal to nest if-else statements, which means you can use one if or else if
statement inside another if or else if statement(s).

Syntax
The syntax for a nested if statement is as follows −
if ( boolean_expression 1)
{
// Executes when the boolean expression 1 is true
if (boolean_expression 2)
{
// Executes when the boolean expression 2 is true
}
}

Example
#include <iostream>
using namespace std;

int main () {
int a = 100;
int b = 200;

if( a == 100 )
{
// if condition is true then check the following
if( b == 200 )
{
// if condition is true then print the following
cout << "Value of a is 100 and b is 200" << endl;
}
}
cout << "Exact value of a is : " << a << endl;
cout << "Exact value of b is : " << b << endl;

return 0;
}

When the above code is compiled and executed, it produces the following result.

Value of a is 100 and b is 200


Exact value of a is : 100
Exact value of b is : 200
Read nested switch statements
It is possible to have a switch as part of the statement sequence of an outer switch. Even if the
case constants of the inner and outer switch contain common values, no conflicts will arise.

C++ specifies that at least 256 levels of nesting be allowed for switch statements.
Syntax

The syntax for a nested switch statement is as follows

switch(ch1) {
case 'A':
cout << "This A is part of outer switch";
switch(ch2) {
case 'A':
cout << "This A is part of inner switch";
break;
case 'B': // ...
}
break;
case 'B': // ...
}

#include <iostream>
using namespace std;

int main () {
int a = 100;
int b = 200;

switch(a)
{
case 100:
cout << "This is part of outer switch" << endl;
switch(b)
{
case 200:
cout << "This is part of inner switch" << endl;
}
}
cout << "Exact value of a is : " << a << endl;
cout << "Exact value of b is : " << b << endl;

return 0;
}

This is part of outer switch


This is part of inner switch
Exact value of a is : 100
Exact value of b is : 200

WEEK 7
Activity: To modularized large programs into subprograms (functions)
Aims: To assist the students to know the function (both in-built and user defiend) and libraries in C++
and how they are used in a C++ program.
Procedure: Writing a simple C++ program containing function and the main program that use this
functions
Example 9:
A program to find the sum of the given numbers using function declaration with the return statement.
#include<iostream>
using namespace std;
void main()
{
float Sum(float, float, float);
float x; float y; float z;
cout<<”Enter the three number to add”<<endl;
cin>>x,y,z;
float total;
total = Sum(x,y,z);
cout<<”the sum of the three numbers is = :”<< total << endl;
}
float Sum(float a, float b, float c) // function definition
{
float temp;
temp = a + b + c;
return (temp);
}
Exercise:
 Write a program to find the factorization of given positive number using function declaration.
 Write a program that print date using function declaration. Hint: use if……….else statement.
 Write a function that swaps any two objects that are passed to it. Write a C++ program that uses
your function.

WEEK SEVEN

FUNCTION AND LIBRARY

FUNCTIONS
A complex problem may be decomposed into a small or easily manageable parts or modules called
Functions. Functions are very useful to read, write, debug and modify complex programs. They can
also be incorporated easily in the main program. In C++, the main itself is a function means the main
function is invoking the other functions to perform various tasks. There are two types of function.
These are user-define function and built-in function.

DEFINING A FUNCTION
A function definition has a return-type, name, parenthesis ( ) pair containing zero or more parameters
and a body. For each parameter, there should be a corresponding declaration that occurs before the
body. Any parameters' not declare is taken to be int by default. It is good programming practice to
declare all parameters.

The general format of the function definition is given below:

Functiontype functionname (datatype argument1, datatype argument2, .. )


{
Body of function
---------------------
---------------------
Return 0;
}

DECLARATION OF FUNCTION

(a) Declaring the type of a function: refers to the type of value it would return to the calling portion
of the program. Any of the basic data types such as int, float, char e.t.c may appear in the function
declarations. In many compilers, when a function is not suppose to return any value, it may be declared
as type void, which informs the compiler not to save any temporary space for a value to be sent back
to the calling program.

For example:
1. void function_ name ( ..... )
2. int function_name ( ....... )
3. float function_name ( .... )
4. char function_name ( ..... )

(b) Function name: can be any name conforming to the syntax rules of the variables. Normally, a
function name is made relevant to the function operation.

For example;
1. square( ),
2. display_value ( )
3. swap( ) etc.

(c) Formal arguments: any variable declared in the body of a function is said to be local to that
function. Other variables which are not declared either as arguments or in the function body are
considered global to the function and must be defined externally.

For example:
1. void square ( int a, int b)
// a, b re the formal arguments
{
……..……;
…..………;
}

2. int counter ( float xl, float x2, int y1, int y2)
{ // xI, x2, y1, and y2 are the formal arguments
……………;
……………;
Return (int value);
}

(a) Function body: Is a statement or a block of statements is enclosed between the { and the }. In
C++, each function is declared almost like main ( ) function. .

For example;
Float find_sum (int a, int b, int c, float r, float y)
{
Int i, j, n;
………….;
Return (expression);
}
Example:
A program to demonstrate a function declaration, function calling and function
definition in C++.
#include <iostream>
using namespace std;
void main ( )
{
void display ( ); // function declaration
display ( ); // function calling
return;
}
void display (void) // function definition
{
cout << "this is a test program \n ";
cout <<” in C++ \n";
}
The main ( ) function invokes the display ( ) function. In C++, each function is almost like separate
program.

Return statement
The keyword return is used to terminate function and returns a value to its caller. The return statement
may also be used to exit a function without returning a value. The return statement may or may not
include an expression.

The general syntax of the return statement is;


Return (expression);

USER-DEFINED FUNCTIONS
At times, the great varieties of function provided by the C++ compiler might not be sufficient enough
for a programmer to use. In this case, user define functions is introduced. This allows, the programmer
to define their own functions.

Here is a simple example of user-defined function:

lnt cube (int x)


{
// returns cube of x
return x * x * x;
}

The function return the cube of the integer passed to it. Thus, the call cube (2) would return 8
A user-defined function has two parts: its head and its body.
The syntax for the head of a function is

Return-type name (parameter-list)

This specify to the compiler the function return type, its name, and it parameter list. In the example
above, the function's return type is int, its name is cube, and its parameter list is int x. So, its head is
int cube (int x).

The body of the function is the block of code that follows its head. It contains the code that performs
the function's action, including the return statement that specifies the value that the function sends back
to the place where it was called. The body of the cube function is:

{
// returns cube of x
return x * x *x;
}

This is about as simple body as function could have. Usually, the body is much larger. But the
function's head typically fits on a single line.
Note that main () itself is a function. Its head is

int main() and its body is the program itself. Its return type is int, its name is main. and its parameter
list is empty.

A function's return statement serves two purposes: it terminates the execution of the function, and it
returns a value to the calling program.

Its syntax is
return expression

Where expression is any expression whose value could be assigned to a variable whose type is the
same as the function's return type. Consult your Lab manual for program on user-defined function.

Example:
A program to find the sum of the given numbers using function declaration with the return statement.

#include<iostream>
using namespace std;
void main( )
{
float Sum(float, float, float);
float x; float y; float z;
cout<<”Enter the three number to add”<<endl;
cin>>x,y,z;
float total;
total = Sum(x,y,z);
cout<<”the sum of the three numbers is = :”<< total << endl;
}
float Sum(float a, float b, float c) // function definition
{
float temp;
temp = a + b + c;
return (temp);
}

LIBRARIES

A library is a package of code that is meant to be reused by many programs. Typically, a C++ library
comes in two pieces:

1) A header file that defines the functionality of the library and exposing it to the programs using it.

2) A precompiled binary that contains the implementation of that functionality pre-compiled into
machine language.

Libraries are precompiled for several reasons

 First, since libraries hardly change, they do not need to be recompiled often. It would be a waste
of time to recompile the library every time you wrote a program that used them.

 Second, because precompiled objects are in machine language, it prevents people from
accessing or changing the source code, which is important to businesses or people who don’t
want to make their source code available for intellectual property reasons.

Built-in functions
Built-in functions are part of your compiler package (library) --they are supplied by the manufacturer
of your compiler. Many of the built-in function you use will have their function prototypes already
written in the files you include in you program by using #include. For functions you write yourself,
you must include the prototype.

The function prototype is a statement, which means it ends with a semicolon. It consists of the
function's return type, name, and parameter list.
The parameter list is a list of all the parameters and their types, separated by commas.
Some C++ libraries functions (In-built functions) are:

 iostream: standard C++ input output library


 stdio: alternate input output library (standard for C programs)
 cmath functions: things like sine, cosine, tan, log, exponential etc.
 string functipns: for manipulating sequences of characters ("strings") - copying them, searching
for occurrences of particular letters, etc.
 ctype functions: for testing whether a character is a letter or a digit, is upper case or lower case,
etc. limits constants defining things like largest integer that can be used on a particular machine.
 Stdlib: assorted "goodies" like U function for generating random numbers.

Example Sample program on cout is used in C++ Output Using cout


1: // using cout
2: #include<iostream>
3: using namespace std;
4: int main()
5: {
6: cout<< “Hello there.\n”;
7: cout << “Here is 5: “<< 5 << “\n;
8: cout << “The manipulator endl writes a new line to the screen. “<<endl;
9: cout << “Here is a very big number:\t” << 70000 << endl;
10: cout << “Here is the sum of 8 and 5:\t” << 8+5 << endl;
11: cout << “Here’s a fraction:\t\t” << (float) 5/8 << endl;
12: cout << “And a very very big number:\t” << (double) 7000 * 7000 <<endl;
13: cout << “Don’t forget to replace Ahmad Ibrahim with your name…\n”;
14: cout << “Opeyemi Ibrahim is a C++ programme!\n;
15: return 0;
16: }

Hello there.
Here is 5:5
The manipulator endl writes a new line to the screen
Here is a very big number: 70000
Here is the sum of 8 and 5: 13
Here’s a fraction: 0.625
And a very big number: 4.9e+07

On line 2, the statement #include <iostream> causes the iostream file to be added to your source code.
This is required if you use cout and its related functions.
On line 6 is the simplest use of cout, printing a string or series of character. The symbol \n is a special
formatting character. It tells cout to print a newline character to the screen. Three values are passed to
cout on line 7, and each value is separated by the insertion operator. The first value is the string “Here
is 5: “. Note the space after the colon. The space is part of the string. Next, the value 5 is passed to the
insertion operator and the newline character (always in double quotes or single quotes). This causes the
line.
Here is 5:5 to be printed to the screen. Because there is no newline character after the first string, the
next value is printed immediately afterwards. This is called concatenating the two values.
On line 8, an informative message is printed, and then the manipulator endl is used. The purpose of
endl is to write a new line to the screen. On line 9, a new formatting character, \t, is introduced. This
insert a tab character and is used on line 8-12 to line up the output. Line 9 shows that not only integers,
but long integers as well can be printed. Line 10 demonstrates that cout will do simple addition. The
value of 8+5 is passed to cout, but 13 is printed.
On line 11, the value 5/8 is inserted into cout. The term (float) tells cout that you want this value
evaluated as a decimal equivalent, and so a fraction is printed. On line 12 the value 7000 * 7000 is
given to cout, and the term (double) is used to tell cout that you want this to be printed using scientific
notation.
On line 14, you substituted your name, and the output confirmed that you are indeed a C++
programmer. It must be true, because the computer said so.
WEEK 8

THE SCOPE OF VARIABLE IN C++


A scope is a region of the program and broadly speaking there are three places, where variables can
be declared.
 Inside a function or a block which is called local variables,
 In the definition of function parameters which is called formal parameters.
 Outside of all functions which is called global variables.

We learn what a function is and it's parameter in previous week. Here let us explain what local and
global variables are.

Local variables: these are variables defined inside a function block or a compound statement.
For example:

Void funct ( int i, int j )


{
Int k, m; // local variables
……………….;
……………….;
/ / body of the function
}

The integer k and m are defined within a function block of the funct( ). All the variables to be used
within the function block must either defined at the beginning of the block itself or before using it in a
statement.

Global variable: Global variables are variables defined outside the main function block. These
variables are referred by the same data type and by the same name throughout the program in both
calling portion of a program and function block. i
For example:

int x, y = 4; // global declaration void


main( )
{
Void function1 ( )
x = 10;
…………..;
…………..;
Function1( );
}
Function1( )
{
int sum;
sum = x +y;
………......;
}

Example:

#include <iostream>
using namespace std;
// Global variable declaration:
int g;
int main () {
// Local variable declaration:
int a, b;
// actual initialization
a = 10;
b = 20;
g = a + b;
cout << g;
return 0;
}

POINTER
As you know every variable is a memory location and every memory location has its own address
defined which can be accessed using ampersand (&) operator which denotes an address in memory.
Consider the following which will print the address of the variables defined.

Example
#include <iostream>
using namespace std;
int main ( )
{
int var1;
char var2 [10];
cout << "Address of var1 variable: " << &var1 << endl;
cout << "Address of var2 variable: " << &var2 << endl;
return 0;
}

When the above code is compiled and executed, it produces the following result

Address of var1 variable: 0xbfebd5c0


Address of var2 variable: 0xbfebd5b6
What is a pointer?
A pointer is a variable whose value is the address of another variable. Like any variable or constant,
you must declare a pointer before you can work with it. The general form of a pointer variable
declaration is −
type *var-name;

Storing the Address in a Pointer


Every variable has an address. Even without knowing the specific address of a given variable, you can
store that address in a pointer.

For example, suppose that howOld is an integer variable. To declare a pointer called pAge to hold its
address, you would write

int howOld;
int *pAge = 0;

int *pAge = &howOld;

This declares pAge to be a pointer that is declared to hold the address of an integer variable. Note that
pAge is a variable like any variables. When you declare an integer variable (type lnt), it is set to hold
an integer. When you declare a pointer variable like pAge, it is set up to hold an address.

In the example above, pAge is initialized to zero. A pointer whose value is zero is called a null pointer.
All pointers, when they are created, should be initialized to something. If you don't know what you
want to assign to the pointer, assign 0. A pointer that is not initialized is called a wild pointer. Wild
pointers are very dangerous.

Pointer Names
Pointers can have any name that is legal for other variables. This handout follows the convention of
naming all pointers with an initial p, as in pAge of pnumber.

The Indirection Operator (*)


When a pointer is dereferences, the value at the address stored by the pointer is retrieved.
Normal variables provide direct access to their own values. If you create a new variable of type
unsigned int called yourAge, and you want to assign the value in howOld to that new variable, you
would write

unsigned int yourAge;


yourAge = howOld;

A pointer provides indirect access to the value of the variable whose address it stores. To assign the
value in howOld to the new variable yourAge by way of the pointer pAge, you would write

yourAge = *pAge;

The indirection operator (*) in front of the variable pAge means "the value stored at" This assignment
says, "Take the value stored at the address in pAge and assign it to yourAge."

NOTE: The indirection operator (*) is used in two distinct ways with pointers: declaration and
dereference.

When a pointer is declared, the star indicates that it is a pointer, not a normal variable. For example,
Unsigned int * pAge = 0; // make a pointer to an unsigned int

When the pointer is dereferences, the indirection operator indicates that the value at the memory
location stored in the pointer is to be accessed, rather than the address itself.

myAge = *pAge; // assign the value at of the address holds by pAge to myAge

Also note that this same character (*) is used as the multiplication operator. The compiler knows
which operator to call, based on context.

POINTERS, ADDRESSES, AND VARIABLES


It is important to distinguish between a pointer, the address that the pointer holds, and the value at the
address held by the pointer. This is the source of much confusion about pointers. Consider the
following code fragment:

Int theVarable = 5;

Int * pPointer = &theVariable;

theVariable is declared to be an integer variable initialize with the value 5. pPointer is declared to be
a pointer to an integer; it is initialized with the address of theVariable. pPointer is the_pointer. The
address that pPointer holds is the address of theVariable. The value at the address that pPointer holds
is 5.

Example using diagram


POINTER TO POINTER
A pointer may point to another pointer. For example
char c = ‘t’;
char *pc = &c;
char **ppc = &pc;
char ***pppc = &ppc;

***pppc = 'w'; // changes value of c to 'w'


We can visualize these variables like this:
The assignment ***pppc = ‘w’ refers to the contents of the address pc that' is pointed to by the address
ppc that is pointed to by the address pppc. Consult "Example 12" in your lab manual for sample of
pointer to pointer.

Example 12: Manipulating Data by Using Pointers


1: //Using pointers
2: #include <iostream.h>
3: typeof unsigned short int USHORT;
4: int main( )
5: {
6: USHORT myAge: // a variable
7: USHORT *pAge = 0; // a pointer
8: myAge = 5;
9: cout << “myAge” << myAge << “\n”;
10: pAge = &myAge; // assign address of myAge to pAge
11: cout << “*pAge: “ << *pAge << “\n\n”;
12: cout << “*pAge = 7\n”;
13: *pAge = 7; // sets myAge to 7
14: cout << “*pAge: “ << *pAge << “\n”;
15: cout << “myAge: “ <<myAge << “\n\n”;
16: cout << “myAge = 9\n”;
17: myAge = 9;
18: cout << “myAge;” << myAge << “\n”;
19: cout<< “*pAge:” << *pAge<<”n”;
20: return 0;
21: }

Output: myAge: 5
*pAge: 5
*pAge = 7
*pAge: 7
myAge: 7

myAge = 9
myAge: 9
*pAge: 9
Analysis: This program declares two variables: an unsigned short, myAge, and a pointer to an unsigned
short, pAge. myAge is assigned the value 5 on line 8; this is verified by the printout in line 9.
On line 10, pAge is assigned the address of myAge. On line 11, pAge is deferenced and printed,
showing that the value at the address that pAge stores is the 5 stored in myAge. In line 12, the value 7
is assigned to the variable at the address stored in pAge. This sets myAge to 7, and the printouts in line
14-15 confirm this.
In line 17, the value 9 is assigned to the variable myAge. This value is obtained in line 18 and inderctly
(by deferencing pAge) in line 19.

WEEK 8
Activity: Manipulating Data by Using Pointers.
Aims: demonstrates how the address of a local variable is assigned to a pointer and how the pointer
manipulates the values in that variable.
Procedure: Writing a simple C++ program to demonstrate how it works
Note the Once a pointer is assigned the address of a variable, you can use that pointer to access the data
in that variable
Example 11: Manipulating Data by Using Pointers

1: //Using pointers
2: #include <iostream.h>
3: typeof unsigned short int USHORT;
4: intmain()
5: {
6: USHORT myAge: // a variable
7: USHORT * pAge = 0; // a pointer
8: myAge = 5;
9: cout << “myAge” “ << myAge << “\n”;
10: pAge = &myAge; // assign address of myAge to pAge
11: cout << “*pAge: “ << *pAge << “\n\n”;
12: cout << “*pAge = 7\n”;
13: *pAge = 7; // sets myAge to 7
14: cout << “*pAge: “ << *pAge << “\n”;
15: cout << “myAge: “ <<myAge << “\n\n”;
16: cout << “myAge = 9\n”;
17: myAge = 9;
18: cout << “myAge;” << myAge << “\n”;
19: cout<< “*pAge:” << *pAge<<”n”;
20: return 0;
21: }

Analysis: This program declares two variables: an unsigned short, myAge, and a pointer to an unsigned
short, pAge. myAge is assigned the value 5 on line 8; this is verified by the printout in line 9.
On line 10, pAge is assigned the address of myAge. On line 11, pAge is deferenced and printed,
showing that the value at the address that pAge stores is the 5 stored in myAge. In line 12, the value 7
is assigned to the variable at the address stored in pAge. This sets myAge to 7, and the printouts in line
14-15 confirm this.
In line 17, the value 9 is assigned to the variable myAge. This value is obtained in line 18 and inderctly
(by deferencing pAge) in line 19.

Exercise:
 Write and compile the program above then write out the output.
 Substitutes the variable myAge and the pointe *pAge with yourAge and *pOld respectively.

You might also like