e3062 programming
DESCRIPTION
ProgrammingTRANSCRIPT
-
MOHD RUDIN B. FAUZI (PKB) ZULKIFFLI B. MOHD YUSOFF (PKB)
MODULE E3062
PROGRAMMING
MALAYSIA POLYTECHNICS
MINISTRY OF EDUCATION
download@http://modul2poli.blogspot.com
-
Name : Mohd Rudin B. Fauzi
Address : Electrical Engineering Department Politeknik Kota Bharu, Pangkal Kalong
16450 Kota Bharu, Kelantan. Telephone No. : 09-7889126 e-mail : [email protected]
Qualifications : M.Ed. (UTM), Bsc (Hons) in Electrical Eng.(UTM), Diploma in Electrical Eng. (ITM) Position : Polytechnic Lecturer
Name : Zulkiffli Bin Mohd Yusoff Address : Electrical Engineering Department
Politeknik Kota Bharu, Pangkal Kalong 16450 Kota Bharu Kelantan. Telephone No. : 09-7889126 e-mail : [email protected]
Qualifications : M.Ed. (UTM), Bsc (Hons) in Electrical Eng.(UTM), Diploma in Electrical (Power) Eng.(ITM) Position : Polytechnic Lecturer
Editor
Name : Address : Telephone No. : e-mail : Qualifications : Position :
BIODATA OF MODULE WRITERS E3062 PROGRAMMING 1
download@http://modul2poli.blogspot.com
-
What Do You Think Of This Module?
Title of Module: _______________________ Module Code : ___________ Students Name: _______________________ Registration No. : ___________ Course : ____________________________________ Module Writers: ______________________________ Please use the following scale for your evaluation:
4 Strongly Agree 3 Agree 2 Disagree 1 Strongly Disagree
Instruction : Please on the space provided.
No. How much do you agree with the following statements? SCALE
A. FORMAT 1 2 3 4 1 The pages are organized in an interesting manner. 2 The font size makes it easy for me to read the module.
3 The size and types of pictures and charts used are suitable for the input.
4 The pictures and charts are easy to read and understand. 5 The tables used are well-organised and easy to understand. 6 The arrangement of the Input makes it easy for me to follow. 7 All the instructions are displayed clearly. B. CONTENTS 1 2 3 4
8 I understand all the objectives clearly. 9 I understand the ideas conveyed.
10 The ideas are presented in an interesting manner. 11 All the instructions are easy to understand. 12 I can carry out the instructions in this module. 13 I can answer the questions in the activities easily. 14 I can answer the questions in the self-assessment. 15 The feedback section can help me identify my mistakes. 16 The language used is easy to understand. 17 The way the module is written makes it interesting to read. 18 I can follow this module easily. 19 Each unit helps me understand the topic better.
20 I have become more interested in the subject after using this module.
download@http://modul2poli.blogspot.com
-
CURRICULUM GRID
The curriculum grid of this module is based on the curriculum used by Malaysian polytechnics.
No. TOPIC UNIT Total Hours
1
Basic Concept And Problem Solving Programming
1
( 2 H)
2 Hours
2
Introduction To The Concept And Basic Instruction Programming C++
2
( 2 H)
3
( 2 H)
4 Hours
3
Data Types, Operator And Expression
4
( 2 H )
2 Hours
4
Logical Structure Types And Basic Instructions
5
( 2 H )
2 Hours
5
Preprocessor and Header File
6
( 2 H )
2 Hours
6
Writing Programmed in Programming C++
7
( 2 H )
2 Hours
7
Introduction To Visual Basic
8
( 2 H )
9
( 2 H )
4 Hours
8
Writing Programmed Using Visual Basic
10
( 2 H )
2 Hours
download@http://modul2poli.blogspot.com
-
UNIT 1 Basic Concept And Problem Solving in Programming
1.0 Programming Basic Concept
1.1 Definition of Programming
1.2 The components of programmed structure
1.2.1 Declaration
1.2.2 Input
1.2.3. Storage
1.2.4. Operation
1.2.5. Control
1.2.6. Output
1.3 Identifying steps in programming
1.3.1. Definition and analyze
1.3.2. Planning user variables
1.3.3. Drawing Flowchart.
1.3.4. Program Writing
1.3.5. Testing and debugging the programmed
1.3.6. Documentation the programmed
UNIT 2 Introduction To The Concept And Basic Instruction of
Programming C++
2.0 Introduction to C++ Program.
2.1 C++ Program Characteristics .
2.1.1 Comments
2.1.2 Header Files
2.1.3 Functions
2.2. Basic Input, Output and Format Code
2.2.1 Console Output (cout)
2.2.2 Console Input (cin).
2.2.3 Format Codes (Backslash Character Constant).
download@http://modul2poli.blogspot.com
-
UNIT 3 Introduction To The Concept And Basic Instruction of
Programming C++
3.0 Introduction The Technique To Develope C++ Programming .
3.0.1. Alogarithm
3.0.2 Flowcharts
3.0.3 Pseudocode
3.0.4 Structure chart.
3.1 Using Algorithm And Flowchart In Programming:
3.1.1 Algorithm
3.1.2. Flowchart
UNIT 4 Data Types, Operator And Expression
4.0 Introduction to data types, operator and expression in
C++ Programming.
4.1 Basic data types
4.1.1 Integer - Int
4.1.2 Character - char
4.1.2 Floating Point - float and double.
4.2 Declaring the constant
4.2.1 Integer Constant
4.2.2 Character and string Constant
4.3 Declaring Variables
4.4 The Operators
4.4.1 Arithmetic Operators
4.4.2 Relational Operators
4.4.3 Logical Operators
4.5 The Expression
UNIT 5 Logical Structures And Basic Instructions
5.0 Introduction to logical structures
5.1 Logical structures and basic instructions:
download@http://modul2poli.blogspot.com
-
5.1.1 Sequence structure
5.1.2 Selection structure Simple If, If-Then-Else, Case
5.1.3 Repetition structure For, While, Whiledo
5.1 Compiles and Runs Program
UNIT 6 Preprocessor and Header Files
6.0 Introduction to pre-processor and header files
6.1 Preprocessor statement.
6.1.1 #include
6.1.2 #define
6.2 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 iostream.h
UNIT 7 Writing Programmed in Programming C++
7.0 Simple programming
7.1 Even Odd
7.2 Grade
7.3 Student List
7.4 Bubble Sort
UNIT 8 Introduction To Visual Basic
8.0 Introduction To Visual Basic
8.1 Visual Basic Enviroment
8.2 Basic Project structure
8.3 The User Interface
8.3.1 Toolbox, project and properties windows .
8.3.2 Design and modify the Toolbox object properties.
download@http://modul2poli.blogspot.com
-
8.4 Save and Run the project.
UNIT 9 Introduction To Visual Basic
9.0 Introduction
9.1 Procedure Events
9.2 Create object an event procedure
9.3 Using a simple Visual Basic statement
9.3.1 Declaration
9.3.2 Sequence
9.3.3 Selection
9.3.4 Repetition
UNIT 10 Writing Programmed Using Visual Basic
10.0 Simple application programmed
download@http://modul2poli.blogspot.com
-
MODULE GUIDELINES
To achieve maximum benefits in using this module, students must follow the instructions carefully and complete all the activities. 1. This module is divided into 10 units. 2. Each page is numbered according to the subject code, unit and page number.
B3062 / UNIT 1 / 5
Subject Unit 1 Page Number 5 3. The general and specific objectives are given at the beginning of each unit. 4. 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. You have to follow the units in sequence. 6. You may proceed to the next unit after successfully completing the unit and
you are confident of your achievement.
download@http://modul2poli.blogspot.com
-
GENERAL AIMS This module is prepared for students in the third semester who are following the Certificate/Diploma programmes in Malaysian Polytechnics. It aims to expose students to the Programming concept in each unit and to lead them towards self-directed learning or with guidance from their lecturers.
PREREQUISITE SKILLS AND KNOWLEDGE The prerequisite for this module is at least the have to know how to used the computer. GENERAL OBJECTIVES
At the end of this module, students should be able to: 1. Understand the concept of program characteristics and steps in Developing
Program 2. know the characteristics and using instructions of C++ program basic language 3. introduce techniques used in program design 4. introduce and use the data types, operator and expression in C++
programming. 5. understand the logical structure types and basic instruction refers to the order of
execution of instructions in program. 6. understand the function of preprocessor directive and header file. 7. write C ++ program 8. understand the basic concept of Visual Basic 9. understand the basic concept of Visual Basic 10. develop a simple Visual Basic program 11. understanding basic structure of project. 12. construct user interface 13. writing the programmed using windows code 14. construct simple application programmed in Visual Basic.
download@http://modul2poli.blogspot.com
-
TEACHING AIDS AND RESOURCES NEEDED
1. Overhead Projector (OHP) 2. LCD Projector 3. Computer
REFERENCES
1. William H. Murray III, Chris H. Pappas, Borland C++ - Depth, Osborne-Mc Graw Hill.
2. Herbert Schildt, The Complete Reference Borland C++, Osborne Mc Graw Hill
3. P. Sellapan, (1994).C++ Through Examples (Includes Object-Oriented Programming),Federal Publication Sdn. Bhd.
4. M Thilla,(2002). C++ A Simplified Beginners Approach, Venton Publishing (M) Sdn. Bhd.
6. Brian Siler and Jeff Sport(1998).Special Edition Using Visual Basic, QUE Corporation.
7. Phil Feldman, Roger Jennings et al, Using Visual Basic, QUE Corporation 8. David I. Schneider (1999). An Introduction To Programming Using Visual
Basic 6.0- fourth edition. Practice Hall. 9. Dr. P. Sellappan. (2000). Programming In Visual Basic 6- first edition.
Sejana Publishing.
download@http://modul2poli.blogspot.com
-
Basic Concept And Problem Solving in Programming E3062/1/1
Basic Concept and Problem Solving in Programming
OBJECTIVES
General Objective : To Understand the Concept of Program Characteristics and Steps in Developing Program
Specific Objectives : At the end of the unit you will be able to :
define what is a program.
explain the meaning of program structure.
discuss steps in programming
UNIT 1
download@http://modul2poli.blogspot.com
-
Basic Concept And Problem Solving in Programming E3062/1/2
1.0 Basic concept of Programming
Before we start writing our own programs let us examine some important
characteristics of well-written computer programs. Basically these apply to
any programming language that provide a useful set of guidelines.
a. Integrity. This refer to the accuracy of the calculations since it will be
meaningless if calculations are not carried out correctly.
b. Clarity. This refer to the overall readability of the program, with
particular emphasis on its underlying logic. If a program is clearly
written, it should be possible for programmer to follow the program logic
with ease.
c. Simplicity. The clarity and accuracy of a program are usually enhanced
by keeping things as simple as possible, consistent with the overall
program objectives.
d. Efficiency. This is concerned with execution speed and efficient memory
utilization.
e. Modularity. Many programs can be broken down into a series of
identifiable subtask that enhances accuracy and clarity of a program and
facilitates future program alterations.
f. Generality. Usually we will want a program to be as general as possible,
within reasonable limits. A considerable amount of generality can be
obtained with very little additional programming effort.
INPUT
download@http://modul2poli.blogspot.com
-
Basic Concept And Problem Solving in Programming E3062/1/3
1.1 Definition of program
A set of instructions that tells the computer what to do is called a program.
For example, a word processor is a program written in computer language
like C++, that tells the computer what to do when you type in a letter.
1.2 The components of program structure.
1.2.1 Declaration A declarations associates a group of variables with a specific data
type. All variables must be declared before they can appear in
excutable statements.
Example :
int a, b, c;
float root1, root2;
char flag, text[80]
1.2.2 Input A set of information called data will be entered into the computer
from keyboard, floppy disk, hard disk etc. and stored in a portion of
the computer memory. This input which is an input to the computer
will then be processed to produced the desired result.
1.2.3 Storage Every piece of information are stored within the computers memory
which is encoded as some unique combination of zeros and ones.
Small computers have memories that are organized into 8-bit
multiples called bytes. Large computer have memories that are
download@http://modul2poli.blogspot.com
-
Basic Concept And Problem Solving in Programming E3062/1/4
organized into words rather than bytes. Computers also employ
auxiliary storage e.g. disks in addition to their primary memories
which allowed information to be stored permanently and can be
physically disconnected when not in use.
1.2.4 Operation There are two different ways computer can be utilized by many
different users. These are batch mode and the interactive mode. In
batch mode of operation the program and the data are typed into the
computer and stored within computers memory and processed in its
proper sequence. Large quantities of information can be transmitted
into and out of the computer without the user present while the job
being processed. Batch processing can be undesirable for simple jobs.
In interactive mode the user and the computer are able to interact with
each other during computational session.
1.2.5 Control Program control refers to the order of execution of instructions in a
program. The instruction can be executed sequentially one by one,
from top downwards or non sequential execution of program
instruction. Most real life problems require some kind of decision
making to take a certain course of action. This means that instruction
or a whole block of instructions can be executed, repeated or skipped.
1.2.6 Output The processed data which produced certain result is known as the
output. The output data will be presented in a sheet of paper through
the printer or display on a monitor.
download@http://modul2poli.blogspot.com
-
Basic Concept And Problem Solving in Programming E3062/1/5
Activity 1A
TEST YOUR UNDERSTANDING BEFORE YOU CONTINUE WITH THE
NEXT INPUT!
1.1 List the characteristics of a well planned program.
1.2 What is a program?
1.3 State the difference between batch mode and interactive mode operation
download@http://modul2poli.blogspot.com
-
Basic Concept And Problem Solving in Programming E3062/1/6
Feedback To Activity 1A
1.1 Integrity, Clarity, Simplicity, Efficiency, Modularity, Generality.
1.2 A set of instructions that tells the computer what to do is called a program.
1.3 In batch mode of operation, the program and the data are typed into the computer
and stored within computers memory and processed in its proper sequence.
Large quantities of information can be transmitted into and out of the computer
without the user present while the job being processed. Batch processing can be
undesirable for simple jobs. In interactive mode the user and the computer are
able to interact with each other during computational session.
download@http://modul2poli.blogspot.com
-
Basic Concept And Problem Solving in Programming E3062/1/7
1.3 Identifying steps in programming
In solving problems of developing program, software development method is
used. It consists of several steps which is known as software life cycle, these
are:
1. Defining and analyzing problems
2. Planning of variables
3. Drawing of flowchart
4. Program writing
5. Testing and debugging program
6. Documentation of program.
Process of designing program can be divided into two phases mainly the
problem solving phase and implementation phase. The problem solving
phase consist of steps 1 through 3 and implementation phase involved steps 4
and 5. While in step 6, documentation is done throughout the process of
designing program.
1.3.1 Defining and analyzing problems Programming begin with a specification of problems. This steps is to
identify and understand what are the problems to resolve. The
problems must be clearly define, explicit and the requirements in
INPUT
download@http://modul2poli.blogspot.com
-
Basic Concept And Problem Solving in Programming E3062/1/8
resolving it. Analyzing the problems will determine the input, output
and information required to solve these problems, as follows:
a. input data to be processed
b. output the desired result
c. the constraint and additional features in resolving the
problems
d.
1.3.2 Planning of variables
Variables are simply references to memory locations. A well plan use
of variables will produce an efficient execution of program in terms
of speed and memory utilization.
1.3.3 Drawing of Flowchart Flowchart represents algorithm in graphic form comprising of
geometrical symbols which is interrelated by line of flow.
1.3.4 Program writing In the design of program it should be written as simple as possible.
The main objective is to give a clear, readable programs through an
orderly and disciplined approach to programming.
1.3.5 Testing and debugging program Once the program has been written it must be compiled and executed.
This is accomplished by an editor and compiler. An editor lets us type
a program, makes changes and save it to a file. The compiler then
translates the program into a form that the computer can read. Once
the program has been compiled and executed the presence of errors
will be readily apparent. Syntactic and execution errors usually result
in the generation of error when compiling or executing a program.
Error of this type is usually quite easy to find and correct. Much more
difficult to detect are logical errors since the output resulting from
download@http://modul2poli.blogspot.com
-
Basic Concept And Problem Solving in Programming E3062/1/9
logically incorrect program may appear to be error free. Thus a good
bit of probing may be required which is known as logical debugging.
1.3.6 Documentation of program Program must be documented for future references and maintenance
process. A well documented program will make it easier for the
original programmer or other programmer to follow the program logic
and design. Program document should consist of :
1. An accurate specification of requirement
2. Detail input, output, constraint and formula for the above
problems
3. Algorithm in the form of flowchart or pseudocode
4. Program source complete with comment
5. Sample program which had been run and executed and the
tested data.
6. Guideline on how to use the program.
download@http://modul2poli.blogspot.com
-
Basic Concept And Problem Solving in Programming E3062/1/10
Activity 1B
TEST YOUR UNDERSTANDING BEFORE YOU CONTINUE WITH THE
NEXT INPUT!
1.4 State the steps in developing program.
1.5 State the components of documenting a program.
1.6 What is a flowchart?
download@http://modul2poli.blogspot.com
-
Basic Concept And Problem Solving in Programming E3062/1/11
Feedback To Activity 1B
1.4 i Defining and analyzing problems
ii Planning of variables
iii Drawing of flowchart
iv Program writing
v Testing and debugging program
vi Documentation of program.
1.5 i An accurate specification of requirement
ii Detail input, output, constraint and formula for the above
problems
iii Algorithm in the form of flowchart or pseudo code
iv Program source complete with comment
v Sample program which had been run and executed and the
tested data.
vi Guideline on how to use the program.
1.6 Flowchart represents algorithm in graphic form comprising of geometrical
symbols which is interrelated by line of flow.
download@http://modul2poli.blogspot.com
-
Basic Concept And Problem Solving in Programming E3062/1/12
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
-
Basic Concept And Problem Solving in Programming E3062/1/13
1.
SELF-ASSESSMENT
You are approaching success. Try all the questions in this self-assessment section
and check your answers with those given in the Feedback on Self-Assessment 1
given on the next page. If you face any problems, discuss it with your lecturer.
Good luck.
Question 1-1
a) Briefly describe the components of program structure below.
i. Declaration
ii. Input
iii. Output
Question 1-2
a) Explain the steps taken in testing and debugging of program.
Question 1-3
a) Why are documentation of programs important?
download@http://modul2poli.blogspot.com
-
Basic Concept And Problem Solving in Programming E3062/1/14
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
-
Basic Concept And Problem Solving in Programming E3062/1/15
result in the generation of error when compiling or executing a program. Error of this
type is usually quite easy to find and correct. Much more difficult to detect are
logical errors since the output resulting from logically incorrect program may appear
to be error free. Thus a good bit of probing may be required which is known as
logical debugging.
Question 1-3
It is important to document program for future references and maintenance process.
A well documented program will make it easier for the original programmer or other
programmer to follow the program logic and design.
CONGRATULATIONS!!!!..May success be with you always.
download@http://modul2poli.blogspot.com
-
Introduction To The Concept and Basic Instruction Of Programming C++
E3062/2/1
Introduction To The Concept And Basic Instruction Of Programming C++
OBJECTIVES
General Objective : To know the characteristics and using instructions of C++ program basic language
Specific Objectives : At the end of the unit you will be able to :
state what is the header file.
state what is the statement main ( ).
state and write comment line using backslash symbol
define the function of input and output statement
UNIT 2
download@http://modul2poli.blogspot.com
-
Introduction To The Concept and Basic Instruction Of Programming C++
E3062/2/2
2.0 Introduction to C++ program
To make C++ work for you, you must be able to write C++ program. To give
C++ instructions to a computer, you will need and editor and a C++
compiler. An editor lets you type a C++ program, make changes and save it
in a file. The compiler then translate your C++ program into a form that your
computer can read. Then finally, you will be able to run your program.
To get started, we introduce in this chapter a simple C++ program and then
go on to briefly explain the various parts that make up a C++ program.
INPUT
Information: C++ is a general purpose programming language developed at Bell Labs by Bjarne Stroustrup in mid-1980s. It is basically an extension of the C language developed by Brian Kernighan and Dennis Ritche (also of Bell Labs). C++ incorporates almost all the features of C but adds a lot more making it one of the most powerful and versatile programming languages available today.
download@http://modul2poli.blogspot.com
-
Introduction To The Concept and Basic Instruction Of Programming C++
E3062/2/3
Getting Started : Example of C++ program
Program 2.0
2.1 C ++ Program Characteristics
Let us examine the program in detail. C++ program is made of a few
components. They are:
2.1.1 Comments
Comments are used to insert remarks into the source code help to
explain about what the program does. In C++, comments can be place
anywhere in the programs. It can be used to include the details of the project
and the programmer who wrote or modified the code.
There are two types of comment used. They are:
/* This is a program that computes the sum of two integer numbers */ #include // This is a preprocessor main( ) // include directive { int x, y, sum; cout > x; // Input from console cout>y; sum = x + y; // Adding x and y cout
-
Introduction To The Concept and Basic Instruction Of Programming C++
E3062/2/4
a. Multi-line Comment
This type of comment is begins with a /* (slash followed by an asterisk)
symbol and ended with a */ (asterisk followed by an slash) symbol.
This type of comment is good to be used when comments written are
longer than 1 line.
Example:
b. Single line Comment
This type of comment is used with the // (double slash) symbol and it
stops at the end of that particular line.
This type of comment can be used when the remark is only 1 line in
length.
Example:
2.1.2 Header Files
Header files contain information that is required to run a program. It
is a pre written and tested function that comes together with the compiler and
is available for the use of the programmers. The format or structure for using
the header file is by using the #include directive. The second line in our
program 2.1 #include is called an include preprocessor
directive. As the file is placed before program the program proper , it is
called a header file (with the file extension .h)
/* This is a program that computes the sum of two integer numbers */
// This is a preprocessor
download@http://modul2poli.blogspot.com
-
Introduction To The Concept and Basic Instruction Of Programming C++
E3062/2/5
Example :
2.1.3 Functions
A function is a block of statements that is part of a large programme.
a. Function main( )
A C++ program must have at least the function main( ). Every C++
function, including main( ), must have a body enclosed in braces { }.
b. Function block { }
The function body, also called block can be of any size. The function always
ends with the return command.
{ - begin block
} - end block
Example
#include
main ( ) { }
download@http://modul2poli.blogspot.com
-
Introduction To The Concept and Basic Instruction Of Programming C++
E3062/2/6
Activity 2A
TEST YOUR UNDERSTANDING BEFORE YOU CONTINUE WITH THE NEXT INPUT!
2.1 What is the only function all C++ programs must contain?
A. start() B. system() C. main() D. program()
2.2 What punctuation is used to signal the beginning and end of code blocks?
A. { } B. -> and
-
Introduction To The Concept and Basic Instruction Of Programming C++
E3062/2/7
Feedback To Activity 2A
2.1 C. main() 2.2 A. { } 2.3 C. /*Comments*/ 2.4. C. causes action to be performed when the program is executed
download@http://modul2poli.blogspot.com
-
Introduction To The Concept and Basic Instruction Of Programming C++
E3062/2/8
2.2. Basic Input, Output and Format Code
In the iostream C++ library, standard input and output operations for a program are supported by two data streams:
a. cin (console input) for input normally assigned to the keyboard b. cout (console input) for output normally directed to the screen.
By handling these two streams you will be able to interact with the user in your programs since you will be able to show messages in the screen and to receive his/her input from the keyboard. 2.2.1. Output (cout ) The function cout is used with the overloaded operator
-
Introduction To The Concept and Basic Instruction Of Programming C++
E3062/2/9
2.2.2 Input ( cin ) Handling the standard input in C++ is done by applying the overloaded operator of extraction ( >> ) on the cin stream, followed by the variable that will store the data that is going to be read. It follows the following format: 2.2.3 Format Code ( Backslash Character Constant) The backslash character constant is also known as the Escape Sequence. Certain characters such as the backspace and carriage return are not printable characters and these characters pose special problems when printing using text editor. The backslash character constant is used together with other character constant when such problems are encountered. Table 2.0: Format Code
Code Meaning \b Backspace \f Form feed \n Newline \r Carriage return \t Horizontal tab \ Double quote \ Single quote character \\ Backslash \v Vertical tab \a Alert
cin >> x ; // x is a variable
cin >> address ; // address is a variable
download@http://modul2poli.blogspot.com
-
Introduction To The Concept and Basic Instruction Of Programming C++
E3062/2/10
Example,
The output would be: What is your name? Age? This example shows the use of the new line (\n) character constant to print characters on the next line.
cout
-
Introduction To The Concept and Basic Instruction Of Programming C++
E3062/2/11
Activity 2B
TEST YOUR UNDERSTANDING BEFORE YOU CONTINUE WITH THE NEXT INPUT!
2.5 Determine which of the following are valid output;. If valid what is the output
a. cout
-
Introduction To The Concept and Basic Instruction Of Programming C++
E3062/2/12
Feedback To Activity 2B
2.5 a. Valid
b. valid
c. Not valid
d. valid
e. valid
2.6 a. valid b. not valid c. not valid d. valid e. not valid
ABC
A B C
ABC
ABC
download@http://modul2poli.blogspot.com
-
Introduction To The Concept and Basic Instruction Of Programming C++
E3062/2/13
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
-
Introduction To The Concept and Basic Instruction Of Programming C++
E3062/2/14
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 main() {
char name[20], gender ; // Variable name can take up to cout>name ; cout>gender; // Test whether gender is male if (gender == M) cout
-
Introduction To The Concept and Basic Instruction Of Programming C++
E3062/2/15
Question 2-2
a. State the errors, if any, in the following programs:
#include main{} (
int m, n; float q; m=5; n=2; q=m/n; cout>> \n>>q; m=m+n+q; out
-
Introduction To The Concept and Basic Instruction Of Programming C++
E3062/2/16
Feedback To Self-Assessment 2
Have you tried the question????? If YES, check your answer now:
Question 2-1 Here is a sample output, after running the program.
Enter your name:Abu Enter your gender ( M or F ): M Goodday, Mr. Abu Question 2-2 Line 2 main{ } - main () not main{ } Line 3 ( - the correct begin block is { Line 9 > Line 11 out - the correct console output is cout Line 13 ) - the correct end block is }
CONGRATULATIONS!!!!..May success be with you always.
download@http://modul2poli.blogspot.com
-
Introduction To The Concept and Basic Instruction Of Programming C++
B3062/3/1
Introduction To The Concept And Basic Instruction Of Programming C++
OBJECTIVES
General Objective : To introduce techniques used in program design. Specific Objectives : At the end of the unit you will be able to :
state the techniques of program designing tools
briefly explain the techniques of designing program by
different designing tools
use algorithm and flowchart to develop computer program
UNIT 3
download@http://modul2poli.blogspot.com
-
Introduction To The Concept and Basic Instruction Of Programming C++
B3062/3/2
3.0 Introduction The Technique To Develope C++ Programming
The first step in writing instructions to carry out a task is to determine what the
output should be that is, what the task should produce. The second step is to
identify the data, or input, necessary to obtain the output. The last step is to
determine how to process the input to obtain the desired output. The general process
of writing program is to analyze the problem, design and plan the solution, coding
INPUT
A recipe provides good and simple example of a plan. The ingredients and the amounts are determined by what is to be baked. That is the output determines the input and processing. The recipe or plan reduces the number of mistakes you might make. Many programmers particularly beginners frequently try to write without first making a careful plan. Step-by step process will enable you to use your time efficiently and help you design error free program that produced the desired output
download@http://modul2poli.blogspot.com
-
Introduction To The Concept and Basic Instruction Of Programming C++
B3062/3/3
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 input-
process-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.
i. Request price of item (Input)
ii. Value of discount = rate of discount * price (Process)
iii. Price after discount = price - value of discount (Process)
iv. Display of discount price (Output)
3.0.2 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
-
Introduction To The Concept and Basic Instruction Of Programming C++
B3062/3/4
Symbol
Name
Meaning
Flowline Used to connect symbols and indicate the flow of logic
Terminal
Used to represent the beginning (start) or the end (End) of a task
Input/output
Used for input and output operations, such as reading and printing. The data to be read or printed are describe inside
Processing
Used for arithmetic and data-manipulation operations. The instruction are listed inside the symbol
Decision
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
Connector
Used to join different flowline
Offpage connector
Used to indicate that the flow chart continues to a second page
download@http://modul2poli.blogspot.com
-
Introduction To The Concept and Basic Instruction Of Programming C++
B3062/3/5
Predefined Process
Used to represent a group of statements that perform one processing task.
Annotation
Used to provide additional information about another flowchart symbol
The main advantage of using a flowchart to plan a task is that it provides a pictorial
representation of the task, which makes the logic easier to follow. We can clearly see
each and every step and how it is connected to the next step. For example lets look at the
discount sales program.
Figure 3.2 Flowchart for the discount sale
(An Introduction To Programming Using Visual Basic 6.0- David I. Schneider),
Start
Read price value
Calculate discount value = price * discount rate
Price of item after discount = price - discount value
Display price after discount
End
input
process
process
output
download@http://modul2poli.blogspot.com
-
Introduction To The Concept and Basic Instruction Of Programming C++
B3062/3/6
The major disadvantage with flowcharts is that when a program is very large, the
flowcharts may continue for many pages, making them difficult to follow and modify.
3.0.3 Pseudocode
Pseudocode is an abbreviated version of actual computer code. The
geometric symbols used in flowcharts are replaced by English-like statements that
outline the process. Pseudocode looks more like computer code than does flowchart.
It allows programmer to focus on the steps required to solve a problem rather than on
how to use computer language.
The programmer can describe the algorithm in computer language form
without being restricted by the rules of the computer language. When the
pseudocode is completed it can be easily translated into any computer language.
The following is pseudocode for the price of discount sales item problem:
Program: determine the price of discount item on sale.
Read price (Input)
Set the value of discount = rate of discount * price entered (Process)
price of discount item = price of item - value of discount (Process)
Display the price after discount (Output)
Pseudocode has several advantages. It is compact and probably will not
extend for many pages as flowcharts commonly do. Also the plan looks like the code
to be written and preferred by many programmers.
3.0.4 Structure Chart
Structure chart is also known as input-process-output or hierarchy chart
shows the overall program structure. It refers to planning diagrams similar to a
download@http://modul2poli.blogspot.com
-
Introduction To The Concept and Basic Instruction Of Programming C++
B3062/3/7
companys organization chart. Structure chart depicts the organization of program
but omit the specific processing logic. They describe what each part, or module, of
the program does and they show how the modules relate to each other. Each module
may be subdivided into succession of sub-modules that branch out under it. The
charts are read from top to bottom and left to right. Figures 3.3 shows an example of
a structure chart. This price of discount item problem was solved by a series of
instructions to read data, perform calculations, and display results. Each steps was in
sequence; that is we moved from one line to the next without skipping over any
lines.
The main benefit of structure charts is in the initial planning program. We
break down the major parts of a program so we can see what must be done in
general. From this point, we can then refine each module into more detailed plans
using flowcharts.
Price of discount item program
Calculate price Read price Display discount price discount value = price * rate of discount discount price = price discount value
Figure 3.3: Structure Chart
(An Introduction To Programming Using Visual Basic 6.0- David I. Schneider),
download@http://modul2poli.blogspot.com
-
Introduction To The Concept and Basic Instruction Of Programming C++
B3062/3/8
Activity 3A
TEST YOUR UNDERSTANDING BEFORE YOU CONTINUE WITH THE NEXT INPUT!
Question 3.1
Draw the standard flowcharts symbol for
i. input/output ii. processing iii. decision
Question 3.2
State the 3 most popular programming tools
Question 3.3
What is an algorithm?
download@http://modul2poli.blogspot.com
-
Introduction To The Concept and Basic Instruction Of Programming C++
B3062/3/9
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
-
Introduction To The Concept and Basic Instruction Of Programming C++
B3062/3/10
3.1 Using Algorithm and Flowchart in programming
3.1.1 Class average Algorithm
Problem: Calculate and report the grade-point average for a class.
Discussion: The average grade equals the sum of all grades divided by
number of students. We need a loop to read and then add (accumulate) the
grades for each student in the class. Inside the loop, we also need to total
(count) the number of students in the class.
Input: Students grades
Processing: Find the sum of the grades; count the number of students;
calculate average grades = sum of grades / number of students.
Output: Average grade
INPUT
download@http://modul2poli.blogspot.com
-
Introduction To The Concept and Basic Instruction Of Programming C++
B3062/3/11
3.1.2. Class Average Flowchart
Start
Initialize counter and
sum to 0
Are There more
Data?
Get next grade
Increment counter
Add grade to sum
Set average to sum/counter
Display average
End
No
Start
Yes
counter and sum start at 0
read next grade
add 1 to counter
accumulate sum of grades
find the average
display the answer
download@http://modul2poli.blogspot.com
-
Introduction To The Concept and Basic Instruction Of Programming C++
B3062/3/12
Activity 3B
TEST YOUR UNDERSTANDING BEFORE YOU CONTINUE WITH THE NEXT INPUT!
Question 3.1
You are to plan a program to sum two integer entered by user and display the result
of the summation by using the flowchart technique, from the following pseudocode;
1. Print text Enter first number 2. Read first number 3. Print text Enter second number 4. Read second number 5. Calculate sum of two number 6. Print the sum of two number
download@http://modul2poli.blogspot.com
-
Introduction To The Concept and Basic Instruction Of Programming C++
B3062/3/13
Feedback To Activity 3B
Question 3.1
Start
Print text Enter first number
Calculate sum of two number
Display the sum of two number
End
Read first number
Print text Enter second number
download@http://modul2poli.blogspot.com
-
Introduction To The Concept and Basic Instruction Of Programming C++
B3062/3/14
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
-
Introduction To The Concept and Basic Instruction Of Programming C++
B3062/3/15
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
-
Introduction To The Concept and Basic Instruction Of Programming C++
B3062/3/16
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
-
Introduction To The Concept and Basic Instruction Of Programming C++
B3062/3/17
CONGRATULATIONS!!!!..May success be with you always.
Start
Print text Enter yearly income
Read yearly income
Calculate income tax return = yearly income * 0.025
Display income tax return
End
More than 50000.00?
YesNo
Calculate income tax return = yearly income * 0
download@http://modul2poli.blogspot.com
-
Data Types, Operator And Expression
E3062/4/1
Data Types, Operator And Expression
OBJECTIVES
General Objective : To Introduce and Use the data types, operator and
expression in C++ Programming.
Specific Objectives : At the end of the unit you will be able to :
describe the essential data type : int,char,float and double declare constant and variable able to use constant and variable explain the arithmetic operator types explain the arithmetic, relational and logical operator types able to used operators to construct expression
UNIT 4
download@http://modul2poli.blogspot.com
-
Data Types, Operator And Expression
E3062/4/2
4.0 INTRODUCTION TO DATA TYPES, OPERATOR AND
EXPRESSION IN C++ PROGRAMMING. The C++ character set includes the keyboard characters, namely the uppercase letter A - Z, the lower letters a z , the digits 0 9 , and other special characters (such as!, #, [, ] , ,&,
-
Data Types, Operator And Expression
E3062/4/3
Example of valid and invalid identifiers: Table 4.1 Valid Identifier Invalid Identifier Comment x x Illegal character Sumx2 2sumx Illegal first character Hourly_rate Hourly-rate Illegal character - name name@ Illegal character @ GROSS_PAY GROSS PAY Illegal blank
C++ identifiers are case-sensitive, meaning, lower and uppercase letter in identifiers are treated as different characters. This means we cannot freely mix the lower and uppercase letter to refer to the same identifier. For example, identifiers HOURLY_RATE, Hourly_Rate, Hourly_rate and hourly_rate are all different, they refer to different memory locations. Variables are identifiers whose value may change during the course of execution of a program. Keywords in C++, also called reserved words, have standard, predefined meanings and must be used only for their intended purpose. Programmers therefore should not use these keywords as identifiers.
4.1 Basic Data Types
There are four main data types in programming C++
i. int ii. char iii. double iv. 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
-
Data Types, Operator And Expression
E3062/4/4
Table 4.2 Data Type C++ Keyword Bits Range Integer int 16 -32768 to 32767 Long integer long 32 -42994967296 to 4294967295 Short integer short 8 -128 to 127 Unsigned integer unsigned 16 0 to 65535 character char 8 0 to 255 Floating point float 32 Approximately 6 digits of
precision Double floating point
double 64 Approximately 12 digits of precision
4.1.1 Integer data types - int
Key words int is use to declare variable integer number
Syntax int name_identifier example : 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
-
Data Types, Operator And Expression
E3062/4/5
4.1.2 Character data types - char
Storage word char is use to declare variable character
Syantax char name_identifier example: char huruf;
char lagi; This declaration means that variable lagi and huruf will given a memory storage for character data type. Character variable store printed data or un printed data in character set of computer includes;
small and capital letters decimal digits (0-9) special character This character represent in 1 byte (8 bit) computer memory. Internal
representative for character value decided by encoder character (ASCII or EBCDIC) that is used in the computer.
4.1.3 Floating Point data types - float and double This type can store floating point in computer memory.
Syntax : double name_identifier Example: double pendapatan_bersih,cukai_pendapatan; double nilai;
Memory storage that use for variable pendapatan_bersih be able to store floating point data. But int and char data types only can be stored according to computer types. The three floating points data in C++ such as;
1. float 2. double 3. long double
download@http://modul2poli.blogspot.com
-
Data Types, Operator And Expression
E3062/4/6
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 data type identifier
4.2.1 Integer constant
Integer constant can be further categorized into four types-short integer, integer,unsigned integer and long integer. Examples of integer constants
Short integer constant: -99 -35 0 45 320
Integer constants: 9999 -1 0 555 32767
Unsigned integer constants: 1 256 1000 60000
Long integer constants: 222 0 33333 9999999
A constant can also be identified as being long by tagging a l or a L to
the end of the number, For example , the constants 212L and 323l. will be viewed by C++ as long constants.
download@http://modul2poli.blogspot.com
-
Data Types, Operator And Expression
E3062/4/7
4.2.2 Character and string Constants
A character constant is any character enclosed between two single quotation marks ( and ). When the several characters are enclosed between two double quotation marks ( and ), it is called a string. Examples of character and string constants;
i. Character constants:
$ * z G
ii. String constants: Name: Telephone No: Postcode:
iii. Floating Point Constants A floating point constant is a decimal number that contains the decimal point (.) or the exponent ( e or E ) or both. Here are some examples of floating point constants. 5.0 0.005 2000.0 987.123 5e-3 0.01e-2 0.2345E8 1.23E4
4.3 Declaring Variables
All variables in a program must be declared prior to their use. The declaration takes the form Type variable_list; Data types variable identifier
Examples of variable declarations. Int x, y, z; Short small_number; Long big_number; Unsigned positive_number;
Char ch; Float amount, rate;
download@http://modul2poli.blogspot.com
-
Data Types, Operator And Expression
E3062/4/8
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
-
Data Types, Operator And Expression
E3062/4/9
Activity 4A
TEST YOUR UNDERSTANDING BEFORE YOU CONTINUE WITH THE NEXT INPUT!
4.1 State 4 main data types and C++ keyword ? a. Data types__________________ Keywords___________ b. Data types__________________ Keywords___________ c. Data types__________________ Keywords___________ d. Data types__________________ Keywords___________ 4.2 Write an expression to declare constant and variable?
a. constant :________________________ b. variable: ________________________
download@http://modul2poli.blogspot.com
-
Data Types, Operator And Expression
E3062/4/10
Feedback To Activity 4A
4.1.
a. Data types: integer Keywords : int b. Data types : character Keywords: char c. Data types : double Keywords : double d. Data types : floating point Keywords ; float 4.2.
a. constant : const Int hourly_rate b. variable: Int a, b, c
download@http://modul2poli.blogspot.com
-
Data Types, Operator And Expression
E3062/4/11
4.4 The Operators C++ is very rich in built-in operators. Operators trigger some computations when applied to operands in an expression. There are several general classes of operators. But for now, we will present just the arithmetic, relational, logical and assignment operators.
4.4.1 Arithmetic Operators
There are seven arithmetic operators in C++ as shown in Table 4.3 Table 4.3
Operator Action - Subtraction + Addition * Multiplication / division
% Modulus division - Decrement
++ increment
INPUT 4
download@http://modul2poli.blogspot.com
-
Data Types, Operator And Expression
E3062/4/12
Examples of operation involving integer variables. With a=7 and b=2, the expression on the values on the right.
Table 4.4
Expression Value a b 5 a + b 9 a * b 14 a / b 3
a % b 1 a - - 6 a - - 3
Note: You can assign a positive or negative number to a variable by using a unary +
or - . Example:
a = -20 // assigns a a negative 20 b = +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
-
Data Types, Operator And Expression
E3062/4/13
Table 4.5
Operator Meaning < Less than Greater than >= Greater than or equal= = Equal ! = Not equal
The result of evaluation of a relational operation is either
true(represented by 1) or false (represented by 0). For example, if a = 7 and b = 5, then a < b yields 0 and a != b yields 1.
4.4.3 Logical Operators
There are three logical operators in C++ are shown in Table 4.6
Table 4.6
Operator Meaning && AND
|| OR ! NOT
The result of the logical operations on a and b are summarized as Table 4.7: Table 4.7
a
b
a | | b either a or b must be true
a&&b Both a and b Must be true
! a Produces the
opposite relation0 0 0 0 1 0 1 1 0 1 1 0 1 0 0 1 1 1 1 0
download@http://modul2poli.blogspot.com
-
Data Types, Operator And Expression
E3062/4/14
*Hierarchy of Operators The hierarchy of operator precedence form highest to lowest is summarized below: Table 4.8
Operator Category Operator Unary - - - + + Arithmetic multiply, devide, remainder + / % Arithmetic add and subtract + - Relational operators < >= Equality operators = = ! = Logical AND && Logical OR ||
4.5 The Expression Expression in C++ are formed by properly combining operators, variables and constants. We have already seen some examples of simple arithmetic and logical expression. As algebra, C++ expression can be complex. Parentheses can be used to force the order of evaluation. An expression may also contain spaces for readability. Examples of expressions.
Gross_pay deductions (basic_pay + hours * rate) (socso + premium + loan) (b * b 4 * a * c) > 0 (gender = = m) && (age > 20) (gender = = m || gender = = f ) && age >= 21
download@http://modul2poli.blogspot.com
-
Data Types, Operator And Expression
E3062/4/15
Activity 4B
TEST YOUR UNDERSTANDING BEFORE YOU CONTINUE WITH THE NEXT UNITS!
4.3 Classify the operators given below:
- , +, &&, ++ ,
-
Data Types, Operator And Expression
E3062/4/16
Feedback To Activity 4B
4.3.
a. arithmetic operators : - , + , ++ , * b. logical operators : && , ! c. Relational operators : = 21
download@http://modul2poli.blogspot.com
-
Data Types, Operator And Expression
E3062/4/17
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
-
Data Types, Operator And Expression
E3062/4/18
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
-
Data Types, Operator And Expression
E3062/4/19
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 > x >> y >> z; or cin >> x;
cin >> y; cin >> z;
e. hasil = x * y * z; f. cout > y >> z;
hasil = x * y * z; cout
-
Logical Structure Types And Basic Instruction
E3062/5/1
Logical Structures And Basic Instructions
OBJECTIVES
General Objective : To Understand the logical structure types and basic instruction refers to the order of execution of instructions in program.
Specific Objectives : At the end of the unit you will be able to :
describe the sequence structure describe the selection structure describe the Repetition structure execute instructions sequentially or line by line explain the program control structures write the simple program using program control structure
UNIT 5
download@http://modul2poli.blogspot.com
-
Logical Structure Types And Basic Instruction
E3062/5/2
5.0 Introduction To Logical Structure Logical structure or program control structures refer to the order of execution of
instructions in a program. So far, in all our examples, the instructions were executed
sequentially one by one, from the top downwards. However, most real life problems
require some kind of decision making, which involves comparing values, and based
on the comparison, to take a certain course of action. Hence, C++ provides structure
that will allow the non-sequential execution of program instructions. This means that
an instruction or a whole block of instructions can be executed, repeated or skipped.
5.1 Logical Structures And Basic Instructions C++ has a set of rich and powerful control structures (statements) that makes it a
popular language. Control structure generally fall into four categories but in this unit
we have to know only three of them, which are:
i. sequence structure
ii. selection structure
iii. repetition or iteration structure
INPUT
download@http://modul2poli.blogspot.com
-
Logical Structure Types And Basic Instruction
E3062/5/3
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 (S1) y = 10 (S2) Total = x * y (S3) cout
-
Logical Structure Types And Basic Instruction
E3062/5/4
In this form, the expression is first evaluated. If the expression evaluates to non-zero (meaning TRUE), the statement is executed; if it evaluates to zero (meaning FALSE), the statement following the if statement is executed. Again, it has one entry point and one exit point.
Figure 5.2 : If - Statement (Ref. C++ Through Examples-PSellapan)
Example 5.1:
If ( gred == A ) cout iVar2) cout
-
Logical Structure Types And Basic Instruction
E3062/5/5
The if statement checks to see if iVar1 is greater than iVar2. If iVar
is greater than iVar2 (which is true in this case), then the instruction is
executed and the output below is achieved.
20 is greater then 5
b. if else statement
The basic form of the if-else statement is :
In this form, the expression is first evaluated. If it evaluates to non-
zero, 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.
Figure 5.3 : If else Statement (Ref. C++ Through Examples-PSellapan)
if (expression) statement_1, else statement_2
x >10?
Print x
Increment x by 1
No
Yes
download@http://modul2poli.blogspot.com
-
Logical Structure Types And Basic Instruction
E3062/5/6
Example 5.3: if ( gred == E ) cout
-
Logical Structure Types And Basic Instruction
E3062/5/7
i. nested if else statement The basic form of the if-else statement is :
In this nested form, expression_1 is evaluated. If it is zero,
statement_4 is executed and the entire nested if statement is terminated; if
not, control goes to the second if and expression_2 is evaluated. If it is zero,
statement_3 is executed; if not, control goes to the third if and expression_3
is evaluated. If it is zero, statement_2 is executed; if not, statement_1 is
executed.
Example 5.5
if (expression_1) if (expression_2) if (expression_3)
statement_1; else
statement_2; else statement_3; else statement_4;
If (sex = M { if (age
-
Logical Structure Types And Basic Instruction
E3062/5/8
In the program, Example 5.5 there are multiplies if statements
used to evaluate the sex of a person whether the person is a male or female. Then, it is further tested on the age of the person to decide on the title used to address the person.
c. Switch statement
The switch statement is the multiple branch decision statement
is sometimes called the multiple-choice statement. The general form of the switch statement is :
The expression evaluates to an integer or character constants
and statement sequence is a block of statements.
Figure 5.4 : Switch Statement(Ref. C++ Through Examples-PSellapan)
Switch (expression) { Case constant_1; Statement sequence; break; case constant_2; statement sequence; break; . . default : statement sequence; }
Expression x = ?
y = x
y = x + 2
y = x + 1
x=1 x=2 default
download@http://modul2poli.blogspot.com
-
Logical Structure Types And Basic Instruction
E3062/5/9
Example 5.6
The sample output of the program:
Please key in grade (A-F) : C
Minimun marks is 40
In the example above, A,B,C and D are the possible values that can be
assigned to the variable cGrade.
In each case of the constants, A to D, a statement or sequence of statements
would be executed.
#include main() { char cGrade; cout > cGrade; switch (cGrade) { case A
cout
-
Logical Structure Types And Basic Instruction
E3062/5/10
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
-
Logical Structure Types And Basic Instruction
E3062/5/11
Activity 5A
TEST YOUR UNDERSTANDING BEFORE YOU CONTINUE WITH THE NEXT INPUT!
5.1 List 3 types of solution statement? i._________________________ ii._________________________ iii._________________________ 5.2 Define the basic form of the if statement and if-else statement? 5.3 What are the break and default statement are needed in the switch
statement ?
download@http://modul2poli.blogspot.com
-
Logical Structure Types And Basic Instruction
E3062/5/12
Feedback To Activity 5A
5.1 i. if statement ii. if else statement iii switch statement
5.2 i. if (expression) statement; ii if else (expression) statement_1, else statement_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
-
Logical Structure Types And Basic Instruction
E3062/5/13
5.1.3 Repetition (or Iteration) structure
The repetition (or iteration) structure permits a sequence of the instructions to
be executed repeatedly until certain condition is reached. The repetition
structure or loop in C++ comes in three forms while, do-while and for .
a) The while loop The while loop repeats the body of the loop as long as the loop condition
holds. The basic form of the while statement is as below:
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
INPUT
while (expression) statement;
download@http://modul2poli.blogspot.com
-
Logical Structure Types And Basic Instruction
E3062/5/14
Figure 5.5 : while loop
(Ref. C++ Through Examples-PSellapan) Example 5.7
b) The do-while loop
The do-while loop executes a statement as long as the loop condition holds. The basic form of the do-while statement as below:
is x >10?
x = x + 1
Yes
No
Print x
Do statement while (expression) ;
While ((cin>>amount) &&(amount > 0) && (amount
-
Logical Structure Types And Basic Instruction
E3062/5/15
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.
Figure 5.6 : do-while loop
(Ref. C++ Through Examples-PSellapan)
Example 5.8
is x >10?
x = x + 1
Yes
No
Print x
//Program to illustrate a do-while loop #include main() { int selection; do { cout
-
Logical Structure Types And Basic Instruction
E3062/5/16
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.
The expression part determines whether the loop execution should be continued. If the expression is zero (false), the for loop is terminated,
if it is not zero (true), the for statement is executed.
The incrementation part typically increments (or decrements) the loop counter variable. This is done after the for statement is executed. This
part, like the initialization part, can also include the incrementation of
other variables.
for (initialization; condition test; incrementation) { statements; }
download@http://modul2poli.blogspot.com
-
Logical Structure Types And Basic Instruction
E3062/5/17
Example 5.9 The example 5.9, given is a very short program and it is easy for us to
understand the for loop.
First, an integer variable is declared. Then, in the initialization part, the
variable, iNum is set to 1. For the condition checking, iNum is checked to see
whether it is equal to or less than 10. In each cycle of the loop, iNum is
incremented by 1. Once iNum reaches 10, the loop exits. We can see that the
program calculates the square of the first ten natural numbers.
Program output: 1 4 9 16 25 36 49 64 81 100
5.2 Compiles And Run Program
To run a C++ program, we must first create it, then compile it, then link it with other
modules ( or other compiled programs), and finally run it. You can create a C++
program using the C++ editor. The editor is like a word processor that allows you to
type, edit and save your program. The program you create is called the source
module.
#include main() { int iNum; for ( iNum =1; iNum
-
Logical Structure Types And Basic Instruction
E3062/5/18
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.
Figure 5.7 : Steps in running a program
(Ref. C++ Through Examples-PSellapan)
Tool Step Product
Editor
Compiler
Linker
Edit
Compile
Link
Run
Source module
Object module
Executable module
Result/Output
Library
download@http://modul2poli.blogspot.com
-
Logical Structure Types And Basic Instruction
E3062/5/19
Feedback To Activity 5B
TEST YOUR UNDERSTANDING BEFORE YOU CONTINUE WITH THE NEXT INPUT!
5.1 What are three loops of iteration statements? i._________________________ ii._________________________ iii._________________________
5.2 State the basic form of the for loop and write the part of program that uses a for statement?
5.3 What is the compiler ? 5.4 What is the linker?
download@http://modul2poli.blogspot.com
-
Logical Structure Types And Basic Instruction
E3062/5/20
Feedback To Activity 5B
5.1 i. while loop ii. do-while loop iii for loop
5.2 for loop form for (initialization; expression; incrementation) statement
Program that uses a for statement: for (i=1; i
-
Logical Structure Types And Basic Instruction
E3062/5/21
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
-
Logical Structure Types And Basic Instruction
E3062/5/22
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
-
Logical Structure Types And Basic Instruction
E3062/5/23
Feedback To Self-Assessment
** Please refer to your lecturer for checking purpose
** The feedback for this Self-assessment test is based on the students creativity as long as the output meets the criteria required by the question. The lecturer have to prepare a scheme or checklist as a guideline to check students response.
Try Your Best!!!
download@http://modul2poli.blogspot.com
-
Preprocessor and Header Files
E3062/6/1
Preprocessor and Header Files
OBJECTIVES
General Objective : To Understand the function of preprocessor directive and header file.
Specific Objectives : At the end of the unit you will be able to :
define the preprocessor and header file. explain the function of preprocessor and header file. write the preprocessor statements using #include and #define. define and use header file stdio.h, ctype.h, math.h, conio.h and
iostream.h in C++ program.
UNIT 6
download@http://modul2poli.blogspot.com
-
Preprocessor and Header Files
E3062/6/2
6.0 Introduction To Preprocessor and Header Files
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.
INPUT
Preprocessor directive and header file were talked about right from the beginning unit of this module. However, it is necessary to cover in more details as to see the various header file available for C++
download@http://modul2poli.blogspot.com
-
Preprocessor and Header Files
E3062/6/3
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:
or
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
# include file.h
# include
download@http://modul2poli.blogspot.com
-
Preprocessor and Header Files
E3062/6/4
looks for in the default directories where it is configured to look for the standard
header files.
In case that the file name is included enclosed between < > the file is directly
looked for in the default directories where the compiler is configured to look for
standard header files.
6.1.2 # define
The processor directive, #define, serves to generate what we call defined
constants or macros and whose form is the following example below.
#define name value
Its function is to define a macro called name that whatever it is found in some
p