0% found this document useful (0 votes)
307 views109 pages

Object-Oriented Programming Basics

The document provides information on object-oriented programming language skills for database administration. It discusses basic C++ syntax such as headers, functions, return types, and variables. It also covers data types in C++ including integer, character, float, and double types. Finally, it describes operators in C++ like arithmetic, relational, logical, and assignment operators.

Uploaded by

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

Object-Oriented Programming Basics

The document provides information on object-oriented programming language skills for database administration. It discusses basic C++ syntax such as headers, functions, return types, and variables. It also covers data types in C++ including integer, character, float, and double types. Finally, it describes operators in C++ like arithmetic, relational, logical, and assignment operators.

Uploaded by

gashu asmare
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd

Injibara Polytechnic College

Ethiopian TVET-System
INFORMATION TECHNOLOGY
Database Administration system
Level IV
LEARNING GUIDE # 1
Unit of Competence: Apply Object-Oriented Programming
Language Skills
Module Title: Applying Object-Oriented Programming Language
Skills
LG Code : ICT DBA4 M05 LO1 0412
TTLM Code : ICT DBA4 M05 0412 v2
Page82

Page 1
LO1. Apply basic language syntax and layout
Information Sheet#1 Apply basic language syntax and layout

[Link] Basic language syntax rules and best practices


What are the Basic programming languages?
Some of the basic programming languages are:
 C, C++, JAVA, Visual Studio (Visual [Link], C-Sharp(C#), and Visual C++), and so on.
 C is a programming language developed in the 1970's alongside (together with) the UNIX
operating system.
 C provides a comprehensive set of features for handling a wide variety of applications, such
as systems development and scientific computation.
 C++ is an “extension” of the C language, in that most C programs are also C++ programs.
 C++, as opposed to C, supports “object-oriented programming.”
 When learning a new language, the first program people usually writes is one that
acknowledgment of the world :)
 C++ is an enhanced C language typically used for object oriented programming.

Here is the Hello world program in C++.


#include <iostream.h>//header or package
int main() { //main function
cout << “Hello world!”; //return type
return 0;
}

 Syntax is a rule that specify how valid instructions (constructs) are written.
Page82

Example: C++ Basic Syntax contains:


 Headers (Package)  Variable
 Return type  Data type
 Main function
 Header: The C++ language defines several headers, which contain information that is
necessary to your program.
 Function: function is a portion of code within a larger program, which performs a specific
task and is relatively independent of the remaining code.
Example: #include <iostream>
int main()
{
std::cout << "Hello World"; // function

Page 2
return 0;
}

 Return type: Return type is used to terminate main ( ) function and causes it to return the
value to its type.
 If a function is defined as having a return type of void, it should not return
a value.
 If a function is defined as having a return type other than void, it should
return a value.
Example :#include <iostream>
int main()
{
std::cout << "Hello World”;
return 0;// return type
}

 Main function: The main function Main () is a function where program execution begins.
Example: #include <iostream.h>
int main()// main function
{
std::cout << "Hello World";
return 0;
}

 Variable: A variable is the name for a memory location where you store some data. A
variable in C++ must be declared (the type of variable) and defined (values assigned to a
variable) before it can be used in a program.
#include <iostream>
using namespace std;
int main( )
Page82

{
char name[50]; // variable declaration or variable
cout << "Please enter your name: ";
cin >> name;
cout << "Your name is: " << name << endl;
}

Page 3
 Variable declaration
Meaning: variable <variable-name> will be a variable of type <type>
Where type can be:

 int //integer
 double //real number

 char //character

Example:
int a, b, c;
double x;
int sum;
Char my-character;

1.2. Understanding Data-Types, Operators and Expressions


Data type:
A data type defines which kind of data will store in variables and also defines memory
storage of data.
There are two kinds of data types User defined data types and Standard data types.
The C++ language allows you to create and use data types other than the fundamental data
types.
These types are called user-defined data types.
 In C++ language, there are four main data types
int
float
double
char
Page82

1. Character data type


A keyword char is used for character data type. This data type is used to represents letters
or symbols.
A character variable occupies 1 byte on memory.
2. Integer data types
 Integers are those values which have no decimal part and they can be positive or negative. Like
12 or -12.
There are 3 data types for integers
a. int
b. short int
c. long int
 Int keyword is used for integers. It takes two bytes in memory.

Page 4
There are two more types of int data type.
i. Signed int    or short int (2nd type of integer data type)       
ii. Unsigned int or unsigned short int
 Signed int: The range of storing value of signed int variable is -32768 to [Link] can interact
with both positive and negative value.
 Unsigned int: This type of integers cannot handle negative values. Its range is 0 to 65535.
 Long int 
 As its name implies, it is used to represent larger integers.
 It takes 4byte in memory and its range is -2147483648 to 2147483648.

 Float: This type of data type is defined for fractional numbers.


Below table is Displaying: 
 Number of bytes or memory taken by numbers. Decimal places up to which they can represent value.
Data type Bytes Decimal places Range of values
float 4 6 3.4E -38 to3.4E+38
double 8 15 1.7E - 308 to1.7E +308
long double 10 19 3.4E -4932 to 304E +4932

Constant
Constant is a data type whose value is never changes and remains the same through the
programme execution.
Example: - Area of the circle A=πr2 ; const float π=3.14
- Total number of days in a week=7 ;
- Total hours in a day=24
- Body temperature of human=23C0;
Here the value of above listed can be treated as a constant through the program execution.
The four basic data types in C++, their meaning, and their size are:
Page82

Type Meaning Size (bytes) Size (bits)

char a single byte, capable of holding one character 1 byte 8 bits

int an integer 2 bytes 16 bits

float single-precision floating point number 4 bytes 32 bits

double double-precision floating point number 8 bytes 64 bits

 Byte is the smallest addressable memory unit. 


 Bit, which comes from Binary digit, is a memory unit that can store either a 0 or a 1.

Page 5
   A byte has 8 bits.  

Operators in C++
 An operator is a symbol that tells the compiler to perform specific mathematical or logical
manipulations.
 C++ is rich in built-in operators and provides following type of operators:
Arithmetic Operators Scope resolution operator
Relational Operators
Logical Operators
Increment Operator
Assignment Operators
Decrement Operator

Arithmetic Operators:
 The following arithmetic operators are supported by C++ language.
 Assume variable A holds 10 and variable B holds 20 then:
Operato Description Example
r
+ Adds two operands A + B will give
30
- Subtracts second operand from the first A - B will give -
10
* Multiply both operands A * B will give
200
/ Divide numerator by de-numerator B / A will give 2
% Modulus Operator and remainder of after B % A will give
an integer division 0
++ Increment operator, increases integer A++ will give
value by one 11
-- Decrement operator, decreases integer A-- will give 9
value by one
Page82

Relational Operators:
 The following relational operators are supported by C++ language:
 Assume variable A holds 10 and variable B holds 20 then:
Operato Description Example
r
== Checks if the value of two operands is (A == B) is not true.
equal or not,
!= Checks if the value of two operands is (A != B) is true.
equal or not,
> Checks if the value of left operand is (A > B) is not true.
greater than the value of right operand,
< Checks if the value of left operand is less (A < B) is true.
Page 6
than the value of right operand,
>= Checks if the value of left operand is (A >= B) is not true.
greater than or equal to the value of right
operand,
<= Checks if the value of left operand is less (A <= B) is true.
than or equal to the value of right
operand,
Now it is time to begin programming. Let’s start by compiling and running the short
sample C++ program
shown here:
/*
This is a simple C++ program.
Call this file [Link].
*/
#include <iostream>
using namespace std;
// A C++ program begins at main().
int main()
{
cout << "C++ is power programming.";
return 0;
}
You will follow these three steps:
Page82

1. Enter the program.


2. Compile the program.
3. Run the program.
Before beginning, let’s review two terms: source code and object code. Source code is
the humanreadable form of the program. It is stored in a text file. Object code is the
executable form of the
program created by the compiler.
#include <iostream>
int main()
Page 7
{
using namespace std;
cout << "Enter a number: ";
int value;
cin >> value;

if (value== 0 || value== 1)
cout << "You picked 0 or 1" << endl;
else
cout << "You did not pick 0 or 1" << endl;
return 0;
}

Logical/Boolean operator:
 The following logical operators are supported by C++ language:
 Assume variable A holds 1 and variable B holds 0 then:

Operato Description Example


r
&& If both the operands are non-zero then (A && B) is false.
condition becomes true.
|| If any of the two operands is non-zero (A || B) is true.
then condition becomes true.
! Use to reverses the logical state of its ! (A && B) is true.
Page82

operand. If a condition is true then


Logical NOT operator will make false.
Assignment Operators:
 Assignment operator is used for assign/initialize a value to the variable during the program
execution.
 The following assignment operators are supported by C++ language:
Operato Description Example
r
= Simple assignment operator, Assigns C = A + B will assign value of A +
values from right side operands to left B into C
side operand
+= Add AND assignment operator, It adds C += A is equivalent to C = C + A
Page 8
right operand to the left operand and
assign the result to left operand
-= Subtract AND assignment operator, It C -= A is equivalent to C = C - A
subtracts right operand from the left
operand and assign the result to left
operand
*= Multiply AND assignment operator, It C *= A is equivalent to C = C *
multiplies right operand with the left A
operand and assign the result to left
operand
/= Divide AND assignment operator, It C /= A is equivalent to C = C / A
divides left operand with the right
operand and assign the result to left
operand
%= Modulus AND assignment operator, It C %= A is equivalent to C = C %
takes modulus using two operands and A
assign the result to left operand
Increment Operator (++):
 This operator is used for increment the value of an operand.
Example: assume that A=20 and B=12, then ++A=21, ++B=12 and A++=20, B++=12
int i, x;

i = 2;
x = ++i;
// now i = 3, x = 3

i = 2;
x = i++;
// now i = 3, x = 2

'Post' means after - that is, the increment is done after the variable is read. 'Pre' means before - so
the variable value is incremented first, then used in the expression.
Page82

// expre_Increment_and_Decrement_Operators.cpp
// compile with: /EHsc
#include <iostream>

using namespace std;

int main() {
int i = 5;
cout << "++i = " << ++i << endl;
}

Page 9
Decrement Operators (--):
 This operator is used for decrement the value of an operand.
 Example: assume that B=14 and C=10, then –B=13, --C=9 and B-- =14, C--=10

Increment and Decrement Operators


 There are some operations that occur so frequently in writing assignment
statements that C++ has shorthand methods for writing them.
 One common situation is that of incrementing or decrementing an integer
variable.

 For example:
n = n + 1;
n = n - 1;

C++ has an increment operator ++ and a decrement operator --. Thus


 n++; can be used instead of n = n + 1;
 n--; can be used instead of n = n - 1;
 The ++ and -- operators here have been written after the variable they apply to, in
which case they are called the post increment and post decrement operators.

 There are also identical pre increment and pre decrement operators which are
written before the variable to which they apply. Thus

++n; can be used instead of n = n + 1;


--n; can be used instead of n = n - 1;
Page82

All are the same:


i = i + 1; Prefix:
 i += 1; ++i;
i++; --i;
increment or decrement occurs before
the variable's value is used in the
remainder of the expression.
Postfix:
i++;
i--;
increment or decrement
occurs after the variable's
value is used in the
remainder of the
expression.

Page 10
Scope resolution operator (::)
 This operator is used to differentiate a local variable from the global variable.
 The variable having the same name can have different meaning at different block.
Expression:
 Expressions are formed by combining operators and operands together following the
programming language.
Compile & Execute C++ Program:
 Let’s look at how to save the file, compile and run the program. Please follow the steps given
below:
 Open a text editor and write the code  Debug the code.
 Save the file as : [Link]
 You will be able to see ' Hello World '
 Compile it to check if it has error printed on the window.
Semicolons & Blocks in C++:
 In C++, the semicolon is a statement terminator. Each individual statement must be ended with a
semicolon.
 For example, following are three different statements: x = y;
y = y+1;
Add(x, y);
A block is a set of logically connected statements that are surrounded by opening and closing
braces.
For example:
{
cout << "Hello World"; // prints Hello World
return 0;
}
 General form of a C++ program
///Program description
Page82

#include directives
int main()
{
constant declarations
variable declarations
executable statements
return 0;
}
Page 11
Output statements
court << variable-name;
Meaning: print the value of variable <variable-name> to the user
cout << “any message “;
Meaning: print the message within quotes to the user
cout << endl;
Meaning: print a new line
Example:
cout << a;
cout << b << c;
cout << “This is my character: “ << my-character << “ he he he”
<< endl;

[Link] the Appropriate Language Syntax for Sequence, Selection and Iteration
Constructs
 Control Structures in C++ is a Statement that used to control the flow of execution in a program.
 There are three types of Control Structures:
1. Sequence structure
2. Selection structure
3. Loops/ Repetition/ Iteration structure
Sequence Structure in C++
 The sequence structure is built into C++ statements that execute one after the other in the
order in which they are written—that is, in sequence.
Page82

Loops/ Repetition/ Iteration structure


 Break and continue statements are example of sequence control structure.
 The ‘break’ statement causes an immediate exit from the inner most ‘while’, ‘do…while’,
‘for loop’ or from a ‘switch- case’ statement.
 If you are using nested loops (ie. one loop inside another loop), the break statement will
stop the execution of the inner most loop and start executing the next line of code after the
block.
 There are 3 types of loops in C++ Programming:

 while Loop

Page 12
 do...while Loop

 for Loop

Syntax of while Loop


while (test expression) {
Statement/s to be executed.
}

 The while loops checks whether the test expression is true or not.
 If it is true, code/s inside the body of while loop is executed,that is, code/s inside the braces
{ } are executed.
 Then again the test expression is checked whether test expression is true or not.
 This process continues until the test expression becomes false.
Syntax:
while (condition) {
S1;
}
S2;
or
Page82

Page 13
Flowchart of while Loop in C++

Example 1: C++ while Loop


C++ program to find factorial of a positive integer entered by user.
(Factorial of n = 1*2*3...*n)
#include <iostream>
using namespace std;
Page82

int main() {
int number, i = 1, factorial = 1;
cout<< "Enter a positive integer: ";
cin >> number;
while ( i <= number) {
factorial *= i; //factorial = factorial * i;
++i;
}
cout<<"Factorial of "<<number<<" = "<<factorial;
return 0;

Page 14
}

Output
Enter a positive integer: 4
Factorial of 4 = 24

Example2:
#include <iostream>

using namespace std; // So we can see cout and endl;

int main()

int x = 0; // Don't forget to declare variables

while ( x < 10 ) { // While x is less than 10

cout<< x <<endl;

x++; // Update x so the condition can be met eventually

[Link]();

}
Example3:
Page82

//read 100 numbers from the user and output their sum
#include <iostream.h>
void main() {
int i, sum, x;
sum=0;
i=1;
while (i <= 100) {
cin >> x;
sum = sum + x;

Page 15
i = i+1;
}
cout << “sum is “ << sum << endl;
}

 Do-while Statement (C++)


 The do-while loop is similar to the while loop, except that the test condition
occurs at the end of the loop. 

 Having the test condition at the end, guarantees that the body of the loop always
executes at least one time. 

 The format of the do-while loop is shown in the box at the right.

 The test condition must be enclosed in parentheses and FOLLOWED BY A


SEMI-COLON. 

 Semi-colons also follow each of the statements within the block. 

 The body of the loop (the block of code) is enclosed in braces and indented for
readability. 

 (The braces are not required if only ONE statement is used in the body of the
loop.)

 The do-while loop is an exit-condition loop. 


Page82

 This means that the body of the loop is always executed first.

   Then, the test condition is evaluated.  If the test condition is TRUE, the
program executes the body of the loop again.

   If the test condition is FALSE, the loop terminates and program execution
continues with the statement following the while.

 Unlike for and while loops, which test the loop condition at the top of the loop,
the do...while loop checks its condition at the bottom of the loop.

Page 16
 A do...while loop is similar to a while loop, except that a do...while loop is
guaranteed to execute at least one time.

Syntax
do

block of code;

}
while (test condition);
Flow Diagram:

