structured programming Introduction to c fundamentals


Published on

its a simplified introduction to C programming language basics

Published in: Technology
  • Be the first to comment

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

structured programming Introduction to c fundamentals

  1. 1. INF 130STRUCTURED PROGRAMMING(3 UNITS)Instructor:Dr. H. Bii / Mr. J Sigei
  2. 2. 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.
  3. 3. 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.
  4. 4. … 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); andMaintaining the program.
  5. 5. … 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‟).
  6. 6. 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.
  7. 7. … 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.
  8. 8. Their Evolution
  9. 9. Machine LanguageMade up of streams of 1s and 0s.Programs written as series of 1s and0s is said to be in machine language:
  10. 10. … 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.
  11. 11. … 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
  12. 12. 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.
  13. 13. … Symbolic / Assembly LanguageThe 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.
  14. 14. … Assembly language
  15. 15. 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.
  16. 16. … High-level languageContinued …
  17. 17. … 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.
  18. 18. 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
  19. 19. 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
  20. 20. Assignment 1:Read about and write short notes on the followinghigh-level languages: FORTRAN; COBOL; ADA; ALGOL; and PL/1.
  21. 21. System and Program Development
  22. 22. System DevelopmentAn old programming proverb:Resist the temptation to code.Note
  23. 23. Program DevelopmentMultistep 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.
  24. 24. … Program DevelopmentCode 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.
  25. 25. ... Programming Steps –1) Understand the ProblemRead 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.
  26. 26. ... Understand the ProblemExample:Compute and display the total cost oforanges given the weight of orangespurchased and the cost per 1000g oforanges.
  27. 27. ... Understand the ProblemFrom 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.).
  28. 28. ... Understand the ProblemFrom 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).
  29. 29. ... 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.
  30. 30. ... 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.
  31. 31. 2) Plan the logic of (Design) the solutionInvolves 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; andFlowcharts.
  32. 32. Structure ChartAlso called hierarchy chart.It shows the functional flow through aprogram – parts (modules) of a programand how they are related e.g.
  33. 33. … structure chartIt 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.
  34. 34. … 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.
  35. 35. Solution?Multiply 2numbersProgramPrint ResultCalculateProductInput first &secondnumbers
  36. 36. 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.
  37. 37. 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.
  38. 38. FlowchartProgram 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.
  39. 39. … FlowchartIt 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.
  40. 40. example StartvStopReadLengthReadWidthPrint AreaCalculateArea = Length XWidth
  41. 41. example
  42. 42. 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!
  43. 43. … auxiliary symbolsc) Connectors:nCircle with numberin it.
  44. 44. 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
  45. 45. StartvStopReadLengthReadWidthPrint AreaCalculateArea = Length XWidth
  46. 46. … 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)
  47. 47. AVRG(rslt, x, y, z)vReturnsum ← x + y + zrslt ← sum/3
  48. 48. 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:
  49. 49. … selection StartvStopRead (a)a > 10TFWrite(newnum)newnum ← a - 10NOTE: Only one statement (ornull) in each branch is allowed & itmay be a compound statement
  50. 50. … selectionMultiway selection:
  51. 51. Example (multiway selection)
  52. 52. 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.
  53. 53. 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.
  54. 54. … for loop actionsQuestion 6:Design a flowchart (or algorithm) for a program thatreads 20 numbers and print their sum.
  55. 55. ? answer…
  56. 56. 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.
  57. 57. NOTE: first number isread before the loop (i.e.priming the loop)
  58. 58. 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.
  59. 59. (num > 1)&& (num < 5)
  60. 60. 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.
  61. 61. 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
  62. 62. Coding Writing instructions in a programming language –high-level language. So we need to learn the language, its structure andsyntax. Choice: C