You are on page 1of 27

RoslanSadjirin/DepartmentofComputerScience/FacultyofComputerandMathematicalSciences/UiTMPahang

CSC128FUNDAMENTALSOFCOMPUTERPROBLEMSOLVING
Chapter1:Introduction

LessonOutcomes
Attheendofthischapter,studentshouldbeableto:
9 Describewhatacomputerprogramis
9 Explaintheimportanceofprogrammingtocomputeruse
9 Appreciatetheimportanceofgoodprograms
9 Explaintherelationshipbetweencompilers,interpretersandprograms
9 Recognizeprogramerrors
9 Becomefamiliarwiththeprogramdesignprocess

________________________________________________________________________________________________________________
References: 1
Malik,D.S.,(2010).C++Programming,FromProblemAnalysistoProgramDesign.CourseTechnology,Canada.
rd
Gary,R.B.,(2010).C++ForEngineers&Scientists:3 Edition.CourseTechnology,Canada.
RoslanSadjirin/DepartmentofComputerScience/FacultyofComputerandMathematicalSciences/UiTMPahang
CSC128FUNDAMENTALSOFCOMPUTERPROBLEMSOLVING
Chapter1:Introduction

ABriefHistoryofC++Language
C++(OOP)isbuiltuponthefoundationofC(structuredimperativeprogramminglanguage).
C++isasupersetofCandC++compilerscanbeusedtocompileCprograms.
C++isanexpandedandenhancedversionofCthatembodiesthephilosophyofobjectoriented
programming.
CwasinventedandfirstimplementedbyDennisRitchiein1970s,whileC++inventedbyBjarne
Stroustrupin1979atBellLaboratoriesinMurrayHill.
The reason for invention of C++ is to cater the increases of complexity in computer problem
solvingorprogramming.

IntroductiontoProgramming
A. Whatisacomputerprogram
1. Program
A program is a set of instructions that direct the computer to accomplish specific tasks. Another
termcommonlyusedforcomputerprogramsissoftware,whichdescribesallprogramsthatareused
inparticularinstallationtogetherwiththeassociateddocumentation.

2. Programminglanguagesanditstypes.
Programming is also known as software engineering. It is the process of writing a program, or
software.Theinstructionsthatcanbeusedtoconstructaprogramconsistofstatementswrittenin
a programming language, the language that the computer can interpret or understand such as
C++orVisualBASIC.Firstintroducedin1945,programminglanguageshaveevolvedovertheyears.

Thebirthsofthegenerationsareasfollow.
Firstgeneration,1945machinelanguage
Secondgeneration,mid1950sassemblylanguage
Thirdgeneration,early1960shighlevellanguages:FORTRAN,COBOL,C,BASIC,C++,and
Pascal




________________________________________________________________________________________________________________
References: 2
Malik,D.S.,(2010).C++Programming,FromProblemAnalysistoProgramDesign.CourseTechnology,Canada.
rd
Gary,R.B.,(2010).C++ForEngineers&Scientists:3 Edition.CourseTechnology,Canada.
RoslanSadjirin/DepartmentofComputerScience/FacultyofComputerandMathematicalSciences/UiTMPahang
CSC128FUNDAMENTALSOFCOMPUTERPROBLEMSOLVING
Chapter1:Introduction

a. FirstGeneration:MachineLanguage(LowLevelLanguage)
Theonlyprogramsthatcanbeusedtooperateacomputer.
Thelowestlevelofcomputerprogramminglanguage.
Machinelanguageoralsoreferredtoasexecutableprograms,orexecutablesforshort,
consistofasequenceofinstructionscomposedofbinarynumbers(0sand1s)suchas:

100000000000000100000010
111100000000001000000011

which correspond to on and off of electrical states of the computer, which not
convenientforpeopletoreadanduse.
Each instruction in a machine language consists of two parts: instruction part and
address part.Theinstructionpartisreferredtoasopcode(operationcode), isusually
the leftmost set of bits in the instruction. It tells the computer operation to be
performed, such as add, subtract, multiply, etc., while the rightmost bits specify the
memoryaddressesofthedatatobeused.
For example, assuming that the eight leftmost bits of the first instruction (i.e.
100000000)listedaboveistheopcodeforadd,andthenexttwogroupsoftwelvebits
aretheaddressesoftwooperandstobeadded.Thisinstructionwouldbeacommand
toaddthedatainmemorylocation1tothedatainmemorylocation2.
Similarly,assumingthattheopcode11110000meansmultiply,thenextinstructionisa
commandtomultiplythedatainmemorylocation3bythedatainlocation4.

b. SecondGeneration:AssemblyLanguage(LowLevelLanguage)
One of the first advances in programming was the substitution of wordlike symbols,
such as ADD, MUL, for the binary opcodes and both decimal numbers and label for
memoryaddresses.
Forexample,theprevioustwomachinelanguageinstructioncannowbewrittenas

ADD1,2
MUL2,3

Theparticularprogramminglanguageiscalledassemblylanguage.Assemblylanguageis
a lowlevel language that allows a programmer to use abbreviations or easily
rememberedwordsinsteadofnumbers.

________________________________________________________________________________________________________________
References: 3
Malik,D.S.,(2010).C++Programming,FromProblemAnalysistoProgramDesign.CourseTechnology,Canada.
rd
Gary,R.B.,(2010).C++ForEngineers&Scientists:3 Edition.CourseTechnology,Canada.
RoslanSadjirin/DepartmentofComputerScience/FacultyofComputerandMathematicalSciences/UiTMPahang
CSC128FUNDAMENTALSOFCOMPUTERPROBLEMSOLVING
Chapter1:Introduction