Example:
#include <iostream.h>
Page82

int main ()
{
int a = 10; // Local variable declaration:
do{ // do loop execution
cout << "value of a: " << a << endl;
a = a + 1;
if( a > 15)
{
break;
}
}while( a < 20 );
return 0;
Page 17
}
When the above code is compiled and executed, it produces following result:
Value of a: 10
Value of a: 11
Value of a: 12
Value of a: 13
Value of a: 14
Value of a: 15
 Flow Diagram:

Example:
#include <iostream.h>
int main ()
{
int a = 10; // Local variable declaration:
LOOP:do // do loop execution
{
if( a == 15)
{
Page82

a = a + 1; // skip the iteration.


goto LOOP;
}
cout << "value of a: " << a << endl;
a = a + 1;
}while( a < 20 );
return 0;
}
When the above code is compiled and executed, it produces following result:
value of a: 10
value of a: 11
value of a: 12
Page 18
value of a: 13
value of a: 14
value of a: 16
value of a: 17
value of a: 18
value of a: 19
 The continue statement is similar to ‘break’ statement but instead of terminating the loop, the
continue statement returns the loop execution if the test condition is satisfied.
Flow Diagram:

Example:
#include <iostream.h>
int main ()
{
int a = 10; // Local variable declaration:
do{ // do loop execution
if( a == 15)
{
Page82

a = a + 1; // skip the iteration.


continue;
}
cout << "value of a: " << a << endl;
a = a + 1;
}while( a < 20 );
return 0;
}
When the above code is compiled and executed, it produces following result:
value of a: 10
value of a: 11
value of a: 12
Page 19
value of a: 13
value of a: 14
value of a: 16
value of a: 17
value of a: 18
value of a: 19

Selection statements in C++


 There are basically two types of control statements in c++ that allows the programmer to
modify the regular sequential execution of statements.
 They are selection and iteration statements.
 The selection statements allow choosing a set of statements for execution depending on a
condition.
 If statement and switch statement are the two selection statements.
If ... else statement:
Syntax: if (expression or condition)
{
Statement 1;
Statement 2;
}
Else
{
Statement 3;
Statement 4;
}
If the condition is true, statement1 and statement2 is executed; otherwise statement 3 and statement
4 is executed.
The expression or condition is any expression built using relational operators which either yields
true or false condition.
Flow Diagram:
Page82

Page 20
 If the condition evaluates to true, then the if block of code will be executed otherwise else
block of code will be executed.
 Following program implements the if statement.
if (condition) {
S1;
}
else {
S2;
}
S3;

# include <iostream.h>
void main()
{
int num;
cout<<"Please enter a number"<<endl;
cin>>num;
if ((num%2) == 0)
cout<<num <<" is a even number";
else
Page82

cout<<num <<" is a odd number";


}
 The above program accepts a number from the user and divides it by 2 and if the remainder
(remainder is obtained by modulus operator) is zero, it displays the number is even, otherwise
it is odd.
 You must use the relational operator ‘ ==’ to compare whether remainder is equal to zero or
not.
Switch statement
 One alternative to nested if statement is the switch statement which 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.

Page 21
Syntax:
Switch (variablename)
{
case value1: statement1; break;
case value2: statement2; break;
case value3: statement3; break;
default: statement4;
}
Flow Diagram:

Example1: #include<iostream.h>
int main() {
int choice;
cout<< “Enter a value for choice \n”;
cin >> choice;
switch (choice)
{
case 1: cout << "First item selected!" << endl;
break;
case 2: cout << "Second item selected!" << endl;
break;
case 3: cout << "Third item selected!" << endl;
break;
default: cout << "Invalid selection!" << endl;
}
}

Example2: #include <iostream>


int main(int argc, char **argv) {
int k;
Page82

cout << "Enter a value between 1 and 3 : ";


cin >> k;
switch(k) {
case 1:
cout << "one!\n";
break;
case 2:
cout << "two!\n";
break;
case 3:
cout << "three!\n";
break;
Page 22
default:
cout << "Didn’t get it, did you ?\n";
break;
}
}
Iteration statements in C++
 Iteration or loops statements are important statements in c++, which helps to accomplish
repeatitive execution of programming statements.
 There are three loop statements in C++. They are - while loop, do while loop and for loop.
While Loop
 The while loop construct is a way of repeating loop body over and over again while a certain
condition remains true.
 Once the condition becomes false, the control comes out of the loop. Loop body will execute
only if condition is true.
Syntax: While (condition or expression)
{
Statement1;
Statement 2;
}
Flow Diagram:
Page82


The flow diagram indicates that a condition is first evaluated.

If the condition is true, the loop body is executed and the condition is re-evaluated.

Hence, the loop body is executed repeatedly as long as the condition remains true.
As soon as the condition becomes false, it comes out of the loop and goes to display the
output.
Example1: #include<iostream.h>
void main()
{
Page 23
int n, i=1, sum=0;
cout<< "Enter a value for n \n";
cin>>n;
while(i<=n)
{
sum=sum+i;
i++;
}
cout<< "sum of the series is "<<sum;
}
Example2:
#include <iostream>
using namespacestd;
intmain ()
{
intn;
cout << "Enter the starting number > ";
cin >> n;
while(n>0) {
cout << n << ", ";
--n;
}
cout << "FIRE!\n";
return0;
}
Do …While loop
 The do... while statement is the same as while loop except that the condition is checked after
the execution of statements in the do..while loop.
Syntax: do{
Statement;
While (test condition);
Page82

Statement;
}
Flow Diagram:

Page 24
Its functionality is exactly the same as the while loop, except that condition in the do-while loop is
evaluated after the execution of statement. Hence in do..while loop, Loop body execute once even
if the condition is false.
Example: #include<iostream.h>
void main()
{
int n, i=1, sum=0;
cout<< "Enter a value for n \n";
cin>>n;
do{
sum=sum+i;
i++;
} while(i<=n);
cout<< "sum of the series is "<<sum;
}
Page82

For loop:
 The for loop statements (loops or iteration statement) in C++ allow a program to execute a
single statement multiple times (repeatedly), given the initial value, the condition, and
increment/decrement value.
 It works in the following way:
