Apply Object Oriented Programming Language Skills
Apply Object Oriented Programming Language Skills
This module aims to provide the trainees with the knowledge, skills and right attitude required to undertake
programming tasks using an object oriented programming language. Competence includes tool usage,
2. Develop normalization
1.
2.
Now let us try to get a little more detail on how the computer understands
a program written by you using a programming language. Actually, the
computer cannot understand your program directly given in the text
format, so we need to convert this program in a binary format, which can
be understood by the computer. The conversion from text program to
binary file is done by software called Compiler and this process of
conversion from text formatted program to binary format file is called
program compilation. Finally, you can execute binary file to perform the
programmed task.
There are other programming languages such as Python, PHP, and Perl,
which do not need any compilation into binary format, rather an interpreter
can be used to read such programs line by line and execute them directly
without any further conversion.
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. 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:
1.3. Using 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
Example:
#include <iostream.h>
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;
}
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
The goto statement provides an unconditional jump from the goto to a labeled statement in the same function.
Syntax of a goto statement in C++:
goto label;
..
.
Example:
#include <iostream.h>
int main ()
{
int a = 10; // Local variable declaration:
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
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.
Example:
#include <iostream.h>
int main ()
{
int a = 10; // Local variable declaration:
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
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 to choose a set of statements for execution depending on a condition.
If statement and switch statement are the two selection statements.
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.
# 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
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.
Syntax:
Switch (variablename)
Applying Object-Oriented Programming Language Skills Page 9
Institution Name Document No.
ወ/ሮ ስህን ፖሊቴክኒክ ኮሌጅ
W/R SIHEEN POLYTECHNIC COLLEGE OF/WSPC /263-01
Title: Issue No. Page No.
2 Page 16 of 63
TTLM
{
case value1: statement1; break;
case value2: statement2; break;
case value3: statement3; break;
default: statement4;
}
Flow Diagram:
Example: #include<iostream.h>
void 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;
}
}
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)
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.
Example: #include<iostream.h>
void main()
{
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;
}
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);
Statement;
}
Flow Diagram:
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;
}
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.
syntax:
for ( initial value ; test condition ; increment/decrement)
{
Statement;
}
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.
Example: #include<iostream.h>
void main()
{
int i, n, sum=0;
cout<< "Enter the value for n";
cin>>n;
for(i=1;i<=n; i++)
{
sum=sum+i;
}
cout<< "the sum is" <<sum;
}
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 complex) programs.
Applying Object-Oriented Programming Language Skills Page 13
Institution Name Document No.
ወ/ሮ ስህን ፖሊቴክኒክ ኮሌጅ
W/R SIHEEN POLYTECHNIC COLLEGE OF/WSPC /263-01
Title: Issue No. Page No.
2 Page 16 of 63
TTLM
1.5. Using 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]
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).
NOTE: The elements field within brackets [], which represents the number of elements the array is going to hold,
must be a constant value.
Arrays of variables of type “class” are known as "Array of objects". The "identifier" used to refer the array of
objects is a user defined data type.
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
}
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 sum;
sum=a+b;
return (sum);
}
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;
}
}
// second name space
namespace second_space{
void func(){
cout << "Inside second_space" << endl;
}
}
int main ()
{
first_space::func(); // Calls function from first name space.
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.
Self Check LO1
5. List the three types of control structure and explain briefly them
with examples.
a) Array
b) Method
c) Namespace
public:
int cube()
{
return (val*val*val);
}
};
int main ()
{
Cube cub;
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
{
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()
{
statement obj;
obj.get();
obj.getsm();
obj.display();
}
public:
void disp(void)
{
tot = sub1+sub2;
put_num();
put_marks();
cout << "Total:"<< tot;
}
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 :
throw: A program throws an exception when a problem shows up. This is done using a throw keyword.
catch: A program catches 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>
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 {
z = division(x, y);
cout << z << endl;
}catch (const char* msg)
{
cerr << msg << endl;
}
return 0;
}
Processor Minimum 1.6 GHz CPU, recommended 2.2 GHz or higher CPU
Hardisk Space Minimum 5400 RPM hard disk, recommended 7200 RPM or higher hard disk
Microsoft Windows XP , Microsoft Windows Server 2003 , Windows Vista, or Latest
Supporting Operating System
version
CD ROM or DVD Drive Required
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.
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 VB.Net
There are many ways for saving a project created using VB.Net 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.
Menu Bar
Menu bar in Visual Basic.net 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.
Solution Explorer
Solution Explorer in Visual Basic.net 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.
Properties Window
Windows form properties in Visual Basic.net 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.
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 VB.net.
Following table lists some important Properties of Forms in Visual Basic.net 2008.
Properties Description
BackColor Set's the background color for the form
BackgroundImage Set's the background image for the form
Specifies whether to accept the data dragged and
AllowDrop
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 by
Control Box
clicking the icon on the upper left corner of the window.
Specifies whether to display the maximize option in the
MaximizaBox
caption bar of the form.
Specifies whether to display the minimize option in the
MinimizeBox
caption bar of the form.
Boolean Integer
Char Long
Date String
Double Single
Constants in VB.NET
Constants in VB.NET 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 datatype = value
In the above syntax, the Public or Private can be used according to the scope of usage. The Value specifies the
unchangable value for the constant specifed using the name constName.
Example:
Public Class Form1
Public Const PI As Double = 3.14
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim r As Single
r = Val(TextBox1.Text)
TextBox2.Text = PI * r * r
End Sub
End Class
Do … while code
Do
statement-block
Loop While condition
Do
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(TextBox1.Text))
TextBox2.Text = fact
Or
Dim fact, i As Integer
fact = 1
i = 1
Do
fact = fact * i
i = i + 1
Loop until(i > Val(TextBox1.Text))
TextBox2.Text = fact
Steps to create a connection to SQL Database VB.Net
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.
We need to select Show Data Source from data on the menu bar. Then, click on Add New Data Source.
When you click on the link Add a New Data Source, you will see a screen shown bellow. Then select Database
and click next.
Write the server name and your Database name. Then click on Test Connection to check the connection.
Click on Next.
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:
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:
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.
Click the Navigation icons to move backwards and forwards through your database.