Computer can only execute machine language programs, the set of instructions
contained within an assembly language program must be translated into machine
language. Translator programs that perform this function for assembly language
programsareknownasassemblers.

AnAssembly TranslationProgram MachineLanguage


LanguageProgram (Assembler) Program

Both machine and assembly languages are classified as lowlevel languages, and they
generally execute at the fastest level possible. As with the case of machine language,
assemblylanguagevariesfromcomputertocomputeritismachinedependent.

c. ThirdGeneration:Highlevellanguage
A highlevel language is an Englishlike programming language. A highlevel language
programcanberunonavarietyofcomputertypes.
Forexamples:FORTRAN,Pascal,Java,C++,C,COBOL,ADA,LISP,PL/1,RPG,Logo,APL,
FORTHandProlog.
Aswithassemblylanguage,highlevellanguagerequiresatranslatortotranslateitinto
machine language. The translator for highlevel languages is either a compiler or an
interpreter(compilerandinterpreterwillbediscussedlaterinthistopic).


Figure1:HierarchyofComputerOrganization

3. Programming,programmersandusers
The process of writing or coding programs is called programming, and the individuals who write
programsarecalledprogrammers.Users,ontheotherhand,areindividualswhousetheprogram.
________________________________________________________________________________________________________________
References: 4
Malik,D.S.,(2010).C++Programming,FromProblemAnalysistoProgramDesign.CourseTechnology,Canada.
rd
Gary,R.B.,(2010).C++ForEngineers&Scientists:3 Edition.CourseTechnology,Canada.
RoslanSadjirin/DepartmentofComputerScience/FacultyofComputerandMathematicalSciences/UiTMPahang
CSC128FUNDAMENTALSOFCOMPUTERPROBLEMSOLVING
Chapter1:Introduction

B. Importanceofcomputerprogramming
A computer without a program is useless. A computer must have a program to accept input,
processtheinputandproduceoutput.
Before a program is written, a programmer analyzes the requirement and designs a correct
algorithmsothattheprogramwillproducethedesiredoutput.Therefore,itisveryimportant
that programmers have a good understanding of computer, problemsolving approaches and
compositionsofthechosenprogramminglanguages.

C. Importanceofgoodprograms
Inorderforaprogramtobeconsideredasagoodprogram,itmusthavethefollowing:
1. Reliabilityofoutput
Agoodprogrammustbeabletoproducecorrectoutput.Forthat,adifferentsetofinputdatais
usedtoensurethereliabilityoftheoutput.

2. Programsefficiency
Agoodprogrammustbedesignedtobeefficientandreliableinthesensethatitproducesno
errors during execution process. Also, the program must achieve its purpose so that the final
result can be trusted. Thus, it is important that the program is outlined first using the
pseudocodeorflowcharttool.

3. Interactivity
The interaction process between the user and the program must be well defined. The
interactivityisimportantsothattheuserknowstheprocessingstatus.Programthatareuser
friendlyallowtheuserstorespondstoinstructioncorrectlyandthiswillhelptheuserstokeyin
inputthusminimizingtheerrorsresultedfrominvaliddata.






________________________________________________________________________________________________________________
References: 5
Malik,D.S.,(2010).C++Programming,FromProblemAnalysistoProgramDesign.CourseTechnology,Canada.
rd
Gary,R.B.,(2010).C++ForEngineers&Scientists:3 Edition.CourseTechnology,Canada.
RoslanSadjirin/DepartmentofComputerScience/FacultyofComputerandMathematicalSciences/UiTMPahang
CSC128FUNDAMENTALSOFCOMPUTERPROBLEMSOLVING
Chapter1:Introduction

Exampleofabadprogramsoutputscreen
Thisoutputproducestheblinkingcursorthatexpectstheusertoentersomedata.However,the
kindofdatatobeenteredisunknowntotheuser.

| Blinkingcursor.Userdoes
notknowwhatdatatobe
enteredhere.


Exampleofagoodprogramsoutputscreen
This output screen tells the user what will be achieved when entering the input data. The
instructionhelpstheusertoenterdatatobecorrectlyprocessedbytheprogram.

**Thisprogramaddstwointegers**

Theinstructionclearlytells
Pleaseenter2integers:| userwhattodo.



4. Programreadability
Readabilityisconcernedwithhowotherpersonviewsonesprogram.Forprogrammers,theuse
ofindentionandcommentsarecommontoimprovetheprogramsreadability.
a. Indentation
Indentationhelpsinmakingthestructureoftheprogramclearerandeasiertoread.
A statement within a statement should be indented to show the user which
statementsaresubordinatedoftheother.
In C++, particularly, ifelse, while and dowhile statements should be indented.
Embedded braces { } are also indented to make it easier to find the matching
pairs.






________________________________________________________________________________________________________________
References: 6
Malik,D.S.,(2010).C++Programming,FromProblemAnalysistoProgramDesign.CourseTechnology,Canada.
rd
Gary,R.B.,(2010).C++ForEngineers&Scientists:3 Edition.CourseTechnology,Canada.
RoslanSadjirin/DepartmentofComputerScience/FacultyofComputerandMathematicalSciences/UiTMPahang
CSC128FUNDAMENTALSOFCOMPUTERPROBLEMSOLVING
Chapter1:Introduction