1. initializationis executed. Generally it is an initial value setting for a counter variable. This
is executed only once.
2. conditionis checked. If it is true the loop continues, otherwise the loop ends and statementis
skipped (not executed).
3. statementis executed. As usual, it can be either a single statement or a block enclosed in
braces { }.

Page 25
4. finally, whatever is specified in the increasefield is executed and the loop gets back to step
2.
Syntax:
For (initial value; test condition; increment/decrement)
{
Statement;
}
Flow Diagram:

A for loop is a repetition control structure that allows you to efficiently write a loop that needs to
execute a specific number of times.
Example1: #include<iostream.h>
Void main ()
{
Int i, n, sum=0;
Cout<< "Enter the value for n";
Page82

cin>>n;
for(i=1;i<=n; i++)
{
sum=sum+i;
}
cout<< "the sum is" <<sum;
}
Example12:
Here is an example of countdown using a for loop:
// countdown using a for loop

Page 26
#include <iostream>
using namespacestd;
intmain ()
{
for(intn=10; n>0; n--) {
cout << n << ", ";
}
cout << "FIRE!\n";
return0;
}
- The initialization and increase fields are optional. They can remain empty, but in all
cases the semicolon signs between them must be written. For example we could write:
for (;n<10;)if we wanted to specify no initialization and no increase; or for (;n<10;n+
+)if we wanted to include an increase field but no initialization (maybe because the
variable was already initialized before). Optionally, using the comma operator (,) we
can specify more than one expression in any of the fields included in a for loop, like in
initialization, for example.
- The comma operator (,) is an expression separator, it serves to separate more than one
expression where only one is generally expected. For example, suppose that we wanted
to initialize more than one variable in our loop:
for( n=0, i=100 ; n!=i ; n++, i-- )
{
// whatever here...
}
- This loop will execute for 50 times if neither nor I are modified within the loop:
Page82

- n starts with a value of 0, and iwith 100, the condition is n!=i(that nis not equal to i).
Because nis increased by one and idecreased by one, the loop's condition will
becomefalse after the 50th loop, when both nand iwill be
equal to 50.
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

Jump statements.
The break statement
 Using breakwe can leave a loop even if the condition for its end is not fulfilled. It can be
used to end an infinite loop, or to force it to end before its natural [Link] example, we

Page 27
are going to stop the count down before its natural end (maybe because of an engine
check failure?):
// break loop example
#include <iostream>
using namespacestd;
intmain ()
{
intn;
for(n=10; n>0; n--)
{
cout << n << ", ";
if(n==3)
{
cout << "countdown aborted!";
break;
}
}
return0;
}
10, 9, 8, 7, 6, 5, 4, 3, countdown aborted!

The continue statement


 The continue
 Statement causes the program to skip the rest of the loop in the current iteration as if
Page82

the end of the statement block had been reached, causing it to jump to the start of the
following iteration. For example, we are going to skip the number 5 in our countdown:
// continue loop example
#include <iostream>
using namespacestd;
intmain ()
{
for(intn=10; n>0; n--) {
if(n==5) continue;
Page 28
cout << n << ", ";
}
cout << "FIRE!\n";
return0;
}

Selection Structure
 Choose among alternative courses of action
 Pseudocode example:

If student’s grade is greater than or equal to 60

Print “Passed”

o If the condition is true


 Print statement executed, program continues to next statement
o If the condition is false
 Print statement ignored, program continues
o Indenting makes programs easier to read
 C++ ignores whitespace characters (tabs, spaces, etc.)

if Selection Structure
 Translation into C++
If student’s grade is greater than or equal to 60
Print “Passed”
if ( grade >= 60 )
cout << "Passed";
 Diamond symbol (decision symbol)
Page82

o Indicates decision is to be made


o Contains an expression that can be true or false
 Test condition, follow path
 if structure
o Single-entry/single-exit
 Flowchart of pseudocode statement

Page 29
if/else Selection Structure
 if
- Performs action if condition true
 if/else
- Different actions if conditions true or false
 Pseudocode
if student’s grade is greater than or equal to 60
print “Passed”
else
- print “Failed”
 C++ code
if ( grade >= 60 )
cout << "Passed";
else
cout << "Failed";
 Nested if/else structures
 One inside another, test for multiple cases
Page82

 Once condition met, other statements skipped


if student’s grade is greater than or equal to 90
Print “A”
else
if student’s grade is greater than or equal to 80
Print “B”
else
if student’s grade is greater than or equal to 70
Print “C”
else
if student’s grade is greater than or equal to 60

Page 30
Print “D”
else
Print “F”
 Example
if ( grade >= 90 ) // 90 and above
cout << "A";
else if ( grade >= 80 ) // 80-89
cout << "B";
else if ( grade >= 70 ) // 70-79
cout << "C";
else if ( grade >= 60 ) // 60-69
cout << "D";
else // less than 60
cout << "F";
1.4. Using modular programming approach
 Many programs are too long or complex to write as a single unit. Programming becomes
much simpler when the code is divided into small functional units (modules).
 Modular programming is a programming style that breaks down program functions into
modules, each of which accomplishes one function and contains all the source code and
variables needed to accomplish that function.
 Modular programs are usually easier to code, compile, debug, and change than large and
complex programs.
The benefits of modular programming are:
 Efficient Program Development
Programs can be developed more quickly with the modular approach since small
subprograms are easier to understand, design, and test than large and complex programs.
 Multiple Use of Subprograms
Code written for one program is often useful in others.
 Ease of Debugging and Modifying
Modular programs is generally easier to compile and debug than monolithic (large and
Page82

complex) programs.
[Link] arrays and arrays of objects
 An Array is a collection of similar data items which shares a common name within the
consecutive memory.
 An Array can be any data type, but it should be the collection of similar items.
 Each item in an array is termed as ‘element’, but each element in an array can be accessed
individually.
 The number of element in an array must be declared clearly in the definition.
 The size or number of elements in the array can be varied according to the user needs.
Syntax for array declaration:
DataType ArrayName [number of element in the array]

Page 31
Example: int a[5]; - ‘int’ is the data type.
- ‘a’ is the array name.
- 5 is number of elements or size.
int a[5] means a[0], a[1], a[2], a[3], a[4] or

Int Int Int int int


a[0] a[1] a[2] a[3] a[4]
- 0, 1, 2, 3, 4 are called subscript which is used to define an array element position and is
called Dimension.
- Array index in C++ starts from 0 to n-1 if the size of array is n.
An individual element of an array is identified by its own unique index (or subscript).

Initializing arrays.
- When declaring a regular array of local scope (within a function, for example), if we do not
specify otherwise, its elements will not be initialized to any value by default, so their content
will be undetermined until we store some value in them. The elements of global and static
arrays, on the other hand, are automatically initialized with their default values, which for all
fundamental types this means they are filled with zeros.
- In both cases, local and global, when we declare anarray, we have the possibility to assign
initial values to each one of its elements by enclosing the values in braces { }.

How to initialize an array in C++ programming?


It's possible to initialize an array during declaration. For example,
int mark[5] = {19, 10, 8, 17, 9};

Another method to initialize array during declaration:


int mark[] = {19, 10, 8, 17, 9};
Page82

Here,
mark[0] is equal to 19
mark[1] is equal to 10
mark[2] is equal to 8

Page 32
mark[3] is equal to 17
mark[4] is equal to 9

How to insert and print array elements?


int mark[5] = {19, 10, 8, 17, 9}
// insert different value to third element
mark[3] = 9;
// take input from the user and insert in third element
cin >> mark[2];
// take input from the user and insert in (i+1)th element
cin >> mark[i];
// print first element of an array
cout << mark[0];
// print ith element of an array
cin >> mark[i-1];

Example: C++ Array


C++ program to store and calculate the sum of 5 numbers entered by the user
using arrays.
#include <iostream>
using namespace std;
int main()
{
int numbers[5], sum = 0;
cout << "Enter 5 numbers: ";
// Storing 5 number entered by user in an array
Page82

// Finding the sum of numbers entered


for (int i = 0; i < 5; ++i)
{
cin >> numbers[i];
sum += numbers[i];
}
cout << "Sum = " << sum << endl;
return 0;
}

Output

Page 33
Enter 5 numbers: 3
4
5
4
2
Sum = 18

Another for example:


int billy [5] = { 16, 2, 77, 40, 12071 };
This declaration would have created an array like this:
0 1 2 3 4
Array 55 3 77 167 475

The amount of values between braces { } must not be larger than the number of elements that we
declar array between square brackets [ ]. For example, in the example of array billywe have
declared that it elements and in the list of initial values within braces { }we have specified 5 values,
one for each elemen When an initialization of values is provided for anarray, C++ allows the
possibility of leaving the square b empty [ ]. In this case, the compiler will assume a size forthe
array that matches the number of values between braces { }:
intbilly [] = { 16, 2, 77, 40, 12071 };
After this declaration, array billywould be 5 ints long, since we have provided 5 initialization
values.

Accessing the values of an array.


Page82

In any point of a program in which an array is visible, we can access the value of any of its elements
individually as if it was a normal variable, thus being able to both read and modify its value. The
format is as simple as: name [index] following the previous examples in which billyhad 5 elements
and each of those elements was of type int, the name which we can use to refer to each element is
the following:
array[0] array [1 ] array[2] array[3 ] array[4]
Array

- For example, to store the value 75 in the third element of billy, we could write the following
statement:

Page 34
billy[2] = 75;and, for example, to pass the value of the third element of billy to a variable
called a, we could write:
a = billy[2];
Therefore, the expression billy[2]is for all purposes like a variable of type int.
Notice that the third element of billyis specified billy[2], since the first one is billy[0], the second
one is billy[1], and therefore, the third one is billy[2]. By this same reason, its last element is
billy[4].
Therefore, if we write billy[5], we would be accessing the sixth element of billy and therefore
exceeding the size of the array. In C++ it is syntactically correct to exceed the valid range of indices
for an array. This can create problems, since accessing out-of-range elements do not cause
compilation errors but can cause runtime errors. The reason why this is allowed will be seen further
ahead when we begin to use pointers. At this point it is important to be able to clearlydistinguish
between the two uses that brackets [ ]have related to arrays. They perform two different tasks: one
is to specify the size of arrays when they are declared;and the second one is to specify indices for
concrete array elements. Do not confuse these two possible uses of brackets [ ]with arrays.
Initially [5]; // declaration of a new array
Billy [2] = 75; // access to an element of the array.
If you read carefully, you will see that a type specifier always precedes a variable or array
declaration, while it never precedes an access.
Some other valid operations with arrays:
billy[0] = a;
billy[a] = 75;
b = billy [a+2];
billy[billy[a]] = billy[2] + 5;
// arrays example
#include <iostream>
Page82

using namespacestd;
intbilly [] = {16, 2, 77, 40, 12071};
intn, result=0;
intmain ()
{
for( n=0 ; n<5 ; n++ )
{
result += billy[n];
}
Page 35
cout << result;
return0;
}
Example2:
#include<iostream>
using namespace std;

int main()
{
int a[8];
int i;

for ( i = 1; i < 8; i++ )


a[i] = 1;
for ( i = 1; i < 8; i++ )
cout << a[i] << '\n';
return 0;
}

1.6. Methods and Namespace


