Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
POLYTECHNICS
MINISTRY OF EDUCATION
MODULE E3062
PROGRAMMING
MOHD RUDIN B. FAUZI (PKB)
ZULKIFFLI B. MOHD YUSOFF (PKB)
download@
http://modul2poli.blogspot.com
Name
Address
:
:
Telephone No. :
e-mail
:
Qualifications :
Position
Name
Address
:
:
Telephone No. :
e-mail
:
Qualifications :
Position
Editor
Name
:
Address
:
Telephone No. :
e-mail
:
Qualifications :
Position
:
download@
http://modul2poli.blogspot.com
Module Code
: ___________
Course : ____________________________________
Module Writers: ______________________________
Please use the following scale for your evaluation:
4
3
2
1
Strongly Agree
Agree
Disagree
Strongly Disagree
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
1
( 2 H)
2 Hours
Introduction To The
Concept And Basic
Instruction
Programming C++
2
( 2 H)
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
1.0
1.1
Definition of Programming
1.2
1.3
UNIT 2
2.0
2.1
Comments
Functions
Console Input
(cin).
2.2.3
download@
http://modul2poli.blogspot.com
UNIT 3
3.0
Flowcharts
3.0.3 Pseudocode
3.0.4
3.1
UNIT 4
4.0
Structure chart.
Algorithm
3.1.2.
Flowchart
4.1
4.2
Integer - Int
4.1.2
Character - char
4.1.2
Integer Constant
4.2.2
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
5.0
5.1
download@
http://modul2poli.blogspot.com
UNIT 6
6.0
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
7.0
Simple programming
7.1
Even Odd
7.2
Grade
7.3
Student List
7.4
Bubble Sort
UNIT 8
8.0
8.1
8.2
8.3
download@
http://modul2poli.blogspot.com
8.4
UNIT 9
9.0
Introduction
9.1
Procedure Events
9.2
9.3
Declaration
9.3.2
Sequence
9.3.3 Selection
9.3.4
UNIT 10
10.0
Repetition
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.
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.
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.
download@
http://modul2poli.blogspot.com
REFERENCES
1.
2.
3.
4.
6.
7.
8.
9.
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
download@
http://modul2poli.blogspot.com
E3062/1/2
Basic Concept And Problem Solving in Programming
INPUT
1.0
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.
download@
http://modul2poli.blogspot.com
E3062/1/3
Basic Concept And Problem Solving in Programming
1.1
Definition of program
1.2
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
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
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.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
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
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
download@
http://modul2poli.blogspot.com
E3062/1/9
Basic Concept And Problem Solving in Programming
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.
download@
http://modul2poli.blogspot.com
E3062/1/10
Basic Concept And Problem Solving in Programming
Activity 1B
download@
http://modul2poli.blogspot.com
E3062/1/11
Basic Concept And Problem Solving in Programming
Feedback To Activity 1B
1.4 i
ii
Planning of variables
iii
Drawing of flowchart
iv
Program writing
vi
Documentation of program.
1.5 i
ii
iii
iv
Sample program which had been run and executed and the
tested data.
vi
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
Declaration
ii.
Input
iii.
Output
Question 1-2
Question 1-3
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
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
download@
http://modul2poli.blogspot.com
E3062/2/2
Introduction To The Concept and Basic Instruction Of Programming C++
INPUT
2.0
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++
comment
Preprocessor directive
Function name
Begin block
Function Body
End Block
Program 2.0
2.1
C ++ Program Characteristics
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
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
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
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
2.4
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.
download@
http://modul2poli.blogspot.com
E3062/2/8
Introduction To The Concept and Basic Instruction Of Programming C++
INPUT
2.2.
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;
download@
http://modul2poli.blogspot.com
E3062/2/9
Introduction To The Concept and Basic Instruction Of Programming C++
2.2.2
Input ( cin )
2.2.3
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;
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
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 (
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
download@
http://modul2poli.blogspot.com
B3062/3/2
Introduction To The Concept and Basic Instruction Of Programming C++
INPUT
3.0
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
(Input)
(Process)
(Process)
(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
Annotation
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
process
process
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.
(Input)
(Process)
(Process)
(Output)
3.0.4
Structure Chart
Structure chart is also known as input-process-output or hierarchy chart
download@
http://modul2poli.blogspot.com
B3062/3/7
Introduction To The Concept and Basic Instruction Of Programming C++
Calculate price
Display discount price
Read price
discount value = price * rate of discount
download@
http://modul2poli.blogspot.com
B3062/3/8
Introduction To The Concept and Basic Instruction Of Programming C++
Activity 3A
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
3.1.1
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.
Processing: Find the sum of the grades; count the number of students;
calculate average grades = sum of grades / number of students.
download@
http://modul2poli.blogspot.com
B3062/3/11
Introduction To The Concept and Basic Instruction Of Programming C++
3.1.2.
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
display the
answer
B3062/3/12
Introduction To The Concept and Basic Instruction Of Programming C++
Activity 3B
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.
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
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
No
More than
50000.00?
Calculate income
tax return =
yearly income * 0
Yes
Calculate income
tax return = yearly
income * 0.025
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
download@
http://modul2poli.blogspot.com
E3062/4/2
Data Types, Operator And Expression
INPUT 4
4.0
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
Invalid Identifier
x
2sumx
Hourly-rate
name@
GROSS PAY
Comment
Illegal character
Illegal first character
Illegal character Illegal character @
Illegal blank
4.1
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
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
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
double name_identifier
double pendapatan_bersih,cukai_pendapatan;
double nilai;
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
download@
http://modul2poli.blogspot.com
E3062/4/7
Data Types, Operator And Expression
4.2.2
ii.
Character constants:
$
*
String constants:
Name:
Telephone No:
Postcode:
iii.
variable identifier
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
4.1
4.2
Keywords___________
Keywords___________
Keywords___________
Keywords___________
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.
download@
http://modul2poli.blogspot.com
int
char
double
float
E3062/4/11
Data Types, Operator And Expression
INPUT 4
Arithmetic Operators
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
// 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
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
- -- ++
+ / %
+ < <= > >=
== !=
&&
||
download@
http://modul2poli.blogspot.com
E3062/4/15
Data Types, Operator And Expression
Activity 4B
4.3
4.4
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
download@
http://modul2poli.blogspot.com
E3062/5/2
Logical Structure Types And Basic Instruction
INPUT
5.0
5.1
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.
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
5.1.2
Selection Structure
if Statement
download@
http://modul2poli.blogspot.com
E3062/5/4
Logical Structure Types And Basic Instruction
x >10
No
Yes
Print x
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
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
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 ;
}
}
download@
http://modul2poli.blogspot.com
E3062/5/7
Logical Structure Types And Basic Instruction
i.
download@
http://modul2poli.blogspot.com
E3062/5/8
Logical Structure Types And Basic Instruction
Switch statement
Expression
x=?
x=1
y=x+1
x=2
y=x+2
default
y=x
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;
}
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
5.1
5.2
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
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
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
Example 5.7
While ((cin>>amount) &&(amount > 0) && (amount<=balance))
{
balance = balance amount;
cout<<\n Please take your cash<<amount;
}
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
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:
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.
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
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
5.2
State the basic form of the for loop and write the part of program that uses a
for statement?
5.3
5.4
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
5.3
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
download@
http://modul2poli.blogspot.com
E3062/6/1
Preprocessor and Header Files
UNIT 6
Preprocessor and Header Files
OBJECTIVES
General Objective
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
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
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:
download@
http://modul2poli.blogspot.com
E3062/6/5
Preprocessor and Header Files
1:
#include <iostream>
2:
3.
5:
6:
void main ( )
7:
8:
int x=5, y:
9:
y = getmax (x,8);
10:
cout<<y;
11:
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
6.1
6.2
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
download@
http://modul2poli.blogspot.com
E3062/6/7
Preprocessor and Header Files
Feedback To Activity 6A
6.1
D.
6.2
C. #define
6.3
B. Value
6.4.
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
For example, to display the phrase Learning C++ is Fun to the screen, just type
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);
Output
%s
String of character
%s
Character
%s
Decimal integer
%s
Floating-point number
%s
Unsigned integer
%s
Hexadecimal integer
%s
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
Return value
salnum (c)
isalpha (c)
isascii (c)
iscntrl (c)
isdigit (c)
isgraph(c)
islower (c)
isprint (c)
ispunct(c)
isspace (c)
isupper (c)
isxdigit (c)
toascii(c)
ASCII equavalent
tolower (c)
toupper (c)
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.
Return value
acos(d)
Arc cosine of d
asin(d)
Arc sine d
atan(d)
Arc sine d
atan2(d1,d2)
ceil(d)
cos(d)
Cosine of d
exp(d)
fabs(d)
Absolute value of d
floor(d)
fmod(d1,d2)
Remainder of d1/d2
log(d)
log10(d)
pow(d1,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
download@
http://modul2poli.blogspot.com
E3062/6/12
Preprocessor and Header Files
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;
}
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
Program 6.2.4
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
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
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.
UNIT 7
Writing C++ Program
OBJECTIVES
General Objective
: To write C ++ program
download@
http://modul2poli.blogspot.com
E3062/7/1
E3062/7/2
INPUT
7.0 Introduction
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
E3062/7/3
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<<f<<endl;
if((f>=0) && (f<50))
{
cout<< Grade is F;
}
else if ((f>=50) && (f<62))
download@
http://modul2poli.blogspot.com
{
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))
{
download@
http://modul2poli.blogspot.com
E3062/7/4
}
else if ((f>=86) && (f<89))
{
cout<< Grade is B+;
}
else if ((f>=89) && (f<92))
{
download@
http://modul2poli.blogspot.com
E3062/7/5
E3062/7/6
Activity 7A
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
Feedback To Activity 7A
7.1.
download@
http://modul2poli.blogspot.com
E3062/7/7
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;
{
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();
}
List of students
Jason
123
Programming
Jenny
124
Multimedia
Susie
125
Networking
download@
http://modul2poli.blogspot.com
E3062/7/9
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 done;
download@
http://modul2poli.blogspot.com
E3062/7/11
cout<<a[i] << ;
cout<< \n;
return 0;
}
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
E3062/7/12
Activity 7B
7.2.
Write a program that checks whether the character you type is a vowel or not
with the following output
download@
http://modul2poli.blogspot.com
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
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:
Question 7-2
Write a program that accepts three values and selects the greatest number with the
following format output:
download@
http://modul2poli.blogspot.com
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
download@
http://modul2poli.blogspot.com
E3062/7/16
B3062/8/1
Introduction To Visual Basic
UNIT 8
Introduction To Visual Basic
OBJECTIVES
General Objective
download@
http://modul2poli.blogspot.com
B3062/8/2
Introduction To Visual Basic
INPUT
8.0
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
8.1
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
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
download@
http://modul2poli.blogspot.com
B3062/8/9
Introduction To Visual Basic
8.2.
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
...
download@
http://modul2poli.blogspot.com
Form n
Text 1
Command1
Command2
Lable1
Lable2
B3062/8/10
Introduction To Visual Basic
Activity 8A
8.1
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
i.
___________________________
ii.
___________________________
iii.
__________________________
iv.
___________________________
v.
___________________________
download@
http://modul2poli.blogspot.com
B3062/8/11
Introduction To Visual Basic
Feedback To Activity 8A
8.1
8.2
i. Bar (Title,menu,Toolbar)
ii.Toolbox
v. Project window
8.3
i. Text box
iii.Vertical scroll bar
download@
http://modul2poli.blogspot.com
v. Timer
B3062/8/12
Introduction To Visual Basic
INPUT
8.3
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
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
Text
Alignment
Multiline
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
Caption
Alignment
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
Caption
Enabled
Font
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
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
Caption
Value
download@
http://modul2poli.blogspot.com
B3062/8/17
Introduction To Visual Basic
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
8.4
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.
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.
download@
http://modul2poli.blogspot.com
B3062/8/20
Introduction To Visual Basic
Activity 8B
8.4
8.5
8.6
8.7
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
8.5
Project 1
8.6
Properties Window
8.7
Commandbutton
8.8
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
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
Event
Click ()
Presses a key
Key Press()
Dblclick()
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
Setting
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.
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:
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
clears the contents of the text box when the command button is
clicked.
download@
http://modul2poli.blogspot.com
B3062/9/6
Introduction To Visual Basic
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)
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.
download@
http://modul2poli.blogspot.com
B3062/9/8
Introduction To Visual Basic
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)
download@
http://modul2poli.blogspot.com
B3062/9/9
Introduction To Visual Basic
download@
http://modul2poli.blogspot.com
B3062/9/10
Introduction To Visual Basic
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.
13. Click on the command button. This calls the event procedure
cmBold_Click, which converts the text to boldface. See Figure 9.11
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
Describe the contents of the text box after the command buttonis clicked.
download@
http://modul2poli.blogspot.com
B3062/9/14
Introduction To Visual Basic
download@
http://modul2poli.blogspot.com
B3062/9/15
Introduction To Visual Basic
Feedback To Activity 9A
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.
download@
http://modul2poli.blogspot.com
B3062/9/16
Introduction To Visual Basic
INPUT
9.3.1
Declaration
Examples:
Dim ProductCode As String
Dim Quantity As Integer
Dim Price As Currency
Dim OrderDate As Date
download@
http://modul2poli.blogspot.com
B3062/9/17
Introduction To Visual Basic
9.3.2. Sequence
End Sub
download@
http://modul2poli.blogspot.com
B3062/9/18
Introduction To Visual Basic
9.3.3
Selection
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)
For Next
Do WhileLoop / Do UntilLoop
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
xsquare
16
25
36
download@
http://modul2poli.blogspot.com
B3062/9/20
Introduction To Visual Basic
Activity 9B
9.10
9.11
9.12
i.
ii.
iii.
iv.
v.
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
9.11
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.
2.
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
CONGRATULATIONS!!!!.
download@
http://modul2poli.blogspot.com
E3062/10/1
Visual Basic Programming
UNIT 10
Visual Basic Programming
OBJECTIVES
General Objective
download@
http://modul2poli.blogspot.com
E3062/10/2
Visual Basic Programming
INPUT
10.0
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.
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
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
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
download@
http://modul2poli.blogspot.com
E3062/10/4
Visual Basic Programming
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.
ab
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).
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
Command buttons
Create the command buttons and set their properties as follows:
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
Similarly, create the second command button (command2) and give it the
name Exit. Your form should now resemble: (as shown in Figure 10.7)
download@
http://modul2poli.blogspot.com
E3062/10/8
Visual Basic Programming
a. double-click on the command button Compute grade and the code window
shown in figure 10.8 will appear:
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.
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.
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:
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
End Sub
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
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
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
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
download@
http://modul2poli.blogspot.com
E3062/10/13
Visual Basic Programming
10.1
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
download@
http://modul2poli.blogspot.com
7
7
7
7
E3062/10/14
Visual Basic Programming
INPUT
Procedure
name
Comment
statement
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 ( )
Variable declaration
The statement
download@
http://modul2poli.blogspot.com
E3062/10/16
Visual Basic Programming
Comments
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
Assignment statement
<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.
Object.Property
Text1.text
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 ( )
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)
Else
Picture1.Print Pass
End If
download@
http://modul2poli.blogspot.com
E3062/10/19
Visual Basic Programming
Activity 10B
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.
ii.
download@
http://modul2poli.blogspot.com
E3062/10/20
Visual Basic Programming
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.
The following steps calculate the balance after 3 years when RM100 is deposited
in a savings account at 5% interest compounded annually.
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:
CONGRATULATIONS!!!!..
May success be with you
always.
elapsedTime = 7-2
averageSpeed = distance/elapsedTime
picOutput.Print averageSpeed
End Sub
download@
http://modul2poli.blogspot.com