Table1:Exampleofindentationusingifelse,forandwhilestatement.
Beforeindentation: Afterindentation:
if (score > 90) if (score > 90)
{ highest = highest + 1; { highest = highest + 1;
cout << Highest scores!!; } cout << Highest scores!!;
}
else if ( score < 40 ) else if ( score < 40 )
{ lowest = lowest + 1; { lowest = lowest + 1;
cout << Lowest scores!!;} cout << Lowest scores!!;
}

for ( int bil = 1; bil < 5; bil++) for ( int bil = 1; bil < 5; bil++)
{ sumAllNum = sumAllNum + num; { sumAllNum = sumAllNum + num;
cout << \n Enter num : ; cout << \n Enter num : ;
cin >> num; } cin >> num;
}

while (y >= 2) while (y >= 2)


{ x = x / 2; { x = x / 2;
if (x > 0 ) if (x > 0 )
y = 1 + y; y = 1 + y;
else else
y = x + y; y = x + y;
i++;} i++;
}



b. Comments
Some explanatory notes or comments (sometimes referred to as internal
documentation)shouldbeplaceintheprogramcodingtoimproveitsreadability.In
other words, comments are there for the convenience of anyone reading the
program.
Comments can be placed anywhere within in a program and they will NOT be
executed by the compiler. Commenting out a section of code is very useful in a
debuggingprocess.



________________________________________________________________________________________________________________
References: 7
Malik,D.S.,(2010).C++Programming,FromProblemAnalysistoProgramDesign.CourseTechnology,Canada.
rd
Gary,R.B.,(2010).C++ForEngineers&Scientists:3 Edition.CourseTechnology,Canada.
RoslanSadjirin/DepartmentofComputerScience/FacultyofComputerandMathematicalSciences/UiTMPahang
CSC128FUNDAMENTALSOFCOMPUTERPROBLEMSOLVING
Chapter1:Introduction