A method (member function) is a function that is a member of a class. Function is a portion of
code within a larger program which performs a specific task and it is relatively independent of the
remaining code.
i.e.:- A function is a group of statements that can be executed when it is called from some point of
the program.
Syntax: Type functionName (parameter1, parameter2, ...)
{
Statements
Page82

}
 Type is the data type specified for the data returned by the function.
 FunctionName is the identifier by which it will be possible to call the function.
 parameters (as many as needed): Each parameter consists of a data type specified for an
identifier (for example: int x) and which acts within the function as a regular local variable.
They allow to pass arguments to the function when it is called. The different parameters are
separated by commas.
 Statements are the function's body. It is a block of statements surrounded by braces { }.

Example: #include <iostream.h>


int addition (int a, int b,int c)
{
int sum,sub,div;
Page 36
sum=a+b;

return (sum);
}
int main ()
{
int z;
z = addition (5,3);
cout << "The result is " << z;
return 0;
} //The result is 8
Namespace
Namespaces are used in the visual C++ programming language to create a separate region for a
group of variables, functions and classes etc. Namespaces are needed because there can be many
functions, variables for classes in one program and they can conflict with the existing names of
variables, functions and classes.
Therefore, you may use namespace to avoid the conflicts.
A namespace definition begins with the keyword namespace followed by the namespace name as
shown bellow.
namespace namespace_name
{
// code declarations
}
Let us see how namespace scope the entities including variable and functions:
#include <iostream>
using namespace std;
// first name space
namespace first_space{
void func(){
cout << "Inside first_space" << endl;
Page82

}
}
// second name space
namespace second_space{
void func(){
cout << "Inside second_space" << endl;
}
}
int main ()
{
first_space::func(); // Calls function from first name space.
Page 37
second_space::func(); // Calls function from second name space.
return 0;
}
If we compile and run above code, the code will produce following result:
Inside first_space
Inside second_space
A namespace declaration identifies and assigns a unique name to a user-declared namespace.
Such namespaces are used to solve the problem of name collision in large programs and libraries.
Programmers can use namespaces to develop new software components and libraries without
causing naming conflicts with existing components.

Exercise
1. Write a C Program to print “Hello, World”
Son:
#include <iostream.h>
//This program prints "Hello, World".
int main)(
{
cout << "Hello, World.\n";
return 0;
}
2. Write a program that display the list of number in c++ program
#include <iostream.h>
using namespace std;

int main()
{
Page82

const int numberOfItems = 5;


double distance[numberOfItems] = {44.14, 720.52, 96.08,8.698,479.258};

cout << "Distance 1: " << distance[0] << endl;


cout << "Distance 2: " << distance[1] << endl;
cout << "Distance 3: " << distance[2] << endl;
cout << "Distance 4: " << distance[3] << endl;
cout << "Distance 5: " << distance[4] << endl;

Page 38
return 0;
}

3. Writ a c++ program that display your name and your address
#include <iostream>
#include <string.h>

using namespace std;

int main()

char name[50];
char address[200];
cout << "Enter you name" << endl;
cin >> name;
cout << "Enter your address" << endl;
cin >> address;
cout << name << address << endl ;
return 0;
}
4. Writ c++ program that display your name.
Page82

