Sei sulla pagina 1di 207

MALAYSIA

POLYTECHNICS
MINISTRY OF EDUCATION

MODULE E3062
PROGRAMMING
MOHD RUDIN B. FAUZI (PKB)
ZULKIFFLI B. MOHD YUSOFF (PKB)

download@
http://modul2poli.blogspot.com

BIODATA OF MODULE WRITERS


E3062 PROGRAMMING 1

Name
Address

:
:

Telephone No. :
e-mail
:
Qualifications :

Position

Name
Address

:
:

Telephone No. :
e-mail
:
Qualifications :

Position

Mohd Rudin B. Fauzi


Electrical Engineering Department
Politeknik Kota Bharu, Pangkal Kalong
16450 Kota Bharu, Kelantan.
09-7889126
mrudin@tm.net.my
M.Ed. (UTM), Bsc (Hons) in Electrical
Eng.(UTM), Diploma in Electrical Eng.
(ITM)
Polytechnic Lecturer

Zulkiffli Bin Mohd Yusoff


Electrical Engineering Department
Politeknik Kota Bharu, Pangkal Kalong
16450 Kota Bharu Kelantan.
09-7889126
zulzur@tm.net.my
M.Ed. (UTM), Bsc (Hons) in Electrical
Eng.(UTM), Diploma in Electrical
(Power) Eng.(ITM)
Polytechnic Lecturer

Editor
Name
:
Address
:
Telephone No. :
e-mail
:
Qualifications :
Position
:

download@
http://modul2poli.blogspot.com

What Do You Think Of This Module?


Title of Module: _______________________

Module Code

: ___________

Students Name: _______________________

Registration No. : ___________

Course : ____________________________________
Module Writers: ______________________________
Please use the following scale for your evaluation:
4
3
2
1

Strongly Agree
Agree
Disagree
Strongly Disagree

Instruction : Please on the space provided.


No.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

How much do you agree with the following statements?


A. FORMAT
The pages are organized in an interesting manner.
The font size makes it easy for me to read the module.
The size and types of pictures and charts used are suitable for
the input.
The pictures and charts are easy to read and understand.
The tables used are well-organised and easy to understand.
The arrangement of the Input makes it easy for me to follow.
All the instructions are displayed clearly.
B. CONTENTS
I understand all the objectives clearly.
I understand the ideas conveyed.
The ideas are presented in an interesting manner.
All the instructions are easy to understand.
I can carry out the instructions in this module.
I can answer the questions in the activities easily.
I can answer the questions in the self-assessment.
The feedback section can help me identify my mistakes.
The language used is easy to understand.
The way the module is written makes it interesting to read.
I can follow this module easily.
Each unit helps me understand the topic better.
I have become more interested in the subject after using this
module.

download@
http://modul2poli.blogspot.com

SCALE
1

CURRICULUM GRID
The curriculum grid of this module is based on the curriculum used by Malaysian
polytechnics.
No.

TOPIC

UNIT

Total
Hours

Basic Concept And


Problem Solving
Programming

1
( 2 H)

2 Hours

Introduction To The
Concept And Basic
Instruction
Programming C++

2
( 2 H)

Data Types, Operator


And Expression

4
(2H)

2 Hours

Logical Structure
Types And Basic
Instructions

5
(2H)

2 Hours

Preprocessor and
Header File

6
(2H)

2 Hours

Writing Programmed
in Programming C++

7
(2H)

2 Hours

Introduction To
Visual Basic

8
(2H)

Writing Programmed
Using Visual Basic

10
(2H)

3
( 2 H)

9
(2H)

download@
http://modul2poli.blogspot.com

4 Hours

4 Hours

2 Hours

UNIT 1

Basic Concept And Problem Solving in Programming

1.0

Programming Basic Concept

1.1

Definition of Programming

1.2

The components of programmed structure


1.2.1 Declaration
1.2.2 Input
1.2.3. Storage
1.2.4. Operation
1.2.5. Control
1.2.6. Output

1.3

Identifying steps in programming


1.3.1. Definition and analyze
1.3.2. Planning user variables
1.3.3. Drawing Flowchart.
1.3.4. Program Writing
1.3.5. Testing and debugging the programmed
1.3.6. Documentation the programmed

UNIT 2

Introduction To The Concept And Basic Instruction of


Programming C++

2.0

Introduction to C++ Program.

2.1

C++ Program Characteristics .


2.1.1

Comments

2.1.2 Header Files


2.1.3
2.2.

Functions

Basic Input, Output and Format Code


2.2.1 Console Output (cout)
2.2.2

Console Input

(cin).

2.2.3

Format Codes (Backslash Character Constant).

download@
http://modul2poli.blogspot.com

UNIT 3

Introduction To The Concept And Basic Instruction of


Programming C++

3.0

Introduction The Technique To Develope C++ Programming .


3.0.1. Alogarithm
3.0.2

Flowcharts

3.0.3 Pseudocode
3.0.4
3.1

UNIT 4
4.0

Structure chart.

Using Algorithm And Flowchart In Programming:


3.1.1

Algorithm

3.1.2.

Flowchart

Data Types, Operator And Expression


Introduction to data types, operator and expression in
C++ Programming.

4.1

4.2

Basic data types


4.1.1

Integer - Int

4.1.2

Character - char

4.1.2

Floating Point - float and double.

Declaring the constant


4.2.1

Integer Constant

4.2.2

Character and string Constant

4.3

Declaring Variables

4.4

The Operators

4.5

UNIT 5

4.4.1

Arithmetic Operators

4.4.2

Relational Operators

4.4.3

Logical Operators

The Expression

Logical Structures And Basic Instructions

5.0

Introduction to logical structures

5.1

Logical structures and basic instructions:

download@
http://modul2poli.blogspot.com

5.1.1 Sequence structure


5.1.2 Selection structure Simple If, If-Then-Else, Case
5.1.3 Repetition structure For, While, Whiledo
5.1

UNIT 6

Compiles and Runs Program

Preprocessor and Header Files

6.0

Introduction to pre-processor and header files

6.1

Preprocessor statement.

6.2

6.1.1

#include

6.1.2

#define

Header file .h
6.2.1

stdio.h

6.2.2

ctype.h

6.2.3

math.h

6.3.4 conio.h
6.3.5

UNIT 7

iostream.h

Writing Programmed in Programming C++

7.0

Simple programming

7.1

Even Odd

7.2

Grade

7.3

Student List

7.4

Bubble Sort

UNIT 8

Introduction To Visual Basic

8.0

Introduction To Visual Basic

8.1

Visual Basic Enviroment

8.2

Basic Project structure

8.3

The User Interface


8.3.1

Toolbox, project and properties windows .

8.3.2 Design and modify the Toolbox object properties.

download@
http://modul2poli.blogspot.com

8.4

UNIT 9

Save and Run the project.

Introduction To Visual Basic

9.0

Introduction

9.1

Procedure Events

9.2

Create object an event procedure

9.3

Using a simple Visual Basic statement


9.3.1

Declaration

9.3.2

Sequence

9.3.3 Selection
9.3.4

UNIT 10
10.0

Repetition

Writing Programmed Using Visual Basic


Simple application programmed

download@
http://modul2poli.blogspot.com

MODULE GUIDELINES
To achieve maximum benefits in using this module, students must follow the
instructions carefully and complete all the activities.
1.
2.

This module is divided into 10 units.


Each page is numbered according to the subject code, unit and page number.
B3062 / UNIT 1 / 5

Subject Unit 1 Page Number 5


3.
4.

The general and specific objectives are given at the beginning of each unit.
The activities in each unit are arranged in a sequential order and the
following symbols are given:

OBJECTIVES
The general and specific objectives for each learning topic are stated
in this section.

INPUT
This section introduces the subject matter that you are going to learn.

ACTIVITIES
The activities in this section test your understanding of the subject
matter. You have to complete this section by following the
instructions carefully.

FEEDBACK
Answers to the questions in the activity section are given here

download@
http://modul2poli.blogspot.com

SELF-ASSESSMENT
Self-assessment evaluates your understanding of each unit.

FEEDBACK OF SELF-ASSESSMENT
This section contains answers to the activities in the self-assessment.
.

5.
6.

You have to follow the units in sequence.


You may proceed to the next unit after successfully completing the unit and
you are confident of your achievement.

download@
http://modul2poli.blogspot.com

GENERAL AIMS
This module is prepared for students in the third semester who are following the
Certificate/Diploma programmes in Malaysian Polytechnics. It aims to expose
students to the Programming concept in each unit and to lead them towards selfdirected learning or with guidance from their lecturers.

PREREQUISITE SKILLS AND KNOWLEDGE


The prerequisite for this module is at least the have to know how to used the
computer.
GENERAL OBJECTIVES

At the end of this module, students should be able to:


1. Understand the concept of program characteristics and steps in Developing
Program
2. know the characteristics and using instructions of C++ program basic
language
3. introduce techniques used in program design
4. introduce and use the data types, operator and expression in C++
programming.
5. understand the logical structure types and basic instruction refers to the order of
execution of instructions in program.
6. understand the function of preprocessor directive and header file.
7. write C ++ program
8. understand the basic concept of Visual Basic
9. understand the basic concept of Visual Basic
10. develop a simple Visual Basic program
11. understanding basic structure of project.
12. construct user interface
13. writing the programmed using windows code
14. construct simple application programmed in Visual Basic.

download@
http://modul2poli.blogspot.com

TEACHING AIDS AND RESOURCES NEEDED


1.
2.
3.

Overhead Projector (OHP)


LCD Projector
Computer

REFERENCES
1.
2.
3.
4.
6.
7.
8.
9.

William H. Murray III, Chris H. Pappas, Borland C++ - Depth, Osborne-Mc


Graw Hill.
Herbert Schildt, The Complete Reference Borland C++, Osborne Mc
Graw Hill
P. Sellapan, (1994).C++ Through Examples (Includes Object-Oriented
Programming),Federal Publication Sdn. Bhd.
M Thilla,(2002). C++ A Simplified Beginners Approach, Venton Publishing
(M) Sdn. Bhd.
Brian Siler and Jeff Sport(1998).Special Edition Using Visual Basic, QUE
Corporation.
Phil Feldman, Roger Jennings et al, Using Visual Basic, QUE Corporation
David I. Schneider (1999). An Introduction To Programming Using Visual
Basic 6.0- fourth edition. Practice Hall.
Dr. P. Sellappan. (2000). Programming In Visual Basic 6- first edition.
Sejana Publishing.

download@
http://modul2poli.blogspot.com

E3062/1/1
Basic Concept And Problem Solving in Programming

UNIT 1
Basic Concept and Problem Solving in
Programming

OBJECTIVES

General Objective

: To Understand the Concept of Program Characteristics and


Steps in Developing Program

Specific Objectives : At the end of the unit you will be able to :

define what is a program.

explain the meaning of program structure.

discuss steps in programming

download@
http://modul2poli.blogspot.com

E3062/1/2
Basic Concept And Problem Solving in Programming

INPUT

1.0

Basic concept of Programming

Before we start writing our own programs let us examine some important
characteristics of well-written computer programs. Basically these apply to
any programming language that provide a useful set of guidelines.
a. Integrity. This refer to the accuracy of the calculations since it will be
meaningless if calculations are not carried out correctly.
b. Clarity. This refer to the overall readability of the program, with
particular emphasis on its underlying logic. If a program is clearly
written, it should be possible for programmer to follow the program logic
with ease.
c. Simplicity. The clarity and accuracy of a program are usually enhanced
by keeping things as simple as possible, consistent with the overall
program objectives.
d.

Efficiency. This is concerned with execution speed and efficient memory


utilization.

e. Modularity. Many programs can be broken down into a series of


identifiable subtask that enhances accuracy and clarity of a program and
facilitates future program alterations.
f. Generality. Usually we will want a program to be as general as possible,
within reasonable limits. A considerable amount of generality can be
obtained with very little additional programming effort.

download@
http://modul2poli.blogspot.com

E3062/1/3
Basic Concept And Problem Solving in Programming

1.1

Definition of program

A set of instructions that tells the computer what to do is called a program.


For example, a word processor is a program written in computer language
like C++, that tells the computer what to do when you type in a letter.

1.2

The components of program structure.

1.2.1

Declaration
A declarations associates a group of variables with a specific data
type. All variables must be declared before they can appear in
excutable statements.
Example :
int a, b, c;
float root1, root2;
char flag, text[80]

1.2.2

Input
A set of information called data will be entered into the computer
from keyboard, floppy disk, hard disk etc. and stored in a portion of
the computer memory. This input which is an input to the computer
will then be processed to produced the desired result.

1.2.3

Storage
Every piece of information are stored within the computers memory
which is encoded as some unique combination of zeros and ones.
Small computers have memories that are organized into 8-bit
multiples called bytes. Large computer have memories that are

download@
http://modul2poli.blogspot.com

E3062/1/4
Basic Concept And Problem Solving in Programming

organized into words rather than bytes. Computers also employ


auxiliary storage e.g. disks in addition to their primary memories

which allowed information to be stored permanently and can be


physically disconnected when not in use.

1.2.4

Operation
There are two different ways computer can be utilized by many
different users. These are batch mode and the interactive mode. In
batch mode of operation the program and the data are typed into the
computer and stored within computers memory and processed in its
proper sequence. Large quantities of information can be transmitted
into and out of the computer without the user present while the job
being processed. Batch processing can be undesirable for simple jobs.
In interactive mode the user and the computer are able to interact with
each other during computational session.

1.2.5

Control
Program control refers to the order of execution of instructions in a
program. The instruction can be executed sequentially one by one,
from top downwards or non sequential execution of program
instruction. Most real life problems require some kind of decision
making to take a certain course of action. This means that instruction
or a whole block of instructions can be executed, repeated or skipped.

1.2.6

Output
The processed data which produced certain result is known as the
output. The output data will be presented in a sheet of paper through
the printer or display on a monitor.

download@
http://modul2poli.blogspot.com

E3062/1/5
Basic Concept And Problem Solving in Programming

Activity 1A

TEST YOUR UNDERSTANDING BEFORE YOU CONTINUE WITH THE


NEXT INPUT!

1.1 List the characteristics of a well planned program.

1.2 What is a program?

1.3 State the difference between batch mode and interactive mode operation

download@
http://modul2poli.blogspot.com

E3062/1/6
Basic Concept And Problem Solving in Programming

Feedback To Activity 1A

1.1 Integrity, Clarity, Simplicity, Efficiency, Modularity, Generality.

1.2 A set of instructions that tells the computer what to do is called a program.

1.3 In batch mode of operation, the program and the data are typed into the computer
and stored within computers memory and processed in its proper sequence.
Large quantities of information can be transmitted into and out of the computer
without the user present while the job being processed. Batch processing can be
undesirable for simple jobs. In interactive mode the user and the computer are
able to interact with each other during computational session.

download@
http://modul2poli.blogspot.com

E3062/1/7
Basic Concept And Problem Solving in Programming

INPUT

1.3

Identifying steps in programming

In solving problems of developing program, software development method is


used. It consists of several steps which is known as software life cycle, these
are:
1. Defining and analyzing problems
2. Planning of variables
3. Drawing of flowchart
4. Program writing
5. Testing and debugging program
6. Documentation of program.

Process of designing program can be divided into two phases mainly the
problem solving phase and implementation phase. The problem solving
phase consist of steps 1 through 3 and implementation phase involved steps 4
and 5. While in step 6, documentation is done throughout the process of
designing program.

1.3.1

Defining and analyzing problems


Programming begin with a specification of problems. This steps is to
identify and understand what are the problems to resolve. The
problems must be clearly define, explicit and the requirements in

download@
http://modul2poli.blogspot.com

E3062/1/8
Basic Concept And Problem Solving in Programming

resolving it. Analyzing the problems will determine the input, output
and information required to solve these problems, as follows:
a. input data to be processed
b. output the desired result
c. the constraint and additional features in resolving the
problems
d.
1.3.2

Planning of variables
Variables are simply references to memory locations. A well plan use
of variables will produce an efficient execution of program in terms
of speed and memory utilization.

1.3.3

Drawing of Flowchart
Flowchart represents algorithm in graphic form comprising of
geometrical symbols which is interrelated by line of flow.

1.3.4

Program writing
In the design of program it should be written as simple as possible.
The main objective is to give a clear, readable programs through an
orderly and disciplined approach to programming.

1.3.5

Testing and debugging program


Once the program has been written it must be compiled and executed.
This is accomplished by an editor and compiler. An editor lets us type
a program, makes changes and save it to a file. The compiler then
translates the program into a form that the computer can read. Once
the program has been compiled and executed the presence of errors
will be readily apparent. Syntactic and execution errors usually result
in the generation of error when compiling or executing a program.
Error of this type is usually quite easy to find and correct. Much more
difficult to detect are logical errors since the output resulting from

download@
http://modul2poli.blogspot.com

E3062/1/9
Basic Concept And Problem Solving in Programming

logically incorrect program may appear to be error free. Thus a good


bit of probing may be required which is known as logical debugging.

1.3.6

Documentation of program
Program must be documented for future references and maintenance
process. A well documented program will make it easier for the
original programmer or other programmer to follow the program logic
and design. Program document should consist of :
1. An accurate specification of requirement
2. Detail input, output, constraint and formula for the above
problems
3. Algorithm in the form of flowchart or pseudocode
4. Program source complete with comment
5. Sample program which had been run and executed and the
tested data.
6.

Guideline on how to use the program.

