0% found this document useful (0 votes)
39 views28 pages

Fundamentals of Computer Programming

The document discusses different types of programming languages and programming paradigms. It describes machine language, assembly language, and high-level languages. It also covers unstructured, structured, and object-oriented programming paradigms.

Uploaded by

mavrickgsnius
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
Download as doc, pdf, or txt
0% found this document useful (0 votes)
39 views28 pages

Fundamentals of Computer Programming

The document discusses different types of programming languages and programming paradigms. It describes machine language, assembly language, and high-level languages. It also covers unstructured, structured, and object-oriented programming paradigms.

Uploaded by

mavrickgsnius
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1/ 28

COMP 120 FUNDAMENTALS OF COMPUTER PROGRAMMING

What is programming?
Programming is the process of writing a sequence of instructions to be executed by a
computer to solve a problem. Computer programming has many facets: It is like
engineering because computer programs must be carefully designed to be reliable and
inexpensive to maintain. It is an art because good programs require that the programmer
use the intuition and a personal sense of style. Programmers, people who write programs
using different programming language to communicate instructions to the computer.

Computer Languages/Programming languages


The programmer communicates with a machine using programming language. Computer
language is a set of instructions used for writing computer programs. There are many
different classifications of programming languages and these programming languages
differ in the way they are structured. Most of the programs have highly structured set of
rules. These primary classifications of programming languages are:
- Machine language
- Assembler language
- High-level language

Machine level is a binary programming language that the computer can run
directly. It does not need a translating program. Programs are written at the most basic
level of operation. Machine language is called a low level language. Instructions are
coded as a series of 1’s and 0’s.
Machine language programs are cumbersome and difficult to write. The machine
language is native to that machine and understood directly by the machine. The machine
language generally has two parts:

OPCODE OPERAND

Operation code
The OPCODE of the machine language tells the computer the type of operation
(function) to be performed. E.g reading the contents of a word, moving a value into a
CPU’s register, adding some value into a register ets
Operand
The OPERAND gives the data on which the operation has to be performed or tell the
location where the data can be found. It may be:
- An address of byte or word in memory or,
- A reference to a CPU’s register.
Example:
Assume the operation code for reading is 10110111, for adding is 0011101100, for
moving is 01001010, while for storing (writing) is 11011011.

1
A machine language to add two values might look as below:

Instruction
Operation operand what it does
10110111 00011001 read first value
01001010 1101000110110000 move the value to register
10110111 00011001 read next value
00101100 1101000110110000 add the value to the register
11011011 1101000110110010 store register’s value into a word in memory
[statements are even worse to mentally interpret]

Advantages
- the Language is typically more machine-oriented and faster to execute.
Disadvantages
1. Difficult to program
It is the most difficult kind programming. Instructions should be encoded as a sequence
of incomprehensible 0’s and 1’s which is very difficult.
2. Error-prone
The programmer has to look into all the activities like memory management which
diverts his attention from the actual logic of the program. This frequently leads to errors.
[closer to the machine rather than the programmer]
3. Machine dependent
Every computer is different from one another in its architecture. Hence instructions of
one machine will be different from another.

Assembly language: The assembly language was developed to allow for higher
level programming, where programmer’s work is simpler. This simplification was in
terms of short codes (mnemonics) that represented operation codes, so the programmer
doesn’t need to remember the binary representation of the code. Mnemonics also
represent the addresses that relate to the main memory and storage register of a computer.
For example ADD is the mnemonic for addition (representing binary representation
00101100), RD for reading, MV for moving and STO for storing (writing contents into a
memory word).
Using the example above, for adding two values might look like this:
Code operand what it doea
RD NUM read first number
MV NUM,AC move read number into register AC
RD NUM read next number
ADD NUM,AC add read numbers to AC
STO TOT,AC store into memory word TOT the contents of AC

NOTE:
Assembly language and machine language are collectively called low level languages.
Each low level language has instructions which correspond closely to inbuilt operations
of a specific computer. Since different brands of computer use different low level

2
languages a program written for one brand of computer will not run on another brand. A
computer manufacturer usually devices a low level language for that type of computer.
The program can therefore not be used in different types of computer hardware.

