structured programming Introduction to c fundamentals
INF 130STRUCTURED PROGRAMMING(3 UNITS)Instructor:Dr. H. Bii / Mr. J Sigei
INTRODUCTION Programming is a required skill today,just like English and Maths. It teaches a variety of skills that areimportant in all kinds of professions: critical reading, analytical thinking, creative synthesis, and attention to detail. It provides immediate feedback, leadingto exploration, experimentation, and self-evaluation.
What is programming? Process of coming up with computerprograms. But what is a program? A PROGRAM is a set of instructions that acomputer can follow to do something. Programming = process of coming upwith instructions that a computer canfollow to do something.
… What is programming? As a process, it involves:Understanding a problem for which asolution is required;Designing a solution;Writing or coding the program in aprogramming language;Testing the code;Correcting any errors (debugging); andMaintaining the program.
… and Structured programming? Programming that: Enforces a logical structure on theprogram to make it efficient and easier tomaintain/modify. Implements modules (procedures /functions), each fulfilling some function. Uses basic programming constructs -sequence, selection and iteration (no gotostatements in „spaghetti code‟).
Programming Language Programming requires a programminglanguage: a set of words, codes, and symbols thatallow a programmer to give instructions tothe computer. Each language has rules (or syntax) forwriting the instructions.
… Programming Language There are many programminglanguages – so many! (like humanlanguages) They may be classified (in manyways, including) into THREE broadcategories: Machine Language; Assembly Language; and High-level Languages.
Machine LanguageMade up of streams of 1s and 0s.Programs written as series of 1s and0s is said to be in machine language:
… Machine Language Machine language is the only languageunderstood by computer hardware. Writing programs in machine languageis difficult and cumbersome –instructions are difficult to remember.The only language understood by computerhardware is machine language.
… Machine Language Each computer has its own machinelanguage; rules of language differ fromone computer hardware to another. Note: Machine language is alsoreferred to as First Generationprogramming language.First generation programmingLanguage; also low-level languages
Symbolic / Assembly Language Developed in 1950s to reduceprogrammers‟ burden – by Grace MurrayHopper, US naval officer. She developed the concept of a specialcomputer program that would convertprograms into machine language.
… Symbolic / Assembly LanguageThe program mirrored the machinelanguages using symbols, or mnemonics,to represent the various machineinstructions.The languages developed in this mannerwere known as symbolic languages.An assembler translates symbolic codeinto machine language – thus AssemblyLanguage.
High-Level Languages Symbolic language improved programmingefficiency, but still tedious and hardware focused. High-level languages were developed to furtherimprove efficiency and change focus fromcomputer to the problem being solved. High-level languages: produce portable programs; easier to learn; require less time to write; easier to maintain; and provide better documentation.
… example Programs written in high-level languages haveEnglish-like statements (and familiar math symbols)and must be converted to machine language (1s and0s). The process of converting them is called compilation. Examples of high-level languages are FORTRAN,COBOL, C, BASIC, Pascal, ALGOL, and manyothers.
Overview of some high-level languagesa) BASIC Beginners‟ All-purpose Symbolic Instruction Code. Developed by John Kemeny & Thomas Kurtz in1964 – for beginners – easy to learn. Example: 5 REM Program to compute sum of 10 numbers10 LET s = 020 FOR i=1 TO 1030 READ n40 LET s = s + n50 NEXT i60 PRINT "The sum of the given numbers ="; s70 DATA 4, 20, 15, 32, 4880 DATA 12, 3, 9, 14, 44100 END
b) Pascal Introduced in 1971 by Niklaus Wirth in Zurich becomingthe first language to fully embody structuredprogramming concepts. Example:PROGRAM SUMNUM(INPUT, OUTPUT);(* Program to Compute the sum of 10numbers *)(* Declaration of variables *)VAR Sum, N :REAL;VAR i :INTEGER;BEGINSum := 0;FOR i := 1 TO 10 DOBEGINREAD (N);Sum := Sum + N;END;WRITELN (THE SUM OF GIVENNUMBERS =, SUM);END
Assignment 1:Read about and write short notes on the followinghigh-level languages: FORTRAN; COBOL; ADA; ALGOL; and PL/1.
System DevelopmentAn old programming proverb:Resist the temptation to code.Note
Program DevelopmentMultistep process that requires that we:Understand the problem – outputrequired; input available; steps to followin processing (algorithm).Plan the logic of the solution (orprogram). Three tools will help in thistask: Flowcharts; Pseudocode; and Structure charts.
… Program DevelopmentCode or write program statements in aprogramming language e.g. BASIC, C,Pascal. This may be done on paper.Key the program into the computer(use text editor).Compile, test and debug the program.Complete the documentation: charts,listings, manuals.
... Programming Steps –1) Understand the ProblemRead the problem or talk to & listen to theperson who posed the problem.Identify the problem inputs, outputs, andany additional requirements or constraints: Inputs – data to work with; Outputs – desired results; Other Requirements/Constraints –Relationships between variables, format ofresults e.g. Table.
... Understand the ProblemExample:Compute and display the total cost oforanges given the weight of orangespurchased and the cost per 1000g oforanges.
... Understand the ProblemFrom the problem, we identify:Compute and display the total cost oforanges given the weight of orangespurchased and the cost per 1000g oforanges.Inputs:Quantity of oranges purchased (in Kgs);Unit cost of oranges (in Kshs.).
... Understand the ProblemFrom the problem, we identify:Compute and display the total cost oforanges given the weight of orangespurchased and the cost per 1000g oforanges.Outputs:Total cost of oranges (in Kshs).
... Understand the ProblemOther requirements/constraints:Total cost = Weight (Kgs) X Unit Cost(Kshs).The process we went thru (extractingessential variables and their relationships)is called ABSTRACTION.
... Understand the ProblemExercises: Read two numbers from the keyboard,sum them up, and display the result. Eldy surveyors want a program thatconverts distances in miles to kilometresand showing the result on screen.
2) Plan the logic of (Design) the solutionInvolves developing a list of steps(algorithm) to solve the problem.Usually the most difficult part of problem-solving process.As noted above, 3 tools are importanthere:Structure charts;Pseudocode; andFlowcharts.
Structure ChartAlso called hierarchy chart.It shows the functional flow through aprogram – parts (modules) of a programand how they are related e.g.
… structure chartIt is drawn before a program is written –thus acting as an architectural blueprint –more like a house plan.In business world, once a structure chartis completed, a structured walkthrough isconducted – where a review panel istaken through the structure to understandhow programmers plan to solve theproblem and attain the objectives theyset out to achieve.
… structure chartQuestion 1:Develop a structure chart for a programthat is meant to obtain two numbersfrom a user, multiply the numbers andshow the result on screen.
Solution?Multiply 2numbersProgramPrint ResultCalculateProductInput first &secondnumbers
Pseudocode Is an English-like statement; part of program logic. It describes what the program will do in precisealgorithmic detail e.g.PseudocodeEnglish-like statements that follow a loosely defined syntaxand are used to convey the design of an algorithm.
Question 2:Write a pseudocode for a program for calculating theamount of tax (at 15% of value for property worth Kshs100,000 and above, and 12% otherwise) of a property.Assume that the user wants to determine taxes for morethan one property.Question 3:Write a pseudocode for a program for calculatingthe cost of flooring the living areas (slide 33).Reading:Do a literature search in the Library or on the Internet about pseudocodeas a design and documentation tool. Read and attempt the questionsabove.
FlowchartProgram design tool that uses standardgraphical symbols to represent logicalflow of data thru a function/program.Its primary purpose is to show the designof an algorithm.
… FlowchartIt frees a programmer from the syntax anddetails of programming to concentrate ondetails of the problem to be solved.It gives a pictorial representation of analgorithm – helps one to think of aproblem pictorially.
example StartvStopReadLengthReadWidthPrint AreaCalculateArea = Length XWidth
Flowcharting Symbols:Two basic categories:1) Auxiliary symbols enhance readability or functionality of aflowchart. They do not directly show instructions orcommands.a) Terminators:START STOPb) Flow lines:Rule: One entry/exit!Rule: Start/Stop has oneExiting/entering line!
… auxiliary symbolsc) Connectors:nCircle with numberin it.
2) Primary Symbols: Show instructions or actions needed a problem presented inthe algorithm. They show all three structured programming constructs:sequence, decision, and repetition.a) Sequence Symbols:Sum ← x + yi) AssignmentStatement:ii) Input/OutputStatement:Read x
… sequence symbols:iii) Module-call statement:AVRG(ave, a, b, c)StartvStopRead (a)Read (b)PrintAverageRead (c)AVRG(ave, a, b, c)Flowchart for thisis elsewhere (below)
AVRG(rslt, x, y, z)vReturnsum ← x + y + zrslt ← sum/3
b) Selection statement symbols Those for specifying conditional statements (thatallow execution of selected statements andskipping of others). There are 2 selection statements (decisions): Two-way selection; Multiway selection.Condition Number > 10TFT – to the right;F – to the left;NB: Not good practice to have any to bottom!2-way:
… selection StartvStopRead (a)a > 10TFWrite(newnum)newnum ← a - 10NOTE: Only one statement (ornull) in each branch is allowed & itmay be a compound statement
Question 4:Design an algorithm (flowchart) that reads an integer. Ifthe integer value is greater than 10, it subtracts 10 andwrites the original number and the result. If the numberis less than 10, it displays the message “That number isless than 10”.Question 5:Design a flowchart for a program that reads a markbetween 0 and 100 and prints a corresponding lettergrade.
c) Looping Statements symbols Iteration/repetition (for, while, do..while)a) for- Counting loop.- pre-test, so body maynever be executed.- good when number oftimes to loop is known.
… for loop actionsQuestion 6:Design a flowchart (or algorithm) for a program thatreads 20 numbers and print their sum.
b) while• Not a counting loop;•Also pre-test loop – bodymay not be executed.•Good when number oftimes to loop is not known.Question 7:Design a flowchart for a program that reads numbers fromthe keyboard and prints their total. We don‟t know howmany numbers the user will input. However, all numbersare positive numbers.
NOTE: first number isread before the loop (i.e.priming the loop)
c) do...while• this is a post-test loop i.e. thecondition is tested at the end ofthe loop.•Body of the loop is executed atleast onceQuestion 8:Design a flowchart for a program that reads andprocesses numbers between 1 and 5. How it processesthe numbers is not important at this stage.
So far in Program Development … Multistep process that requires that we: Understand the problem – output required; inputavailable; steps to follow in processing (algorithm). Plan the logic of the solution (or program). Three toolswill help in this task: Flowcharts; Pseudocode; and Structure charts. Code or write program statements in a programminglanguage e.g. BASIC, C, Pascal. This may be done onpaper. Key the program into the computer (use text editor). Test and debug the program. Complete the documentation: charts, listings, manuals.
ExercisesWrite a pseudocode and develop a flowchart for each ofthe following problems:1) Calculate the circumference and area of a circle (PI =3.142).2) Compute and display the letter grade of a student‟smark in a certain course.3) Compute and print the net pay of an employee giventhe number of hours worked and the hourly rate ofpay.4) Convert the temperature given in degrees fahrenheitto degrees celcius given that:Degrees Celcius = (Degrees Fahrenheit – 32) * 5/9
Coding Writing instructions in a programming language –high-level language. So we need to learn the language, its structure andsyntax. Choice: C