download@
http://modul2poli.blogspot.com

E3062/1/10
Basic Concept And Problem Solving in Programming

Activity 1B

TEST YOUR UNDERSTANDING BEFORE YOU CONTINUE WITH THE


NEXT INPUT!

1.4 State the steps in developing program.

1.5 State the components of documenting a program.

1.6 What is a flowchart?

download@
http://modul2poli.blogspot.com

E3062/1/11
Basic Concept And Problem Solving in Programming

Feedback To Activity 1B

1.4 i

Defining and analyzing problems

ii

Planning of variables

iii

Drawing of flowchart

iv

Program writing

Testing and debugging program

vi

Documentation of program.

1.5 i
ii

An accurate specification of requirement


Detail input, output, constraint and formula for the above
problems

iii

Algorithm in the form of flowchart or pseudo code

iv

Program source complete with comment

Sample program which had been run and executed and the
tested data.

vi

Guideline on how to use the program.

1.6 Flowchart represents algorithm in graphic form comprising of geometrical


symbols which is interrelated by line of flow.

download@
http://modul2poli.blogspot.com

E3062/1/12
Basic Concept And Problem Solving in Programming

KEY FACTS
1. Program is a set of instructions that tells the computer what to do is called a
program
2. Characteristics of a good program are integrity, clarity, simplicity, efficiency,
modularity and generality.
3. Process of designing program can be divided into two phases mainly the
problem solving phase and implementation phase.

download@
http://modul2poli.blogspot.com

E3062/1/13
Basic Concept And Problem Solving in Programming

1.

SELF-ASSESSMENT

You are approaching success. Try all the questions in this self-assessment section
and check your answers with those given in the Feedback on Self-Assessment 1
given on the next page. If you face any problems, discuss it with your lecturer.
Good luck.

Question 1-1

a) Briefly describe the components of program structure below.


i.

Declaration

ii.

Input

iii.

Output

Question 1-2

a) Explain the steps taken in testing and debugging of program.

Question 1-3

a) Why are documentation of programs important?

download@
http://modul2poli.blogspot.com

E3062/1/14
Basic Concept And Problem Solving in Programming

Feedback To Self-Assessment

Have you tried the question????? If YES, check your answer now:

Question 1-1

i. Declaration
A declarations associates a group of variables with a specific data type. All
variables must be declared before they can appear in executable statements.
ii. Input
A set of information called data entered into the computer from
keyboard, floppy disk, hard disk etc. and stored in a portion of the computer
memory is known as input.
iii. Output
The processed data which produced certain result is known as the output. The
output data is usually presented in a sheet of paper through the printer or
display on a monitor.

Question 1-2

Once the program has been written it must be compiled and executed. This is
accomplished by an editor and compiler. An editor lets us type a program, makes
changes and save it to a file. The compiler then translates the program into a form
that the computer can read. Once the program has been compiled and executed the
presence of errors will be readily apparent. Syntactic and execution errors usually

download@
http://modul2poli.blogspot.com

E3062/1/15
Basic Concept And Problem Solving in Programming

result in the generation of error when compiling or executing a program. Error of this
type is usually quite easy to find and correct. Much more difficult to detect are
logical errors since the output resulting from logically incorrect program may appear
to be error free. Thus a good bit of probing may be required which is known as
logical debugging.

Question 1-3

It is important to document program for future references and maintenance process.


A well documented program will make it easier for the original programmer or other
programmer to follow the program logic and design.

CONGRATULATIONS!!!!..
May success be with you
always.

download@
http://modul2poli.blogspot.com

E3062/2/1
Introduction To The Concept and Basic Instruction Of Programming C++

UNIT 2
Introduction To The Concept And Basic
Instruction Of Programming C++

OBJECTIVES

General Objective

: To know the characteristics and using instructions of


C++ program basic language

Specific Objectives : At the end of the unit you will be able to :

state what is the header file.

state what is the statement main ( ).

state and write comment line using backslash symbol

define the function of input and output statement

download@
http://modul2poli.blogspot.com

E3062/2/2
Introduction To The Concept and Basic Instruction Of Programming C++

INPUT

Information: C++ is a general purpose programming


language developed at Bell Labs by Bjarne
Stroustrup in mid-1980s. It is basically an extension
of the C language developed by Brian Kernighan and
Dennis Ritche (also of Bell Labs). C++ incorporates
almost all the features of C but adds a lot more
making it one of the most powerful and versatile
programming languages available today.

2.0

Introduction to C++ program

To make C++ work for you, you must be able to write C++ program. To give
C++ instructions to a computer, you will need and editor and a C++
compiler. An editor lets you type a C++ program, make changes and save it
in a file. The compiler then translate your C++ program into a form that your
computer can read. Then finally, you will be able to run your program.
To get started, we introduce in this chapter a simple C++ program and then
go on to briefly explain the various parts that make up a C++ program.

download@
http://modul2poli.blogspot.com

E3062/2/3
Introduction To The Concept and Basic Instruction Of Programming C++

Getting Started : Example of C++ program

comment
Preprocessor directive
Function name
Begin block

Function Body

End Block

/* This is a program that computes the sum of two integer


numbers */
#include <iostream.h>
// This is a preprocessor
main( )
// include directive
{
int x, y, sum;
cout << \nEnter first number : ;
// This is a prompt
cin >> x;
// Input from console
cout<< \nEnter second number:;
cin>>y;
sum = x + y;
// Adding x and y
cout << \nSum = <<sum;
// Output to console
return 0;
// Returning a value to the environment
}

Program 2.0

2.1

C ++ Program Characteristics

Let us examine the program in detail. C++ program is made of a few


components. They are:

2.1.1 Comments

Comments are used to insert remarks into the source code help to
explain about what the program does. In C++, comments can be place
anywhere in the programs. It can be used to include the details of the project
and the programmer who wrote or modified the code.
There are two types of comment used. They are:

download@
http://modul2poli.blogspot.com

E3062/2/4
Introduction To The Concept and Basic Instruction Of Programming C++

a. Multi-line Comment

This type of comment is begins with a /* (slash followed by an asterisk)


symbol and ended with a */ (asterisk followed by an slash) symbol.

This type of comment is good to be used when comments written are


longer than 1 line.
Example:
/* This is a program that computes the sum of two integer
numbers */

b. Single line Comment


This type of comment is used with the // (double slash) symbol and it
stops at the end of that particular line.
This type of comment can be used when the remark is only 1 line in
length.
Example:
// This is a preprocessor

2.1.2 Header Files

Header files contain information that is required to run a program. It


is a pre written and tested function that comes together with the compiler and
is available for the use of the programmers. The format or structure for using
the header file is by using the #include directive. The second line in our
program 2.1 #include <iostream.h> is called an include preprocessor
directive. As the file is placed before program the program proper , it is
called a header file (with the file extension .h)

download@
http://modul2poli.blogspot.com

E3062/2/5
Introduction To The Concept and Basic Instruction Of Programming C++

Example :
#include <iostream.h>

2.1.3 Functions

A function is a block of statements that is part of a large programme.


a. Function main( )
A C++ program must have at least the function main( ). Every C++
function, including main( ), must have a body enclosed in braces { }.

b. Function block { }
The function body, also called block can be of any size. The function always
ends with the return command.

- begin block

- end block

Example

main ( )
{
}

download@
http://modul2poli.blogspot.com

E3062/2/6
Introduction To The Concept and Basic Instruction Of Programming C++

Activity 2A

TEST YOUR UNDERSTANDING BEFORE YOU CONTINUE WITH THE


NEXT INPUT!
2.1

What is the only function all C++ programs must contain?


A. start()
B. system()
C. main()
D. program()

2.2

What punctuation is used to signal the beginning and end of code blocks?
A. { }
B. -> and <C. BEGIN and END
D. ( )

2.3

Which of the following is a correct comment?


A. */ Comments */
B. ** Comments **
C. /* Comments */
D. { Comments }

2.4

Which of the following are false about Comments used in C++?


A. Used to document programs
B. Improve the readability and understanding of programmer
C. Causes action to be performed when the program is executed
D. None of the above.

download@
http://modul2poli.blogspot.com

E3062/2/7
Introduction To The Concept and Basic Instruction Of Programming C++

Feedback To Activity 2A

2.1

C. main()

2.2

A. { }

2.3

C. /*Comments*/

2.4.

C. causes action to be performed when the program is executed

download@
http://modul2poli.blogspot.com

E3062/2/8
Introduction To The Concept and Basic Instruction Of Programming C++

INPUT

2.2.

Basic Input, Output and Format Code


In the iostream C++ library, standard input and output operations for a
program are supported by two data streams:
a. cin (console input) for input normally assigned to the keyboard
b. cout (console input) for output normally directed to the screen.
By handling these two streams you will be able to interact with the user in
your programs since you will be able to show messages in the screen and to
receive his/her input from the keyboard.
2.2.1. Output (cout )
The function cout is used with the overloaded operator << (a pair of less
than signs). It follows the following format as in the following examples:
cout << \n Enter First number: ;

Example 2.2.1(a) This format is used to print out string values to the screen
cout << 1000 ;
Example 2.2.1(b) This format is used to print number
cout << variable_name;

Example 2.2.1(c) This format is used to print the value of a variable.

download@
http://modul2poli.blogspot.com

E3062/2/9
Introduction To The Concept and Basic Instruction Of Programming C++

2.2.2

Input ( cin )

Handling the standard input in C++ is done by applying the overloaded


operator of extraction ( >> ) on the cin stream, followed by the variable that
will store the data that is going to be read. It follows the following format:
cin >> x ; // x is a variable
cin >> address ; // address is a variable

2.2.3

Format Code ( Backslash Character Constant)

The backslash character constant is also known as the Escape Sequence.


Certain characters such as the backspace and carriage return are not printable
characters and these characters pose special problems when printing using
text editor. The backslash character constant is used together with other
character constant when such problems are encountered.
Table 2.0: Format Code
Code
\b
\f
\n
\r
\t
\
\
\\
\v
\a

Meaning
Backspace
Form feed
Newline
Carriage return
Horizontal tab
Double quote
Single quote character
Backslash
Vertical tab
Alert

download@
http://modul2poli.blogspot.com

E3062/2/10
Introduction To The Concept and Basic Instruction Of Programming C++

Example,
cout << What is your name?\nAge?\n;

The output would be:


What is your name?
Age?

This example shows the use of the new line (\n) character constant to print characters
on the next line.

download@
http://modul2poli.blogspot.com

E3062/2/11
Introduction To The Concept and Basic Instruction Of Programming C++

Activity 2B

TEST YOUR UNDERSTANDING BEFORE YOU CONTINUE WITH THE


NEXT INPUT!
2.5 Determine which of the following are valid output;. If valid what is the
output
a. cout << A;
cout << B;
cout << C;
b. cout << A\n;
cout << B\n;
cout << C\n;
c. cout << A;
<< B;
<< C;
d. cout << A\n; cout << B\n; cout << C\n;
e. cout << A << B << C;
2.6 Which of the following are valid input
a.
b.
c.
d.
e.

cin >> 80;


cin >> x, y, z;
cin >> x + y;
cin >> x ;
cin >> number ;

download@
http://modul2poli.blogspot.com

E3062/2/12
Introduction To The Concept and Basic Instruction Of Programming C++

Feedback To Activity 2B

2.5
a. Valid

b. valid

ABC

A
B
C

c. Not valid
d. valid

ABC

e. valid

ABC

2.6
a. valid
b. not valid
c. not valid
d. valid
e. not valid

download@
http://modul2poli.blogspot.com

E3062/2/13
Introduction To The Concept and Basic Instruction Of Programming C++

KEY FACTS
1. To make the C++ program executable you must be able to write a set of
instructions that tells the computer what to do.
2. Various components that make up a C++ program are comments, pre
processor directives, function name, function block and function body.

download@
http://modul2poli.blogspot.com

E3062/2/14
Introduction To The Concept and Basic Instruction Of Programming C++

3.

SELF-ASSESSMENT

You are approaching success. Try all the questions in this self-assessment section
and check your answers with those given in the Feedback on Self-Assessment 2
given on the next page. If you face any problems, discuss it with your lecturer.
Good luck.
Question 2-1
a. Trace the output from the following programs:
// Program to display greetings
#include <iostream.h>
main()
{
char name[20], gender ;
// Variable name can take up to
cout<< \nEnter your name: ;
// 20 characters.
cin>>name ;
cout<< \nEnter your gender (M or F): ;
cin>>gender;
// Test whether gender is male
if (gender == M)
cout<< \nGoodday, Mr. <<name;
else
cout<< \nGoodday, Ms. <<name;
return 0;
}

download@
http://modul2poli.blogspot.com

E3062/2/15
Introduction To The Concept and Basic Instruction Of Programming C++

Question 2-2
a. State the errors, if any, in the following programs:

#include <iostream.h>
main{}
(
int m, n;
float q;
m=5;
n=2;
q=m/n;
cout>> \n>>q;
m=m+n+q;
out<< \n<<m;
return 0;
)

download@
http://modul2poli.blogspot.com

E3062/2/16
Introduction To The Concept and Basic Instruction Of Programming C++

Feedback To Self-Assessment 2

Have you tried the question????? If YES, check your answer now:
Question 2-1
Here is a sample output, after running the program.
Enter your name:Abu
Enter your gender ( M or F ): M
Goodday, Mr. Abu
Question 2-2
Line 2 main{ } - main () not main{ }
Line 3 (

- the correct begin block is {

Line 9 << - the correct redirection operator for cout is >>


Line 11 out - the correct console output is cout
Line 13 ) - the correct end block is }

CONGRATULATIONS!!!!..
May success be with you
always.

download@
http://modul2poli.blogspot.com

B3062/3/1
Introduction To The Concept and Basic Instruction Of Programming C++

UNIT 3
Introduction To The Concept And Basic
Instruction Of Programming C++

OBJECTIVES

General Objective

: To introduce techniques used in program design.

Specific Objectives : At the end of the unit you will be able to :

state the techniques of program designing tools

briefly explain the techniques of designing program by


different designing tools

use algorithm and flowchart to develop computer program

download@
http://modul2poli.blogspot.com

B3062/3/2
Introduction To The Concept and Basic Instruction Of Programming C++

INPUT

A recipe provides good and simple example of a plan.


The ingredients and the amounts are determined by what
is to be baked. That is the output determines the input
and processing. The recipe or plan reduces the number of
mistakes you might make. Many programmers
particularly beginners frequently try to write without first
making a careful plan. Step-by step process will enable
you to use your time efficiently and help you design error
free program that produced the desired output

3.0

Introduction The Technique To Develope C++ Programming

The first step in writing instructions to carry out a task is to determine what the
output should be that is, what the task should produce. The second step is to
identify the data, or input, necessary to obtain the output. The last step is to
determine how to process the input to obtain the desired output. The general process
of writing program is to analyze the problem, design and plan the solution, coding

download@
http://modul2poli.blogspot.com

B3062/3/3
Introduction To The Concept and Basic Instruction Of Programming C++

which is to translate the algorithm into a programming language and finally testing
and debugging.
In this unit we shall discuss the logical sequence of precise steps that solve the
problem known as algorithm and three popular programming tools or techniques
used to develop the logic plan: flowcharts, pseudo code and structure chart or inputprocess-output chart.

3.0.1

Algorithm
The techniques of selecting program statements and their logical sequencing

which emphasize the translating of each step of program outline into one or
equivalent C++ instruction is known by algorithm. Every detail, including obvious
steps , should appear in algorithm.
You use algorithm everyday to make decisions or perform tasks. For example, a 30%
discount sales at the supermarket, you must be able to write program that calculate
and display the price of item after discount according to the price entered by
consumer.

3.0.2

i. Request price of item

(Input)

ii. Value of discount = rate of discount * price

(Process)

iii. Price after discount = price - value of discount

(Process)

iv. Display of discount price

(Output)

Flowcharts
Graphic representation of algorithm is known as flowchart which consist of

geometric symbols. These symbols are connected by line of arrows called flowlines
which indicate the direction of flow of processes or activities. The shape of the
symbol indicates the type of operation that is to occur. Flowchart should flow from
the top of the page to the bottom. The symbols used in flowchart are standardized.

download@
http://modul2poli.blogspot.com

B3062/3/4
Introduction To The Concept and Basic Instruction Of Programming C++

Symbol

Name
Flowline

Terminal

Input/output

Processing

Decision

Connector

Offpage connector

download@
http://modul2poli.blogspot.com

Meaning
Used to connect symbols
and indicate the flow of
logic
Used to represent the
beginning (start) or the end
(End) of a task
Used for input and output
operations, such as reading
and printing. The data to be
read or printed are describe
inside
Used for arithmetic and
data-manipulation
operations. The instruction
are listed inside the symbol
Used for any logic or
comparison operations.
Unlike the input/output and
processing symbols, which
have one entry and one exit
flowline, the decision
symbol has one entry and
two exit paths. The path
chosen depends on whether
the answer to a question is
yes or no
Used to join different
flowline
Used to indicate that the
flow chart continues to a
second page

B3062/3/5
Introduction To The Concept and Basic Instruction Of Programming C++

Predefined Process

Used to represent a group


of statements that perform
one processing task.

Annotation

Used to provide additional


information about another
flowchart symbol

The main advantage of using a flowchart to plan a task is that it provides a pictorial
representation of the task, which makes the logic easier to follow. We can clearly see
each and every step and how it is connected to the next step. For example lets look at the
discount sales program.