Limitation
- The language is still low level. An assembler translates only one assembly
language statement into one machine language statement.
- Assembly language is also machine language. For example, the immediate above
program still refers to CPU’s register as well as the hardware-level logic of
carrying out the operations.
- Assembly language is also still hard to use. The mnemonics are still hard to
remember.

High level languages provide everything the programmer might want to do already built
into the language. High-level languages contain statements that are written in English
words, contain commonly used mathematical notations and symbols. Such languages are
not designed specifically for any particular brand of computer. In other words, "high-
level" languages are more abstract and easier to use but execute less quickly.
Examples of high level languages include C, C++, Microsoft Visual Studio
languages and Java. Students’ examination program written in high level language might
contain a statement such as
Total Mark= CAT1+ CAT2+ Tot_fin_ex

Advantages of high level languages


1. Easier to program
The programmer can concentrate on the logic of the program rather than on the registers,
ports and memory usage.
2. Machine independent
The program can be ported across various platforms.
3. Easy to learn
The learning curve for high level language is relatively smooth that low-level language
4. High level language can be easily documented.
Disadvantage
- It must be translated into the equivalent machine language program, making the
speed of execution slower than a machine language program.

Computer programming paradigms.


There are many programming languages in the market (C, C++, Java, C# etc). These
languages may hold common features or instructions (as indicated below) but have
various differences like the syntax rules applied to individual program or the type of
paradigm they belong to. Different programming languages support different styles of
programming called programming paradigms. The paradigm here define how a
particular language is structured. These include:-
1. Unstructured programming paradigm
During the 1950’s and 1960’s many people did not think about the question of
developing general method for organizing a program. Instead, programs were written

3
much the same way you might off the top of your head give someone instructions on how
to change a tire or worse build a house. When program did not work, it was simply
“patched” (fixed) error by error until the programmer felt that he had found them all.
Usually, however, errors continued to appear even after the program was released for use.
Unstructured programming has been heavily criticized for producing hardly-readable
("spaghetti") code and is sometimes considered a bad approach for creating major
projects, but had been praised for the freedom it offers to programmers. This paradigm
uses a GOTO statement as a control statement.
There are both high- and low-level programming languages that use non-structured
programming. These include early versions of BASIC (such as MSX BASIC and GW-
BASIC), FORTRAN, JOSS, FOCAL, MUMPS, TELCOMP, COBOL, machine-level
code etc.
A program in a non-structured language usually consists of sequentially ordered
commands, or statements, usually one in each line. The lines are usually numbered or
may have labels: this allows the flow of execution to jump to any line in the program
using GOTO statement.

4
Q.
Based on the above description and the discussions in class, name various disadvantages
of unstructured programming paradigm.

2. Structured programming paradigm

5
6
7
8
9
10
3. Object oriented programming paradigm

Object-oriented programming (OOP) is a programming paradigm based on the concept of


"objects", which may contain data, in the form of fields, often known as attributes; and
code, in the form of procedures, often known as methods. A feature of objects is that an
object's procedures can access and often modify the data fields of the object with which
they are associated (objects have a notion of "this" or "self"). In OOP, computer
programs are designed by making them out of objects that interact with one another.
There is significant diversity of OOP languages, but the most popular ones are class-
based, meaning that objects are instances of classes, which typically also determine their
type. Significant object-oriented languages include Java, C++, C#, Python, PHP, Ruby,
Perl, Delphi, Objective-C, Swift, Common Lisp, Smalltalk etc.

Common instructions in languages


The details look different in different languages, but a few basic instructions appear in
just about every language:
- input: Get data from the keyboard, a file, or some other device.
- output: Display data on the screen or send data to a file or other device.
- arithmetic: Perform basic arithmetical operations like addition and
multiplication.
- conditional execution: Check for certain conditions and execute the
appropriate sequence of statements.
- repetition: Perform some action repeatedly, usually with some variation.

Language considerations
The choice of language used is subject to many considerations, such as:
- company policy,
- suitability to task,
- availability of third-party packages, or
- individual preference.

11
PROBLEM FORMULATION AND SOLVING METHODOLOGY
Programming is a process of problem solving. Problem solving is the act of finding a
solution to a difficult, distressing, troublesome, or unsettled question.
Before you start solving a problem, you must ask yourself the following questions:
– What do I know about the problem?
– What is the information that I have to process in order the find the
solution?
– What does the solution look like?
– What sort of special cases exist?
– How will I recognize that I have found
the solution?

To solve a problem as a programmer, you need an understanding of the software


development life cycle (SDLC). In general, SDLC involves a number of steps/phases.
These steps are:
- Requirement gathering
- Analysis of requirements
- Designing
- Implementation
- Testing
- Maintenance

Step 1: Requirements gathering

The requirements for a system are the descriptions of what the system should do— the
services that it provides and the constraints on its operation. These requirements reflect
the needs of customers for a system that serves a certain purpose such as controlling a
device, placing an order, or finding information. The process of finding out (gathering),
analyzing, documenting and checking these services and constraints is called
requirements engineering (RE). We will only look at requirements gathering
Requirements discovery (sometime called requirements elicitation) is the process of
gathering information about the required system and existing systems, and distilling the
user and system requirements from this information. Sources of information during the
requirements discovery phase include documentation, system stakeholders, and
specifications of similar systems. You interact with stakeholders through interviews and
observation and you may use scenarios and prototypes to help stakeholders understand
what the system will be like. Stakeholders range from end-users of a system through
managers to external stakeholders such as regulators, who certify the acceptability of the
system. For example, system stakeholders for the mental healthcare patient information
system include:
1. Patients whose information is recorded in the system.
2. Doctors who are responsible for assessing and treating patients.
3. Nurses who coordinate the consultations with doctors and administer some treatments.
4. Medical receptionists who manage patients’ appointments.
5. IT staff who are responsible for installing and maintaining the system.

12
6. A medical ethics manager who must ensure that the system meets current ethical
guidelines for patient care.
7. Healthcare managers who obtain management information from the system.
8. Medical records staff who are responsible for ensuring that system information can be
maintained and preserved, and that record keeping procedures have been properly
implemented
In addition to system stakeholders, we have already seen that requirements may also
come from the application domain and from other systems that interact with the system
being specified. All of these must be considered during the requirements elicitation
process.

The first step during requirements gathering and analysis is stating the problem. The
programmer must understand the semantics of the problem. This preliminary
investigation of what need to be done is called problem definition. In other words,
problem definition is a clear cut representation of what the user needs from the system
and the task the programmer wants to accomplish through the system. Clear and concise
problems help to avoid misunderstandings. For example, the problem statement is the
following:
Give the sum of the integers from 1 to 100.

Step 2: Analyze the problem.


This activity takes the unstructured collection of requirements, groups related
requirements, and organizes them into coherent clusters. The most common way of
grouping requirements is to use a model of the system architecture to identify sub-
systems and to associate requirements with each sub-system.

The next step in problem analysis involves description of input/output and the operations
to be performed by the system. At this point the program is an “abstraction” because we
are not defining the steps to determine the output: instead we are only showing the
information that is required to compute the desired output. The I/O diagram for this
example follows;

Integer 1
to Sum of int 1 to 100

Integer 100

Step 3 . Design steps (algorithm) to solve the problem


Once you have clearly stated the problem and understood its requirements, you can then
convert them to implementable statements. One way of designing a product(program) is
by use of an algorithm.
What exactly is an algorithm?
An algorithm is an ordered set of unambiguous executable steps, defining a terminating
process.

13
Properties of Algorithms
• Definite and Unambiguous: Each an every step of the algorithm should be
rigorously defined so that it is clear what each instruction is meant to accomplish.
• Simple and Precise: The language used to write algorithm should not convey
more than one meaning to the reader. Must be simple enough that they can be
carried out by a computer.
• Efficient: Can be measured in terms of Time and Space. Time tends to be more
important. For example the algorithm 2 above solves problems in less time. this is
because, to compute sum of integers from 1 to 100, algorithm 1 must repeat the
loop in step 3 100 times. Which means it must perform 100 additions, 100
assignment, 100 increments of I and 100 comparisons of I with n, for a total of
100 operations.
• Finiteness: An algorithm must always terminate after a finite number of steps
• Input: The algorithm should take zero and more input
• Output: The algorithm should produce one or more outputs and should return the
correct output
• Effective: A human should be able to calculate the values involved in the
procedure of the algorithm using paper and pencil.

A single algorithm can be represented in many ways:


 Formulas: F = (9/5)C + 32
 Words: Multiply the Celsius by 9/5 and add 32.
 Flow Charts.
 Pseudo-code.

For such a simple problem, the algorithm can be listed as operations that are performed
one after another.
For example;
Algorithm 1
1. Accept an integer for n
2. initialize sum to 0
3. for each integer i in the range 1 to n
assign sum+i to sum
4. return the value of sum
Algorithm 2
1. Accept an integer for n
2. return the value of n*(n+1)/2

Developing an algorithm using Pseudocode


Algorithms are commonly written in pseudocode, a pseudo-programming language that is
a mixture of English phrases and ind ention to make the steps in the solution explicit.
Example of a pseudo code;
The Problem: The organization you work for is in need of a tool that will calculate
the cost of a product purchased with a foreign currency.

14
The Requirements and analysis: The Sales Department of your organization has
customers from Canada and Mexico. Your catalogs on the web site express all prices
in U.S. dollars. It has been decided that the easiest way to provide support for foreign
customers is to create a program that will accept as input the price of the product and
the currency factor necessary for the customer to convert dollars into their currency.
For example, if the Canadian customer purchases a skateboard for $50.00, that $50.00
would need to be multiplied by a factor of approximately 1.2 to convert dollars to
Canadian dollars. In this case, the customer will need to pay $60 Canadian dollars for
the item that costs $50 dollars US.

Pseudocode
#Start Program
Amount = input("Enter Amount"
ConvRate = input("Enter Conversion Rate")
Amount = Amount * ConvRate
print Amount
#End of Program

Other examples of pseudocode:


Algorithm to Convert base-10 number to other bases
While ( the quotient is not zero )
Divide the decimal number by the new base
Make the remainder the next digit to the left in the answer
Replace the original decimal number with the quotient

There are no grammar rules in pseudocode and are not case sensitive but it typically
includes the following features:
1. the usual computer symbol +, -, * and / for basic arithmetic operations
2. symbolic names (identifiers) to represent the qualities being processed by the
algorithm
3. some provision for indicating comments – for example, the symbol such as /* and
*/
4. key words that are common in high-level languages – for example, read or enter
for input operations; display, print or write for output operations; if and else
selection structures ; for and while for repition structures
5. indention to set off blocks of instructions

For example write pseudocode for the following problem:

What is 93 in base 8?
93/8 gives 11 remainder 5
11/6 gives 1 remainder 3
1/ 8 gives 0 remainder 1
answer 135
Pseudocode

15
Write "Enter the new base"
Read newBase
Write "Enter the number to be converted"
Read decimalNumber
Set quotient to 1
While (quotient is not zero)
Set quotient to decimalNumber DIV newBase
Set remainder to decimalNumber REM newBase
Make the remainder the next digit to the left in the answer
Set decimalNumber to quotient
Write "The answer is "
Write answer

Like pseudocode, flowcharts are useful for developing and representing algorithms.
Flowcharts clearly show how control structures operate.
A flowchart is a graphical representation of an algorithm or a portion of an algorithm.
Flowcharts are drawn using certain special-purpose symbols such as rectangles,
diamonds, ovals and small circles; these symbols are connected by arrows called
flowlines.
Pseudocode Functionality
Repetition
Repeating a series of statements
Set count to 1
While ( count < 10)
Write "Enter an integer number"
Read aNumber
Write "You entered " + aNumber
Set count to count + 1
Selection
Making a choice to execute or skip a statement (or group of statements)
Read number
If (number < 0)
Write number + " is less than zero."
or
Write "Enter a positive number."
Read number
If (number < 0)
Write number + " is less than zero."
Write "You didn't follow instructions."
Selection
Choose to execute one statement (or group of statements) or another statement (or
group of statements)
If ( age < 12 )
Write "Pay children's rate"
Write "You get a free box of popcorn"

16
else If ( age < 65 )
Write "Pay regular rate"
else
Write "Pay senior citizens rate"

Pseudo Code Rules:

 The pseudo code program should begin with the Start instruction and complete
with the End instruction.

 Each pseudo code statement should contain at least one instruction.

 Each pseudo code statement should contain a verb that represents the action
performed along with any identifier and operators that hold program values or
perform calculations.

The Advantages of Pseudo Code

The primary advantage of pseudo code comes from the fact that it is a programming
language. It’s a very simple and unstructured programming language and it is very easy
to transition pseudo code to a programming language. Since we want our models to
represent the best of all possible solutions, pseudo code probably requires the least
amount of modification from model to actual program. Whereas a flowchart may
represent a perfect world solution it might not be easily implemented into a program.
Pseudo code can be more easily transitioned so it is more likely that our model logic will
be very close to the implemented program.

Another advantage may be in its simplicity. It may take some time for a programmer to
learn a new programming language but since pseudo code is so familiar and similar to
reading instructions (i.e. recipe), it does not involve a steep learning curve. If you can
read and write you can create pseudo code and understand pseudo code instructions.

The Disadvantages of Pseudo Code

The disadvantages of pseudo code may start with its lack of standards. One person’s
logic instructions may not seem as logical as the next. Given the unstructured nature of
pseudo code, it is few rules and is hard to standardize. One programmer might not see the
logic written by someone else.

Another disadvantage over other modeling tools like flowcharts may be pseudo codes
inability to show logic flows or the bigger picture. Whereas flowcharts provide an
overview of logic and can be understood at a higher level, pseudo code is far more detail
oriented and requires more concentration and practice to see the bigger picture. Put
another way, pseudo code focuses more on the details and the graphics of flowcharts
allow for a 10,000 foot big picture perspective.

17
FLOWCHARTS

Certainly the most obvious benefit of flowcharting is its graphical nature. Unlike pseudo
code, flowcharts consist of standard flow chart symbols connected by lines where each
symbol reflects an operation of logic. In addition, each symbol not only is standardized to
represent an operation (i.e. an IF decision statement) but also labels the logic operation
with a short explanation what the logic instruction performs.

Flow Charting Symbols: Flowcharting is a standardized set of symbols that represent


different types of logic operations. The symbol shapes are standardized and the way they
are read (top to bottom) is also standardized to the flowchart diagram.. The flowchart
represents a graphical view of a logic model with each symbol representing a logic step.

Flow Chart Symbols

 Rounded Rectangle: The rounded rectangle is used to show the start and finish of
the logic flow. This symbol is called the terminator symbol.

 Circle: The circle is used to connect drawings that span more than one piece of
paper and help to connect the logic paths from page to page. The circle shows the
end of the drawing on that page and has a number inside it. The next page of the
diagram starts with a circle with that same number. This helps to tie the two pages
together and when the logic ends on one page, it should be picked up in the circle
on the drawing for the next page.

 Rectangle: The rectangle is used to show a single step in the model logic. Some
activity (i.e. expression, calculation, etc.)

 Diamond: The diamond is used to represent a decision. The outcome may be true
or true/false and is usually implemented in program code as an IF statement.

 Parallelogram: The parallelogram represents logic input or output (i.e. reading


from a keyboard or file or writing to a display or printer).

 Lines: Lines show the movement of logic and the direction of information from
symbol to symbol

18
Flow Chart Rules:

All modeling environment have standards and rules that need to be followed. In some
cases, the rule is necessary for the diagram to work and in other cases the standard is
there so that other programmers can look at the logic model and see the same logic
solution. I have used the analogy of a blueprint to help understand what a logic model is
for the programmer. Blueprints are standardized. If they were not then one blueprint
might be understood differently from one home builder to another.

 Each symbol will have one line coming into the symbol and one line going out.
The exception is the diamond (decision) which can have two lines.

19
 Lines should never cross

 Every Symbol should be appropriately labeled with a short explaination of that


logic step

Key Concept: Flow Chart Symbol Labels - Although flow chart labels tended not to be
as a verbose as pseudo code, the labels tend to be very much like pseudo code and that
they provide an English like statement to express what the symbols logic needs to
accomplish. One could probably construct pseudo code from a flow chart simply by
pulling the text from each symbol label.

The Advantages of Flow Charts

The flowcharts greatest advantage comes from its simplicity. They are both simple to
understand and create. Since most programmers (and most people in general) tend to
prefer concepts explained visually, the flowchart is perfect. Seeing the logic in front of
you seems to make a discussion of the programs purpose and steps much simpler. Less
intimidating then pseudo code, which itself is also very easy to understand but, still
consists of statements which must be read. With flowcharting applications like
Microsoft’s Visio, even people with the weakest of artistic skill can put together a
flowchart quickly and efficiently. A final advantage of flowcharts maybe the less bias
nature of flow charts over pseudo code. With pseudo code you are still creating a
program and programming syntax should not come into play when designing the model.
With flowcharting there may be more of a spirit of “brainstorming”, creating that perfect
world solution, since the flow chart model is dramatically different (i.e. no statements)
than the computer program. Flowcharting might be a better tool to reach an unbiased
ideal logic model solution. I have always felt that it was much easier to formulate a high
level plan with a quick drawing then with the English like statements of pseudo code
which seems to draw you into the details too soon.

The Disadvantages of Flow Charts

Flowcharts have three disadvantages. The first disadvantage comes from the difficulty in
drawing sophisticated logic without spanning several pieces of paper. Either the symbols
need to be resized to a microscopic level when looking at complicated logic or the reader
will need a large table to line up the multiple pages of the flowchart.

The second disadvantage stems from the artistic nature of the drawing which can be
difficult for some programmers. Drawing software (i.e. MS Visio) goes a long way
towards eliminating this problem but if one is left with a ruler and pencil the assembling
of the chart takes some practice. Until one gets the hang of it flowcharts may require
going through a few pencils and erasers.

20
A final disadvantage of flowcharts maybe the difficulty in translating flowcharting logic
into programming language statements. Pseudo code looks much more like a
programming language and can usually be implemented much faster and more efficiently
than a flowchart.

Flow Chart Example

To allow for us to compare the strengths and weaknesses of the three logic modeling
tools discussed in this chapter, I have created a common problem so that we can create
the same model with each of the three tools.

This logic path will be a simple one. Logic paths in full programs are much more
complicated than what we will try to accomplish in chapter two . We need to start slowly
to help retain the information learned.

 The Problem: The organization you work for is in need of a tool that will
calculate the cost of a product purchased with a foreign currency.

 The Requirements: The Sales Department of your organization has customers


from Canada and Mexico. Your catalogs on the web site express all prices in U.S.
dollars. It has been decided that the easiest way to provide support for foreign
customers is to create a program that will accept as input the price of the product
and the currency factor necessary for the customer to convert dollars into their
currency. For example, if the Canadian customer purchases a skateboard for
$50.00, that $50.00 would need to be multiplied by a factor of approximately 1.2
to convert dollars to Canadian dollars. In this case, the customer will need to pay
$60 Canadian dollars for the item that costs $50 dollars US.

 Symbol A - represents the terminator simple which is used to indicate the start of
the logic model.

 Symbol B - represents a parallelogram which is used for input/output operations


and in this case to capture information about the Amount of the item form the
keyboard.

 Symbols C - represents another parallelogram which is used this time to input the
conversion factor used to converts dollars into the currency of the customer.

 Symbol D - here we have a rectangle which is used to document the calculation


step which will take amounts and multiply that times the currency factor

 Symbol E - here we use a parallelogram again this time to display output the
screen in the form of reported message displaying the results of the calculation
done in the previous step.

21
 Symbol F - Another terminator symbol, this one is used to indicate the end of the
logic.

Key Concept: Both Logic models and programming languages use variables to
temporary hold text and numbers that are manipulated by the logic statements. Variables

22
are given names to make them easy to reference in the logic model or computer program.
The term amount in item B in figure 3 is an example of a variable.

Logic Tip: We will discuss naming conventions in the next chapter but both flow chart
and pseudo code models use variables to store and retrieve values used in the model. You
will want to choose a variable name that is short to make it easy to type but long enough
so that it is descriptive and accurately describes the value. Since many times, one word
can not describe the value held by the variable, you can use “camel casing” to define
variables. This is done by joining the words that make up the variable but the first
character in each joined word is capitalized (i.e. AnnualTotalCost or also
AnnualTotCost).

Step 4 - Implement the algorithm

Implement the algorithm in code. This involves conversion of the algorithm into an
executable format (code).
For example, the problem above (repeated below) can be implemented in C language as
follows:
The Problem: The organization you work for is in need of a tool that will calculate the
cost of a product purchased with a foreign currency.

The Requirements: The Sales Department of your organization has customers from
Canada and Mexico. Your catalogs on the web site express all prices in U.S. dollars.
It has been decided that the easiest way to provide support for foreign customers is to
create a program that will accept as input the price of the product and the currency
factor necessary for the customer to convert dollars into their currency. For example,
if the Canadian customer purchases a skateboard for $50.00, that $50.00 would need
to be multiplied by a factor of approximately 1.2 to convert dollars to Canadian
dollars. In this case, the customer will need to pay $60 Canadian dollars for the item
that costs $50 dollars US.

#include<stdio.h>
int main()
{
int double amount, conv_Rate;
printf(”Enter amount”);
scanf(“%lf”, amount);
printf(”Enter conversion Rate”);

23
scanf(“%lf”, &conv_Rate) ;
amount = amount * conv_Rate ;
printf(”%lf”, amount);
return 0;
}

Still in step 4, (implementation), let us look at C language (environment, syntax and


various programming concepts…..)

C Language environment or structure

/*This is my first C program */


// I want to be a guru
#include <stdio.h>
main()
{
//declarations
printf (“Hello World\n”);
}

The symbol /*…..*/ is used to add a comment to the program. These comments are not
shown when the program results are displayed on the screen. Programmers use them to
explain the meaning of various statements in the program, for remembrance- to remind
them why they used an element and also help someone else who uses and/or edits the
program to easily learn and understand. Two ways of commenting code include the use
of double forward slash “//” for single line comment and the use of single forward slash
then asterisk ending with an asterisk and a single forward slash “/*…..*/” for multiple
line comment.
To be able to communicate to the users, C program standard library called stdio.h is
necessary. This library deals with inputting and outputting of data and is declared before
the main function. Thus the .h indicates that this is a header file. As discussed earlier, the
pre-processors such as stdio.h begin with # and must start at the first column.
The C program #include <stdio.h> directive uses the angle brackets <and> to indicate
that the header file is to be looked for on the system disk which stores the rest of the C
program application. The header file does not use a semi-colon as a delimiter.
All C programs consist of at least one function called main. The main function is the first
function that is executed when a program is run. At the same time, it is possible to have
more functions in a program. This will be discussed later in this book.
The brackets () are used in conjunction with function names for example main (). The
curly brackets are used to delimit the C statements that are associated with the function.
In other words, {} mark the start and end of the list of instructions that make up the
program. A semi-colon (;) is used to terminate C statement that is, it informs the C
compiler that the end of the statement has been reached. The function printf is used to
display whatever the program has been directed to do. For example the program above
displays Hello World. The \n is used to move to a new line on the screen.

24
return 0;
The return statement causes the main function to finish. return may be followed by a
return code (in our example is followed by the return code 0). A return code of 0 for the
main function is generally interpreted as the program worked as expected without any
errors during its execution. This is the most usual way to end a C console program.

NOTE:
Notice that the statement ends with a semicolon character (;). This character is used to
mark the end of the statement and in fact it must be included at the end of all expression
statements in all C programs (one of the most common syntax errors is indeed to forget to
include some semicolon after a statement).

Noticed that not all the lines of this program perform actions when the code is executed.
There were lines containing only comments (those beginning by //). There were lines
with directives for the compiler's preprocessor (those beginning by #). Then there were
lines that began the declaration of a function (in this case, the main function) and, finally
lines with statements (like the insertion into cout), which were all included within the
block delimited by the braces ({}) of the main function.
The program has been structured in different lines in order to be more readable, but in C+
+, we do not have strict rules on how to separate instructions in different lines. For
example, instead of
int main ()
{
cout << " Hello World!";
return 0;
}
We could have written:
int main () { cout << "Hello World!"; return 0; }
All in just one line and this would have had exactly the same meaning as the previous
code. In C++, the separation between statements is specified with an ending semicolon (;)
at the end of each one. We can write many statements per line or write a single statement
that takes many code lines. The division of code in different lines serves only to make it
more legible and schematic for the humans that may read it. Let us add an additional
instruction to our first program:
// my second program in C++
#include <iostream>
using namespace std;
int main ()
{
cout << "Hello World! ";
cout << "I'm a C++ program";
return 0;
}
Hello World! I'm a C++ program
In this case, we performed two insertions into cout in two different statements. Once
again, the separation in different lines of code has been done just to give greater
readability to the program, since main could have been perfectly valid defined this way:

25
int main () { cout << " Hello World! "; cout << " I'm a C++ program "; return 0; }
We were also free to divide the code into more lines if we considered it more convenient:
int main ()
{
cout <<
"Hello World!";
cout
<< "I'm a C++ program";
return 0;
}
And the result would again have been exactly the same as in the previous examples.
Preprocessor directives (those that begin by #) are out of this general rule since they are
not statements. They are lines read and processed by the preprocessor and do not produce
any code by themselves. Preprocessor directives must be specified in their own line and
do not have to end with a semicolon (;).
Comments
Notice also that comments are parts of the source code disregarded by the compiler. They
simply do nothing. Their purpose is only to allow the programmer to insert notes or
descriptions embedded within the source code.
C++ supports two ways to insert comments:

// line comment
/* block comment */
The first of them, known as line comment, discards everything from where the pair of
slash signs (//) is found up to the end of that same line. The second one, known as block
comment, discards everything between the /* characters and the first appearance of the */
characters, with the possibility of including more than one line. We are going to add
comments to our second program:
/* my second program in C++
with more comments */
#include <iostream>
using namespace std;
int main ()
{
cout << "Hello World! "; // prints Hello
World!
cout << "I'm a C++ program"; // prints I'm a
C++ program
return 0;
}
Hello World! I'm a C++ program
If you include comments within the source code of your programs without using the
comment characters combinations //, /* or */, the compiler will take them as if they were
C++ expressions, most likely causing one or several error messages when you compile it.

Executing a computer program

26
A program written in assembler or high level language must be translated into computer
language before the instructions can be executed by the computer. A language translator
is software that translates a program written by a programmer in language such as C/C++
into machine language, which the computer can understand. All software must be turned
into machine language because a computer stores and uses information in a binary
format, therefore, the computer cannot understand programs written in either high or low
level languages.

1. Assemblers
Assemblers are programs that are used to convert assembler language program to
machine language.

2. Compilers, linking and loading


a compiler program translates the instructions of a high level language to a machine level
language. To be able to able to write and execute a program e.g. C++ on computer the
computer’s software must include a C++ compiler. This means, a high level program
cannot be executed in their source. The actual high level program is called source
program. It is compiled to machine level language program called object program.

Compiler compiles the full program and reports the errors at the end. The corresponding
error messages are printed. We must correct our program statements and then perform the
compilation step again. The errors identified at this stage are called parse errors or
syntax errors. For example if we want to divide the value stored in variable called sum
by 3, the correct expression e.g. in C++ is sum/3. if we incorrectly write the expression
using the backslash, as in sum\3, we have a syntax error.

To build an executive file, the linker collects files and libraries. The linker’s primary
function is to bind symbolic names to memory addresses. To do this, it first scans the
files and concatenates the related file sections to form one large file. Then it makes
another pass on resulting file to bind real symbolic names to real memory address.

Program loading is basically copying a program from secondary storage into main
memory so it is ready to run. After linking/loading, the program steps are then executed
by the computer. New errors known as execution errors, run-time errors or logic
errors may be identified in this stage: thee errors are also called program bugs.
Execution errors often cause termination of a program. For example, the program
statements may attempt to reference an invalid memory location. Some execution errors
do not stop the program from executing, but they cause incorrect results to be computed.
These types of errors can be caused by programmer errors in determining the correct
steps in the solutions and by errors in the data processed by the program.
When execution errors occur due to errors in the program statements, we must correct the
errors in the source program and then begin again with the compilation step. This process
is called debugging. Input data
High level Machine
language Compiler language Link/Load Execute Program
program program output

27
Program compilation/linking/execution

Interpreters
An interpreter is system software that is fairly similar to a compiler. It is also used to
convert a high level language program to a machine level language program. The
difference is that, it analyses every line of source program and if any error, reports them
instantaneously and stops further translation. Interpreters occupy less space than a
compiler. The interpreter is 5-25 time slower that the compiler. The disadvantage with
interpreter is that, whenever a high level program is executed, it has to translate each and
every time but a compiler translates just once and produces an object file that can be
executed from then onwards.

Step 5 – Software testing

Will look at this later……

Step 6 – Maintenance
- This phase involves the use and modification of the program if the problem domain
changes

28

You might also like