C++supportstwotypesofcomments:
i. Linecomment
Alinecommentbeginswithtwoslashes(//)andcontinuestotheendofline.
Example1:
//This program is to calculate the perimeter this is line //comment
#include <iostream.h>

int main()
{
//declare variables this is line comment
float perimeter = 0.0, length = 10.5, width = 8.6;

//calculate perimeter
perimeter = (length + width) * 2;

//print to the screen console


cout << Perimeter is << perimeter;
return 0; //indicates program ended normally this is comment
} //end of main function this is line function


Example2:
//This program is to calculate area of the circle this is line //comment
#include <iostream.h>

int main()
{ //declare variables this is line comment
float radius = 5.6, area;
float const PI = 3.142;

//calculate area of the circle this is line comment


area = PI * radius * radius;

//print to screen console


cout << The area of the circle is << area;
return 0; //indicates program ended normally this is comment
} //end of main function this is line function

________________________________________________________________________________________________________________
References: 8
Malik,D.S.,(2010).C++Programming,FromProblemAnalysistoProgramDesign.CourseTechnology,Canada.
rd
Gary,R.B.,(2010).C++ForEngineers&Scientists:3 Edition.CourseTechnology,Canada.
RoslanSadjirin/DepartmentofComputerScience/FacultyofComputerandMathematicalSciences/UiTMPahang
CSC128FUNDAMENTALSOFCOMPUTERPROBLEMSOLVING
Chapter1:Introduction

ii. Blockcomment
Block comment begins with the symbol /* and end with symbol */. Block
commentsareconvenientlyusedforstatementsthatspanacrosstwoormore
lines.
Example:
/*
Programmer : Roslan Sadjirin
Course Code : CSC125 / CSC128
This program is to calculate the perimeter this is block comment
*/

#include <iostream.h>

int main()
{
//declare variables this is line comment
float perimeter = 0.0;
float length = 10.5;
float width = 8.6;

//calculate perimeter
perimeter = (length + width) * 2;

//print to screen console


cout << Perimeter is << perimeter;

return 0; /*indicates program ended normally this is block


comment*/

} //end of main function this is line function

________________________________________________________________________________________________________________
References: 9
Malik,D.S.,(2010).C++Programming,FromProblemAnalysistoProgramDesign.CourseTechnology,Canada.
rd
Gary,R.B.,(2010).C++ForEngineers&Scientists:3 Edition.CourseTechnology,Canada.
RoslanSadjirin/DepartmentofComputerScience/FacultyofComputerandMathematicalSciences/UiTMPahang
CSC128FUNDAMENTALSOFCOMPUTERPROBLEMSOLVING
Chapter1:Introduction

D. Relationshipbetweencompilers,interpreters,assemblersandprograms
1. Whatarethecompilerandinterpreter?
Compilerandinterpreterisalanguagetranslatorprogramthattranslatessourcecode(human
readablecode)intomachinelanguage.

LanguageTranslator
Program
Compiler Interpreter

Translatealloftheinstructionsofhighlevel Convertshighlevellanguageinstruction
intomachinelanguageoneatatime,in
languageasacompleteunit. succession.
Theoriginalprogramthatiswritteninhigh
levellanguageiscalledsourcecode. Anyoftheinstructionsthatcontainerror,
Sourcecodetheoriginalprogram interpretersprovidesimmediate
written in assembly language or feedback.
highlevel languages. The file Doesnotproduceobjectcode.

containing the source code is
called source file, and in C++, it is
uses the filename extension .cpp
(cppstandsforCplusplus)
While attempting to translate each of the
statement, the compiler also detects error
messageaftertranslationiscompleted.
Otherwise, the compiler successfully
translates the source code into machine
language,whichinthiscaseobjectcode.
Object code created from the
compilation process in machine
readable form. The file containing

theobjectcodeiscalledtheobject
file, and it uses the file name
extension .obj (obj stands for
object)
After compiler creates the object file, it

then invokes another program called a
linker. The linker combines the object file
withothermachinecodenecessaryforthe
C++ program to run correctly. The linker
files then produces an executable file that
has an extension of .exe (exe stands for
executable).

________________________________________________________________________________________________________________
References: 10
Malik,D.S.,(2010).C++Programming,FromProblemAnalysistoProgramDesign.CourseTechnology,Canada.
rd
Gary,R.B.,(2010).C++ForEngineers&Scientists:3 Edition.CourseTechnology,Canada.
RoslanSadjirin/DepartmentofComputerScience/FacultyofComputerandMathematicalSciences/UiTMPahang
CSC128FUNDAMENTALSOFCOMPUTERPROBLEMSOLVING
Chapter1:Introduction

2. Stepsinrunningaprogramusingcompiler


Figure2:Stepsinrunningaprogramusingcompiler

3. Stepsinrunningaprogramusinginterpreter


Figure3:Stepsinrunningaprogramusinginterpreter

4. Programerrors
Although the principle in programming is for efficiently produce readable and errorfree
programsthatworkcorrectly,errorsorsometimesarecalledbugscanoccuratanytime.

Therearedifferenttypesoferrors:
a. Runtimeerrors
b. Syntaxerrors
c. Logicerrors


________________________________________________________________________________________________________________
References: 11
Malik,D.S.,(2010).C++Programming,FromProblemAnalysistoProgramDesign.CourseTechnology,Canada.
rd
Gary,R.B.,(2010).C++ForEngineers&Scientists:3 Edition.CourseTechnology,Canada.
RoslanSadjirin/DepartmentofComputerScience/FacultyofComputerandMathematicalSciences/UiTMPahang
CSC128FUNDAMENTALSOFCOMPUTERPROBLEMSOLVING
Chapter1:Introduction

a. Runtimeerrors
Runtimeerrorsoccurduringtheexecutionofaprogramandaredetectedbythecompiler.
Example:
1 #include <iostream.h>
2
3 int main()
4 {
5 int a = 0 , b = 7, result; // declaration
6 result = b / a;
7
8 cout << The result is << result << endl; /*Run-time Error
9 here!*/
10
11 return 0;
12 }
13


Attempting to divide by zero in the above statement causes a runtime error such as
Floating point division by error or divideerror exception. The method for detecting
errorsafteraprogramhasbeenexecutediscalleddebuggingprocess.Adebuggerprogram
isavailableinC++fordetectingerrorswhileaprogramisbeingexecuted.

b. Syntaxerrors
A syntax error is an error in the structure or spelling of a statement. This error can be
detectedbythecompilerduringcompilationoftheprogram.
Example:
1 #include <iostream.h>
2
3
4 int main()
5 {
6 cout << /nThere are 5 syntax errors here
7 cot >> correct them;
8
9 return 0;
10 }


________________________________________________________________________________________________________________
References: 12
Malik,D.S.,(2010).C++Programming,FromProblemAnalysistoProgramDesign.CourseTechnology,Canada.
rd
Gary,R.B.,(2010).C++ForEngineers&Scientists:3 Edition.CourseTechnology,Canada.
RoslanSadjirin/DepartmentofComputerScience/FacultyofComputerandMathematicalSciences/UiTMPahang
CSC128FUNDAMENTALSOFCOMPUTERPROBLEMSOLVING
Chapter1:Introduction

Explanation:
i. Invaliduseofbackslash(/)inline6
ii. Missingsemicolon(;)inline6
iii. Keywordcoutismisspelledinline7
iv. Invaliduseofinsertionsymbol(>>)inline7
v. Missingaclosingquote()inline7

A C++ statement with correct syntax will be accepted by the compiler without any error
messages. Nevertheless, a statement or program can be syntactically correct but still be
logicallyincorrect.Consequently,incorrectresultwouldbeproduced.

c. Logicerrors
Logicerrorsrefertotheunexpectedorunintentionalerrorsresultedfromsomeflawinthe
programslogic.Logicerrorisverydifficulttodetectsincecompilercannotdetectthiserror.
The only way to detect it is by testing the program thoroughly and comparing its output
againstmanuallycalculatedresults.

Someindicationsoflogicerrorsinclude:
i. Nonumericaloutput
Thisiscausedbyamissingnumericaloutputinacoutstatement.
Example:
1 #include <iostream.h>
2
3 int main()
4 {
5 int qty;
6 double price;
7 cout<<Enterquantityofitemspurchased:;
8 cin>>qty;
9 cout<<\nEnterthepriceunit:RM;
10 cin>>price;
11 cout<<ThetotalpriceisRM; //logicerrorhere
12 cout<<\nThankyou.;
13 return 0;
14 }

________________________________________________________________________________________________________________
References: 13
Malik,D.S.,(2010).C++Programming,FromProblemAnalysistoProgramDesign.CourseTechnology,Canada.
rd
Gary,R.B.,(2010).C++ForEngineers&Scientists:3 Edition.CourseTechnology,Canada.
RoslanSadjirin/DepartmentofComputerScience/FacultyofComputerandMathematicalSciences/UiTMPahang
CSC128FUNDAMENTALSOFCOMPUTERPROBLEMSOLVING
Chapter1:Introduction

Theoutputfortheaboveprogramstatementis
Enter quantity of items purchased: 5
Enter the price unit: RM 50;
The total price is
Thank you.


ii. Unappealingormisalignedoutput
This either caused by an error in cout statement or the use of formatting output
statement(\n,\t).
Example:
1 #include <iostream.h>
2
3 int main()
4 {
5 int qty;
6 double price, total;
7 cout << Enter quantity : \t\t ; //logicerrorhere
8 cin >> qty;
9 cout << \n Enter price: RM ;
10 cin >> price;
11 total = qty * price;
12 cout << The total price is RM << total;
13 cout << Thank you.; //logicerrorhere
14 return 0;
15 }


Sampleoutput
Enter quantity: 5
Enter price: RM 10
The total price is RM 50Thank you





________________________________________________________________________________________________________________
References: 14
Malik,D.S.,(2010).C++Programming,FromProblemAnalysistoProgramDesign.CourseTechnology,Canada.
rd
Gary,R.B.,(2010).C++ForEngineers&Scientists:3 Edition.CourseTechnology,Canada.
RoslanSadjirin/DepartmentofComputerScience/FacultyofComputerandMathematicalSciences/UiTMPahang
CSC128FUNDAMENTALSOFCOMPUTERPROBLEMSOLVING
Chapter1:Introduction

iii. Incorrectnumericalresults
Thisiscausedbyeitherincorrectvaluesordatatypesassignedtothevariablesused
inanexpression,incorrectarithmeticexpression,anomissionofastatement,round
offerror,orimproperusesequenceofstatement.
Example:
int main()
{
char fnum = 10; // error here
int snum = 5;
int sum = fnum + snum;
.
.
return 0;
}


Wherefnumisoftypecharacter.Thevalidcharactertobeassignedis
charfnum=A;

iv. Prematureprogramtermination
iftheerrorisdetectedduringtheprogramexecution,aruntimeerroroccursthat
results in an error message being generated or abnormal and premature program
termination.
Example:
1 int radius = 4.562, num = -4, count = 0;
2 float total = 10.0, average;
3 average = total / count;
4 cout << Average is ;
5 cout << \n The square root of << num << is << sqrt(num);


Explanation:
Thelogicerrorsare:
i. Assigninginvalidvaluestovariableoftypeintegerinline1
ii. Attemptingtodividebyzeroinline3
iii. Missingnumericaloutputinline4
iv. Takingthesquarerootofanegativenumberinline5

________________________________________________________________________________________________________________
References: 15
Malik,D.S.,(2010).C++Programming,FromProblemAnalysistoProgramDesign.CourseTechnology,Canada.
rd
Gary,R.B.,(2010).C++ForEngineers&Scientists:3 Edition.CourseTechnology,Canada.
RoslanSadjirin/DepartmentofComputerScience/FacultyofComputerandMathematicalSciences/UiTMPahang
CSC128FUNDAMENTALSOFCOMPUTERPROBLEMSOLVING
Chapter1:Introduction

E. ProgramDevelopmentLifeCycle
In designing a program, there is no complete set of rules or specific algorithm to follow.
However,softwaredeveloperstrytouseareasonablyconsistentproblemsolvingapproachfor
constructingcomputerprograms.
Thephasesintheproblemsolvingapproachareoutlinedasfollows:
Phase1:ProblemDefinition(Analysis)
Phase2:Algorithmdesign
Phase3:Algorithmimplementation
Phase4:Programtesting
Phase5:Programmaintenance

Thephasescanbefurtherdividedintotwo:
a. Problemsolvingphases:consistofproblemdefinitionandalgorithmdesign
b. Implementation phases: consist of algorithm implementation, program testing and
programmaintenancephases.

________________________________________________________________________________________________________________
References: 16
Malik,D.S.,(2010).C++Programming,FromProblemAnalysistoProgramDesign.CourseTechnology,Canada.
rd
Gary,R.B.,(2010).C++ForEngineers&Scientists:3 Edition.CourseTechnology,Canada.
RoslanSadjirin/DepartmentofComputerScience/FacultyofComputerandMathematicalSciences/UiTMPahang
CSC128FUNDAMENTALSOFCOMPUTERPROBLEMSOLVING
Chapter1:Introduction

1. Problemdefinition(Analysis)
Problemdefinitionisalsocalledtheanalysisphase.Theproblemisdefinedtoobtainaclear
understandingoftheproblemrequirement.
Thefollowingquestionsshouldbeaskedtogetacompleteproblemspecification:
a. Whataretheinputdata?
b. Whataretheoutput(desired)data?
c. Whatformulaistobeused?
d. Whatotherassumptionsorconstraintscanbemade?
e. Whatistheexpectedoutputscreen?

2. Algorithmdesign
Thespecificationsderivedearlierintheanalysisphasearetranslatedintothealgorithm.An
algorithm is a stepbystep sequence of precise instructions that must terminate and
describeshowthedataistobeprocessedtoproducethedesiredoutputs.Theinstruction
maybeexpressedinahumanlanguage.
Analgorithmmustsatisfysomerequirements:
a. Inputandoutput
Itmusthavezeroormoreinputandmustproduceatleastoneoutput.
b. Unambiguous
Every step in algorithm must be clear as to what it is supposed to do and how many
timesitisexpectedtobeexecuted.
c. Correctandefficient
Itmustbecorrectandefficientlysolvetheproblemforitisdesigned.
d. Finite
Itmustexecuteitsinstructionandterminateinafinitetime.

Analgorithmcanbewrittenordescribedusingseveraltools:
a. Pseudocode
Use Englishlike phrases to describe the processing task. It is not standardized since
everyprogrammerhashisorherownwayofplanningthealgorithm.

________________________________________________________________________________________________________________
References: 17
Malik,D.S.,(2010).C++Programming,FromProblemAnalysistoProgramDesign.CourseTechnology,Canada.
rd
Gary,R.B.,(2010).C++ForEngineers&Scientists:3 Edition.CourseTechnology,Canada.
RoslanSadjirin/DepartmentofComputerScience/FacultyofComputerandMathematicalSciences/UiTMPahang
CSC128FUNDAMENTALSOFCOMPUTERPROBLEMSOLVING
Chapter1:Introduction

Table2:Pseudocodestyle
Style1 Style2(Modulardesign)
Problem Problem
Begin Begin
1. Subproblem 1 1. Subproblem 1
Task 1,1 2. Subproblem 2
Action 1,1,1 3. End
Action 1,1,2
2. Subproblem 2 1. Subproblem 1
Task 1,2 Task 1,1
Action 1,2,1 Action 1,1,1
Action 1,2,2 Action 1,1,2
End
2. Subproblem 2
Task 1,2
Action 1,2,1
Action 1,2,2
End


b. Flowchart
Usestandardizedsymboltoshowthestepsthecomputerneedstotaketoaccomplish
theprogramsobjective.Becauseflowchartsarecumbersometorevise,theyhavefallen
outoffavourbyprofessionalprogrammers.Pseudocode,ontheotherhand,hasgained
increasingacceptance.
Table3:Flowchartsymbols
Name Symbol Description

Lozenge Terminal(start/stop)

Parallelogram Data(input/output)

Rectangle Process

Diamond Decision/Selection

Rectangle Module(Predefinedprocess)

Arrow Flowline(flowchart)

________________________________________________________________________________________________________________
References: 18
Malik,D.S.,(2010).C++Programming,FromProblemAnalysistoProgramDesign.CourseTechnology,Canada.
rd
Gary,R.B.,(2010).C++ForEngineers&Scientists:3 Edition.CourseTechnology,Canada.
RoslanSadjirin/DepartmentofComputerScience/FacultyofComputerandMathematicalSciences/UiTMPahang
CSC128FUNDAMENTALSOFCOMPUTERPROBLEMSOLVING
Chapter1:Introduction

Mostcomputeralgorithmsconsistofatleastthefollowingprocesses.
i. Gettheinput(data)
ii. Performthecomputation(processing)
iii. Displaytheoutput(results)

3. Algorithmimplementation
The algorithm is translated into a computer program by using a specific programming
language,forexampleC++.Theprocesscalledcoding,whichinvolvesediting,compilingand
debugging.

4. Programtesting
Programtestingrequirestestingthecompletedprogramtoverifythatitproducesexpected
output. A different set of testing data is normally used to verify that the program works
properlyandthatitisindeedsolvingthegivenproblem.

5. Programmaintenance
Often, there may be new requirements to be added into the current program. Making
revisions to meet the changing needs with ongoing correction of problem are the major
effortsintheprogrammaintenance.Asaresult,theprogramcodesmaybemodified,added
or deleted accordingly. Thus, it is very important that a program is well documented for
futuredevelopment.










________________________________________________________________________________________________________________
References: 19
Malik,D.S.,(2010).C++Programming,FromProblemAnalysistoProgramDesign.CourseTechnology,Canada.
rd
Gary,R.B.,(2010).C++ForEngineers&Scientists:3 Edition.CourseTechnology,Canada.
RoslanSadjirin/DepartmentofComputerScience/FacultyofComputerandMathematicalSciences/UiTMPahang
CSC128FUNDAMENTALSOFCOMPUTERPROBLEMSOLVING
Chapter1:Introduction

F. Exampleofproblemsthatcanbesolvedusingcomputers
Problem1:WriteacompleteC++programtocalculatethesumandaverageof2integernumbers,and
thendisplaythesumandtheaverageofthosenumbers.
Step1:Problemdefinition(analysis)
Output Input Process
Outputvariable: Inputvariable: Processingitems:
sum number_1 sum,average
average number_2
Formula:
Constant: sum=number_1+number_2
NONE average=sum/2

Step/Solutionalgorithm:
1. Getinput(fromkeyboard)
2. Calculatesum(inCPUandMemory)
3. Calculateaverage(inCPUandMemory)
4. Displayoutput(toscreenconsole/monitor)

Step2:Algorithmdesign(Pseudocodeorflowchart)
a. Pseudocode
Simpledesign Modulardesign
Calculatethesumandaverage Calculatethesumandaverage
Begin Begin
1.Getinput 1.get_Input()
Readnumber_1 2.calculate_Sum()
Readnumber_2 3.calculate_Average()
2.Calculatesum 4.display_Output()
sum=number_1+number_2 End
3.Calculateaverage
average=sum/2 1.get_Input()
4.Displayoutput Readnumber_1
Printsum Readnumber_2
Printaverage
End 2.calculate_Sum()
sum=number_1+number_2

3.calculate_Average()
average=sum/2

4.display_Output()
Printsum
Printaverage


________________________________________________________________________________________________________________
References: 20
Malik,D.S.,(2010).C++Programming,FromProblemAnalysistoProgramDesign.CourseTechnology,Canada.
rd
Gary,R.B.,(2010).C++ForEngineers&Scientists:3 Edition.CourseTechnology,Canada.
RoslanSadjirin/DepartmentofComputerScience/FacultyofComputerandMathematicalSciences/UiTMPahang
CSC128FUNDAMENTALSOFCOMPUTERPROBLEMSOLVING
Chapter1:Introduction

b. Flowchart
Simpledesign

Begin

Readnumber_1,number_2

sum=number_1+number_2

average=sum/2

Printsum,average

End

________________________________________________________________________________________________________________
References: 21
Malik,D.S.,(2010).C++Programming,FromProblemAnalysistoProgramDesign.CourseTechnology,Canada.
rd
Gary,R.B.,(2010).C++ForEngineers&Scientists:3 Edition.CourseTechnology,Canada.
RoslanSadjirin/DepartmentofComputerScience/FacultyofComputerandMathematicalSciences/UiTMPahang
CSC128FUNDAMENTALSOFCOMPUTERPROBLEMSOLVING
Chapter1:Introduction

Modulardesign Submodule

Start get_Input

get_Input()
Read Read
number_1 number_2


calculate_Sum()

Return

calculate_Average()
calculate_Sum()

display_Output() sum=number_1+number_2

Stop Return

calculate_Average()

average=sum/2

Return

display_Output()

Printsum Printaverage

Return

________________________________________________________________________________________________________________
References: 22
Malik,D.S.,(2010).C++Programming,FromProblemAnalysistoProgramDesign.CourseTechnology,Canada.
rd
Gary,R.B.,(2010).C++ForEngineers&Scientists:3 Edition.CourseTechnology,Canada.
RoslanSadjirin/DepartmentofComputerScience/FacultyofComputerandMathematicalSciences/UiTMPahang
CSC128FUNDAMENTALSOFCOMPUTERPROBLEMSOLVING
Chapter1:Introduction

Step3:AlgorithmImplementation(Coding)
Simplesequentialprogrammingdesign
//Implementation of simple sequential programming design

#include <iostream.h> //to handle output (cout) and input (cin) statement

int main() // general function


{
//declare input variable place a space to store value in a computer memory
int number_1, number_2;

//declare output variable place a space to store value in a computer memory


int sum, average;

cout << Enter first number ; //prompt user to enter first number
cin >> number_1; //read value from keyboard and store in number_1
cout << Enter second number ; //prompt user to enter second number
cin >> number_2; //read value from keyboard and store in number_2

//calculate sum in CPU and memory


sum = number_1 + number_2;

//calculate average in CPU and memory


average = sum / 2;

//Display output (sum and average) to the screen console (monitor)


cout << The sum of << number_1 << and << number_2 << is << sum << endl;
cout << The average of << number_1 << and << number_2 << is << average;

return 0;
} //end of main()

________________________________________________________________________________________________________________
References: 23
Malik,D.S.,(2010).C++Programming,FromProblemAnalysistoProgramDesign.CourseTechnology,Canada.
rd
Gary,R.B.,(2010).C++ForEngineers&Scientists:3 Edition.CourseTechnology,Canada.
RoslanSadjirin/DepartmentofComputerScience/FacultyofComputerandMathematicalSciences/UiTMPahang
CSC128FUNDAMENTALSOFCOMPUTERPROBLEMSOLVING
Chapter1:Introduction

Simplemodularprogrammingdesign
/*
Implementation of simple modular programming design in C++, module also known as function
*/

#include <iostream> //to handle output (cout) and input (cin)statements

using namespace std; /*Allow the compiler to use the standard header file
defined in ANSI/ISO standard*/

//declare input variable place a space to store value in a computer memory


int number_1, number_2;

//declare output variable place a space to store value in a computer memory


int sum, average;

/*
declare module or function prototype - place a space to store value and processed value in
a computer memory
*/
void get_Input();
void calculate_Sum();
void calculate_Average();
void display_Output();

int main()
{
get_Input(); //invoke get_Input() function
calculate_Sum(); //invoke calculate_Sum() function
calculate_Average(); //invoke calculate_Average() function
display_Output(); //invoke display_Output () function

return 0;
}

void get_Input()
{
cout << Enter first number ; //prompt user to enter first number
cin >> number_1; //read value from keyboard and store in number_1
cout << Enter second number ; //prompt user to enter second number
cin >> number_2; //read value from keyboard and store in number_2
}

void calculate_Sum()
{
//calculate sum in CPU
sum = number_1 + number_2;
}

void calculate_Average()
{
//calculate average in CPU
average = sum / 2;
}

void display_Output()
{
//Display output (sum and average) to the screen console (monitor)
cout << The sum of << number_1 << and << number_2 << is << sum;
cout << The average of << number_1 << and << number_2 << is << average;
}

________________________________________________________________________________________________________________
References: 24
Malik,D.S.,(2010).C++Programming,FromProblemAnalysistoProgramDesign.CourseTechnology,Canada.
rd
Gary,R.B.,(2010).C++ForEngineers&Scientists:3 Edition.CourseTechnology,Canada.
RoslanSadjirin/DepartmentofComputerScience/FacultyofComputerandMathematicalSciences/UiTMPahang
CSC128FUNDAMENTALSOFCOMPUTERPROBLEMSOLVING
Chapter1:Introduction

TUTORIAL

1. Whatisacomputerprogram?
2. NameTWO(2)typesofcomputerlanguages.
3. Whatistheonlylanguagethatacomputercandirectlyunderstand?
4. Giveanexampleoflowlevelprogramminglanguages.
5. WhattypeofcomputerlanguageusesEnglishlikeabbreviationsformachinelanguageinstructions?
6. ListFIVE(5)examplesofhighlevelprogramminglanguages.
7. Whatisacompiler?
8. Whatisthepurposeofthepreprocessingdirective?
#include <iostream.h>

9. Whatpurposedobracesserve?
10. Whataresymbolsusedtowritecomments?

11. Whatisasourcecode?

12. Whatisanobjectcode?

13. Listfivebasicstepsintheprogrammingprocess.

14. Defineanalgorithm.

15. Defineaflowchart.

16. Defineapseudocode.

17. Whatissyntaxerror?

18. Whatislogicerror?

19. Whatisthepurposeofdocumentationinaprogram?

________________________________________________________________________________________________________________
References: 25
Malik,D.S.,(2010).C++Programming,FromProblemAnalysistoProgramDesign.CourseTechnology,Canada.
rd
Gary,R.B.,(2010).C++ForEngineers&Scientists:3 Edition.CourseTechnology,Canada.
RoslanSadjirin/DepartmentofComputerScience/FacultyofComputerandMathematicalSciences/UiTMPahang
CSC128FUNDAMENTALSOFCOMPUTERPROBLEMSOLVING
Chapter1:Introduction

PROBLEMSOLVINGANDPROGRAMMINGACTIVITIES

1. Writeaprogramtodisplayoutputasbelow:

*****************************
* Thank You *
* Please come again *
*****************************


2. Writeaprogramtodisplayyourname,addressandtelephone.Printyourinformationlinebyline.
3. Writeaprogramtodisplayyourownmessage.Yourmessagemustatleastfivelines.
4. People who lives in Shah Alam are imposed a charges 3% income tax on yearly wages. Write a
programthatwilldisplaytheincometax.
a. Identifytheoutput,inputandprocessfortheaboveproblem.
b. Drawaflowcharttosolvetheproblem.
c. TranslatethealgorithmintoC++programminglanguage.
5. Afinancecompanywillgivealoantoacustomerforbuyingacarbasedontheamountoftheloan.
IftheloanisRM100,000ormore,theinterestratewillbe3.5%,otherwiseitwillbe5%annually.
Givetheamountofloanandtheperiodofrepayment,
a. Identifytheoutput,inputandprocess.
b. Draw a flowchart to calculate the amount of interest and the monthly payment or
installment.
6. Assumethatyourweightisxkilograms.Youneedtoconvertyourweighttopoundanddisplayit.
Hint:1kg=2.2pounds.
a. Definetheoutput,inputandprocessofthistask.
b. Drawtheflowchart.
c. Writethepseudocode.
d. WriteaC++programbasedonthealgorithm.
7. The length and width of a rectangle is x cm and y cm respectively. You need to calculate the
perimeterandareaofrectangle.
a. Definetheoutput,inputandprocess
b. Drawtheflowchart.
c. Writethepseudocode.
d. WriteaprogrambasedonthealgorithmusingC++programminglanguage.
________________________________________________________________________________________________________________
References: 26
Malik,D.S.,(2010).C++Programming,FromProblemAnalysistoProgramDesign.CourseTechnology,Canada.
rd
Gary,R.B.,(2010).C++ForEngineers&Scientists:3 Edition.CourseTechnology,Canada.
RoslanSadjirin/DepartmentofComputerScience/FacultyofComputerandMathematicalSciences/UiTMPahang
CSC128FUNDAMENTALSOFCOMPUTERPROBLEMSOLVING
Chapter1:Introduction

8. Yourprogramshouldbeabletodeterminewhethertheapplicantisqualifiedtoapplyforacredit
cardornotbasedonhissalary.IfthesalaryisgreaterthanRM1500,thendisplayamessagethatthe
applicant entitles to apply. Otherwise, display a message that the applicant cannot apply for the
creditcard.
a. Definetheoutput,inputandprocessofthistask.
b. Drawtheflowchart.
c. Writetheprogrambasedontheflowchart.
9. Your program should be able to determine the correct password. A message, Password
Accepted, is display when the user enters the correct password. Otherwise a message

Incorrect Password, Please Try Againwillbedisplayed.Theprocesswillrepeatuntil

thecorrectpasswordisentered.
a. Definetheoutput,inputandprocess.
b. Drawtheflowchart.
c. Writeapseudocode.
10. Draw a flowchart and write C++ program to calculate and display an average salary of three
employees.
11. Drawaflowcharttofindthehighestsalaryofthreeemployees.Afterward,writeaC++program.
12. Draw aflowchart to calculate an average of aseries of positiveinteger numbers. The process will
stopifthenumberenteredhasanegativevalue.

________________________________________________________________________________________________________________
References: 27
Malik,D.S.,(2010).C++Programming,FromProblemAnalysistoProgramDesign.CourseTechnology,Canada.
rd
Gary,R.B.,(2010).C++ForEngineers&Scientists:3 Edition.CourseTechnology,Canada.

You might also like