Start
Read price
value

input

Calculate discount value = price *


discount rate

process

Price of item after discount


= price - discount value

process

Display price after discount

output

End
Figure 3.2 Flowchart for the discount sale
(An Introduction To Programming Using Visual Basic 6.0- David I. Schneider),

download@
http://modul2poli.blogspot.com

B3062/3/6
Introduction To The Concept and Basic Instruction Of Programming C++

The major disadvantage with flowcharts is that when a program is very large, the
flowcharts may continue for many pages, making them difficult to follow and modify.

3.0.3 Pseudocode
Pseudocode is an abbreviated version of actual computer code. The
geometric symbols used in flowcharts are replaced by English-like statements that
outline the process. Pseudocode looks more like computer code than does flowchart.
It allows programmer to focus on the steps required to solve a problem rather than on
how to use computer language.

The programmer can describe the algorithm in computer language form


without being restricted by the rules of the computer language. When the
pseudocode is completed it can be easily translated into any computer language.
The following is pseudocode for the price of discount sales item problem:

Program: determine the price of discount item on sale.


Read price

(Input)

Set the value of discount = rate of discount * price entered

(Process)

price of discount item = price of item - value of discount

(Process)

Display the price after discount

(Output)

Pseudocode has several advantages. It is compact and probably will not


extend for many pages as flowcharts commonly do. Also the plan looks like the code
to be written and preferred by many programmers.

3.0.4

Structure Chart
Structure chart is also known as input-process-output or hierarchy chart

shows the overall program structure. It refers to planning diagrams similar to a

download@
http://modul2poli.blogspot.com

B3062/3/7
Introduction To The Concept and Basic Instruction Of Programming C++

companys organization chart. Structure chart depicts the organization of program


but omit the specific processing logic. They describe what each part, or module, of
the program does and they show how the modules relate to each other. Each module
may be subdivided into succession of sub-modules that branch out under it. The
charts are read from top to bottom and left to right. Figures 3.3 shows an example of
a structure chart. This price of discount item problem was solved by a series of
instructions to read data, perform calculations, and display results. Each steps was in
sequence; that is we moved from one line to the next without skipping over any
lines.

The main benefit of structure charts is in the initial planning program. We


break down the major parts of a program so we can see what must be done in
general. From this point, we can then refine each module into more detailed plans
using flowcharts.
Price of discount item program

Calculate price
Display discount price

Read price
discount value = price * rate of discount

discount price = price discount value

Figure 3.3: Structure Chart


(An Introduction To Programming Using Visual Basic 6.0- David I. Schneider),

download@
http://modul2poli.blogspot.com

B3062/3/8
Introduction To The Concept and Basic Instruction Of Programming C++

Activity 3A

TEST YOUR UNDERSTANDING BEFORE YOU CONTINUE WITH THE


NEXT INPUT!
Question 3.1
Draw the standard flowcharts symbol for
i.
ii.
iii.

input/output
processing
decision

Question 3.2
State the 3 most popular programming tools

Question 3.3
What is an algorithm?

download@
http://modul2poli.blogspot.com

B3062/3/9
Introduction To The Concept and Basic Instruction Of Programming C++

Feedback To Activity 3A

Question 3.1
i. input/output

ii. processing

iii. decision

Question 3.2
1. Pseudocode
2. flowchart
3. structure chart

Question 3A.3
Algorithm is the techniques of selecting program statements and their logical
sequencing which emphasize the translating of each step of program outline into one
or equivalent computer language instruction.

download@
http://modul2poli.blogspot.com

B3062/3/10
Introduction To The Concept and Basic Instruction Of Programming C++

INPUT

3.1

Using Algorithm and Flowchart in programming

3.1.1

Class average Algorithm


Problem: Calculate and report the grade-point average for a class.

Discussion: The average grade equals the sum of all grades divided by
number of students. We need a loop to read and then add (accumulate) the
grades for each student in the class. Inside the loop, we also need to total
(count) the number of students in the class.

Input: Students grades

Processing: Find the sum of the grades; count the number of students;
calculate average grades = sum of grades / number of students.

Output: Average grade

download@
http://modul2poli.blogspot.com

B3062/3/11
Introduction To The Concept and Basic Instruction Of Programming C++

3.1.2.

Class Average Flowchart

Start
counter and
sum start at 0

Initialize
counter and
sum to 0

Are
There more
Data?

No

Yes
Get next
grade

Increment
counter

Add grade
to sum

Set average to
sum/counter

Display
average

End

download@
http://modul2poli.blogspot.com

read next
grade

add 1 to
counter

accumulate
sum of grades

find the average

display the
answer

B3062/3/12
Introduction To The Concept and Basic Instruction Of Programming C++

Activity 3B

TEST YOUR UNDERSTANDING BEFORE YOU CONTINUE WITH THE


NEXT INPUT!

Question 3.1
You are to plan a program to sum two integer entered by user and display the result
of the summation by using the flowchart technique, from the following pseudocode;
1.
2.
3.
4.
5.
6.

Print text Enter first number


Read first number
Print text Enter second number
Read second number
Calculate sum of two number
Print the sum of two number

download@
http://modul2poli.blogspot.com

B3062/3/13
Introduction To The Concept and Basic Instruction Of Programming C++

Feedback To Activity 3B

Question 3.1

Start
Print text Enter
first number
Read first number

Print text Enter


second number
Calculate sum of
two number

Display the sum of two


number

End

download@
http://modul2poli.blogspot.com

B3062/3/14
Introduction To The Concept and Basic Instruction Of Programming C++

KEY FACTS
1. The algorithm should be tested at the flowchart stage before being coded
into a program.
2. Pseudocode, flowcharts and structure charts are universal problem
solving tools that can be used to construct program in any computer
language
3. Flowcharts are used to provide visualization of the flow of certain
programming tasks

download@
http://modul2poli.blogspot.com

B3062/3/15
Introduction To The Concept and Basic Instruction Of Programming C++

1.

SELF-ASSESSMENT

You are approaching success. Try the question in this self-assessment section and
check your answers with those given in the Feedback on Self-Assessment given on
the next page. If you face any problems, discuss it with your lecturer. Good luck.
Question 3-1
Every employee who earns more than RM 50,000.00 per annum is required to pay
2.5 % of their nett yearly income. Write a complete program algorithm which will
calculate and display all the employees income tax return. Also, show the flowchart
for the program.

download@
http://modul2poli.blogspot.com

B3062/3/16
Introduction To The Concept and Basic Instruction Of Programming C++

Feedback To Self-Assessment

Have you tried the question????? If YES, check your answer now:
Question 3-1
Problem: Calculate and display income tax return
Discussion: The program must read the yearly income entered by user and select
income more than RM 50,000.00 to be multiplied by 2.5 %. Income less than
RM50,000.00 will be multiplied by 0. The result will be displayed..
Input: Employee yearly income
Processing: Select the value of income; more than 50000.00 calculate the income
tax return = yearly income * 0.025. Less than 50000.00 calculate the income tax
return = yearly income * 0.00.
Output: Income tax return

download@
http://modul2poli.blogspot.com

B3062/3/17
Introduction To The Concept and Basic Instruction Of Programming C++

Start

Print text Enter


yearly income

Read yearly income

No

More than
50000.00?

Calculate income
tax return =
yearly income * 0

Yes

Calculate income
tax return = yearly
income * 0.025

Display income tax return

End

CONGRATULATIONS!!!!..
May success be with you
always.

download@
http://modul2poli.blogspot.com

E3062/4/1
Data Types, Operator And Expression

UNIT 4
Data Types, Operator And Expression

OBJECTIVES

General Objective

: To Introduce and Use the data types, operator and


expression in C++ Programming.

Specific Objectives : At the end of the unit you will be able to :

describe the essential data type : int,char,float and double


declare constant and variable
able to use constant and variable
explain the arithmetic operator types
explain the arithmetic, relational and logical operator types
able to used operators to construct expression

download@
http://modul2poli.blogspot.com

E3062/4/2
Data Types, Operator And Expression

INPUT 4

We will look at the basic elements


need to construct a C++ program
including the C++ data types, constant,
variable, operator and expression.

4.0

INTRODUCTION TO DATA TYPES, OPERATOR AND


EXPRESSION IN C++ PROGRAMMING.

The C++ character set includes the keyboard characters, namely the
uppercase letter A - Z, the lower letters a z , the digits 0 9 , and other special
characters (such as!, #, [, ] , ,&,<,?, and * ). The blank space is also a character in
the set.
Identifiers are simply references to memory location which can hold values.
They are formed by combining letters (both upper and lowercase), digits and the
underscore( _ ). The first character of an identifier, however, must be a letter. The
blank character is not permitted in an identifier. Although identifiers can be formed
by freely combining the letters, digits and underscores, common sense tells us that
we should give them suggestive names, that is, names that reflect the data items that
they are going to store. Identifiers can be of any length although in practice they
seldom exceed 25 characters.

download@
http://modul2poli.blogspot.com

E3062/4/3
Data Types, Operator And Expression

Example of valid and invalid identifiers:


Table 4.1
Valid Identifier
x
Sumx2
Hourly_rate
name
GROSS_PAY

Invalid Identifier
x
2sumx
Hourly-rate
name@
GROSS PAY

Comment
Illegal character
Illegal first character
Illegal character Illegal character @
Illegal blank

C++ identifiers are case-sensitive, meaning, lower and uppercase letter in


identifiers are treated as different characters. This means we cannot freely mix the
lower and uppercase letter to refer to the same identifier. For example, identifiers
HOURLY_RATE, Hourly_Rate, Hourly_rate and hourly_rate are all different, they
refer to different memory locations.
Variables are identifiers whose value may change during the course of
execution of a program.
Keywords in C++, also called reserved words, have standard, predefined
meanings and must be used only for their intended purpose. Programmers therefore
should not use these keywords as identifiers.

4.1

Basic Data Types

There are four main data types in programming C++


i.
ii.
iii.
iv.

int
char
double
float

For additional of basic data types programming C++ can support another built-in
data types such as short, long, signed and unsigned. The various data types, the
number of bits required to store them, and their range are shown in Table 4.1

download@
http://modul2poli.blogspot.com

E3062/4/4
Data Types, Operator And Expression

Table 4.2
Data Type
Integer
Long integer
Short integer
Unsigned integer
character
Floating point
Double floating
point

4.1.1

C++ Keyword
int
long
short
unsigned
char
float

Bits
16
32
8
16
8
32

double

64

Range
-32768 to 32767
-42994967296 to 4294967295
-128 to 127
0 to 65535
0 to 255
Approximately 6 digits of
precision
Approximately 12 digits of
precision

Integer data types - int

Key words int is use to declare variable integer number


Syntax
example :

int name_identifier
int bilangan ;
int nom1,nom2;

This declaration means that the compiler was asked to hold integer
data name bilangan, nom1 and nom 2. Integer data types is classified as sign
(+) and unsigned (-).For all the computer system, data integer is refer to 0
and 1 bits. There are three types of integer short int, int, long int. The
comparison of this integer range in value.
Short int :
-32768 to 32767
Int :
-32768 to 32767
Long int ;
-2147483648 to 2147483648
Unsigned short int: 65535
Unsigned int:
65535
Unsigned long int : 4294967295

download@
http://modul2poli.blogspot.com

E3062/4/5
Data Types, Operator And Expression

4.1.2 Character data types - char


Storage word char is use to declare variable character
Syantax
example:

char name_identifier
char huruf;
char lagi;

This declaration means that variable lagi and huruf will given a
memory storage for character data type. Character variable store printed data
or un printed data in character set of computer includes;
small and capital letters
decimal digits (0-9)
special character
This character represent in 1 byte (8 bit) computer memory. Internal
representative for character value decided by encoder character (ASCII or
EBCDIC) that is used in the computer.

4.1.3

Floating Point data types - float and double

This type can store floating point in computer memory.


Syntax :
Example:

double name_identifier
double pendapatan_bersih,cukai_pendapatan;
double nilai;

Memory storage that use for variable pendapatan_bersih be able to


store floating point data. But int and char data types only can be stored
according to computer types. The three floating points data in C++ such as;
1. float
2. double
3. long double

download@
http://modul2poli.blogspot.com

E3062/4/6
Data Types, Operator And Expression

The comparison of the three types are range value and digits.
Float : 1.175494e-38 to 3.402823e+38
(6 place decimal )
Double : 2.225074e308 to 1.797693e+308 (15 place decimal)
Long double : 3.362103e-4932 to 1.189731e+4932 (19 place dec.)
4.2

Declaring Constant

Constant are values that do not change during program execution. They can be of
type integer, character or floating point. To declare a constant, use the keyword const
as in the example
Const int days_of_week=7;

Constants

4.2.1

data type

identifier

Integer constant

Integer constant can be further categorized into four types-short integer,


integer,unsigned integer and long integer.
Examples of integer constants
Short integer constant:
-99
-35
0
45
320
Integer constants:
9999
-1
0
555
32767
Unsigned integer constants:
1
256
1000
60000
Long integer constants:
222
0
33333
9999999
A constant can also be identified as being long by tagging a l or a L to
the end of the number, For example , the constants 212L and 323l. will be
viewed by C++ as long constants.

download@
http://modul2poli.blogspot.com

E3062/4/7
Data Types, Operator And Expression

4.2.2

Character and string Constants

A character constant is any character enclosed between two single quotation


marks ( and ). When the several characters are enclosed between two
double quotation marks ( and ), it is called a string. Examples of character
and string constants;
i.

ii.

Character constants:
$
*
String constants:
Name:

Telephone No:

Postcode:

iii.

Floating Point Constants


A floating point constant is a decimal number that contains the
decimal point (.) or the exponent ( e or E ) or both. Here are some examples
of floating point constants.
5.0
0.005
2000.0
987.123
5e-3
0.01e-2
0.2345E8
1.23E4
4.3 Declaring Variables
All variables in a program must be declared prior to their use. The declaration takes
the form
Type variable_list;
Data types

variable identifier

Examples of variable declarations.


Int x, y, z;
Short small_number;
Long big_number;
Unsigned positive_number;
Char ch;
Float amount, rate;

download@
http://modul2poli.blogspot.com

E3062/4/8
Data Types, Operator And Expression

Variables may be initialized by assigning constants to them either at the time of their
declaration or at a later time.
Example of variable initialization and declaration
int m, n=10;
float rate, total = 0.0;
char response= n;
char color{6}=green;

download@
http://modul2poli.blogspot.com

E3062/4/9
Data Types, Operator And Expression

Activity 4A

TEST YOUR UNDERSTANDING BEFORE YOU CONTINUE WITH THE


NEXT INPUT!

4.1

4.2

State 4 main data types and C++ keyword ?


a. Data types__________________
b. Data types__________________
c. Data types__________________
d. Data types__________________

Keywords___________
Keywords___________
Keywords___________
Keywords___________

Write an expression to declare constant and variable?


a. constant :________________________
b. variable: ________________________

download@
http://modul2poli.blogspot.com

E3062/4/10
Data Types, Operator And Expression

Feedback To Activity 4A

4.1.
a. Data types: integer
b. Data types : character
c. Data types : double
d. Data types : floating point

Keywords :
Keywords:
Keywords :
Keywords ;

4.2.
a.
b.

constant : const Int hourly_rate


variable: Int a, b, c

download@
http://modul2poli.blogspot.com

int
char
double
float

E3062/4/11
Data Types, Operator And Expression

INPUT 4

4.4 The Operators


C++ is very rich in built-in operators. Operators trigger some computations when
applied to operands in an expression. There are several general classes of operators.
But for now, we will present just the arithmetic, relational, logical and assignment
operators.
4.4.1

Arithmetic Operators

There are seven arithmetic operators in C++ as shown in Table 4.3


Table 4.3
Operator
+
*
/
%
++

Action
Subtraction
Addition
Multiplication
division
Modulus division
Decrement
increment

download@
http://modul2poli.blogspot.com

E3062/4/12
Data Types, Operator And Expression

Examples of operation involving integer variables. With a=7 and b=2, the
expression on the values on the right.
Table 4.4
Expression
ab
a+b
a*b
a/b
a%b
a-a--

Value
5
9
14
3
1
6
3

Note: You can assign a positive or negative number to a variable by


using a unary +
or - . Example:
a = -20
b = +20

// assigns a a negative 20
// assigns b a positive 20 ( + sign normally not
needed)

Unary operators operate on single value. Thus the size of operator is a unary
operator. So are the decrement and increment operator.
4.4.2 Relational Operators
There are six relational operators and three logical operators in C++ are
shown in Table 4.5 and Table 4.6

download@
http://modul2poli.blogspot.com

E3062/4/13
Data Types, Operator And Expression

Table 4.5
Operator
<
<=
>
>=
==
!=

Meaning
Less than
Less than or equal
Greater than
Greater than or equal
Equal
Not equal

The result of evaluation of a relational operation is either


true(represented by 1) or false (represented by 0). For example, if a = 7 and b
= 5, then a < b yields 0 and a != b yields 1.
4.4.3

Logical Operators

There are three logical operators in C++ are shown in Table 4.6
Table 4.6
Operator
&&
||
!

Meaning
AND
OR
NOT

The result of the logical operations on a and b are summarized as Table 4.7:
Table 4.7
a

0
0
1
1

0
1
0
1

a||b
either a or b
must be true
0
1
1
1

a&&b
Both a and b
Must be true
0
0
0
1

download@
http://modul2poli.blogspot.com