#include <iostream>
using namespace std;
int main( )
{
char name[50];
cout << "Please enter your name: ";
cin >> name;
Page 39
cout << "Your name is: " << name << endl;
}
5. write a C Program to print “Hello, World” with sequential output of several strings
Son:
#include <iostream.h>
//This program illustrates the sequential ouput of several strings.
int main)(
{
cout << "Hello, " << "Wor" << "ld.\n";
return 0; }
6. calculate the sum and the average of the two number in c++ program
#include<iostream>
using namespace std;

int main(){

int x,y,sum;
float average;
cout << "Enter 2 integers : " << endl;
cin>>x>>y;
sum=x+y;
average=sum/2;
cout << "The sum of " << x << " and " << y << " is " << sum << "." << endl;
cout << "The average of " << x << " and " << y << " is " << average << "." << endl;
system("pause");

7. Calculate the average of three numbers.


#include <iostream>
Page82

using namespace std;

const int NUM_SCORES = 3;

int main()
{
int score1, score2, score3;
float ave;
cout << "Enter 3 scores separated by spaces: ";
cin >> score1 >> score2 >> score3;

ave = float(score1 + score2 + score3) / float(NUM_SCORES);


Page 40
cout << "The average of " << score1 << ", " << score2 << ", and "
<< score3 << " is " << ave << "." << endl;
return 0;
}

8. Write the c++ program that increment the operand for a is 21


#include <iostream>
using namespace std;

int main()
{
int a = 21;
int c ;

// Value of a will not be increased before assignment.


c = a++;
cout << "Line 1 - Value of a++ is :" << c << endl ;

// After expression value of a is increased


cout << "Line 2 - Value of a is :" << a << endl ;

// Value of a will be increased before assignment.


c = ++a;
cout << "Line 3 - Value of ++a is :" << c << endl ;
return 0;
}

9. Write a program to tell whether a number is prime.


Son: #include <iostream>
Page82

using namespace std;

int main()
{
int n, i, flag=0;
cout << "Enter a positive integer: ";
cin >> n;
for(i=2;i<=n/2;++i)
{

Page 41
if(n%i==0)
{
flag=1;
break;
}
}
if (flag==0)
cout << "This is a prime number";
else
cout << "This is not a prime number";
return 0;

}
[Link] the sum of two number in c++ program
#include <iostream>

using namespace std;

int main()
{
int a, b, c;

cout << "Enter two numbers to add\n";


cin >> a >> b;

c = a + b;
cout <<"Sum of entered numbers = " << c << endl;
Page82

return 0;
}
[Link] a c++ program that calculate the sum of the two decimal number.
#include <iostream>
using namespace std;

int main() {
float n1, n2, sum;
cout << "Enter two numbers: ";
cin >> n1 >> n2;
sum = n1+n2;
cout << "Sum = " << sum;

Page 42
return 0;
}

[Link] a program that says the number is positive or negative number.

#include <iostream>

using namespace std;

int main ()

int i, number, count;

count = 0;

for (i = 1; i <=20; i = i + 1)

{
cout << "Enter an integer value ";

cin >> number;

if ( number <= 0) i = i + 1;

else cout << "Positive" << endl;

if ( number >= 0) i = i + 1;

else cout << "Negative" << endl;


Page82

[Link] a C++ program to calculate the area of a triangle with sides a,b and c
#include<iostream.h >
#include<cmath>
using namespace std;
int main()
{
float a,b,c,s,Area;

Page 43
cout<<"Enter three sides of triangle : ";
cin>>a>>b>>c;
s=(a+b+c)/2;
Area=sqrt(s*(s-a)*(s-b)*(s-c));
cout<<"Area of triangle is : "<<Area;
return 0;
}

14. Writ a c++ program to calculate factorial for a given number


#include <iostream.h>
int main()
{
int n, f = 1;
cout << "Enter a positive integer: "; cin >> n;
for (int i = 2; i <= n; i++)
f *= i;
cout << n << " factorial is " << f << endl;
return 0;
}
15. Write a C++ Program To display the half pyramid of *.
#include <iostream.h>
using namespace std;
int main()
{
int i,j,rows;
cout<<"Enter the number of rows: ";
cin>>rows;
Page82

for(i=1;i<=rows;++i)
{
for(j=1;j<=i;++j)
{
cout<<"* ";
}
cout<<"\n";
}
return 0;
Page 44
}

16. C++ Program to print half pyramid as using numbers as shown in figure below.

1
12
123
1234
12345

Son:

#include <iostream>
using namespace std;
int main()
{
int i,j,rows;
cout<<"Enter the number of rows: ";
cin>>rows;
for(i=1;i<=rows;++i)
{
for(j=1;j<=i;++j)
{
cout<<j<<" ";
}
cout<<"\n";
Page82

}
return 0;
}
16. Write a C++ Program to print triangle of characters as below
A
BB
CCC
DDDD
EEEEE

Page 45
Son:
#include <iostream>
using namespace std;
int main()
{
int i,j;
char input,temp='A';
cout<<"Enter uppercase character you want in triangle at last row: ";
cin>>input;
for(i=1;i<=(input-'A'+1);++i)
{
for(j=1;j<=i;++j)
cout<<temp<<" ";
++temp;
cout<<endl;
}
return 0;
}
17. C++ Program to print inverted half pyramid using * as shown below.
*****
****
***
**
*
Son:
#include <iostream>
using namespace std;
int main()
{
Page82

int i,j,rows;
cout<<"Enter the number of rows: ";
cin>>rows;
for(i=rows;i>=1;--i)
{
for(j=1;j<=i;++j)
{
cout<<"* ";
}
cout<<"\n";
}
return 0;
Page 46
}
18. Write a C++ program to print pyramid using * as shown.

*
***
*****
*******
********
Son:
#include <iostream>
using namespace std;
int main()
{
int i,space,rows,k=0;
cout<<"Enter the number of rows: ";
cin>>rows;
for(i=1;i<=rows;++i)
{
for(space=1;space<=rows-i;++space)
{
cout<<" ";
}
while(k!=2*i-1)
{
cout<<"* ";
++k;
}
k=0;
cout<<"\n";
}
Page82

Return 0;
}
[Link] a program that display triangle with number.
0
01
012
0123
01234
012345

Son:

Page 47
#include<iostream>
using namespace std;
int main()
{
   for(int i=0;i<=5;i++){

        for(int j=0;j<=i;j++)
      {
                cout<<j;
      }
       cout<<endl;
  }
 return 0;
}
20. Solved Exercise 1: Display the numbers from 1 - 10. Take the input from the user.
(Hint user will enter 10 in this case)
#include <iostream.h>
int main()
{
int number; // This is the variable that the user will input.
int i=1;
cin >> number;

while (i!=number)
{
cout <<i; // You could also use i++. It is the same as i = i+1
i=i+1; //NOTE: IT IS VERY IMPORTNT TO INCREMENT THE VALUE
Page82

} // ON WHOSE BASIS THE LOOP IS GOING ON.


}
21. Write a program for Counting Digits and displaying their total count at the end of the program.
#include <iostream.h>
int main()
{
int N;
cin >> N;
int ndigits = 0; // Inv: ndigits contains the number of digits in the
part (head) of the number
Page 48
while (N > 9) {
ndigits = ndigits + 1;
N = N/10; // extracts one digit
}
cout << ndigits + 1 << endl;
}

Self-check#1 Lap Test

Name:_________________ Date:_______
Time Started:______________ Time Finished:______

Instruction

Q 1 - What is the output of the following program?

#include<iostream>

using namespace std;

int main() {

int i = 1, j = 2, k = 3, r;

r = (i, j, k);
Page82

cout<<r<<endl;

A - 1

B - 2

C - 3

Page 49
D - Compile Error

Q2. What is the output of the following program?

#include<iostream>

[Link] namespace std;

main() {

char s[] = "hello", t[] = "hello";

if(s==t)

cout<<"eqaul strings";

A - Equal strings

B - Unequal strings

C - No output

D - Compilation error

Q 3 - Compiler generates ___ file

A - Executable code

B - Object code


Page82

C - Assembly code

D - None of the above.

Q4. Write a C Program to get the area of circle

Q5 .Write a program to calculate the average and sum of ten number using for loop in c++.

Q6. Develop a c++ program that calculates student grade:

>=90,gade 'A'

Page 50
>=80,grade 'B'

>=70,grade 'C'

>=55,grade 'D'

eles

Grade'F'
Page82

Page 51
Enjibara Polytechnic College

Ethiopian TVET-System
INFORMATION TECHNOLOGY
Database Administration system
Level IV
LEARNING GUIDE # 2
Unit of Competence: Apply Object-Oriented Programming
Language Skills
Module Title: Applying Object-Oriented Programming Language
Skills
LG Code : ICT DBA4 M05 LO2 0412
TTLM Code : ICT DBA4 M05 0412 v2
Page82

Page 52
LO2. Apply basic OOP principles in the target language
Information Sheet#1 Apply basic OOP principles in the target language

2.1 Introduction to class


 A class in C++ is an encapsulation of data members and functions that manipulate the data.
 In terms of variables, a class would be the type, and an object would be the variable.
Classes and Objects
 A class is a type, and an object of this class is just a variable.
 Before we can use an object, it must be created.
o Classes are generally declared using the keyword class.
Syntax: class class_name {
access_specifier_1:
member1;
access_specifier_2:
member2;
...
} object_names;
 Where class_name is a valid identifier for the class, object_names is an optional list of names
for objects of this class.
 The body of the declaration can contain members, that can be either data or function
declarations, and optionally access specifiers.
 These specifiers modify the access:
 Public: Access to all code in the program. public members are accessible from anywhere
where the object is visible.
 Private: Access to only members of the same class
 Protected: Access to members of same class and its derived classes
Page82

Example: #include <iostream.h>


class Rectangle {
int x, y;
public:
void set values (int, int);
int area () {
Return (x*y);
}
};
void Rectangle::set_values (int a, int b)
{
x = a;
Page 53
y = b;
}
int main () {
Rectangle rect;
rect.set_values (3,4);
cout << "area: " << [Link]();
return 0;
}

[Link] inheritance
Modern object-oriented (OO) languages provide 3 capabilities:
 Encapsulation
 Inheritance which can improve the design, structure and reusability of the code.
 Polymorphism

 Encapsulation is the method of combining the data and functions inside a class. This hides the
data from being accessed from outside a class directly, only through the functions inside the
class is able to access the information.
This is also known as "Data Abstraction", as it gives a clear separation between properties of data
type and the associated implementation details. There are two types, they are "function abstraction"
and "data abstraction". Functions that can be used without knowing how its implemented is function
abstraction. Data abstraction is using data without knowing how the data is stored.
Features and Advantages of the concept of Encapsulation:
Makes Maintenance of Application Easier:
Improves the Understandability of the Application
Enhanced Security
Example: #include <iostream.h>
class Add
{
private:
int x,y,r;
Page82

public:
int Addition(int x, int y)
{
r= x+y;
return r;
}
void show( )
{
cout << "The sum is::" << r << "\n";}
}s;
Int main()
{
Page 54
Add s;
[Link](10, 4);
[Link]();
}
Result: The sum is: 14
 Inheritance is the process of creating new classes from the existing class or classes with
inheriting some properties of the base class. Using Inheritance, some qualities of the base classes
are added to the newly derived class.
The advantage of using "Inheritance" is due to the reusability (inheriting) of a class in multiple
derived classes.
The ":" operator is used for inheriting a class.
The old class is referred to as the base class and the new classes, which are inherited from the base
class, are called
derived classes.
Example: #include <iostream.h>
class Value
{
protected:
int val;
public:
void set_values (int a)
{
val=a;
}
};
class Square: public Value
{
public:
int square()
{
Page82

return (val*val);
}
};
int main ()
{
Square sq;
sq.set_values (5);
cout << "The square of “<<5<<” is::" << [Link]() << endl;
return 0;
}
Forms/types of Inheritance:
Single Inheritance Multiple Inheritance
Page 55
Multilevel Inheritance Hybrid Inheritance
Hierarchical Inheritance
1. Single inheritance: - If a class is derived from a single base class, it is called as single
inheritance.
In Single Inheritance, there is only one Super Class and Only one Sub Class Means they have one to
one Communication between them.

Example: #include <iostream.h>


class Value
{
protected:
int val;
public:
void set_values (int a)
{
val=a;
}
};
class Cube: public Value
{

public:
int cube()
{
return (val*val*val);
Page82

}
};
int main ()
{
Cube cub;
cub.set_values (5);
cout << "The Cube of 5 is::" << [Link]() << endl;
return 0;
}
2. Multiple Inheritances: - If a class is derived from more than one base class, it is known as
multiple inheritances.

Page 56
Example: #include<iostream.h>
class student
{
    protected:
       int rno,m1,m2;
    public:
                void get()
               {
                    cout<<"Enter the Roll no :";
                    cin>>rno;
                    cout<<"Enter the two marks:";
                    cin>>m1>>m2;
              }
};
class sports
{
    protected:
       int sm;                   // sm = Sports mark
    public:
                void getsm()
               {
                 cout<<"\nEnter the sports mark :";
                 cin>>sm;
             }
};
class statement: public student,public sports
Page82

{
     int tot,avg;
   public:
   void display()
               {
                 tot=(m1+m2+sm);
                 avg=tot/3;
                 cout<<"\n\n\tRoll No :"<<rno<<"\n\tTotal : "<<tot;
               cout<<"\n\tAverage    : "<<avg;
               }
};
void main()
{
Page 57
   statement obj;
   [Link]();
   [Link]();
   [Link]();
}
3. Multilevel Inheritance:
When a derived class is created from another derived class, then that inheritance is called as multi
level inheritance.

Example: #include <iostream.h>


class A
{
protected:
int rollno;
public:
void get_num(int a)
{
rollno = a;
}
void put_num()
{
cout << "Roll Number Is:\n"<< rollno << "\n";
}
};
class marks : public A
Page82

{
protected:
int sub1;
int sub2;
public:
void get_marks(int x,int y)
{
sub1 = x;
sub2 = y;
}
void put_marks(void)
{

Page 58
cout << "Subject 1:" << sub1 << "\n";
cout << "Subject 2:" << sub2 << "\n";
}
};
class C : public marks
{
protected:
float tot;

public:
void disp(void)
{
tot = sub1+sub2;
put_num();
put_marks();
cout << "Total:"<< tot;
}
};
int main()
{
C std1;
std1.get_num(5);
std1.get_marks(10,20);
[Link]();
return 0;
}
Result:
Roll Number Is:5
Subject 1: 10
Subject 2: 20
Total: 30
Page82

4. Hierarchical Inheritance:
If a number of classes are derived from a single base class, it is called as hierarchical
inheritance.
This means a Base Class will have Many Sub Classes or a Base Class will be inherited by
many Sub Classes.

Page 59
Example:

Example: #include<iostream.h>
Class A
{
int a,b;
public :
void getdata()
{
cout<<"\n Enter the value of a and b";
cin>>a>>b;
}
void putdata()
{
cout<<"\n The value of a is :"<<a "and b is "<<b;
}
};
class B : public A
{
int c,d;
public :
void intdata()
{
cout<<"\n Enter the value of c and d ";
cin>>c>>d;
Page82

}
void outdata()
{
cout<<"\n The value of c"<<c"and d is"<<d;
}
};
class C: public A
{
int e,f;
public :
void input()
{
Page 60
cout<<"\n Enter the value of e and f";
cin>>e;>>f
}
void output()
{
cout<<"\nthe value of e is"<<e"and f is" <<f;
}
void main()
{
B obj1
C obj2;
[Link](); //member function of class A
[Link](); //member function of class B
[Link](); //member function of class A
[Link](); //member function of class C
[Link](); //member function of class A
[Link](); //member function of class B
[Link](); //member function of class A
[Link](); //member function of class C
}

5. Hybrid Inheritance: This is a Mixture of two or More Inheritance types.


I.e.: Any combination of single, hierarchical and multi level inheritances is called as hybrid
inheritance.
Page82

Example: #include <iostream.h>


class A
{
protected:
int rollno;
public:
void get_num(int a)
{
rollno = a;
}
void put_num()
{

Page 61
cout << "Roll Number Is:"<< rollno << "\n"; }
};
class B : public A
{
protected:
int sub1;
int sub2;
public:
void get_marks(int x,int y)
{
sub1 = x;
sub2 = y;
}
void put_marks(void)
{
cout << "Subject 1:" << sub1 << "\n";
cout << "Subject 2:" << sub2 << "\n";
}
};
class C
{
protected:
float e;
public:
void get_extra(float s)
{
e=s;
}
void put_extra(void)
{
cout << "Extra Score::" << e << "\n";}
Page82

};

class D : public B, public C


{
protected:
float tot;
public:
void disp(void)
{
tot = sub1+sub2+e;
put_num();
put_marks();

Page 62
put_extra();
cout << "Total:"<< tot;
}
};
int main()
{
D std1;
std1.get_num(10);
std1.get_marks(10,20);
std1.get_extra(33.12);
[Link]();
return 0;
}
Result:
Roll Number Is: 10
Subject 1: 10
Subject 2: 20
Extra score: 33.12
Total: 63.12
2.3. Implementing polymorphism
The process of representing one Form in multiple forms is known as Polymorphism. Here one form represent
original form or original method always resides in base class and multiple forms represents overridden method
which resides in derived classes.
Polymorphism is derived from 2 Greek words: poly and morphs. The word "poly" means many
and morphs means forms. So polymorphism means many forms.
 Polymorphism is a generic term that means 'many shapes/forms '.
 Polymorphism is a mechanism that allows you to implement a function in different ways.
 In C++ the simplest form of Polymorphism is overloading of functions or operators.
Page82

Typically, polymorphism occurs when there is a hierarchy of classes and they are related by inheritance.

Real life example of Polymorphism in C++

Suppose if you are in class room that time you behave like a student, when you are in market at that time you
behave like a customer, when you at your home at that time you behave like a son or daughter, Here one person
have different-different behaviours.

Page 63
Type of polymorphism

 Compile time polymorphism


 Run time polymorphism

Compile time polymorphism

In C++ programming you can achieve compile time polymorphism in two way, which is given below;

 Method overloading
 Method overriding

Method Overloading in C++


Page82

Whenever same method name is exiting multiple times in the same class with different number of parameter or
different order of parameters or different types of parameters is known as method overloading. In below
example method "sum()" is present in Addition class with same name but with different signature or arguments.
Example of Method Overloading in C++

#include<iostream.h>
#include<conio.h>

Page 64
class Addition
{
public:
void sum(int a, int b)
{
cout<<a+b;
}
void sum(int a, int b, int c)
{
cout<<a+b+c;
}
};
void main()
{
clrscr();
Addition obj;
[Link](10, 20);
cout<<endl;
[Link](10, 20, 30);
}

Output

30

60
Page82

Method Overriding in C++

Define any method in both base class and derived class with same name, same parameters or signature, this
concept is known as method overriding. In below example same method "show()" is present in both base and
derived class with same name and signature.
Example of Method Overriding in C++

#include<iostream.h>
#include<conio.h>

Page 65
class Base
{
public:
void show()
{
cout<<"Base class";
}
};
class Derived:public Base
{
public:
void show()
{
cout<<"Derived Class";
}
}

int mian()
{
Base b; //Base class object
Derived d; //Derived class object
[Link](); //Early Binding Ocuurs
[Link]();
getch();
}

Output
Page82

Base class

Derived Class

Page 66
Run time polymorphism

In C++ Run time polymorphism can be achieve by using virtual function.

Virtual Function in C++

A virtual function is a member function of class that is declared within a base class and re-
defined in derived class.
When you want to use same function name in both the base and derived class, then the function
in base class is declared as virtual by using the virtual keyword and again re-defined this function
in derived class without using virtual keyword.
Syntax

virtual return_type function_name()

.......

.......

Virtual Function Example


Page82

#include<iostream.h>
#include<conio.h>

class A
{
public:
virtual void show()
{
cout<<"Hello base class";

Page 67
}
};

class B : public A
{
public:
void show()
{
cout<<"Hello derive class";
}
};

void main()
{
clrsct();
A aobj;
B bobj;
A *bptr;
bptr=&aobj;
bptr->show(); // call base class function

bptr=&bobj;
bptr->show(); // call derive class function
getch();
}

Output
Page82

Hello base class

Hello derive class

2.4. Introduction to Delegates and Events


Delegates
A delegate is similar to a function pointer that allows the programmer to encapsulate a reference to a method inside a
delegate object. The delegate object can then be passed to code which can call the referenced method, without
having to know at compile time which method will be invoked /call up.

Page 68
Events
Events are the actions that are performed by the user during the applications usage.
If a user clicks a mouse button on any object, then the Click event occurs.
If a user moves the mouse, then the mouse move event occurs.
By the same way an application can generate Key down event, Key up event, mouse double click event.
Delegate and Event concepts are completely tied together. Delegates are just function pointers, That is, they hold
references to functions.

2.5. Introduction to Exception Handling


An exception is a special condition that changes the normal flow of program execution.
Exceptional conditions are things that occur in a system that are not expected or are not a part of normal system
operation. When the system handles these exceptional conditions improperly, it can lead to failures and system
crashes.
Exception handling is the method of building a system to detect and recover from exceptional conditions.
Exceptional conditions are any unexpected occurrences that are not accounted for in a system's normal operation.
Some examples of exceptional conditions:
 incorrect inputs from the user
 bit level memory or data corruption
If these exceptional conditions are not properly caught and handled, they can cause an error or failure in the system.
An exception is a problem that arises during the execution of a program. A C++ exception is a response to an
exceptional circumstance that arises while a program is running, such as an attempt to divide by zero.
Exceptions provide a way to transfer control from one part of a program to another. C++ exception handling is built
upon three keywords: try, catch, and throw.

Throw: A program throws an exception when a problem shows up. This is done using a throw keyword.
Catch: A program catches/holds an exception with an exception handler at the place in a program where you
want to handle the problem. The catch keyword indicates the catching of an exception.

Try: A try block identifies a block of code for which particular exceptions will be activated. It's followed by
one or more catch blocks
Example: #include <iostream.h>
Page82

double division(int a, int b)


{
if( b == 0 )
{
throw "Division by zero condition!";
}
return (a/b);
}
int main ()
{
int x = 50;
int y = 0;
double z = 0;
try {
Page 69
z = division(x, y);
cout << z << endl;
}catch (const char* msg)
{
cerr << msg << endl;
}

return 0;
}

2.6. Using Attributes and Overloading Operators


Attributes are a means of decorating your code with various properties at compile time.
Operator overloading is the ability to tell the compiler how to perform a certain operation when its corresponding
operator is used on one or more variables. Example
Overloading Unary Operators Overloading Function Calls
Overloading Increment and Decrement Overloading Subscripting or array
Overloading Binary Operators Overloading Class Member Access
Overloading Assignments
Page82

Page 70
2.7. Encapsulation
Encapsulation is the method of combining the data and functions inside a class. This hides the data from being
accessed from outside a class directly, only through the functions inside the class is able to access the information.
Encapsulation is the term given to the process of hiding all the details of an object that do not necessary to its user.
Encapsulation enables a group of properties, methods and other members to be considered a single unit or object.
Features and Advantages of the concept of Encapsulation:
Makes Maintenance of Application Easier
Improves the Understandability of the Application
Enhanced Security
Protection of data from accidental corruption
Flexibility and extensibility of the code and reduction in complexity

Self-check#1 theorytical Test

Name:_________________ Date:_______
Time Started:______________ Time Finished:______

Instruction

1. A class means_______
A. Is a type, and an object of this class is just a variable.
B. Are generally declared using the keyword class.
C. Is used to specify the form of an object and it combines data representation and methods for manipulating that data into one
neat package.
D. The data and functions within a class are called members of the class.
E. all
2. Which one is true about Encapsulation?
A.  The method of combining the data and functions inside a class.
B.  It is a mechanism of bundling the data, and the functions that use them.
C. It is the term given to the process of hiding all the details of an object
D. none
3. _____ process of creating new classes from the existing class or classes with inheriting
some properties of the base class
A. class C. encapsulation
B. Inheritance D. polymorphism
4. __________is a generic term that means 'many shapes/forms '.
A. class C. encapsulation
B. Inheritance D. polymorphism
5. __the ability to tell the compiler how to perform a certain operation when its
corresponding operator is used on one or more variables.
A. operator overloading C. encapsulation
B. Inheritance D. polymorphism
6. If a number of classes are derived from a single base class, it is called_______.
A. Inheritance C. Multilevel Inheritance
B. Hybrid Inheritance D. Single inheritance
Injibara Polytechnic College

Ethiopian TVET-System
INFORMATION TECHNOLOGY
Database Administration system
Level IV
LEARNING GUIDE # 3
Unit of Competence: Applying Object-Oriented Programming
Language Skills
Module Title: Applying Object-Oriented Programming Language
Skills
LG Code : ICT DBAS4 M05 LO3 0412
TTLM Code : ICT DBAS4 M05 0412 v2

LO3. Debug code


Information Sheet#1 Debug code
3.1. Using an Integrated Development Environment
 An integrated development environment (IDE) is a software application that provides
comprehensive facilities to computer programmers for software development.
 An IDE normally consists of a source code editor, build automation tools,compiler or interpreter
and a debugger.
 I.e.: An integrated development environment (IDE) is a programming environment that
consisting of a code editor, a compiler, a debugger, and a graphical user interface (GUI) builder.
3.2. The Language Debugging Facilities
This topic describes methods of debugging routines in Language Environment. Debug tools are
designed to help you to detect errors early in your routine.
Debug Tool also provides facilities for setting breakpoints and altering the contents and values of
variables.
3.2.1. Visual C++, C#, [Link]
Visual C++ program is an application development tool developed by Microsoft for C++
programmers that supports object-oriented programming with an integrated development
environment (IDE).
3.2.2. Visual Studio suite
What Is Visual Studio?
The Microsoft Visual Studio development system is a suite of development tools designed to aid
software developers.
It is used to develop graphical user interface applications along with Windows Forms applications,
web sites, web applications, and web services.
System Requirement to install Visual [Link] 2008:
System Components Recommended Configuration
Processor Minimum 1.6 GHz CPU, recommended 2.2 GHz or higher CPU
RAM Minimum 384 MB RAM, recommended 1024 MB or more RAM
Minimum 5400 RPM hard disk, recommended 7200 RPM or higher
Hardisk Space
hard disk
Supporting Operating Microsoft Windows XP , Microsoft Windows Server 2003 , Windows
System Vista, or Latest version
CD ROM or DVD
Required
Drive
VGA Minimum 1024x768 display, recommended 1280x1024 display
How to Install Visual [Link] 2008
     Visual Studio can be installed from a CD or by downloading from Microsoft Website at
[Link]
The downloaded file would be a .exe file, when double clicked on, it will open up an wizard.
By choosing the location, the type of installation like custom or standard user can install only the
required applications like Visual [Link] 2008 from the available choices.

The setup wizard will start copying needed files into a temporary folder. Just wait.

In the welcome setup wizard page you can enable the tick box to send your setup experience to
Microsoft if you want .in this case we just leave it unchecked. Just wait for the wizard to load the
installation components.
Click the next button to go to the next step
The setup wizard will list down all the required components need to be installed. Notice that visual
studio 2008 needs .Net Framework version 3.5. Then click the next button.
In the installation type, there are three choices: default, full or custom. In our case, select the full
and click the install button. Full installation required around 4.3GB of space

The installation starts. Just wait and see the step by step, visual studio 2008 components being
installed.
Any component that failed to be installed will be marked with the Red Cross mark instead of the
green tick for the successful. In this case we just exit the setup wizard by clicking the Finish button.

Click Restart Now to restart you machine.

The Windows Start menu for Visual Studio 2008 is shown below.
Depending on your programming needs, you will select one of the visual studio component Settings.

The Visual Studio 2008 is configuring the development environments to the chosen one for the first
time use.
Create a Project in [Link]
     A Visual Basic Project is container for the forms, methods, classes, controls that are used for a
Visual Basic Application.
Steps to Create a [Link] Project:
1. Click on the Programs->Microsoft Visual [Link] 2008.
2. Choose File -->New Project from the Menu Bar to get the New Project window.

3. Select the type of Project as per the requirement from following choices Windows Application,
Class Library, Console Application, Windows Control Library, Web Control Library,
Windows Service, Empty Project, and Crystal Reports.
To develop a Windows Based Application, Choose Windows Application, and fill in a Name for
the application

By default, a project named My Project and a form Form1 will be created. Project name and form
name can be renamed later.

4. Saving Project in [Link]


     There are many ways for saving a project created using [Link] 2008. But the recommended
option is to browse to File->Save All. This option saves all the files associated with a project.
5. Provide a Name that will be populated as the Solution Name, also specify the location to save the
project.

6. Run a Visual Basic .Net 2008 Project


     Run a Visual Basic .Net 2008 Project by pressing the F5 key or by choosing Debug -> Start
Debugging.

7. Open Existing Project in [Link]


     In Visual [Link] 2008, an existing project can be opened using the Recent Projects option in
the Start Page or can be opened using the File -> Open Project from the Menu Bar. Both these
displays a window with project folder, once the project is selected and opened using the file with the
extension .sln for windows application, the Solution Browser displays all the components of that
project.
Visual [Link] 2008 IDE
     VB Integrated Development Environment (IDE) consists of inbuilt compiler, debugger, editors,
and automation tools for easy development of code.
I.e. it consists of Solution Explorer, Toolbox, Form, Properties Window, and Menu Bar.
The following is the screen shot of the IDE of Visual [Link] 2008.

Menu Bar
     Menu bar in Visual [Link] 2008 consist of the commands that are used for constructing a
software code. These commands are listed as menus and sub menus.
Menu bar also includes a simple Toolbar, which lists the commonly used commands as buttons. This
Toolbar can be customized, so that the buttons can be added as required.
Following table lists the Toolbars Buttons and their actions.

Butt Undo.
Description
on
Redo.
Adds a new Project.
Continue Debugging.
Open a New Window.
Break Debugging.
Open a File.
Stop Debugging.
Saves the Current Form.
Displays Solution
Saves all files related to a Explorer.
project. Displays Properties
Cut the selection. Window.
Copy the selection. Displays Object Browser.
Paste the selection. Displays ToolBox
Window.
Find the searched text.
Displays Error List
Comment out selected Window.
lines.
Displays Command
Uncomment the selected Window.
lines.
Tool Box
     Toolbox in Visual [Link] 2008, consist of Controls, Containers, Menu Options, Data
Controls, Dialogs, Components, Printing controls, that are used in a form to design the interfaces of
an application.
The following table lists the Common Controls listed in the Toolbox.
Images Control Name Description
Pointer Used to move and resize controls and forms.
Button This Control triggers an action when accessed.
Check Box Control that has values either true or false
Checked List Box Lists check box next to each item
A combination of list and text box controls that enables
Combo Box
to select as well as edit text.
Label Displays a label text.
Link Label Displays a label with a link text.
List Box Control that lists number of items.
Extension of List Box control with options to add icons,
List View
headings.
Picture Box Display image files
Progress Bar Display the progress of a task.
Radio Button Allows to choose a choice from a group of choices.
Text Box Control used to input or display text.
ToolTip Displays tooltip text.

Solution Explorer
Page102

     Solution Explorer in Visual [Link] 2008 lists of all the files associated with a project. It is
docked on the right under the Toolbar in the VB IDE. In VB 6 this was known as 'Project Explorer'
Solution Explorer has options to view the code, form design, and refresh listed files. Projects files
are displayed in a drop down tree like structure, widely used in Windows based GUI applications.

Page 84 prepared by AY@[Link]


Properties Window
     Windows form properties in Visual [Link] 2008 lists the properties of a selected object. Every
object in VB has it own properties that can be used to change the look and even the functionality of
the object.
Properties Window lists the properties of the forms and controls in an alphabetical order by default.

Following is the screen shot of Properties Window.


Page102

Page 85 prepared by AY@[Link]


Visual Basic Forms
     Forms in Visual [Link] 2008 are the basic object used to develop an application; it also
contains the coding as well as the controls embedded in it.
Following is the screenshot of a Form in Visual [Link] 2008.
Page102

A form is created by default when a Project is created with a default name Form1. Every form has
its own Properties, Methods and Events. Usually the form properties name, caption are changed as
required, since multiple forms will be used in a Project.
Form Properties
The developers may need to alter the properties of the forms in [Link].
Following table lists some important Properties of Forms in Visual [Link] 2008.

Page 86 prepared by AY@[Link]


Properties Description
Back Color Set's the background color for the form
Background Image Set's the background image for the form
Specifies whether to accept the data dragged and
Allow Drop
dropped onto the form.
Font Get or sets the font used in the form
Locked Specifies whether the form is locked.
Text Provide the title for a Form Window
Determines whether the ControlBox is available
Control Box by clicking the icon on the upper left corner of
the window.
Specifies whether to display the maximize option
Maximize a Box
in the caption bar of the form.
Specifies whether to display the minimize option
Minimize Box
in the caption bar of the form.

Show / Hide Forms


     Form in Visual [Link] 2008 are displayed and hidden using two different methods.
To display a form the, Show () method is used and to hide a form, Hide () method is used.
Show Method: This method is used to display the form on top of all other windows.
Syntax: [Link]()
Hide Method: This method hides a form object from the screen, still with the object being loaded
in the memory.
Syntax: Form [Link]()
Example:
Public Class Form1
Page102

Private Sub Button1_Click(ByVal sender As [Link],ByVal e As


[Link])Handles [Link]
[Link]()
End Sub
Private Sub Button2_Click(ByVal sender As [Link],ByVal e As [Link])
Handles [Link]
[Link]()
End Sub

Page 87 prepared by AY@[Link]


End Class
Visual [Link] 2008 Data types
     Data Type in Visual [Link] 2008 defines the type of data a programming element should be
assigned, how it should be stored and the number of bytes occupied by it.
Following are the common data types used in Visual [Link] 2008.
Boolean Integer
Char Long
Date String
Double Single

Constants in [Link]
     Constants in [Link] 2008 are declared using the keyword Const. Once declared, the value of
these constants cannot be altered at run time.
Syntax:
[Private | Public | Protected ]
Const constName As data type = value
In the above syntax, the Public or Private can be used according to the scope of usage. The Value
specifies the unchangeable value for the constant specified using the name constName.
Example:
Public Class Form1
Public Const PI As Double = 3.14
Private Sub Button1_Click(ByVal sender As [Link], ByVal e As [Link])
Handles [Link]
Dim r As Single
r = Val([Link])
[Link] = PI * r * r
End Sub
End Class
Page102

Visual [Link] 2008 Variables


     Variables in [Link] 2008 are used to store values and also they have a data type and a name.
Naming Convention:
i. Variables in Visual Basic should start with an alphabet or a letter and should not contain any
special characters like %,&,!,#,@ or $.
ii. The variable should not exceed 255 characters.
Scope of Variables:
 A variable declared in the general declaration of a form can be used in all the procedures.
 Variables declared inside a procedure will have a scope only inside the procedure, so they are
declared using the Dim keyword.
Page 88 prepared by AY@[Link]
Example
Public Class Form1
Private Sub Button1_Click(ByVal sender As [Link], ByVal e As [Link])
Handles [Link]
Dim c As Integer
c = Val([Link]) + Val([Link])
[Link] = c
End Sub
End Class
User Defined Data Types
     User defined data type in [Link] 2008 is a collection of variables of different primitive data
types available in Visual [Link] 2008 combined under a single user defined data type. This gives
the flexibility to inlcude real time objects into an application.
User defined data types are defined using a Structure Statement and are declared using the Dim
Statement.
Structure Statement:
The Structure statement is declared in the general declaration part of form or a Module.
Syntax:
[ Public | Protected | Private]
Structure varname element name [([subscripts])] As type
[element name [([subscripts])] As type]
...
End Structure
In the above syntax varname is the name of the user defined data type that follows the naming
convention of a variable. Public option makes these datatypes available in all projects, modules,
classes. Type is the primitive data type available in visual basic.
Dim Statement:
This is used to declare and allocate a storage space for a variable or an user defined variable.
Syntax: Dim variable [As Type]
Page102

Example:
Structure EmpDetails
Dim EmpNo As Integer
Dim EmpName As String
Dim EmpSalary As Integer
Dim EmpExp As Integer
End Structure
Public Class Form1
Private Sub Button1_Click ByVal sender As [Link],ByVal e As
[Link])
Handles [Link]
Page 89 prepared by AY@[Link]
Dim TotalSal As New EmpDetails()
[Link] = [Link]
[Link] = [Link]
[Link] = [Link]
[Link] = [Link]
[Link] = Val([Link]) * Val([Link])
End Sub
End Class
If Then Statement
     If Then statement is a control structure which executes a set of code only when the given
condition is true.
Syntax:
If [Condition] Then
[Statements]
In the above syntax, when the Condition is true then the Statements after Then are executed.
Example:
Private Sub Button1_Click_1(ByVal sender As [Link],ByVal e As [Link])
Handles [Link]
If Val([Link]) > 25 Then
[Link] = "Eligible"
End If
If Then Else Statement
     If Then Else statement is a control structure which executes different set of code statements
when the given condition is true or false.

Syntax: If [Condition] Then


[Statements]
Else
[Statements]
Page102

In the above syntax when the Condition is true, the Statements after Then are executed.
If the condition is false then the statements after the Else part is executed.
Example:
Private Sub Button1_Click(ByVal sender As [Link],ByVal e As [Link])
Handles [Link]
If Val([Link]) >= 40 Then
MsgBox("GRADUATED")
Else
MsgBox("NOT GRADUATED")
End If
End Sub

Page 90 prepared by AY@[Link]


Nested If Then Else Statement
     Nested If..Then..Else statement is used to check multiple conditions using if then else
statements nested inside one another.
Syntax: If [Condition] Then
If [Condition] Then
[Statements]
Else
[Statements]
Else
[Statements]
In the above syntax when the Condition of the first if then else is true, the second if then else is
executed to check another two conditions. If false the statements under the Else part of the first
statement is executed.
Example:
Private Sub Button1_Click(ByVal sender As [Link], ByVal e As [Link])
Handles [Link]
If Val([Link]) >= 40 Then
If Val([Link]) >= 60 Then
MsgBox("You have FIRST Class")
Else
MsgBox("You have SECOND Class")
End If
Else
MsgBox("Check your Average marks entered")
End If
End Sub
Select Case Statement
     Select case statement is used when the expected results for a condition can be known previously
so that different set of operations can be done based on each condition.
Syntax: Select Case Expression
Page102

Case Expression1
Statement1
Case Expression2
Statement2
Case Expressionn
Statementn
...
Case Else
Statement
End Select

Page 91 prepared by AY@[Link]


In the above syntax, the value of the Expression is checked with Expression1..n to check if the
condition is true. If none of the conditions are matched the statements under the Case Else is
executed.
Example:
Private Sub Button1_Click(ByVal sender As [Link],ByVal e As [Link])
Handles [Link]
Dim c As String
c = [Link]
Select c
Case "Red"
MsgBox("Color code of Red is::#FF0000")
Case "Green"
MsgBox("Color code of Green is::#808000")
Case "Blue"
MsgBox("Color code of Blue is:: #0000FF")
Case Else
MsgBox("Enter correct choice")
End Select
End Sub
In the above example based on the color input in TextBox1, the color code for RGB colors are
displayed, if the color is different then the statement under Case Else is executed.
While Statement
     While Statement is a looping statement where a condition is checked first, if it is true a set of
statements are executed.
Syntax:
While condition
[statements]
End
In the above syntax the Statements are executed when the Condition is true.
Example:
Page102

Private Sub Form1_Load(ByVal sender As [Link],ByVal e As [Link]) Handles


[Link]
Dim n As Integer
n=1
While n <= 1
n=n+1
MsgBox("First incremented value is:" & n)
End While
End Sub

Page 92 prepared by AY@[Link]


Do Loop While Statement
     Do Loop While Statement executes a set of statements and checks the condition; this is repeated
until the condition is true.
Syntax:
Do
[Statements]
Loop While [Condition]
In the above syntax the Statements are executed first then the Condition is checked to find if it is
true.
Example 1:
Private Sub Form1_Load(ByVal sender As [Link],ByVal e As [Link])
Handles [Link]
Dim cnt As Integer
Do
cnt = 10
MsgBox("Value of cnt is::" & cnt)
Loop While cnt <= 9
End Sub
Example 2:
Private Sub Form1_Load(ByVal sender As [Link],
ByVal e As [Link]) Handles [Link]
Dim X As String
Do
X$ = InputBox$("Correct Password Please")
Loop Until X$ = "Ranger"
End Sub
In the above Do Until Loop example, a input box is displayed until the correct password is typed.
For Next Loop Statement
     For Next Loop Statement executes a set of statements repeatedly in a loop for the given initial,
Page102

final value range with the specified step by step increment or decrement value.
Syntax:
For counter = start To end [Step]
[Statement]
Next [counter]
In the above syntax the Counter is range of values specified using the Start ,End parameters. The
Step specifies step increment or decrement value of the counter for which the statements are
executed.
Example:
Private Sub Form1_Load(ByVal sender As [Link],
ByVal e As [Link]) Handles [Link]
Dim i As Integer
Page 93 prepared by AY@[Link]
Dim j As Integer
j=0
For i = 1 To 10 Step 1
j=j+1
MsgBox("Value of j is::" & j)
Next i
End Sub
Description:
In the above For Next Loop example the counter value of i is set to be in the range of 1 to 10 and is
incremented by 1. The value of j is increased by 1 for 10 times as the loop is repeated.
Exercise: For loop code
Syntax:
Dim variables As datatype
For initializedValue To endValue
Loop body
MsgBox answer
Example: Find the factorial of a number n inputted from the keyboard using for loop.
Dim fact, i As Integer
fact = 1
For i = 1 To Val([Link])
fact = fact * i
Next i
[Link] = fact
While loop code
Syntax: While condition
[statements]
End while
Example: Find the factorial of a number n inputted from the keyboard using while loop.
Dim fact, i As Integer
Page102

fact = 1
i=1
While (i <= Val([Link]))
fact = fact * i
i=i+1
End While
[Link] = fact
Do … while code
Do
statement-block
Loop While condition
Do
Page 94 prepared by AY@[Link]
statement-block
Loop Until condition
Example: find the factorial of a number n inputted from the keyboard using do…while or do …
until loop.
Dim fact, i As Integer
fact = 1
i=1
Do
fact = fact * i
i=i+1
Loop While (i <= Val([Link]))
[Link] = fact
Or
Dim fact, i As Integer
fact = 1
i=1
Do
fact = fact * i
i=i+1
Loop until(i > Val([Link]))
[Link] = fact
Steps to create a connection to SQL Database [Link]
1. Using wizard:
Once you have your VB software open, do the following:
 Click File > New Project from the menu bar
 Select Windows Application, and then give it the Name. Click OK
 Locate the Solution Explorer on the right hand side.
Page102

We need to select Show Data Source from data on the menu bar. Then, click on Add New Data
Source.

Page 95 prepared by AY@[Link]


When you click on the link Add a New Data Source, you will see a screen shown bellow. Then
select Database and click next.

Select DataSet and click Next.


Page102

Click the New Connection button.

Page 96 prepared by AY@[Link]


Write the server name and your Database name. Then click on Test Connection to check the
connection.

Click Test Connection to see if everything is OK.


Page102

Click on Next.

Page 97 prepared by AY@[Link]


Here, you can select which tables and fields you want. Tick the Tables box to include them all. You
can give your DataSet a name, if you prefer. Click Finish and you're done.

When you are returned to your form, you should notice your new Data Source has been added:
Page102

The Data Sources area of the Solution Explorer (or Data Sources tab on the left) now displays
information about your database. Click the plus symbol next to tblContacts:

Page 98 prepared by AY@[Link]


All the Fields in the Address Book database are now showing.
To add a Field to your Form, click on one in the list. Hold down your left mouse button, and drag it
over to your form:

In the image above, the FName field is being dragged on the Form.
When your Field is over the Form, let go of your left mouse button. A textbox and a label will be
added.
Page102

Click the Navigation arrows to scroll through the database.

Page 99 prepared by AY@[Link]


Click the Navigation icons to move backwards and forwards through your database.

3.2. Using Program Debugging Techniques to Detect and Resolve Errors.


3.2.1. Errors handling
Error handling refers to the anticipation, detection, and resolution of programming, application, and
communications errors. Specialized programs, called error handlers, are available for some
applications.
Errors in general come in three situations:
- Compiler errors such as undeclared variables that prevent your code from compiling.
- User data entry error such as a user entering a negative value where only a positive number is
acceptable
- Run time errors such as the lack of sufficient memory to run an application or a memory
conflict with another program. 
A run-time error takes place during the execution of a program, and usually happens because of
adverse/undesirable system parameters or invalid input data.
The above types of errors can be resolved or minimized by the use of error handler programs.
Page102

Example: The On Error statement is an example of error handler program.


On Error Go to 0 or
On Error Go to <label>: or
On Error Resume Next
3.2.2. Debugging options
In computers, debugging means running (executing) the programming code to perform an action
and display the result. Debugging is a necessary process in almost any new software development
process.
Debugging tools (called debuggers) help identify coding errors at various development stages.
Some programming language packages include a facility for checking the code for errors as it is
being written.

Page 100 prepared by AY@[Link]


To debug a programming code, start with a problem, isolate the source of the problem (compile),
and then fix it.
3.2.3. Compiling the program
A compiler is a computer program that transforms source code written in a programming
language(the source language) into another computer language (the target language, often having a
binary form known as object code). The most common reason for wanting to transform source code
is to create an executable program.
The name "compiler" is primarily used for programs that translate source code from a high-level
programming language to a lower level language (e.g., assembly language or machine code).
A program that translates from a low level language to a higher level one is a decompiler.
3.2.4. Run the application or program
 When running an application, Select Run/Debug Configuration drop-down list on the main
toolbar or press F5 from function keys on the keyboard.

Self-check#1 theoretical Test

Name:_________________ Date:_______
Time Started:______________ Time Finished:______

Instruction

1. A class means_______
F. Is a type, and an object of this class is just a variable.
Page102

G. Are generally declared using the keyword class.


H. Is used to specify the form of an object and it combines data representation and methods for manipulating that data into
one neat package.
I. The data and functions within a class are called members of the class.
J. all
2. Which one is true about Encapsulation?
E.  The method of combining the data and functions inside a class.
F.  Is a mechanism of bundling the data, and the functions that use them.
G. is the term given to the process of hiding all the details of an object
H. none

Page 101 prepared by AY@[Link]


Operation Sheet
1. Install the visual studio program on your computer and after you install
open the program in order to check the program to be functional.
2. Open the visual studio and create form that calculates the sum of two
even numbers.
3. Create form that accepts the input from user in order to record student
profile.
4. create form that delete the data that exist in the database
5. connect the visual studio with sql server management studio
Page102

Page 102 prepared by AY@[Link]


Injibara Polytechnic College

Ethiopian TVET-System
INFORMATION TECHNOLOGY
Database Administration system
Level IV
LEARNING GUIDE # 4
Unit of Competence: Applying Object-Oriented Programming
Language Skills
Module Title: Applying Object-Oriented Programming Language
Skills
LG Code: ICT DBAS4 M05 LO4 0412
TTLM Code: ICT DBAS4 M05 0412 v2
Page102

Page 103 prepared by AY@[Link]


Information Sheet#1 Document activities

LO4. Document activities


4.1. Guidelines for Developing Maintainable Code
Guidelines for developing maintainable code adhering to a set of coding standard is followed
4.2. The Use of Internal Documentation Standards and Tools
4.2.1. Documentation techniques
At the completion of the design process, a comprehensive package of documentation is assembled.
Detail documentation of the system should be created during each phase of the design process. The
package should contain a clear description of every facet of the new system in sufficient detail to
support its development, including these aspects:
Examples of output.
Descriptions and record layouts of each file.
Data-flow diagrams.
A data dictionary.
Identification of individual programs.
High-level documentation provides a picture of the overall structure of the system, including input,
processing, storage, and output. The general flow of information throughout the major processes of
the system can be depicted in either a data-flow diagram or a systems flowchart
The purpose of detail documentation is to provide a programmer with sufficient information to
write the program. The documentation should include report layouts for input and output, record
layouts that define the files, and the relationship among the components of the programs.
4.2.2. Program and documentation standards
Documentation standard is the structure and presentation of documents on a software development.
4.2.3. Internal documentation techniques
There are two kinds of documentations 1) System documentation 2) User documentation
System documentation is detailed information about a system’s design specifications, its internal
Page102

workings, and its functionality.


System documentation is further divided into internal and external documentation.
- Internal documentation is part of the program source code or is generated at compile time.
- External documentation includes the outcome of all of the structured diagramming
techniques such as DFD and ERD.
User documentation is written or visual information about an application system, how it works and
how to use it.
 The kinds of user documents are reference guide, user’s guide, release description, system
administrator’s guide and acceptance sign-off.

Page 104 prepared by AY@[Link]


Self-check#1 theoretical Test

Name:_________________ Date:_______
Time Started:______________ Time Finished:______

Instruction

1. A class means_______
K. Is a type, and an object of this class is just a variable.
L. Are generally declared using the keyword class.
M. Is used to specify the form of an object and it combines data representation and methods for manipulating that data into
one neat package.
N. The data and functions within a class are called members of the class.
O. all
2. Which one is true about Encapsulation?
I.  The method of combining the data and functions inside a class.
J.  Is a mechanism of bundling the data, and the functions that use them.
K. is the term given to the process of hiding all the details of an object
L. none
Page102

Page 105 prepared by AY@[Link]


Injibara Polytechnic College

Ethiopian TVET-System
INFORMATION TECHNOLOGY
Database Administration system
Level IV
LEARNING GUIDE # 5
Unit of Competence: Applying Object-Oriented Programming
Language Skills
Module Title: Applying Object-Oriented Programming
Language Skills
Page102

LG Code : ICT DBAS4 M05 LO5 0412


TTLM Code : ICT DBAS4 M05 0412 v2

Page 106 prepared by AY@[Link]


LO5. Test code
Information Sheet#1 Test code

5.1. Conducting Simple Tests to Confirm the Coding Process Meets Design Specifications
Simple tests are developed and conducted to confirm the coding process meets design specification
5.1.1. Testing techniques
The tests performed are documented.
 The detailed specifications produced during the design phase are translated into hardware,
communications, and executable software.
 The design must be translated into a machine-readable form. The code generation step
performs this task. If the design is performed in a detailed manner, code generation can be
accomplished without much complication. Different high level programming languages are
used for coding. With respect to the type of application, the right programming language is
chosen.
 Depending on the size and complexity of the system, coding can be an involved, intensive
activity. Once coding is begun, the testing process can begin and proceed in parallel. As each
program module is produced, it can be tested individually, then as a part of a larger program,
and then as part of larger system.
 The deliverables and outcome from the coding are the code and program documentation.
5.1.2. User manual
A user manual is, also known as a user guide, is a technical communication document intended to
give assistance to people using a particular system.
Page102

It is a step-by-step describes how the users can use the system. Generally the description is in detail
keeping in view the fact that the target users using the system have limited knowledge about it.
5.1.3. Printing documents of the program
You may print document of the program code.
5.2. Implementation of Required Corrections
Corrections are made to the code and the documentation as needed

Self-check#1 theoretical Test

Page 107 prepared by AY@[Link]


Name:_________________ Date:_______
Time Started:______________ Time Finished:______

Instruction

1. A class means_______
A. Is a type, and an object of this class is just a variable.
B. Are generally declared using the keyword class.
C. Is used to specify the form of an object and it combines data representation and methods for manipulating that data into
one neat package.
D. The data and functions within a class are called members of the class.
E. all
2. which one is true about Encapsulation?
A. the method of combining the data and functions inside a class.
B. is a mechanism of bundling the data, and the functions that use them.
C. is the term given to the process of hiding all the details of an object
D. none
Page102

Page 108 prepared by AY@[Link]


Page102

Page 109 prepared by AY@[Link]

You might also like