principles of programming

advertisement
PRINCIPLES OF PROGRAMMING
USING
C++ LANGUAGE AND VISUAL BASIC
FOR APPLICATIONS
GETTING STARTED WITH C++
•
•
•
•
•
BRIEF HISTORY OF C to C++
C++ as a Programming Language
Running C++ Programs
Structure of a C++ Program
What is Computer Programming?
COMPUTER PROGRAMMING
• WHAT IS COMPUTER PROGRAMMING/CODING?
is the process of
writing
testing and
maintaining
the source code of computer programs.
COMPUTER PROGRAMMING:SOURCE CODE
• SOURCE CODE
THE source code is written in a
Programming Language
e.g. C++ language
Visual BASIC ( VB)
Visual BASIC for Applications (VBA)
SOURCE CODE
The process of writing the Source Code requires
expertise in many different subjects including
knowledge of
– the application domain
– algorithms to implement the desired behaviour
COMPUTER PROGRAMMING
Within software engineering,
computer programming ( the implementation)
is regarded as one phase in a software
development process.
SOFTWARE ENGINEERING
• Software Engineering
involves the
specification
development
management and
Evolution
Of software systems.
It is concerned with all aspects of software production, from the
early stages to use and evolution.
COMPUTER PROGRAMMING:METHODOLGY
• Methodology
–
–
–
–
–
–
Problem Definition
Requirement Analysis
Modeling/ Design
Implementation
Testing/ failure elimination ( debugging)
Documentation
COMPUTER PROGRAMMING: COMPILER
• COMPILER
A computer language has a compiler
a special software that must be installed on
the computer system to be used to do the
coding.
e.g. C++ language compiler e.g.
Dev-C++ (Bloodshed)
COMPUTER PROGRAMMING:SYNTAX
• SYNTAX
The Computer Language has
RULES
governing its
word usage and
puntuation
These RULES are called
the language’s SYNTAX
SYNTAX
NOTE:
Unless the SYNTAX is perfect
the computer cannot interpret the
programming language instruction at all.
COMPUTER PROGRAMMING
• TRANSLATORS
Programming Language uses a piece of
software
to
translate
the
specific
programming language instructions into
the computer’s on/off circuitry language or
machine language
TRANSLATORS
– Compiler or Interpreter
this is the language translation software
Function
it translates the program / instructions into the
machine language
It tells the programmer if he/she has used a
programming language correctly
TRANSLATORS
– Compiler or Interpreter :
SYNTAX Errors
During translation, instructions that do not
conform to the programming language’s
particular syntax or used incorrectly are detected
and highlighted as Syntax errors
TRANSLATORS
– Compiler or Interpreter :
SYNTAX Errors Correction
Syntax Errors are relatively easy to locate and
correct
The compiler or interpreter you use highlights
every syntax error.
You do the corrections by referring to the
language’s manual or library documentation.
Execution
– Logical Errors / BUGs / semantic errors
A program without syntax errors can be executed
on a computer
But it might not produce correct results.
Due to logical errors
– bad / incorrect logic or algorithm
– Instructions out of sequence
– Presence of Extraneous instructions
– Missing instructions
Execution
– Logical Errors / BUGs /semantic errors
Are much more difficult to
locate than syntax errors
Troubleshooting should be at the Design stage
i.e. Algorithm and flowchart
Execution
– RUN / EXECUTE
When all the program instructions have been input
into the computer and
Translated into machine language
A program can be RUN or Executed
PROGRAM DEVELOPMENT
TWO MAJOR TECHNIQUES
1. PROCEDURAL
2.
OBJECT- ORIENTED
PROGRAM DEVELOPMENT
1. PROCEDURAL
Focuses on the
procedures
that programmers create
PROGRAM DEVELOPMENT
Procedures
actions that are carried out
get input data
calculate
sort
merge
display output
store input / output
PROGRAM DEVELOPMENT
Procedures / Top-Down Approach
break down the Main Task / Process
into
manageable
subtasks
PROGRAM DEVELOPMENT
2.
Object-Oriented Programming
( O-OP )
Focuses on
objects
And describes their
features / attributes and
behaviours
PROGRAM DEVELOPMENT
2.
Object-Oriented Programming
( O-OP )
example :
Students Records Management Application
objects
student
End-of-semester Result Slip
Project
STRUCTURE OF A PROGRAM
Example of C++ Program Structure
STRUCTURE OF A C++ PROGRAM
pre-processor directives
global declarations
data-type function-name()
{
local variables to function main;
statements associated with function main;
}
STRUCTURE OF A C++ PROGRAM
The main()
pre-processor directives
global declarations
data-type main()
{
local variables to function main;
statements associated with function main;
}
STRUCTURE OF A C++ PROGRAM
Other functions
f1()
{
local variables to function f1;
statements associated with function f1;
}
f2()
{
local variables to function f2;
statements associated with function f2;
}
Etc.
C++ PROGRAM- source code
#include <iostream>
using namespace std;
int main()
{
cout << “Computer Science”;
return 0;
}
RUNNING C++ PROGRAM
Source code
Pre-processor
compiler
assembly code
assembler
object
code
libraries
linker
executable code
Pre-processor
• Accepts source code as input and
removes comments
extends the code according to the
preprocessor directives included in the
source code ( all lines starting with # )
COMPILER
• Takes the output of the preprocessor and
produces assembly code
• The Assembler takes the assembly code and
produces the machine code ( object code)
• The linker takes the object code, joins it with
other pieces of object code and libraries and
produces code that can be executed(executable
code)
#include < iostream>
• Tells the preprocessor portion of the c compiler to
attach the iostream file to the file with the source code
• Causes the preprocessor to act, it is called
preprocessor directive
• <iostream>
is a header file, included with the C++ compiler
contains information about the library function,
cout << and cin >>
CONSTANTS
DEFINITION
CONSTANT
Is a quantity that doesn’t change
The quantity can be stored at a location in the
memory
eg. PI = 3.14
interest = 0.15
CONSTANTS
CONSTANT
eg
big = 3.14 + k – 7j
big = PI + k – 7j
CONSTANTS
Types of C++ CONSTANTs
C++ constants
Primary Constant
Secondary
Integer
Real
Character
Array
Pointer
Structure
Union
Enum etc.
VARIABLES / IDENTIFIERS
DEFINITION
VARIABLES are
symbolic NAMES
used by computer programmers to
identify MEMORY locations
VARIABLES
• VARIABLES
name , data type , content
sun
31 56 A k 0
The Variable name is sun
The Variable content is 31
VARIABLES
The content of the one memory location sun
can vary or differ overtime when the
programme is being executed
It is currently holding 31
it can hold 50 the next time, 40 the next etc.
VARIABLES
• VARIABLES
One memory location can be used over and over
again with different values.
It is the ability of memory variables
to change
in value that makes computers and
programming worthwhile
VARIABLES
• VARIABLES NAME
Constructing the Name
Every computer Programming Language has
its own set of RULES for naming variables or
identifiers
RULES
it is important to study the rules for a
particular language in terms of
VARIABLES
• VARIABLES NAME
Constructing the Name
RULES
it is important to study the rules for a particular
language in terms of
- combination of letters, digits , special characters
- use of space
- length of the name
- case sensitiveness
VARIABLES
• VARIABLES NAME
Constructing the Name
Camel casing format
eg
totalOfNumbers
- uses multiple word running together
- each new word within the name begins with
an uppercase letter
VARIABLES
• VARIABLES NAME
Constructing the Name
caveat
- Names should have some appropriate meaning
- Use of white space ( avoid )
- Use of underscore and hyphen ( _ - )
- Case sensitive ( be aware )
- Unnecessary long names ( can be confusing )
VARIABLES
• VARIABLES NAME
Constructing the Name
C++ Rules
- any combination of 1 to 8 alphabets, digits or
underscore ( more than 8 for some
compilers)
- The first character in the name must be alphabet
- No commas or blanks allowed
- No special symbol other than an underscore can
be used
VARIABLES
• VARIABLES NAME
Constructing the Name
KEYWORDS / RESERVED WORDS
These are words
which has predefined meaning
to the compiler.
They cannot be used as Variable Names
C++ Keywords are 32
INSTRUCTIONS/STATEMENTS
• WHAT IT IS
TO specify to the computer what to do
C++ instructions
1. Type Declaration
2. Input / Output ( I/O )
3. Arithmetic
4. Control
STATEMENTS
• WHAT IT IS
statement
a statement may be a combination of
variables
constants
keywords or
operators
In a form of an instruction
STATEMENT: TYPES
C++ instructions/statement
1. Type Declaration
to declare the type of variable
2. I/ O
to perform the function of supplying input
data to a program and obtaining the output
results from it.
STATEMENT TYPES
C++ instructions/statements
3. Arithmetic
to perform arithmetic operations between
constants and variables
4. Control
to control the sequence of execution of
various statements
DECLARATION
C++ instructions
1. Type Declaration
to declare the type of variables being used in the
program
- any variable used in the program
must be declared before using it in any statement
- Usually written at the beginning of the program
DECLARATION
integer data values : int
e.g. int sum;
int kofi;
for integer data values such as 23 , 101
DECLARATION
Real data values : float
e.g.
float sum;
float amount;
for real data values such as 23.0 , 101.09
DECLARATION
For character data values: char
char myname;
char mtitle;
for character data values such as “a” , “B”
DECLARATION
C++
Note:
C++ compiler is able to distinguish between
the variable names, by making it compulsory
for the programmer to
declare the type of any variable name that
you wish to use in a program
DECLARATION
variant
other compilers e.g. VB will allow a generic
declaration of type variant
the context in which it is used will then
determine the type of variable
DECLARATION
the Primary Data Types so far are
integer
float
char
bool
DECLARATION
subtypes of the Primary Data Type (integer)
short int
long int
Eg of declaration
short int numb;
long int amount;
DECLARATION
subtypes of the Primary Data Type (integer)
or
short numb;
long amount;
DECLARATION
subtypes of the Primary Data Type (integer)
OS and memory allocation
OS
short (bytes)
int (bytes)
Long (bytes)
16-bit
32-bit
64-bit
2
2
?
2
4
?
4
4
?
DECLARATION
subtypes of the Primary Data Type (integer)
Range of possible values
OS
short (bytes)
int (bytes)
Long (bytes)
16-bit
2 (-32768 to +32767 ) 2 (-32768 to
32-bit
2
4 (-2147483648 to
+2147483647)
4
64-bit
?
?
?
+32767 )
4
DECLARATION
subtypes of the Primary Data Type (integer)
signed and unsigned
the value stored in integer variable can be
positive (+)
or negative ( - )
by default all int, short, long are signed
i.e. can be of value positive or negative
DECLARATION
subtypes of the Primary Data Type (integer)
unsigned
when it is known that the value to be stored in
an integer variable will always be positive then
it is efficient to declare such a variable as
unsigned
DECLARATION
subtypes of the Primary Data Type (integer)
unsigned
e.g. of declaration
unsigned int kount; or
unsigned kount;
short unsigned int kount;
long unsigned int numb;
DECLARATION
subtypes of the Primary Data Type (float)
note
float
( 4 bytes -3.4e38 to +3.4e38)
double
(8 bytes : -1.7e308 to +1.7e308)
long double
(10 bytes : -1.7e4932 to + 1.7e4932)
Eg of declaration
double numb;
long double amount;
DECLARATION
subtypes of the Primary Data Type (char)
ARITHMETIC INSTRUCTION
ARITHMETIC Instruction/statement
Consists of
a variable name on the left hand side of
= (assignment operator)
and variable name(s) and constant(s) or
expression on the right hand side of
=
e.g.
myvar = xnumb – xmean;
ARITHMETIC INSTRUCTION
ARITHMETIC Instruction
e.g. myvar = xnumb – xmean;
If int xnumb has the value 40
and int xmean has the value 25
then the expression on the right hand side of the
assignment operator ( = ) will evaluate to 15 and the result
assigned to the variable on the left hand side of the
assignment operator i.e.
myvar is assigned 15
ARITHMETIC INSTRUCTION
arithmetic operators
OPERATOR SYMBOL
+
*
/
%
FUNCTION
ADDITION
SUBTRACTION
MULTIPLICATION
DIVISION
MODULAR
ARITHMETIC INSTRUCTION
arithmetic expression
consists of
operands - the variables and constants
and
operators
e.g. In the expression
xnum - xmean
the operands are:- xnum and xmean
the operator is:-
ARITHMETIC INSTRUCTION
Types of Arithmetic statements
Integer Mode
- Real mode
- Mixed Mode
-
ARITHMETIC INSTRUCTION
Types of Arithmetic statements
Integer Mode
all operands are either
integer variables or
integer constants
e.g.
int xnum, myvar, xmean,xss;
xnum = 40;
xmean = 25;
myvar = xnum – xmean;
xss = myvar + 101;
ARITHMETIC INSTRUCTION
Types of Arithmetic statements
Real Mode
all operands are either
real variables or
real constants
e.g.
float xnum, myvar, xmean,xss;
xnum = 40.86;
xmean = 25.0;
myvar = xnum – xmean;
xss = myvar + 101.0;
ARITHMETIC STATEMENT
Types of Arithmetic statements
Mixed Mode
some of the operands are either
integer and some are
real
e.g.
int xnum, myvar;
float xmean,xss;
xnum = 40;
xmean = 25.0;
myvar = xnum – xmean;
xss = myvar + 101;
ARITHMETIC STATEMENT
Notes:
1. - Variable name on the left hand
side of the statement
- no constants allowed
ARITHMETIC STATEMENT
Notes:
2. The right hand side expression is
evaluated first and the result
assigned to the variable on the left
hand side of the statement.
ARITHMETIC STATEMENT
Notes:
3. Arithmetic operation can be performed
on
integers (int) ,
reals (float) and
characters ( char )
e.g. char ama;
ama = ‘B’;
ARITHMETIC STATEMENT
Notes:
4. - No operator is assumed to be present
- it must be written
e.g. Write the ff normal arithmetic
expressions as C-lang arithmetic
expressions
ARITHMETIC STATEMENT
Normal
C++-lang
xy
x *y
or x.y
b2 – 4ac
b*b – 4*a*c
ARITHMETIC STATEMENT
integer and float
1. Operation between
integer and integer
always yields
integer result
Eg
int costp; sellp; profit;
profit = sellp – costp;
Conversions Rules:
ARITHMETIC STATEMENT
integer and float
Operation between
real and real
always yields
real result
Conversions Rules:
2.
60.0 – 20.5 = 39.5
Eg
float costp; sellp; profit;
profit = sellp – costp;
ARITHMETIC STATEMENT
Conversions Rules : integer and float
3.
Operation between
integer and real
always yields
real result
60 – 40.5 = 39.5
Eg
int costp;
float sellp; profit;
profit = sellp – costp;
ARITHMETIC STATEMENT
Type Conversions in Assignments
Variable = arithmetic expression type ;
Same variable type is assumed
int variable = int arithmetic expression;
float variable = float arithmetic expression;
ARITHMETIC STATEMENT
Type Conversions in Assignments
Variable = arithmetic expression type ;
NOT Same type
int variable = float arithmetic expression;
float variable = int arithmetic expression;
ARITHMETIC STATEMENT
Type Conversions in Assignments
NOT Same type
THEN the value of the arithmetic expression is
either
Promoted or
Demoted
ARITHMETIC STATEMENT
Type Conversions in Assignments
NOT Same type
Consider:int costp;
float sellp;
costp = 60.5;
sellp = 20;
ARITHMETIC STATEMENT
Type Conversions in Assignments
NOT Same type
Demotion:
in the case of
int costp;
costp = 60.5;
the expression value is 60.5 (float) and cannot be
stored in costp (int)
The value (60.5) float is demoted to (60) int then
stored
ARITHMETIC STATEMENT
Type Conversions in Assignments
NOT Same type
Promotion:
in the case of
float sellp;
sellp = 20;
the expression value is 20 (int) and cannot be
stored in sellp (float)
The value (20) int is promoted to (20.00000) float
then stored
ARITHMETIC STATEMENT
Hierarchy of Operations
Priority
Operators
Description
1st
*
Multiplication, Division, modular
2nd
+
3rd
=
/
-
%
Addition, subtraction
assignment
ARITHMETIC STATEMENT
Hierarchy of Operations
Notes:
1.
Left to right Associativity
e.g.
beta = alpha * t / kappa;
* and / enjoy the same priority
alpha * t would be performed first
the result obtained would be divided by
kappa
ARITHMETIC STATEMENT
Hierarchy of Operations
Notes:
2.
-
-
Use of Parenthesis ( )
Within parentheses the same hierarchy is
operative
In nested parentheses, the operations within the
innermost parenthesis would be performed first
( ( ( a + b) / b – 10) – bb)
Followed by the operations within the second
outermost pair and so on
CONTROL INSTRUCTION
THESE are a set of instructions that enable the
programmer to
specify the order in which the
various instructions in a program are
to be executed
by the compiler/computer
CONTROL INSTRUCTION
STRUCTURE
Definition
a basic unit of programming logic
Each structure is a
Sequence
Selection or
loop
CONTROL INSTRUCTION
Generally there are three main types
1 Sequence control
2 Selection or Decision Control/Branching/Case
3 Repetition or Loop Control
CONTROL INSTRUCTION
1.SEQUENCE STRUCTURE
entry
STEP 1
STEP 2
STEP 3
STEP .....
CONTROL INSTRUCTION
1.SEQUENCE STRUCTURE
How it works
- you perform an action or task and then
you perform the next action or task
- can contain any number of tasks
- there is no chance to branch off and skip any of
the tasks
- once you start a series of actions in a sequence,
you must continue step-by-step until the
sequence ends
CONTROL INSTRUCTION
1.SEQUENCE STRUCTURE
How it works : a program with pure sequence structure
include <stdio.h>
main() {
unsigned short age;
printf(“type in your age from keyboard”);
scanf(“%d”, &age);
// display my name and age
printf( “My name is Abrebrese Mepeasem”);
printf( “ I am %d years old “, age );
system(“pause”);
}
CONTROL INSTRUCTION
2.SELECTION STRUCTURE
entry
STEP 1
?
OR STEP 2
OR STEP 2
CONTROL INSTRUCTION
2.SELECTION STRUCTURE
How it works
- you ASK A Question and depending on the
answer
- You take one of two courses
- Then no matter which path you follow you
continue with the NEXT task
CONTROL INSTRUCTION
1.SEQUENCE STRUCTURE
How it works : a program with pure sequence structure
include <stdio.h>
main() {
unsigned short myage;
printf(“type in your age from keyboard”);
scanf(“%d”, &age);
// display my name and age only if I am 18 years or older
if ( myage > =18) {
printf( “My name is Abrebrese Mepeasem”);
printf( “ I am %d years old “, age );
}
system(“pause”);
}
CONTROL INSTRUCTION
2.SELECTION STRUCTURE
Popularly referred to as
if – then - else
if ( someCondition is true )
{
do thisProcess
}
else
{
do thisProcess
}
then
CONTROL INSTRUCTION
2.SELECTION STRUCTURE
Popularly referred to as
if – then - else
Note : the then process and the else process are
mutually exclusive events
then
{
do thisProcess
}
else
{
do thisProcess
}
CONTROL INSTRUCTION
2.SELECTION STRUCTURE
That after either of the two is performed execution of
task continues as indicated by the arrow
if ( someCondition is true ) then
{
do thisProcess
}
else
{
do thisProcess
}
CONTROL INSTRUCTION
2.SELECTION STRUCTURE
Various substructures of if-then-else
– Dual-alternative ifs
– Single-alternative ifs
– Nested ifs
CONTROL INSTRUCTION
2.SELECTION STRUCTURE
- Dual-alternative ifs
both the then process and else process are present
if ( someCondition is true )
{
do thisProcess
}
else
{
do thisProcess
}
then
CONTROL INSTRUCTION
2.SELECTION STRUCTURE
- single-alternative ifs
only the then process is present
if ( someCondition is true )
{
do thisProcess
}
then
CONTROL INSTRUCTION
2.SELECTION STRUCTURE
- Nested ifs
( deferred )
CONTROL INSTRUCTION
3.LOOP STRUCTURE
entry
STEP 1
?
exit
STEP 2
CONTROL INSTRUCTION
3.LOOP STRUCTURE
How it works
- You continue to repeat actions based on the
answer to a question
INPUT/OUTPUT INSTRUCTION
The use of
scanf() as an input instruction
printf() as an output instruction
CSCD IA 2011
Download