!a
Produces the
opposite relation
1
1
0
0

E3062/4/14
Data Types, Operator And Expression

*Hierarchy of Operators
The hierarchy of operator precedence form highest to lowest is summarized
below:
Table 4.8
Operator Category
Unary
Arithmetic multiply, devide, remainder
Arithmetic add and subtract
Relational operators
Equality operators
Logical AND
Logical OR

Operator
- -- ++
+ / %
+ < <= > >=
== !=
&&
||

4.5 The Expression


Expression in C++ are formed by properly combining operators, variables and
constants. We have already seen some examples of simple arithmetic and logical
expression. As algebra, C++ expression can be complex. Parentheses can be used to
force the order of evaluation. An expression may also contain spaces for readability.
Examples of expressions.
Gross_pay deductions
(basic_pay + hours * rate) (socso + premium + loan)
(b * b 4 * a * c) > 0
(gender = = m) && (age > 20)
(gender = = m || gender = = f ) && age >= 21

download@
http://modul2poli.blogspot.com

E3062/4/15
Data Types, Operator And Expression

Activity 4B

TEST YOUR UNDERSTANDING BEFORE YOU CONTINUE WITH THE


NEXT UNITS!

4.3

Classify the operators given below:


- , +, &&, ++ , <= , ! , * , !=, % , = =

4.4

Write an expression to mention the arithmetic relational and logical


operators?

download@
http://modul2poli.blogspot.com

E3062/4/16
Data Types, Operator And Expression

Feedback To Activity 4B

4.3.
a. arithmetic operators : - , + , ++ , *
b. logical operators
: && , !
c. Relational operators : <= , != , = =

4.4.
( a + b * 2 ) (x + y + z) arithmetic
(sex = = m || sex = = f ) && age >= 21

download@
http://modul2poli.blogspot.com

E3062/4/17
Data Types, Operator And Expression

KEY FACTS
1. To construct a C++ program, we have to look at basic elements of data types,
identifiers and constant and variable declaration.
2. The arithmetic, relational and logical operators is to trigger some computations
when applied to operands in an expression .

download@
http://modul2poli.blogspot.com

E3062/4/18
Data Types, Operator And Expression

SELF-ASSESSMENT

You are approaching success. Try all the questions in this self-assessment section
and check your answers with those given in the Feedback on Self-Assessment 14
given on the next page. If you face any problems, discuss it with your lecturer.
Good luck.
Question 4-1
Write a statement (or comment) for the sentence below;
a. State the program to determine three integer number.
b. Declare the variables x , y, z and hasil as integers type.
c. Show the message where the user can input the three integers.
d. Read three integers value from keyboard and save every value into
variables x , y and z.
e. Calculate the multiplication integer that store in variable x,y ,z and
variable hasil
f. Print Hasil darab ialah followed by variable hasil.

Question 4-2
Using the statement that you write in statement for question no.1, write the complete
program to calculate and printed multiplication of the three integers.

download@
http://modul2poli.blogspot.com

E3062/4/19
Data Types, Operator And Expression

Feedback To Self-Assessment

Have you tried the questions????? If YES, check your answers now.
Question 4-1
a. // Program to determine three integer multiplication
or
/* Program to determine three integers multiplication*/
b. int x, y, z, hasil;
c. cout << Enter three integers number:;
d. cin >> x >> y >> z;
or
cin >> x;
cin >> y;
cin >> z;
e. hasil = x * y * z;
f. cout << Multipication is : << hasil;
Question 4-2
/* Program to determine three integer multiplication*/
# include <iostream.h>
int x, y, z, hasil;
void main( )
CONGRATULATIONS
{
!!!!..May success be
cout << Enter 3 integer number:;
with you always.
cin >> x >> y >> z;
hasil = x * y * z;
cout << Multipication is : << hasil;
}

download@
http://modul2poli.blogspot.com

E3062/5/1
Logical Structure Types And Basic Instruction

UNIT 5
Logical Structures And Basic Instructions

OBJECTIVES

General Objective

: To Understand the logical structure types and basic instruction


refers to the order of execution of instructions in program.

Specific Objectives : At the end of the unit you will be able to :

describe the sequence structure


describe the selection structure
describe the Repetition structure
execute instructions sequentially or line by line
explain the program control structures
write the simple program using program control structure

download@
http://modul2poli.blogspot.com

E3062/5/2
Logical Structure Types And Basic Instruction

INPUT

5.0

Introduction To Logical Structure

Logical structure or program control structures refer to the order of execution of


instructions in a program. So far, in all our examples, the instructions were executed
sequentially one by one, from the top downwards. However, most real life problems
require some kind of decision making, which involves comparing values, and based
on the comparison, to take a certain course of action. Hence, C++ provides structure
that will allow the non-sequential execution of program instructions. This means that
an instruction or a whole block of instructions can be executed, repeated or skipped.

5.1

Logical Structures And Basic Instructions

C++ has a set of rich and powerful control structures (statements) that makes it a
popular language. Control structure generally fall into four categories but in this unit
we have to know only three of them, which are:
i.

sequence structure

ii.

selection structure

iii.

repetition or iteration structure

download@
http://modul2poli.blogspot.com

E3062/5/3
Logical Structure Types And Basic Instruction

5.1.1

Sequence structure

The sequence control structure is the simplest of all the structures. The
program instructions are executed one by one, starting from the first
instruction and ending in the last instruction as in the program segment.
Example :
x = 5
y = 10
Total = x * y
cout<< \n << Total = <<Total<< \n;

(S1)
(S2)
(S3)
(S4)

Entry

Exit
S1

S2

S3

S4

Figure 5.1 : The sequence structure


(Ref. C++ Through Examples-PSellapan)

5.1.2

Selection Structure

The selection structure allows to be executed non-sequentially. It allows the


comparison of two expressions, and based on the comparison, to select a
certain course of action. In C++ , there are three types of selection
statements. They are:
a. if statement
b. if-else statement
c. Switch statement.
a.

if Statement

The basic form of the if statement is:


If (expression) statement

download@
http://modul2poli.blogspot.com

E3062/5/4
Logical Structure Types And Basic Instruction

In this form, the expression is first evaluated. If the expression


evaluates to non-zero (meaning TRUE), the statement is executed; if
it evaluates to zero (meaning FALSE), the statement following the if
statement is executed. Again, it has one entry point and one exit point.

x >10

No

Yes
Print x

Figure 5.2 : If - Statement


(Ref. C++ Through Examples-PSellapan)

Example 5.1:
If ( gred == A )
cout<< \n PASS ;
Example 5.2:
#include<iostream.h>
main()
{
int iVar1;
int iVar2;
iVar1 =20;
iVar2 =10;
if (iVar1 > iVar2)
cout << iVar1 << is greater than <<iVar2;
}

download@
http://modul2poli.blogspot.com

E3062/5/5
Logical Structure Types And Basic Instruction

The if statement checks to see if iVar1 is greater than iVar2. If iVar


is greater than iVar2 (which is true in this case), then the instruction is
executed and the output below is achieved.
20 is greater then 5

b. if else statement
The basic form of the if-else statement is :
if (expression) statement_1, else statement_2

In this form, the expression is first evaluated. If it evaluates to nonzero, statement_1 is executed, otherwise (i.e, if it evaluates to zero)
statement_2 is executed. The execution of the statements are mutually
exclusive, meaning, either statement_1 is executed or statement_2,
but not both. The statement can, of course, take the form of blocks.

x >10?

Yes

No

Increment
x by 1

Print x

Figure 5.3 : If else Statement


(Ref. C++ Through Examples-PSellapan)

download@
http://modul2poli.blogspot.com

E3062/5/6
Logical Structure Types And Basic Instruction

Example 5.3:
if ( gred == E )
cout<< \n FAIL ;
else
cout<< \n PASS ;

Example 5.4:

#include<iostream.h>
main()
{
int iNum;
cout << Enter a Number ;
cin >> iNum;
if (iNum !=0) && (iNum%2) == 0)
{
cout << Even Number;
}
else
{
cout << Odd Number or Number is 0 ;
}
}

The if else statement in the Example5.4 is to checks the value of


iNum to be not equals to zero and also that the modulus value of the variable
iNum is equal to zero. If condition is true, then the message Even Number
is printed on the screen. If condition is not true, then the message Odd
Number or Number is 0 is printed on screen.

download@
http://modul2poli.blogspot.com

E3062/5/7
Logical Structure Types And Basic Instruction

i.

nested if else statement

The basic form of the if-else statement is :


if (expression_1)
if (expression_2)
if (expression_3)
statement_1;
else
statement_2;
else
statement_3;
else
statement_4;
In this nested form, expression_1 is evaluated. If it is zero,
statement_4 is executed and the entire nested if statement is terminated; if
not, control goes to the second if and expression_2 is evaluated. If it is zero,
statement_3 is executed; if not, control goes to the third if and expression_3
is evaluated. If it is zero, statement_2 is executed; if not, statement_1 is
executed.
Example 5.5
If (sex = M
{
if (age <=12)
{
cout << Good Day Master;
}
else
cout << Good Day Mister;
}
else if (sex = F)
{
if (age <= 12)
{
cout << Good Day Miss;
}
else
cout << Good Day Madam;
}

download@
http://modul2poli.blogspot.com

E3062/5/8
Logical Structure Types And Basic Instruction

In the program, Example 5.5 there are multiplies if statements


used to evaluate the sex of a person whether the person is a male or
female. Then, it is further tested on the age of the person to decide on
the title used to address the person.
c.

Switch statement

The switch statement is the multiple branch decision statement


is sometimes called the multiple-choice statement. The general form
of the switch statement is :
Switch (expression)
{
Case constant_1;
Statement sequence;
break;
case constant_2;
statement sequence;
break;
.
.
default :
statement sequence;
}

The expression evaluates to an integer or character constants


and statement sequence is a block of statements.

Expression
x=?

x=1
y=x+1

x=2
y=x+2

default
y=x

Figure 5.4 : Switch Statement(Ref. C++ Through Examples-PSellapan)

download@
http://modul2poli.blogspot.com

E3062/5/9
Logical Structure Types And Basic Instruction

Example 5.6
#include<iostream.h>
main()
{
char cGrade;
cout << Please key in grade (A-F) : ;
cin >> cGrade;
switch (cGrade)
{
case A
cout << Minimun marks is 80 <<endl;
break;
case B:
cout << Minimun marks is 60 <<endl;
break;
case C
cout << Minimun marks is 40 << endl;
break;
case D:
cout << Minimun marks is 25 << endl;
break;
default :
cout<< Marks between 0-24 <<endl;
}

The sample output of the program:

Please key in grade (A-F) : C


Minimun marks is 40

In the example above, A,B,C and D are the possible values that can be
assigned to the variable cGrade.
In each case of the constants, A to D, a statement or sequence of statements
would be executed.

download@
http://modul2poli.blogspot.com

E3062/5/10
Logical Structure Types And Basic Instruction

You would have noticed that every line has statement under it called break.
The break is the only thing that stops a case statement from continuing all the
way down through each case label under it. In fact, if you do not put break in,
the program will keep going down in the case statements, into other case
labels, until it reaches the end of a break.
However, the default part is the codes that would be executed if there were
no matching case of constants values.

download@
http://modul2poli.blogspot.com

E3062/5/11
Logical Structure Types And Basic Instruction

Activity 5A

TEST YOUR UNDERSTANDING BEFORE YOU CONTINUE WITH THE


NEXT INPUT!

5.1

List 3 types of solution statement?


i._________________________
ii._________________________
iii._________________________

5.2

Define the basic form of the if statement and if-else statement?

5.3

What are the break and default statement are needed in the switch
statement ?

download@
http://modul2poli.blogspot.com

E3062/5/12
Logical Structure Types And Basic Instruction

Feedback To Activity 5A

5.1
i.
ii.
iii

if statement
if else statement
switch statement

i.

if (expression) statement;

ii

if else (expression) statement_1, else statement_2;

5.2

5.3

The break statement is the only thing that stops a case statement
from continuing.
The default statement is the part of the codes that would be
executed if there were no matching case of constants values.

download@
http://modul2poli.blogspot.com

E3062/5/13
Logical Structure Types And Basic Instruction

INPUT

5.1.3

Repetition (or Iteration) structure

The repetition (or iteration) structure permits a sequence of the instructions to


be executed repeatedly until certain condition is reached. The repetition
structure or loop in C++ comes in three forms while, do-while and for .

a) The while loop


The while loop repeats the body of the loop as long as the loop condition
holds. The basic form of the while statement is as below:
while (expression) statement;

In this loop, the expression is first evaluated. If it is true (not zero), the
statement (which can be a block is executed; if it is (zero), the statement is
bypassed

download@
http://modul2poli.blogspot.com

E3062/5/14
Logical Structure Types And Basic Instruction

is
x >10?

Yes

No
Print x

x=x+1

Figure 5.5 : while loop


(Ref. C++ Through Examples-PSellapan)

Example 5.7
While ((cin>>amount) &&(amount > 0) && (amount<=balance))
{
balance = balance amount;
cout<<\n Please take your cash<<amount;
}

b) The do-while loop


The do-while loop executes a statement as long as the loop condition
holds. The basic form of the do-while statement as below:

Do
while

statement
(expression) ;

download@
http://modul2poli.blogspot.com

E3062/5/15
Logical Structure Types And Basic Instruction

This do-while loop is quite similar to the while loop except that the
expression is evaluated after the statement is executed. This means the
statement in the do-while will be executed at least once. In the while
statement, the statement will not be executed if the expression is false.

x=x+1

Print x

No

is
x >10?
Yes

Figure 5.6 : do-while loop


(Ref. C++ Through Examples-PSellapan)

Example 5.8
//Program to illustrate a do-while loop
#include<iostream.h>
main()
{
int selection;
do
{
cout << \n Menu << \n ;
cout << \n 0. Exit ;
cout << \n 1. Append ;
cout << \n 2. Delete ;
cout << \n 3. Modify ;
cout << \n\n Enter selection : ;
cin >> selection;
}
while (selection > 0 && selection < 4 );
return 0;
}

download@
http://modul2poli.blogspot.com

E3062/5/16
Logical Structure Types And Basic Instruction

In the example 5.8, the program displays the menu and then requests
a selection. If the selection is 1, 2, or 3, the menu is displayed again;
otherwise, the loop is terminated. Note that the loop is repeatedly executed so
long as the selection is 1,2 or 3.
c) The for Loop
The for loop repeats the body of the loop as long as the loop condition holds.
The basic form of the for loop as below:

for (initialization; condition test; incrementation)


{
statements;
}

The initialization part typically refers to the initial value (if any) given
to a loop variable or counter. But it can also include the initialization
of any other variable. This initialization part is carried out just once at
the beginning of the loop.

The expression part determines whether the loop execution should be


continued. If the expression is zero (false), the for loop is terminated,
if it is not zero (true), the for statement is executed.

The incrementation part typically increments (or decrements) the loop


counter variable. This is done after the for statement is executed. This
part, like the initialization part, can also include the incrementation of
other variables.

download@
http://modul2poli.blogspot.com

E3062/5/17
Logical Structure Types And Basic Instruction

Example 5.9
#include<iostream.h>
main()
{
int iNum;
for ( iNum =1; iNum<=10 ; iNum++ )
{
cout << iNum*iNum << ;
}
}

The example 5.9, given is a very short program and it is easy for us to
understand the for loop.
First, an integer variable is declared. Then, in the initialization part, the
variable, iNum is set to 1. For the condition checking, iNum is checked to see
whether it is equal to or less than 10. In each cycle of the loop, iNum is
incremented by 1. Once iNum reaches 10, the loop exits. We can see that the
program calculates the square of the first ten natural numbers.
Program output:
1 4 9 16 25 36 49 64 81 100

5.2

Compiles And Run Program

To run a C++ program, we must first create it, then compile it, then link it with other
modules ( or other compiled programs), and finally run it. You can create a C++
program using the C++ editor. The editor is like a word processor that allows you to
type, edit and save your program. The program you create is called the source
module.

download@
http://modul2poli.blogspot.com

E3062/5/18
Logical Structure Types And Basic Instruction

After you have created the source program, you compiled it using the C++ compiler.
The compiler translates your C++ instructions into a machine-readable form. The
compiled program is called the object module.
Besides compiling the source module into an object module, the compiler also
generates information necessary for linker. The linker links the object module
generated by the compiler and any other object modules, your program may request
into a final executable module.

Tool

Step

Editor

Edit

Product

Source module
Compiler

Compile
Object module

Linker

Library

Link
Executable module
Run
Result/Output
Figure 5.7 : Steps in running a program
(Ref. C++ Through Examples-PSellapan)

download@
http://modul2poli.blogspot.com

E3062/5/19
Logical Structure Types And Basic Instruction

Feedback To Activity 5B

TEST YOUR UNDERSTANDING BEFORE YOU CONTINUE WITH THE


NEXT INPUT!
5.1

What are three loops of iteration statements?


i._________________________
ii._________________________
iii._________________________

5.2

State the basic form of the for loop and write the part of program that uses a
for statement?

5.3

What is the compiler ?

5.4

What is the linker?

download@
http://modul2poli.blogspot.com

E3062/5/20
Logical Structure Types And Basic Instruction

Feedback To Activity 5B

5.1
i.
ii.
iii

while loop
do-while loop
for loop

5.2
for loop form
for (initialization; expression; incrementation)
statement

Program that uses a for statement:


for (i=1; i<=20; i++)
Cout<< \n Increment the first 20 numbers=;

5.3

The compiler translates your C++ instructions into a machinereadable form.

The linker links the object module generated by the compiler and
any other object modules.

5.4

download@
http://modul2poli.blogspot.com

E3062/5/21
Logical Structure Types And Basic Instruction

KEY FACTS
1. Logical structure or program control structures refer to the order of
execution of instructions in a program.
2. The three control structure generally we have to know are: sequence
structure , selection structure, repetition or iteration structure.
3. To run a C++ program, we must first create it, then compile it, then link it
with other modules and finally run it.

download@
http://modul2poli.blogspot.com

E3062/5/22
Logical Structure Types And Basic Instruction

4.

SELF-ASSESSMENT

You are approaching success. Try all the questions in this self-assessment section
and check your answers with those given in the Feedback on Self-Assessment 2
given on the next page. If you face any problems, discuss it with your lecturer.
Good luck.

Question 5-1
Write the program using selection and repetition structure (if, if else and for) to solve
following problem.
Enter 30 integer values in [1,200]. Find how many of these values fall in the range
1-50, 51-100, 101-150 and 151-200 ?

Question 5-2
Write the program using switch loop to solve following problem.
Given integer variables x ,y and a character variable ch. Input values for x,y and ch 9
the value for ch must be a, m, s, d or r.
Compute and output
x + y if ch = a
x *y if ch = m
x - y if ch = s
x / y if ch = d
x % y if ch = r

download@
http://modul2poli.blogspot.com

E3062/5/23
Logical Structure Types And Basic Instruction

Feedback To Self-Assessment

** Please refer to your lecturer for checking purpose


** The feedback for this Self-assessment test is based on the students creativity as
long as the output meets the criteria required by the question.
The lecturer have to prepare a scheme or checklist as a guideline to check
students response.

Try Your Best!!!

download@
http://modul2poli.blogspot.com

E3062/6/1
Preprocessor and Header Files

UNIT 6
Preprocessor and Header Files

OBJECTIVES

General Objective

: To Understand the function of preprocessor directive and header file.

Specific Objectives : At the end of the unit you will be able to :

define the preprocessor and header file.

explain the function of preprocessor and header file.

write the preprocessor statements using #include and #define.

define and use header file stdio.h, ctype.h, math.h, conio.h and
iostream.h in C++ program.

download@
http://modul2poli.blogspot.com

E3062/6/2
Preprocessor and Header Files

INPUT

6.0

Introduction To Preprocessor and Header Files

Preprocessor directive and header file were


talked about right from the beginning unit of
this module. However, it is necessary to
cover in more details as to see the various
header file available for C++

Preprocessor directive are orders that we include within the code of our programs that
are not instructions for the program itself but for the preprocessor. The preprocessor is
executed automatically by the compiler when we compile a program in C++ and is the one in
charge to make first verification and digestions of the program code.

Header files are basically pre-written function that help programmer to write new
code faster. Since header files are all tested and free from bugs, hence the new programs
written can also be said as less error prone programs.

download@
http://modul2poli.blogspot.com

E3062/6/3
Preprocessor and Header Files

Definition:
a. Preprocessor
Preprocessor is the directive to enables the program to use certain function
contained in the external file such as iostream.h.
b. File Header
Header files contain specific functions that we can use to accomplish the
programming tasks. Example of header files are ctype.h and math.h.

6.1

Preprocessor Statement

Before we can use any of the functions contained in a header file, we must include the
header file in the program. We can do this by using the #include and # define preprocessor
directive placed before the function main ( ).

6.1.1 #include
When preprocessor find an #include directive it replaces it by the whole
content of specified file. There are two ways to specify a file to be included as in
example below:
# include file.h
or
# include <file.h>

The difference between both expressions in the example above, is in the directories in
which the compiler is going to look for the file. In the first case in that the file is
specified between quotes the file is looked for from the same directory in which the
file that includes the directive is, and only in case that is not there the compiler

download@
http://modul2poli.blogspot.com

E3062/6/4
Preprocessor and Header Files

looks for in the default directories where it is configured to look for the standard
header files.

In case that the file name is included enclosed between < > the file is directly
looked for in the default directories where the compiler is configured to look for
standard header files.

6.1.2 # define

The processor directive, #define, serves to generate what we call defined


constants or macros and whose form is the following example below.

#define name value

Its function is to define a macro called name that whatever it is found in some
point of the code is replaced by value . For example:

#define MAX_ WIDTH 100


Char str1[ MAX_WIDTH ] ;
Char str2 [ MAX_WIDTH ] ;

download@
http://modul2poli.blogspot.com

E3062/6/5
Preprocessor and Header Files

It defines two strings to score up to 100 characters. An example of macro


function using #define is shown in program below

1:

#include <iostream>

2:

using namespace std;

3.

#define getmax(a,b) (a>b ? a : b)

5:
6:

void main ( )

7:

8:

int x=5, y:

9:

y = getmax (x,8);

10:

cout<<y;

11:

On line no. 7, after substitution , it will look like this:

Y= getmax (x>8 ? x:8);

And the output of program will be the bigger value, in this case:
8

download@
http://modul2poli.blogspot.com

E3062/6/6
Preprocessor and Header Files

Activity 6A

TEST YOUR UNDERSTANDING BEFORE YOU CONTINUE WITH THE


NEXT INPUT!

6.1

Choose the most accurate statement regarding #define


A. It is a preprocessor directive.
B. Serves to generate defined constants or macros
C. It defines two strings to store up to 100 characters.
D. All the above

6.2

Which directive creates macros and symbolic constants?


A. #undef
B. #ifdef
C. #define
D. #include

6.3

The #define functions to define a macro called name where at some point of
the code is replaced by___________________
a.

address

b. Value
c. String
d. Type

6.4

There are two ways to specify a file to be included, which are


___________ or ________________.

download@
http://modul2poli.blogspot.com

E3062/6/7
Preprocessor and Header Files

Feedback To Activity 6A

6.1

D.

All the above

6.2

C. #define

6.3

B. Value

6.4.

#include file , #include <file>.

download@
http://modul2poli.blogspot.com

E3062/6/8
Preprocessor and Header Files

INPUT

6.2

Header files .h

Header files contain numerous frequently-used functions that programmers can use
without having to write codes for them. In addition, programmers can also write their own
declarations and functions and store them in header files which they can include in any C++
program. We will discuss the functions contained in a standard header files.

6.2.1

stdio.h
This header file is used for declaring standard I/O streams. Here are some

functions from this header file.


The function printf ( ) sends formatted output to the screen. It has the form

int printf(const char *format[ ,argument,.])

For example, to display the phrase Learning C++ is Fun to the screen, just type

Printf(Learning C++ is Fun)

The function scanf() reads formatted input from the keyboard. It has the form
int scanf(const char *format[ , ..])

download@
http://modul2poli.blogspot.com

E3062/6/9
Preprocessor and Header Files

Special conversion characters can be used to describe the data you want to print in
printf function or input in scanf function as shown in table 6.1.
For printf the statement
printf(I am %d years old and I make $%f a month, 18, 2200.50);

will produce the following output on the screen:

I am 18 years old and I make 2200.50 a month.

For scanf the statement, to read a persons name,


Scanf(%s, name);

Table 6.1: printf() and scanf() conversion character


.Conversion character

Output

%s

String of character

%s

Character

%s

Decimal integer

%s

Floating-point number

%s

Unsigned integer

%s

Hexadecimal integer

%s

Percent sign (%)

(Ref. C++ Through Examples-PSellapan)

6.2.2

ctype.h
Table 6.2 gives a partial list of function contained in the character type
header file. These functions come in handy when you want to
determine whether a character data is alphanumeric, alphabetic, digital,
uppercase, lowercase and so on. They are often used inside an if or
while statement.

download@
http://modul2poli.blogspot.com

E3062/6/10
Preprocessor and Header Files

Table 6.2: List of functions in ctype.h


Function

Return value

salnum (c)

Non- zero if ( c ) is alphanumeric; 0 otherwise

isalpha (c)

Non- zero if ( c ) is alphabetic; 0 otherwise

isascii (c)

Non- zero if ( c ) is ASCII character; 0 otherwise

iscntrl (c)

Non- zero if ( c ) is control character ; 0 otherwise

isdigit (c)

Non- zero if ( c ) is a digit; 0 otherwise

isgraph(c)

Non- zero if ( c ) is a graphic character(including space); 0


otherwise

islower (c)

Non- zero if ( c ) is lowercase letter ; 0 otherwise

isprint (c)

Non- zero if ( c ) is printable character ( including space ) ; 0


otherwise

ispunct(c)

Non- zero if ( c ) is punctuation character ; 0 otherwise

isspace (c)

Non- zero if ( c ) is a space, tab, formfeed or new line


character; 0 otherwise

isupper (c)

Non- zero if ( c ) is uppercase letter; 0 otherwise

isxdigit (c)

Non- zero if ( c ) is hexadecimal digit ; 0 otherwise

toascii(c)

ASCII equavalent

tolower (c)

Lowercase equivalent of c if it is latter; unchanged otherwise

toupper (c)

Uppercase equivalent of c if it is latter; unchanged otherwise

(Ref. C++ Through Examples-PSellapan)

download@
http://modul2poli.blogspot.com

E3062/6/11
Preprocessor and Header Files

6.2.3

math.h
This header file contains several mathematical functions. Table 6.3 shows
functions contained in this file. The argument (d) for each of these functions is
of type double.

Table 6.3: List of functions in math.h


Function

Return value

acos(d)

Arc cosine of d

asin(d)

Arc sine d

atan(d)

Arc sine d

atan2(d1,d2)

Arc tangent of d1/d2

ceil(d)

Smallest integer greater than d

cos(d)

Cosine of d

exp(d)

e(i.e.,2.718) raised to the power d

fabs(d)

Absolute value of d

floor(d)

Largest integer smaller than d

fmod(d1,d2)

Remainder of d1/d2

log(d)

Natural logarithm of (d>0)

log10(d)

Base logarithm of d (d>0)

pow(d1,d2)

D1 raised to the power of d2

sin(d)

Sine of d

sinh(d)

Hyperbolic sine of d

sqrt(d)

Square root of d

tan(d)

Tangent of d

tanh(d)

Hyperbolic tangent of d

(Ref. C++ Through Examples-PSellapan)

download@
http://modul2poli.blogspot.com

E3062/6/12
Preprocessor and Header Files

To illustrate the use of some of the functions, consider program 6.2.3

Program 6.2.3
//program that uses mathematical functions
#include <math.h>
#include <iostream.h>
main( )
{
double d,d1,d2;
d=100.0; d1=100.5; d2=2.0;
cout<<\nSquare root of <<d<< = <<sqrt(d);
cout<<\nlog (to base 10 of <<d<< = <<log10(d);
cout<<\n <<d<< raised to the power of <<d2;
cout<< = <<pow(d,d2);
cout<<\nThe ceiling value of <<d1<< = <<ceil(d1);
return 0;
}

The program outputs the following:

Square root of 100 = 10


Log (to base 10) of 100 = 2
100 raised to the power of 2 = 10000
The ceiling value of 100.5 = 101

download@
http://modul2poli.blogspot.com

E3062/6/13
Preprocessor and Header Files

6.2.4

conio.h
This header file has several screen handling functions suchas the function
gotoxy( ) which position the cursor in the text window. It has the form

void gotoxy ( int x, int y )


An example of this function is given in program 6.2.4

Program 6.2.4

// Program that uses gotoxy ( ) function


#include < conio.h >
#include < stdio.h > //Header file containing function getch( )
main( )
{
clrscr ( );

// Clears the screen

gotoxy(35,12) // Place cursor at column 35 , row 12


printf ( Hello world );
return o;
}

The program will display Hello world at column 35, row 12

6.2.5

iostream.h
The name iostream.h stand for input / output stream header . The basic input /
output ( I / O ) function contained in this header file are cin for console input
( keyboard) and Cout for console output ( the screen). The function cin is used
with redirection operator >> while the function cout is used with redirection
operator <<.

download@
http://modul2poli.blogspot.com

E3062/6/14
Preprocessor and Header Files

Activity 6B

TEST YOUR UNDERSTANDING BEFORE YOU CONTINUE WITH THE


NEXT INPUT!

1. Which header file is required for the following functions:


a. sqrt( )
b. sin( )
c. ceil( )
d. isgraph( )
e. gets( )
f. scanf( )
g. islower( )
h. log10( )
i. atof( )
j. isspace( )

download@
http://modul2poli.blogspot.com

E3062/6/15
Preprocessor and Header Files

Feedback To Activity 6B

a. sqrt( ) math.h
b. sin( ) - math.h
c. ceil( ) - math.h
d. isgraph( ) ctype.h
e. gets( ) stdio.h
f. scanf( ) stdio.h
g. islower( ) ctype.h
h. log10( ) math.h
i. atof( ) - math.h
j. isspace( ) ctype.h

download@
http://modul2poli.blogspot.com

E3062/6/16
Preprocessor and Header Files

KEY FACTS
1. Preprocessor is the directive to enables the program to use certain function contained
in the external file that we include within the code of our programs that are not
instructions for the program but for the preprocessor

2. Header files contain specific functions that we can use to accomplish the
programming tasks which are basically pre-written function that help programmer to
write new code faster.

download@
http://modul2poli.blogspot.com

E3062/6/17
Preprocessor and Header Files

SELF-ASSESSMENT

You are approaching success. Try all the questions in this self-assessment section
and check your answers with those given in the Feedback on Self-Assessment 2 given
on the next page. If you face any problems, discuss it with your lecturer. Good luck.

Question 6-1
Write the outputs for the following for the following functions
#include <math.h>
#include <iostream.h>
main ()
{
double d,d1,d2;
d=100.0; d1=100.5; d2=2.0;
cout<<\nSquare root of <<d<< = <<sqrt(d);
cout<<\nLog (to base 10) <<d<< = <<log10(d);
cout<<\n<<d<< raised to the power of <<d2;
cout<< = <<pow(d,d2);
return 0;
}

Question 6-2
Write program segments to output the following:
a. The square, square root, natural logarithm of the number 20.
b. The remainder of 11 divided by 6

download@
http://modul2poli.blogspot.com

E3062/6/18
Preprocessor and Header Files

Feedback To Self-Assessment

Have you tried the question????? If YES, check your answer now:

Question 6.1

Square root of 100 = 10


Log (to base 10) of 100 = 2
100 raised to the power of 2 = 10000

Question 6.2

#include <math.h>
#include <iostream.h>
main ()
{
cout<<\nThe square of 20 is <<pow(20,2);
cout<<\nThe square root of 20 is <<sqrt(20,0);
cout<<\nThe natural logarithm of 20 is <<log(20,0);
return 0;
}

download@
http://modul2poli.blogspot.com

CONGRATULATIONS!!!
!..May success be with
you always.

Writing C++ Program

UNIT 7
Writing C++ Program

OBJECTIVES

General Objective

: To write C ++ program

Specific Objectives : At the end of the unit you will be able to :

design and write a C++ program

use C++ program on various applications

download@
http://modul2poli.blogspot.com

E3062/7/1

Writing C++ Program

E3062/7/2

INPUT

7.0 Introduction

In this unit , we will analyze some set of


sample programs to demonstrate C++
versatility and power in various kind of
applications. This will show the diversity of
C++ program in the development of software
applications.

7.1

Simple programming

7.1.1

Even odd
/* This program evaluates the number input is an even or odd number */
#include <iostream.h>
void main ( )
{
int n;
cout<< Enter a number;
cin>>n;
if (( n %2==0) && ( n!=0))

download@
http://modul2poli.blogspot.com

Writing C++ Program

E3062/7/3

cout<<it is an even number;


else
cout<<it is an odd number;
}
The output would be:
Sample 1:
Enter a number : 12
It is an even number
Sample 2:
Enter a number : 5
It is an odd number

7.1.2

Grade

/* This program accepts the mark of 5 subjects, calculates and outputs the
average and its appropriate grade */
#include<iostream.h>
void main( )
{
float a,b,c,d,e,f ;

cout<< Enter 5 mark values: ;


cin>>a>>b>>c>>d>>e;
f=(a+b+c+d+e)/5;

cout<<f<<endl;
if((f>=0) && (f<50))
{
cout<< Grade is F;
}
else if ((f>=50) && (f<62))

download@
http://modul2poli.blogspot.com

Writing C++ Program

{
cout<< Grade is D-;
}
else if ((f>=62) && (f<66))
{
cout<< Grade is D;
}
else if ((f>=66) && (f<69))
{
cout<< Grade is D+;
}
else if ((f>=69) && (f<72))
{

cout<< Grade is C-;


}
else if ((f>=72) && (f<76))
{
cout<< Grade is C;
}
else if ((f>=76) && (f<79))
{
cout<< Grade is C +;
}

else if ((f>=79) && (f<82))


{
cout<< Grade is B-;
}
else if ((f>=82) && (f<86))
{
cout<< Grade is B;

download@
http://modul2poli.blogspot.com

E3062/7/4

Writing C++ Program

}
else if ((f>=86) && (f<89))
{
cout<< Grade is B+;
}
else if ((f>=89) && (f<92))
{

cout<< Grade is A-;


}

else if ((f>=92) && (f<100))


{
cout<< Grade is A;
}
}

The output would be :

Enter 5 mark values: 76 79 87.5 93 99


86.9
Grade is B+

download@
http://modul2poli.blogspot.com

E3062/7/5

Writing C++ Program

E3062/7/6

Activity 7A

TEST YOUR UNDERSTANDING BEFORE YOU CONTINUE WITH THE


NEXT INPUT!
7.1

Find out the output.

Positive Negetive
/* This program evaluates the number keyed in is either a positive or negetive
value */
#include <iostream.h>
void main ( )
{
int n;
cout<< Enter Value:;
cin>>n
if((n>0) && (n!=0))
cout<<n<< n is a positive value;
else
cout<<n<< n is a negetive value;
}

download@
http://modul2poli.blogspot.com

Writing C++ Program

Feedback To Activity 7A

7.1.

The output would be:


Sample 1:
Enter a value: 30
30 is a positive value
Sample 2:
Enter a value : -29
-29 is a negetive value

download@
http://modul2poli.blogspot.com

E3062/7/7

Writing C++ Program

E3062/7/8

INPUT

7.1.3

Student List

/* This program prompt 3 students details and list them accordingly( name,
id, and major) */
#include<iostream.h>
#include<string.h>
int i;
class student
{
private : string name;
int idno;
string major;
public : void insert( )
{
cout<< \nEnter details of student:<<endl;
cin>>name>>idno>>major;
}
void display ( )
{
cout<< \n<<name<<

<<idno<<

}
}

void main ()

download@
http://modul2poli.blogspot.com

<<major<<endl;

Writing C++ Program

{
student s[ 4 ];
for (i=1;i<4;i++)
s[ i ].insert();
cout<< \n\nList of students<<endl;
for( i=1;i<4; i++)
s[ i ] .display();
}

The output would be:

Enter details of student:


Jason
123
Programming
Enter details of student:
Jenny
124
Multimedia
Enter details of student:
Susie
125
Networking

List of students

Jason

123

Programming

Jenny

124

Multimedia

Susie

125

Networking

download@
http://modul2poli.blogspot.com

E3062/7/9

Writing C++ Program

7.1.4

E3062/7/10

Bubble Sort
/* This sample program illustrates how to write a Bubble Sort */
#include<iostream.h>
using namespace std;
/* Set the total number of integers that will sorted. */
#define MAX 25
int main()
{

int a[MAX]; /* Allocate an array to hold MAX integers. */


int I;

/* This will be used an index into the array.*/

int done;

/* This is a flag used to indicate when the array of numbers is


completely sorted and that no other work needs to be done */

/* Initialise the array with random values from 0 to 99 */


for (i=0; i<MAX;i++)
a[ i ]= rand( ) % 100;
/* Display original array.*/
cout<< ORIGINAL ARRAY\n;
for ( i=0; i< MAX ; i++)
cout<<a[ i ] << ;
cout<< \n\n;
do {
/* Start by assuming you are done.*/
done = 1;
/* Now go through the array checking that everything is already sorted.*/
for ( i=0;i<MAX-1; i++) {
/* If there are numbers out of order then swap them and declare the job
of sortingto be not done. */
if( a[ i ] > a[i+1] {
int tmp;

/* To perform the swap you need to have temporary storage


area for of the integers.

download@
http://modul2poli.blogspot.com

Writing C++ Program

E3062/7/11

Look at this section carefully and try to understand


Why you need to have the tmp variable. */
Tmp = a[ i ];
a[ i ] = a[ i+1];
a[i+1] = tmp;
done = 0
}
}
} while ( !done);
/* Display sorted array */
cout<< SORTED ARRAY\N;
for ( i=0;i<MAX; i++)

cout<<a[i] << ;
cout<< \n;
return 0;
}

The output would be:

OROGINAL ARRAY
41 67 34 0 69 24 78 58 62 64 5 45 81 27 61 91 95
42 27 36 91 4 2

53 92

SORTED ARRAY
0 2

24 27 27 34 36 41 42 45 53 58 61 62 64

67 69 78 81 91 91 92 95

download@
http://modul2poli.blogspot.com

Writing C++ Program

E3062/7/12

Activity 7B

TEST YOUR UNDERSTANDING BEFORE YOU CONTINUE WITH THE


NEXT INPUT!

7.2.

Write a program that checks whether the character you type is a vowel or not
with the following output

Sample 1 for non vowel character


Enter a Character: t
It is a non vowel character
Sample 2 for vowel character
Enter a Character: a
It is a vowel character

download@
http://modul2poli.blogspot.com

Writing C++ Program

Feedback To Activity 7B

7.2.
/* This program checks whether the character typed is vowel or not */

#include<iostream.h>
using namespace std;
void main ()
{
char c;
cout<< Enter a character:;
cin>>c;
switch (c)
{
case a:cout<< It is a vowel character;
break;
case e:cout<< It is a vowel character;
break;
case i:cout<< It is a vowel character;
break;
case o:cout<< It is a vowel character;
break;
case u:cout<< It is a vowel character;
break;
default:cout<< It is a non vowel character;
}
}

download@
http://modul2poli.blogspot.com

E3062/7/13

Writing C++ Program

E3062/7/14

1.

SELF-ASSESSMENT

You are approaching success. Try all the questions in this self-assessment section
and check your answers with those given in the Feedback on Self-Assessment 2
given on the next page. If you face any problems, discuss it with your lecturer.
Good luck.

Question 7-1

Write a program that finds the square of the number entered with the following
format output:

Enter a value: number


The square of the number entered is answer

Question 7-2

Write a program that accepts three values and selects the greatest number with the
following format output:

Enter 3 different numbers: 3 different values of numbers


One of the number selected is the greatest

download@
http://modul2poli.blogspot.com

Writing C++ Program

E3062/7/15

Feedback To Self-Assessment

Have you tried the question????? If YES, check your answer now:

Question 7.1
/* This program finds the square of the number entered*/

#include<iostream.h>
using namespace std;
void main( )
{
int a;
cout<< Enter a value:;
cin>>a;
cout<<endl<< The square of <<a<< is<<a*a;
}

Question 7.2
/* This program accepts three values and selects the greatest
number */
#include<iostream.h>
using namespace std;
void main ( )
{
int a,b,c;

download@
http://modul2poli.blogspot.com

Writing C++ Program

cout<< Enter 3 values: ;


cin>>a>>b>>c;
if (( a>b) && ( b>a))
{
cout<<a<< is greatest;
}
else if ((b>c) && (b>a))
{
cout<<b<< is the greatest;
}
else
{
cout<<c<< is the greatest;
}
}
CONGRATULATIONS!!!!..
May success be with you
always.

download@
http://modul2poli.blogspot.com

E3062/7/16

B3062/8/1
Introduction To Visual Basic

UNIT 8
Introduction To Visual Basic

OBJECTIVES

General Objective

: To understand the basic concept of Visual Basic

Specific Objectives : At the end of the unit you will be able to :

explain the programming concept of Visual Basic

discuss the Integrated Development Environment in Visual


Basic

identify the basic structure of project

describe the user interface

download@
http://modul2poli.blogspot.com

B3062/8/2
Introduction To Visual Basic

INPUT

8.0

Introduction to Visual Basic

Visual Basic was originally developed by Prof.


John Kemedy and Thomas Kurtz of Darmouth
College. It was developed by using BASIC
(Beginners All-purpose Symbolic Instruction
Code) language. Visual basic needs Microsoft
Windows environment and translator to run.

To develop program in Visual Basic is quiet easy because the tools in programming
such as editor and translator is integrated in one Visual Basic Program known as
Integrated Development Environment (IDE). Basically Visual Basic is an Object
Oriented Program

download@
http://modul2poli.blogspot.com

B3062/8/3
Introduction To Visual Basic

Figure 8.0 : Starting The Visual Basic

8.1

The Visual Basic Environment

The Visual Basic environment is where you create and plan your interface. This is
where you use the Visual Basic element for program development at design time. This
includes the Menu bar, Toolbar, Toolbox, Form Window, Property Window, Project
Window as shown in Figure 8.0.

download@
http://modul2poli.blogspot.com

B3062/8/4
Introduction To Visual Basic

Title Bar

Tool Bar
Properties
window

Menu Bar

Properties windows
Form
window

Tool box

Figure 8.1 : Visual Basic Enviroment. (Ref. Microsoft Visual Basic 6.0 Program)

a. Title Bar
The Title Bar display the project name (Project1). The default name is
Project1. Subsequent projects are named Projects, Project3, etc.

download@
http://modul2poli.blogspot.com

B3062/8/5
Introduction To Visual Basic

b. Menu Bar
The Menu Bar has the usual menu items such as File, Edit, View, Project,
Run and Tools. You can click on a menu item to view the list of command
available for that menu item.
c. Tool Bar
The Tool Bar contains several group of icons, each of which represents a
command. They denote the most frequently used operation or commands.
They acts as short cuts to the commands. You can also select the from the
menu bar.

Add Form

Add
Standard
EXE
project

Menu
Editor

Save
Project

Open
Project

End
Start (Run)

Break

Properties
Windows

Project
Explorer

Toolbox

Object
Browser

Figure 8.2 : Tool Bar (Ref. Microsoft Visual Basic 6.0 Program)

d. Toolbox Window

The Toolbox consists of a number of controls/objects that you can place on


the form. Some of the common controls/objects are Pointer, Label,
Command Button, Text box, Picture Box, Combo Box, Option Button, and
etc. You can also add additional components by right clicking on the
toolbox and then selecting the required components.

download@
http://modul2poli.blogspot.com

B3062/8/6
Introduction To Visual Basic

Pointer
Label
Frame
Checkbox
Combo box
Horizontal scroll bar
Timer
Folder list box
Shape
Image

Picture box
Text box
Command button
Option button
List box
Vertical scroll bar
Drive list box
Folder list box
Line
Data

OLE

Figure 8.3 :Toolbox Control Object (Ref. Microsoft Visual Basic 6.0 Program)

e. Form Window

The window at the center of the main screen is the Form Window. This is
where you design your applications interface. When you begin a project,
Visual Basic gives you a new form with default name Form1. You can
change it to a more meaningful name when you save the form.

download@
http://modul2poli.blogspot.com

B3062/8/7
Introduction To Visual Basic

Figure 8.4 : Form Window (Ref. Microsoft Visual Basic 6.0 Program)

f. Project windows

The Project Explorer window stores information about the current project.
By default, a project is given the name Project1. You can assign a more
meaningful name when you save the project.
The window also displays the various forms and windows modules (if there
are any) for the current project.

Figure 8.5: Project window (Ref. Microsoft Visual Basic 6.0 Program)

g. Properties Window

The properties window is where you set the properties for the different
window objects in your project. Each object has different set of properties.

download@
http://modul2poli.blogspot.com

B3062/8/8
Introduction To Visual Basic

You can set properties according to your needs. You will see more on
Setting properties.

Figure 8.6 : Properties Window (Ref. Microsoft Visual Basic 6.0 Program)

h. Form Layout

This Form layout window allows you to position the form layaout window.
This determines the position of the desktop when the project begins
execution.

i. Menu Editor

The Menu editor is used to create menus.

download@
http://modul2poli.blogspot.com

B3062/8/9
Introduction To Visual Basic

8.2.

Basics Project Structure.

Projects in Visual Basic are labeled Project1, Project2 and so on. You can however
rename them to more appropriate names. Similarly, the forms in a project are
labeled Form1, Form2, etc. You can also rename them as necessary.
A Visual Basic application takes the form of a project. A project may consist of one
or more forms, each of which may have several controls (command buttons, text
boxes, labels, etc) as shown below.

Project

Form 1

Form 2

Text 1
Text 2
Command 1
Command 2
Lable 1

Text 1
Text 2
Command 1
Picture1
Picture2

...

Figure 8.7 : Basic Project Structure


(Ref.Programming In Visual Basic 6-P. Sellapan)

download@
http://modul2poli.blogspot.com

Form n
Text 1
Command1
Command2
Lable1
Lable2

B3062/8/10
Introduction To Visual Basic

Activity 8A

TEST YOUR UNDERSTANDING BEFORE YOU CONTINUE WITH THE NEXT


INPUT!

8.1

Visual Basic was developed using BASIC language by ________________


and ________________________

8.2

The Visual Basic Environment consists of several elements. List five elements
how to develop the project?

i.______________________

iv.________________________

ii.______________________

v._________________________

iii.______________________

8.3

Name the Toolbox control object below:

i.

___________________________

ii.

___________________________

iii.

__________________________

iv.

___________________________

v.

___________________________

download@
http://modul2poli.blogspot.com

B3062/8/11
Introduction To Visual Basic

Feedback To Activity 8A

8.1

Prof. John Kennedy , Thomas Kurtz

8.2

i. Bar (Title,menu,Toolbar)

ii.Toolbox

iv. properties window

v. Project window

8.3

i. Text box
iii.Vertical scroll bar

iii. Form window

ii. Command button


iv. Data

download@
http://modul2poli.blogspot.com

v. Timer

B3062/8/12
Introduction To Visual Basic

INPUT

8.3

The User interface


The user interface shows the visible parts of a Visual Basic program. You use the
interface to interact with the system such as for entering data, controlling the program
and viewing results.

8.3..1 Toolbox, Project and Properties Window


The Toolbox, located on the left hand side of the main window, contains a set
of icons, each of which represents control object or just control is use to control to
develop Visual Basic application. For example, to write a program, you will use the
command button, and to enter data you will use the textbox. If you not sure of the
purpose of control icon , you can position the mouse pointer on the control and you
will see a ToolTip explaining what it is for.
The Project window appears on the top right hand corner of the main window.
The title bar holds the name of the project (.Vbp) file. The default name is
Project1. It shows all the files in up your current project. The files are arranged in
a tree structure fashion ( similar to windows directory). You can expand or collapse

by clicking on the plus and the minus signs. You can use the Project Window to
activate any of files that you want.
The Properties window is where you set the properties for the objects in your
project. Each object (form, text box, command button, etc) has its own properties.
The property names are shown on the left while the selection are shown on the
right. You use this window to set the objects properties such as its caption,
appearance, and colour. Some of form properties are shown below.

download@
http://modul2poli.blogspot.com

B3062/8/13
Introduction To Visual Basic

8.3.2

Design and Modify The Properties of Toolbox Object

i.

Text Box
The Text box control is only used when the user needs to type in
input. To create a text box, firstly you have to double click on
Text Box control (in the Tool box) and drag the text box to
position and resize it (as shown in Figure 8.8). Some of the text
box properties that are normally changed are Name, Text,
Alignment and Multiline.
Name

- Name used in code to identify the textbox


object.

Text

-Returns or sets the text contained in the control

Alignment

-Returns or sets the alignment(0-left, 1-right,


2-center) of the object.

Multiline

- Returns or sets a value that determines whether


a control can accept multiple lines of text.

Figure 8.8 : Text Box Control & Properties


(Ref. Microsoft Visual Basic 6.0 Program)

download@
http://modul2poli.blogspot.com

B3062/8/14
Introduction To Visual Basic

ii.

Labels
A label control displays text as caption. The difference between
a label and a text box control is that a label displays text as
Caption , where a text box control displays text as Text. Double
click on the label control in the toolbox, click the label and drag
to the position and resize it (as shown in Figure 8.9).Some label
properties that are normally changed are Name, Caption,
Alignment, and Multi line.
Name

- It is the name used in code to identify the label


object.

Caption

- Returns or sets the text displayed in the label


control.

Alignment

- Returns or sets the alignment (0-left, 1-right,


2-center) of the label control.

Figure 8.9 : Label Control & Properties


(Ref. Microsoft Visual Basic 6.0 Program)

download@
http://modul2poli.blogspot.com

B3062/8/15
Introduction To Visual Basic

iii.

Command Button
Visual Basic command button control acts as a control for the
user to click on it. Once the command button control is clicked,
the appropriate procedure will be activated. To create a
command button, double click on the command button control
in the toolbox, click the command button and drag to the
position and resize it (as shown in Figure 8.10). Some command
button properties that are normally changed are Name, Caption,
Enabled, Font, and ToolTip Text.
Name

- Name used in code to identify the command


button object.

Caption

-Returns or sets the text displayed in the


command buttons control title bar or below the
command buttons icon.

Enabled

-Returns or set a value that determines whether


the command button can respond to usergenerated events. By default, it is set to True.

Font

- Returns or sets the users desired Font for the


command button object.

Tool Tip Text - Returns or sets the text displayed when the
mouse is paused over the command buttons
control.

download@
http://modul2poli.blogspot.com

B3062/8/16
Introduction To Visual Basic

Figure 8.10 : Command button Control & Properties


(Ref. Microsoft Visual Basic 6.0 Program)

iv.

Option Button
Option buttons are used when only one button of a group may
selected. Click on option button control from the toolbox. Use
the cross hair pointer, draw and position the option button on the
form. The default naming convention for an option button is opt.
The setting option button property in the properties window:
Name

it is the name used to refer to the option button


in the code

Caption

displays the text that you want to appear next to


the option button.

Value

It determine whether the option button is


selected or deselected. If the option button is
selected, the value is set to True. If it is
unselected, the value is set to False.

download@
http://modul2poli.blogspot.com

B3062/8/17
Introduction To Visual Basic

Figure 8.11 : Option Button Control & Properties


(Ref. Microsoft Visual Basic 6.0 Program)

v.

Checkbox
Checkbox allows the user to select or deselect an option. The
process of setting or creating a check box is the same as creating
an option button. Click on check box control form and use the
crosshair pointer, place and draw the check box.
The setting option button property in the properties window:
Name It is the name that used to reference the check box
control in coding.
Caption - It displays the text you want to appear next to the
check box control.
Value - It determines whether the check box is checked or
unchecked. The Value property of a check box is set
to 0 if unchecked, 1 if checked and 2 if disabled.

download@
http://modul2poli.blogspot.com

B3062/8/18
Introduction To Visual Basic

Figure 8.12 : Checkbox Control & Properties


(Ref. Microsoft Visual Basic 6.0 Program)

8.4

Save and Run The Project

After you have finished with your current session, you can Save your current project
by clicking on the Save icon on the standard tool bar, or you can click File menu and
select Save Project.

Figure 8.13 : Save the project


(Ref. Microsoft Visual Basic 6.0 Program)

download@
http://modul2poli.blogspot.com

B3062/8/19
Introduction To Visual Basic

To run the program in Visual Basic is by clicking on the Start button on the
standard tool bar or click on Run in the Menu bar and then select Start or
press the F5 function key. When you run your program you will get the result
of your project.

Figure 8.14 : Run the project


(Ref. Microsoft Visual Basic 6.0 Program)

download@
http://modul2poli.blogspot.com

B3062/8/20
Introduction To Visual Basic

Activity 8B

TEST YOUR UNDERSTANDING BEFORE YOU CONTINUE WITH THE NEXT


INPUT!

8.4

Why do you use the user interface in the Visual Basic ?

8.5

What is the default name for the Project Windows?

8.6

The properties for the objects can be set in _______________.

8.7

In Visual Basic project ___________________ control acts as a control for the


user to click on it.

8.8

Name some properties to change the label and commandbutton control objects?

download@
http://modul2poli.blogspot.com

B3062/8/21
Introduction To Visual Basic

Feedback To Activity 8B

8.4

-to interact with the system such as


- for entering data
-controlling the program
-view results.

8.5

Project 1

8.6

Properties Window

8.7

Commandbutton

8.8

name, caption, alignment, etc.

download@
http://modul2poli.blogspot.com

B3062/8/22
Introduction To Visual Basic

KEY FACTS
1. Visual Basic programs display a windows style screen (called a form) with boxes
into which users type information and buttons that they click to initiate actions.
The boxes and buttons are referred to as controls. Forms and controls are called
objects.

2. Visual Basic programs consist of three parts interface, values of properties and
code.

3. The user interface is use to interact with the system such as for entering data,
controlling the program and viewing results

download@
http://modul2poli.blogspot.com

B3062/8/23
Introduction To Visual Basic

SELF-ASSESSMENT

You are approaching success. Try all the questions in this self-assessment section and
check your answers with those given in the Feedback on Self-Assessment 2 given on
the next page. If you face any problems, discuss it with your lecturer. Good luck.

In self-assessment Questions 8.1 to 8.3, create the interface shown in the figure.
(These assessment give you practice creating objects and assigning properties. The
interface do not necessarily correspond to actual programs.)

Question 8-1

Question 8-3

Question 8-2

download@
http://modul2poli.blogspot.com

B3062/8/24
Introduction To Visual Basic

Feedback To Self-Assessment

Have you tried the question????? If YES, check your answer now:

Question 8-1

Create a new project. Change the forms caption to Dynamic Duo. Place two
command buttons on the form. Enter as the caption of the first &Batman and of the
second &Robin. Increase the font size for both command buttons to 14.

Question 8-2

Create a new project. Change the forms caption to Fill in the Blank. Place a label, a
text box, and another label on the form at appropriate locations. Change the caption of
the first label to Toto, I dont think were in and of the second label to A Quote
from the Wizard of Oz . Delete Text1 from the Text property of the text box.
Resize and position the labels as needed.

Question 8-3

Create a new project. Change the forms caption to Picture Box. Place a picture box
and a label on the form. Change the labels Caption property to the sentence shown.
Change the labels BackColor property to white, and its Font Size property to 14.
Access the picture boxs Picture property and select the picture file PICBOX.BMP
from the Pictures foleder on the CD accompanying this textbook.

download@
http://modul2poli.blogspot.com

B3062/9/1
Introduction To Visual Basic

UNIT 9
Introduction To Visual Basic

OBJECTIVES

General Objective

: To Understand the basic concept of Visual Basic

Specific Objectives : At the end of the unit you will be able to :

define Visual Basic events

write program using code window

identify events procedure

write the program using events

explain the Visual Basic statement.

download@
http://modul2poli.blogspot.com

B3062/9/2
Introduction To Visual Basic

INPUT

9.0

Introduction

When a Visual Basic program is run, a form and its control appear on the
screen. Normally, nothing happen until the user takes an action, such as
clicking a control or pressing the Tab key. Such an action is called an events.
The three steps to creating a Visual Basic program are as follows:
1. Create the interface, that is, generate, position and size the objects.
2. Set properties, that is, set relevant properties for the objects.
3. Write the code that executes when the events occur.

9.1

Event Procedures
There are two types of procedures in Visual Basic Event procedure and
General procedure.
General procedure process specific tasks such as printing header messages,
computing insurance premium, justify a string, or sorting an array.
Event procedures process events that take place when the user performs
some actions such as when the user clicks on command button, activates a
form, presses a key, or moves the mouse up or down.

download@
http://modul2poli.blogspot.com

B3062/9/3
Introduction To Visual Basic

Here are a few examples of event procedure:


User action

Event

Click control button

Click ()

Presses a key

Key Press()

Double click object

Dblclick()

Moves the mouse up or down

MouseUp()

Code consists of statements that carry out tasks. Visual Basic has a repertoire
of over 200 statements and we will use many of them in this text. In this unit,
we limit ourselves to statements that change properties of objects while a
program is running.
Properties of an object are change in code with statements of the form :
ObjectName.property = setting

Where;
ObjectName the name of the form or a control
Property

- one of the properties of the object

Setting

- a valid setting for that object.

Such statements are called assignment statements. They assign values to


properties. Examples:

i.

The statement
txtBox.Font.Size = 12

sets the size of the characters in the text box named txtBox to 12.

download@
http://modul2poli.blogspot.com

B3062/9/4
Introduction To Visual Basic

ii.

The statement
txtBox.Font.Bold = True

ii.

converts the characters in the text box to boldface.

The statement
txtBox.Text=

clear contents of the text box; that invokes the blank setting

Most events are associated with objects. The event clicking cmdButton is
different from the event clicking picBox. These two events are specified
cmdButton_Click and picBox_Click. The statements to be executed when an
event occurs are written in a block of code called an event procedure. The
structure of an event procedure is:

Private Sub objectName_event()


statements
End Sub

The word Sub in the first line signals the beginning of the event procedure,
and the first line identifies the object and the event occurring to that object.
The last line signals the termination of the event procedure. The statements to
be executed appear between these two lines. The word Private indicates that
the event procedure cannot be invoke by an event from another form. This
will no concern us until much later in the text. The word Sub is an
abbreviation of Subprogram.

download@
http://modul2poli.blogspot.com

B3062/9/5
Introduction To Visual Basic

For the instance, the event procedure (example):


Private Sub cmdButton_Click()
TxtBox.Text =
End Sub

clears the contents of the text box when the command button is
clicked.

9.2 Create object and event procedure


The form in Figure 9.1, which contain text box and a command button, will
be used to demonstrate what event procedures are and how they are created.
The three event procedures will be used to alter the appearance of a phrase
that is typed into the text box. The event procedure are txtPhrase_LostFocus,
txtPhrase_GotFocus, and cmdBold_Click.

Figure 9.1 (Ref. Microsoft Visual Basic 6.0 Program)


1. Create the interface in Figure 9.1. the name properties of the form, text
box, and the command button should be set as shown in the object
column. The Caption property of the form should be set to
Demonstration, the text property of the text box should be made bank,
and the caption property of the command button should be set to make
phrase bold.

download@
http://modul2poli.blogspot.com

B3062/9/6
Introduction To Visual Basic

2. Double-click on the text box. A window, called the code window,


appears ( Figure 9.2) just below the title bar are two drop-down list
boxes. The left box is called the Object box and the right box is called the
procedure box.

Figure 9.2(Ref. Microsoft Visual Basic 6.0 Program)

3. Click on the down arrow button to the right of the procedure box. The
drop-down menu that appears contains a list of all possible event
procedures associated with text boxes. ( Figure 9.3)

Figure 9.3(Ref. Microsoft Visual Basic 6.0 Program)

download@
http://modul2poli.blogspot.com

B3062/9/7
Introduction To Visual Basic

4. Scroll down the list of event procedures and click on LostFocus. The
lines
Private Sub txtPhrase_LostFocus()
End Sub
Appear in the code window with blinking cursor poised at the beginning
of the blank line.

5. Type the line


TxtPhrase.Font.Size = 12
Between the existing two lines. The screen appears as in Figure. 9.4 &
Figure 9.5. we have now created an event procedure that is activated
whenever the text box loses the focus.

Figure 9.4 (Ref. Microsoft Visual Basic 6.0 Program)

download@
http://modul2poli.blogspot.com

B3062/9/8
Introduction To Visual Basic

Figure 9.5 (Ref. Microsoft Visual Basic 6.0 Program)

6. Lets create another event procedure for the text box. Click on the downarrow button to the right of the Procedure box, scroll up the list of event
procedures and click on GotFocus. Then type the lines
TxtPhrase.Font.Size = 8
TxtPhrase.Font.Bold = False
between the existing two lines. (see Figure 9.6)

Figure 9.6(Ref. Microsoft Visual Basic 6.0 Program)

download@
http://modul2poli.blogspot.com

B3062/9/9
Introduction To Visual Basic

7. The txtPhrase_Change event procedure in figure in Figure 9.6was not


used and can be deleted. To delete the procedure, highlight it by dragging
the mouse across the two lines of code, and then press the Del key.
8. Lets now create an event procedure for the command button. Click on
the down-arrow button to the right of the object box. The drop down
menu contains a list of the objects.(See Figure 9.7)

Figure 9.7 (Ref. Microsoft Visual Basic 6.0 Program)

9. Click on cmBold. The event procedure cmBold_Click is displayed. Type


in the line
TxtPhrase.Font.Bold = True
The screen appears as in Figure. 9.8 and the program is completed

download@
http://modul2poli.blogspot.com

B3062/9/10
Introduction To Visual Basic

Figure 9.8 (Ref. Microsoft Visual Basic 6.0 Program)

10. Now run the program by pressing F5.


11. type something into the text box.in Figure. 9.9 the words Apa Khabar
have been typed. ( A text box has the focus whenever it is ready to accept
typing; that is, whenever it contains a blinking cursor.)

Figure 9.9 (Ref. Microsoft Visual Basic 6.0 Program)

download@
http://modul2poli.blogspot.com

B3062/9/11
Introduction To Visual Basic

12. Press the tab key. The contents of the text box will be enlarged as in
Figure 9.10. when tab was pressed, the text box lost the focus; that is the
event LostFocus happened to txtPhrase. Thus, the event procedure
txtPhrase_LostFocus was called, and the code inside the procedure is
executed.

Figure 9.10(Ref. Microsoft Visual Basic 6.0 Program)

13. Click on the command button. This calls the event procedure
cmBold_Click, which converts the text to boldface. See Figure 9.11

Figure 9.11 (Ref. Microsoft Visual Basic 6.0 Program)

download@
http://modul2poli.blogspot.com

B3062/9/12
Introduction To Visual Basic

14. Click on the text box or press the Tab key to move the cursor to the text
box. This calls the event procedure txtPhrase_GotFocus, which restore
the text to its original state.
15. You can repeat steps 11 through 14 as many times as you like. When you
have finished, end the program by pressing Alt+F4, clicking the End icon
on the toolbar, or clicking the Close button (X) on the form.

download@
http://modul2poli.blogspot.com

B3062/9/13
Introduction To Visual Basic

Activity 9A

TEST YOUR UNDERSTANDING BEFORE YOU CONTINUE WITH THE


NEXT INPUT!

Describe the contents of the text box after the command buttonis clicked.

9.1 Private Sub cmdButton_Click()


TxtBox.Text = Hello
End Sub

9.2 Private Sub cmdButton_Click()


TxtBox.Font.Italic = True
TxtBox.Text = Hello
End Sub

9.3 Private Sub cmdButton_Click()


TxtBox.Text = Hello
TxtBox.Visible = False
End Sub

download@
http://modul2poli.blogspot.com

B3062/9/14
Introduction To Visual Basic

Determine the error

9.4 Private Sub cmdButton_Click()


FrmHi = Hello
End Sub

9.5 Private Sub cmdButton_Click()


TxtBox.Caption = Hello
End Sub

9.6 Private Sub cmdButton_Click()


LblTwo.Borderstyle = 2
End Sub

Write a line (or lines) of code to carry out the task.

9.7 Display Good Morning in lblTwo

9.8 Display Merahnya Mak Ngah in red letters in txtBox

9.9 Place a bold italic Hello in txtBox.

download@
http://modul2poli.blogspot.com

B3062/9/15
Introduction To Visual Basic

Feedback To Activity 9A

9.1 The word Hello

9.2 The word in italic letters

9.3 The text box vanishes; nothing is visible

9.4 The name of the control has been given but not the property being assigned.
frmHi = Hello needs to be changed to frmHi.Caption = Hello.

9.5 Text boxes does not have a caption property. Information to be displayed in
a text box must be assigned to the text property.

9.6 Only 0 and 1 are valid values for the borderStyle property of a label.

9.7 lblTwo.Caption = Good Morning

9.8 TxtBox.ForeColor = vbRed


TxtBox.Text = Merahnya Mak Ngah

9.9 TxtBox.Font.Bold = True


TxtBox.Font.Italic = True
TxtBox.Text = Hello

download@
http://modul2poli.blogspot.com

B3062/9/16
Introduction To Visual Basic

INPUT

9.3 Using A Simple Visual Basic Statement

9.3.1

Declaration

Before you use a variable and constant in a program, you should


declare it using a Dim (dimension) and Const (constant) statement.
The Dim statement declares the name of the variable and its data type
such as integer, string or currency.
The general form of variable declaration is:
Dim Identifier [As Data Type]

Examples:
Dim ProductCode As String
Dim Quantity As Integer
Dim Price As Currency
Dim OrderDate As Date

The Constants have fixed values. Name constants are constants


defined by user.
The general form of a constant declaration is:

Const Identifier [As Data type]= value

download@
http://modul2poli.blogspot.com

B3062/9/17
Introduction To Visual Basic

Examples of constant declaration:


Const Rate As Currency = 7.50
Const BufferSize As integer = 1024
Const Greeting As String = Hello

9.3.2. Sequence

The instructions are executed sequentially one by one , starting from


the first instruction and ending with the last instructions one by one
(sequentially) and displays the results.
Example:
Private Sub Form_Activate()
Print Insert Your Card
Print Enter Your ID number
Print Enter Password
Print Thank You

End Sub

The code will produce the following output:


Insert Your Card
Enter Your ID number
Enter Password
Thank You

download@
http://modul2poli.blogspot.com

B3062/9/18
Introduction To Visual Basic

9.3.3

Selection

The selection allows Visual Basic to execute instructions in the


procedure, which may not be the next instruction. It compares two
expressions, and based on the result (True or False), it branches off to
another instruction.

Example:
Private Sub Form_Activate()
Dim mark As Interger
mark = InputBox (Enter your mark:)
If mark > 49 Then
Print PASS
End If
End Sub.

If you enter the value 74 for mark, the program will display the
following output:
PASS

9.3.4

Repetition (loop)

A loop is any group of instruction that executes repeatedly until a


specified condition is met. When the loop terminates, program control
passes to the statement following the loop.
There are three types of loop in Visual Basic:

For Next

Do WhileLoop / Do UntilLoop

DoLoop Until / DoLoop While

download@
http://modul2poli.blogspot.com

B3062/9/19
Introduction To Visual Basic

Example:
Private Sub Command1_Click()
Dim x As Integer
Dim xsquare As Integer
Print x, xsquare
For x = 0 To 6
Xsquare = x * x
Print x, xsquare
Next x
End Sub

Here is the program output.

xsquare

16

25

36

download@
http://modul2poli.blogspot.com

B3062/9/20
Introduction To Visual Basic

Activity 9B

TEST YOUR UNDERSTANDING BEFORE YOU CONTINUE WITH THE


NEXT INPUT!

9.10

What are Dim and Const statement use for?

9.11

Write the general form to declare variable and constant in a program


of below statement:

9.12

i.

Student Number as an integer

ii.

Student Name as a string

iii.

Student status as a single

iv.

Student timetable as Date

v.

Total student = 100

State the three types of loop structure in Visual Basic programming?

download@
http://modul2poli.blogspot.com

B3062/9/21
Introduction To Visual Basic

Feedback To Activity 9B

9.10

Dim (dimension) and Const (constant) statement are use to declare a variable

(data types) and constant (fixed value) in a program.

9.11

i. Dim Studentnumber As integer


ii. Dim Studentname As string
iii. Dim Studentstatus As single
iv. Dim Studenttimetable As Date
v. Const Totalstudent As Integer = 100

9.12

i. For Next
ii. Do WhileLoop / Do UntilLoop
iii. DoLoop Until / DoLoop While

download@
http://modul2poli.blogspot.com

B3062/9/22
Introduction To Visual Basic

KEY FACTS
1.

The two procedures types in Visual Basic is Event procedure and


General procedure.

2.

General procedure - process specific tasks such as printing header


messages, computing insurance premium, justify a string, or sorting
an array.

3.

Event procedures - process events that take place when the user
performs some action such as when the user clicks on command
button, activates a form, presses a key, or moves the mouse up or
down.

download@
http://modul2poli.blogspot.com

B3062/9/23
Introduction To Visual Basic

1.

SELF-ASSESSMENT

You are approaching success. Try all the questions in this self-assessment section
and check your answers with those given in the Feedback on Self-Assessment 9
given on the next page. If you face any problems, discuss it with your lecturer.
Good luck.

Question 9-1

Write a program to find the larger of two numbers input by the user?

download@
http://modul2poli.blogspot.com

B3062/9/24
Introduction To Visual Basic

Feedback To Self-Assessment

Have you tried the question????? If YES, check your answer now:

Question 9-1

Private Sub cmdFindLarger_Click()


Dim largerNum As Single
picResult.Cls
If Val(txtFirstNum.Text)> Val(txtSecondNum.Text) Then
largerNum = Val(txtFirstNum.Text)
Else
largerNum = Val(txtSecondNum.Text)
End If
picResult.Print The larger number is; largerNum
End Sub

CONGRATULATIONS!!!!.

download@
http://modul2poli.blogspot.com

E3062/10/1
Visual Basic Programming

UNIT 10
Visual Basic Programming

OBJECTIVES

General Objective

: To develop a simple Visual Basic program

Specific Objectives : At the end of the unit you will be able to :

plan a Visual Basic project

design the user interface

write a Visual Basic program

download@
http://modul2poli.blogspot.com

E3062/10/2
Visual Basic Programming

INPUT

10.0

Basic concept of Programming

This unit presents a simple Visual Basic program that requires input, processing and
output. Its interface includes the main form and six controls objects one text box,
one picture box, two labels and two command buttons. The labels are used for
labeling text box; the text box for entering data; and the picture box, for displaying
results. The two command buttons are used to control the program execution.

10.1 Planning The Project

Planning a Visual Basic project basically involves the following steps:

a. Plan the project which involves determining what we want the program to do.
b. Design the user interface which is the most visible part of the project. It is
used to interact with the system. You determine the controls that are needed
to enter data, to display results, and to control the program execution.
c. Set the properties of the controls. Determine the controls that you will need
for your project and set the properties (e,g., appearance, name, caption, color)
for each of the controls used.
d. Write the code (program) which represents the action that must be taken
when the user clicks on a command button. Clicking a command button is
called an event and the code represents a response to that event.
e. Test and debug the code. This is done to ensure that the program works
correctly.

download@
http://modul2poli.blogspot.com

E3062/10/3
Visual Basic Programming

10.2

Grade calculation program

We will use an example to illustrate the basic steps needed to do a Visual Basic
program. Lets say we want to compute and display the grade of a student given
his/her mark. Passing mark will be between 50 to 100 and a fail between 0 to 49.

10.3

Designing the user interface

The user interface shows the visible parts of a Visual Basic program. You use the
interface to interact with the system such as for entering data, controlling the
program and displaying results.

Form
Lets name the form compute grade and set its Appearance property to 0-Flat.

a. In the main window, select File > New Project (Ctrl+N). You will see the
title Project1 Form1 (form) in the project title bar and the title Form1 in
the form title bar Figure 10.1

Figure 10.1 (Ref. Microsoft Visual Basic 6.0 Program)

download@
http://modul2poli.blogspot.com

E3062/10/4
Visual Basic Programming

b. Set the form properties as follows (Figure 10.2)


Appearance to 0-Flat
BackColor to white
Caption to Grade Computation

Figure 10.2(Ref. Microsoft Visual Basic 6.0 Program)


Labels
Lets name the label1 for entering mark as Enter your mark (0 100) and the
label2 for viewing the results as Your grade is.

Figure 10.3 (Ref. Microsoft Visual Basic 6.0 Program)

download@
http://modul2poli.blogspot.com

E3062/10/5
Visual Basic Programming

a. Highlight the label icon A in the toolbox and double-click on it. Visual Basic
will place the label button label1 in the center of the form. Move and resize
it to a suitable size and location (as shown in Figure 10.3).
b. Click on the label and set the Appearance property to 0-Flat (the
BackColor property will automatically change to white) and the Caption
property to Enter your mark (0 100) as shown in Figure 10.3

To create the next label (label2) follow the steps above and set the caption to
Your grade is.

Text box
Create a text box for entering mark.

a. Highlight the text box icon

ab

in the toolbox and double-click on it.

Visual Basic will place a text box with the text Text1 inside.
b. Click on the text box and set the text property to empty (i.e., clear text1) as
shown in Figure 10.4 (dont change the other settings).

Figure 10.4 (Ref. Microsoft Visual Basic 6.0 Program)

download@
http://modul2poli.blogspot.com

E3062/10/6
Visual Basic Programming

Picture box
Create the picture box for displaying the results (grade).

a. Highlight the picture box icon (just above the text box icon) in the toolbox
and double-click on it. Visual Basic will place a picture box.
b. Click on the picture box and set the BackColor property to white as shown
in Figure 10.5

Figure 10.5(Ref. Microsoft Visual Basic 6.0 Program)

Command buttons
Create the command buttons and set their properties as follows:

a. Highlight the command button icon

in the toolbox and double-click on it.

Visual basic will place the command button command1 at the center of the
form. Resize the button if necessary and move it to the bottom of the form (as
shown in the Figure 10.6).
b. Set the property Caption to Compute Grade as follows.

download@
http://modul2poli.blogspot.com

E3062/10/7
Visual Basic Programming

Figure 10.6 (Ref. Microsoft Visual Basic 6.0 Program)

Similarly, create the second command button (command2) and give it the
name Exit. Your form should now resemble: (as shown in Figure 10.7)

Figure 10.7 (Ref. Microsoft Visual Basic 6.0 Program)

download@
http://modul2poli.blogspot.com

E3062/10/8
Visual Basic Programming

Write code for the command buttons

a. double-click on the command button Compute grade and the code window
shown in figure 10.8 will appear:

Figure 10.8 (Ref. Microsoft Visual Basic 6.0 Program)

Visual basic displays the name of the control Command1 on the top left and
the name of the event Click on the top right. Notice that the Visual Basic still
retains the name Command1 even though we have changed it to Compute
Grade.
b. Enter the code in the code window as shown. Note that Visual Basic
automatically supplies the first and the last line of the code.

Private Sub Command1_Click ()


Dim mark As Integer
Mark = Val(Text1.text)
Picture1.Cls
If mark < 50 Then
Picture1.Print Fail

download@
http://modul2poli.blogspot.com

E3062/10/9
Visual Basic Programming

Else
Picture1.Print Pass
End If

End Sub

Private is a reserved word used to specify that this event cannot be invoked
from another form.

Sub stands for subprogram (also called procedure)


Command1_Click ( ) is the name given to the procedure. It is an event
procedure, hence the word Click. The procedure will execute when the user
clicks on the command button (Compute Grade) for the code.

End Sub, the last line in the program signals the end of the program.

Similarly, double-click on the command button Exit and enter the code as below:

Private Sub Command2_Click ( )


End
End Sub

There is only one command, End, in this procedure (between the first and the last
line). End simply stops the program execution. This is also an event procedure.
When the user clicks on the Exit command button, the program execution will stop.

If you double-click on the Exit button, you will see the code for both the Compute
Grade button (at the top) and the code for the Exit button (at the bottom) with a line
separating the two as shown below.

download@
http://modul2poli.blogspot.com

E3062/10/10
Visual Basic Programming

Private Sub Command1_Click ()


Dim mark As Integer
Mark = Val(Text1.text)
Picture1.Cls
If mark < 50 Then
Picture1.Print Fail
Else
Picture1.Print Pass
End If

End Sub

Private Sub Command2_Click ()


End
End Sub

10.4 Running The Program

To run the program

1. First double-click on the Compute Grade command button.


2. Then run the program by (a) clicking on the start button

on the standard tool

bar, (b) click on Run in the Menu bar and then select Start or press the F5
function key.

download@
http://modul2poli.blogspot.com

E3062/10/11
Visual Basic Programming

When you run the program, you will see the screen shown in Figure 10.9

Figure 10.9 (Ref. Microsoft Visual Basic 6.0 Program)

3. Click on the text box at the top and enter the mark. Then click on the Compute
Grade command button. You will see the grade displayed in the Picture box as
shown in the screen below in Figure 10.10

Figure 10.10 (Ref. Microsoft Visual Basic 6.0 Program)

To stop the execution, click on the Exit command button. Visual Basic will take you
back to the code window.

download@
http://modul2poli.blogspot.com

E3062/10/12
Visual Basic Programming

Activity 10A

TEST YOUR UNDERSTANDING BEFORE YOU CONTINUE WITH THE


NEXT INPUT!

Question 10.1
a. Rewrite the code with fewer line
PicOutput.Print 1;
PicOutput.Print 2;
PicOutput.Print 1 + 2

b. Complete the table by filling in the value of each variable after each line is
executed.
a

Private Sub cmdCompute_Click ( )


a=3
b=4
c=a+b
a=c*a
PicResults.Print a - b
b=b*b
End Sub

c. Write an event procedure to calculate, and display the value of the


expression.
i. 7 x 8 + 5
ii. 17(3 +162)

download@
http://modul2poli.blogspot.com

E3062/10/13
Visual Basic Programming

Feedback To Activity 10A

10.1

a. Private Sub cmdCompute_Click ( )


picOutput.Print 1; 2; 1 + 2
End Sub

b.
a
Private Sub cmdCompute_Click ( )
a=3
b=4
c=a+b
a=c*a
PicResults.Print a - b
b=b*b
End Sub

3
3
3
21
21
21

4
4
4
4
16

c. i. Private Sub cmdCompute_Click ( )


picOutput.Cls
picOutput.Print 7 * 8 + 5
End Sub

ii. Private Sub cmdCompute_Click ( )


picOutput.Cls
picOutput.Print 17 * (3 + 162)
End Sub

download@
http://modul2poli.blogspot.com

7
7
7
7

E3062/10/14
Visual Basic Programming

INPUT

10.5 Program Parts


The different parts of the previous Visual Basic program are as follows:
Scope of Abreviation for
procedure subprogram

Procedure
name

Private Sub Command1_Click ()


Dim mark As Integer
Declare mark as integer
Read mark input, convert it value, then store in variable mark
Mark = Va1(Text1.text)
Picture1.Cls
Clear picture box
If mark < 50 Then
Test if mark is less than 50
Picture1.Print Fail
Print Fail if mark is less than 50
Else
Picture1.Print Pass
Print Pass if mark is 50 or more
End If
End Sub
Signals the end of the subprogram/procedure
Private Sub Command2_Click ()
End Terminate/stop the program execution
End Sub

Comment
statement

Line to separate the


procedures

download@
http://modul2poli.blogspot.com

E3062/10/15
Visual Basic Programming

Reserved words

Reserved words or keywords have special meaning in Visual Basic. You cannot use
them for any other purpose. Some of the reserved words in the above program are:

Private
Private is a reserved word in Visual Basic. It tells Visual Basic that this procedure
cannot be invoked from another form.

Sub
Stands for subprogram. The term procedure is also used to refer to a subprogram.

Command_Click ( )

This is the name of the subprogram/procedure. Visual Basic automatically supplies


this name. The word Click tells that this program will respond to a Click event, i.e.,
when the user clicks the command button Command1 or a renamed version of the
command button such as the Compute Grade.

Subsequent subprograms (corresponding to other command Buttons) will be named


Command2_Click ( ), Command3_Click ( ) and so on.

Variable declaration

The statement

Dim mark As Integer

download@
http://modul2poli.blogspot.com

E3062/10/16
Visual Basic Programming

is a declaration statement. The word Dim is a reserved or keyword; it stands for


dimension (or size). You declare variables in a Visual Basic program using this
keyword. The variable mark in this subprogram is declared as an integer variable.
Variables is a name that is used to refer to an item of data.

Comments

Comments are non-executable statements inserted into Visual Basic program to


make the program more readable. Comments help the programmer as well as the
maintenance staff to understand, debug and maintain the code.

Comments in Visual Basic start with an apostrophe (). Comments can be placed
anywhere in the program. It can be placed on a separate line as in

Read mark input, convert it value, then store in variable mark or after a Visual Basic
command/statement as in

Picture1.Cls

Clear picture box

Assignment statement

An assignment statement takes the form

<variables> = <expression>

The expression on the right-hand side of the equal sign (=) is evaluated and the result
is assigned to the variable on the left-hand side. The variable represents an area of
computer memory that can hold data. The statement

Mark = Va1(Text1.text)

download@
http://modul2poli.blogspot.com

E3062/10/17
Visual Basic Programming

first reads input data from text box (Text1, text), then converts it to a numerical
value, and finally stores the number in the variable mark. The function Va1 does the
conversion.

Note that the property of an object takes the form

Object.Property

Thus in the expression

Text1.text

Text1 is the object and Text is the property.

Methods

Visual Basic provides procedures known as methods for each of the controls it
provides. You can use these methods to change the control objects properties.

To use a method associated with an object, you suffix a period (.) and the method to
the object as follows:

Object.method ( )

Thus in the statement

Picture1.Cls

download@
http://modul2poli.blogspot.com

E3062/10/18
Visual Basic Programming

Picture1 is the object and Cls (clear screen) is the method associated with that object.
This method simply clears the picture box.

Another method we have used with the picture1 object is the Print method, which is
used to send output to the picture box as in

Picture1.Print Pass

Decision-making

Visual Basic provides several control structures (e.g. If-end, DO-Loop) to support
the decision-making.

One of the control structures is If-Else-If. In the example program, the statement
tests if the mark entered is less than 50, and if it is, it prints Fail in the picture box,
otherwise it prints pass. (if mark is entered 50 or more)

If mark < 50 Then


Picture1.Print Fail

Test if mark is less than 50


Print fail if mark is less than 50

Else
Picture1.Print Pass

Print pass if mark is 50 or more

End If

download@
http://modul2poli.blogspot.com

E3062/10/19
Visual Basic Programming

Activity 10B

TEST YOUR UNDERSTANDING BEFORE YOU CONTINUE WITH THE


NEXT INPUT!

10.2 Explain what is meant by reserved words or keywords in Visual Basic. States 3
reserved words.
10.3 What is a variables. Show a general form of variable statement assignment in Visual
Basic program.
10.4 Consider the following Visual Basic program;

i.

Private Sub cmdDisplay_Click ( )


picResults.Cls
picResults.Print 3
picResults.Print -3
End Sub

ii.

Private Sub cmdDisplay_Click ( )


picResults.Cls
picResults.Print 3;
picResults.Print 3;
picResults.Print 99;
picResults.Print 100;
End Sub

Show the output of the above program.

download@
http://modul2poli.blogspot.com

E3062/10/20
Visual Basic Programming

Feedback To Activity 10B

10.2 Reserved words or keywords have special meaning in Visual Basic that cannot
be use for any other purpose. Examples of reserved words are Sub, End, False,
True and private.
10.3 Variable is a name that is used to refer to an item of data and it represents an
area of computer memory that can hold data. General expressions of variables
statement assignment; <variables> = <expression>
10.4
(i)

(ii)

download@
http://modul2poli.blogspot.com

E3062/10/21
Visual Basic Programming

KEY FACTS
1. One of the key elements in planning a Visual Basic application is deciding what the
user sees. What data will the user entering? Will the applications have places to enter
text and places to display output.
2. The sequence of procedures executed in your program is controlled by events that
the user initiates rather than by a predetermined sequence of procedures in your
program.

download@
http://modul2poli.blogspot.com

E3062/10/22
Visual Basic Programming

SELF-ASSESSMENT

You are approaching success. Try all the questions in this self-assessment section
and check your answers with those given in the Feedback on Self-Assessment given
on the next page. If you face any problems, discuss it with your lecturer. Good luck.

1. Write code starting with Private Sub cmdCompute_Click ( ) and picOutput.Cls


statements, ending with an End Sub statement, and having one line for each step.
Lines that display data should use the given variable name.

The following steps calculate the balance after 3 years when RM100 is deposited
in a savings account at 5% interest compounded annually.

a. Assign the value 100 to the variable balance


b. Increase the variable balance by 5% of its value
c. Increase the variable balance by 5% of its value
d. Increase the variable balance by 5% of its value
e. Display the value of the variable balance in a picture box.

2. Write an event procedure to solve the problem and display the answer in a
picture box. The program should use variables for each of the quantities.

If a car left Kota Bharu at 2 oclock and arrived in Pulau Pinang at 7 oclock,
what was its average speed ? The distance between Pulau Pinang from Kota
Bharu is 350 km.

download@
http://modul2poli.blogspot.com

E3062/10/23
Visual Basic Programming

Feedback To Self-Assessment 1

Have you tried the question????? If YES, check your answer now:

1. Private Sub cmdCompute_Click ( )


PicOutput.Cls
balance = 100
balance = balance + balance * 0.05
balance = balance + balance * 0.05
balance = balance + balance * 0.05
picOutput.Print balance
End Sub

2. Private Sub cmdCompute_Click ( )


PicOutput.Cls
distance = 350

CONGRATULATIONS!!!!..
May success be with you
always.

elapsedTime = 7-2
averageSpeed = distance/elapsedTime
picOutput.Print averageSpeed
End Sub

download@
http://modul2poli.blogspot.com

Potrebbero piacerti anche