KEMBAR78
structured programming Introduction to c fundamentals | PDF
INF 130
STRUCTURED 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 are
important in all kinds of professions:
 critical reading,
 analytical thinking,
 creative synthesis, and
 attention to detail.
 It provides immediate feedback, leading
to exploration, experimentation, and self-
evaluation.
What is programming?
 Process of coming up with computer
programs.
 But what is a program?
 A PROGRAM is a set of instructions that a
computer can follow to do something.
 Programming = process of coming up
with instructions that a computer can
follow to do something.
… What is programming?
 As a process, it involves:
Understanding a problem for which a
solution is required;
Designing a solution;
Writing or coding the program in a
programming language;
Testing the code;
Correcting any errors (debugging); and
Maintaining the program.
… and Structured programming?
 Programming that:
 Enforces a logical structure on the
program to make it efficient and easier to
maintain/modify.
 Implements modules (procedures /
functions), each fulfilling some function.
 Uses basic programming constructs -
sequence, selection and iteration (no goto
statements in „spaghetti code‟).
Programming Language
 Programming requires a programming
language:
 a set of words, codes, and symbols that
allow a programmer to give instructions to
the computer.
 Each language has rules (or syntax) for
writing the instructions.
… Programming Language
 There are many programming
languages – so many! (like human
languages)
 They may be classified (in many
ways, including) into THREE broad
categories:
 Machine Language;
 Assembly Language; and
 High-level Languages.
Their Evolution
Machine Language
Made up of streams of 1s and 0s.
Programs written as series of 1s and
0s is said to be in machine language:
… Machine Language
 Machine language is the only language
understood by computer hardware.
 Writing programs in machine language
is difficult and cumbersome –
instructions are difficult to remember.
The only language understood by computer
hardware is machine language.
… Machine Language
 Each computer has its own machine
language; rules of language differ from
one computer hardware to another.
 Note: Machine language is also
referred to as First Generation
programming language.
First generation programming
Language; also low-level languages
Symbolic / Assembly Language
 Developed in 1950s to reduce
programmers‟ burden – by Grace Murray
Hopper, US naval officer.
 She developed the concept of a special
computer program that would convert
programs into machine language.
… Symbolic / Assembly Language
The program mirrored the machine
languages using symbols, or mnemonics,
to represent the various machine
instructions.
The languages developed in this manner
were known as symbolic languages.
An assembler translates symbolic code
into machine language – thus Assembly
Language.
… Assembly language
High-Level Languages
 Symbolic language improved programming
efficiency, but still tedious and hardware focused.
 High-level languages were developed to further
improve efficiency and change focus from
computer 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.
… High-level language
Continued …
… example
 Programs written in high-level languages have
English-like statements (and familiar math symbols)
and must be converted to machine language (1s and
0s).
 The process of converting them is called compilation.
 Examples of high-level languages are FORTRAN,
COBOL, C, BASIC, Pascal, ALGOL, and many
others.
Overview of some high-level languages
a) BASIC
 Beginners‟ All-purpose Symbolic Instruction Code.
 Developed by John Kemeny & Thomas Kurtz in
1964 – for beginners – easy to learn.
 Example: 5 REM Program to compute sum of 10 numbers
10 LET s = 0
20 FOR i=1 TO 10
30 READ n
40 LET s = s + n
50 NEXT i
60 PRINT "The sum of the given numbers ="; s
70 DATA 4, 20, 15, 32, 48
80 DATA 12, 3, 9, 14, 44
100 END
b) Pascal
 Introduced in 1971 by Niklaus Wirth in Zurich becoming
the first language to fully embody structured
programming concepts.
 Example:
PROGRAM SUMNUM(INPUT, OUTPUT);
(* Program to Compute the sum of 10
numbers *)
(* Declaration of variables *)
VAR Sum, N :REAL;
VAR i :INTEGER;
BEGIN
Sum := 0;
FOR i := 1 TO 10 DO
BEGIN
READ (N);
Sum := Sum + N;
END;
WRITELN ('THE SUM OF GIVEN
NUMBERS =', SUM);
END
Assignment 1:
Read about and write short notes on the following
high-level languages:
 FORTRAN;
 COBOL;
 ADA;
 ALGOL; and
 PL/1.
System and Program Development
System Development
An old programming proverb:
Resist the temptation to code.
Note
Program Development
Multistep process that requires that we:
Understand the problem – output
required; input available; steps to follow
in processing (algorithm).
Plan the logic of the solution (or
program). Three tools will help in this
task:
 Flowcharts;
 Pseudocode; and
 Structure charts.
… Program Development
Code or write program statements in a
programming 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 Problem
Read the problem or talk to & listen to the
person who posed the problem.
Identify the problem inputs, outputs, and
any additional requirements or constraints:
 Inputs – data to work with;
 Outputs – desired results;
 Other Requirements/Constraints –
Relationships between variables, format of
results e.g. Table.
... Understand the Problem
Example:
Compute and display the total cost of
oranges given the weight of oranges
purchased and the cost per 1000g of
oranges.
... Understand the Problem
From the problem, we identify:
Compute and display the total cost of
oranges given the weight of oranges
purchased and the cost per 1000g of
oranges.
Inputs:
Quantity of oranges purchased (in Kgs);
Unit cost of oranges (in Kshs.).
... Understand the Problem
From the problem, we identify:
Compute and display the total cost of
oranges given the weight of oranges
purchased and the cost per 1000g of
oranges.
Outputs:
Total cost of oranges (in Kshs).
... Understand the Problem
Other requirements/constraints:
Total cost = Weight (Kgs) X Unit Cost
(Kshs).
The process we went thru (extracting
essential variables and their relationships)
is called ABSTRACTION.
... Understand the Problem
Exercises:
 Read two numbers from the keyboard,
sum them up, and display the result.
 Eldy surveyors want a program that
converts distances in miles to kilometres
and showing the result on screen.
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 important
here:
Structure charts;
Pseudocode; and
Flowcharts.
Structure Chart
Also called hierarchy chart.
It shows the functional flow through a
program – parts (modules) of a program
and how they are related e.g.
… 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 chart
is completed, a structured walkthrough is
conducted – where a review panel is
taken through the structure to understand
how programmers plan to solve the
problem and attain the objectives they
set out to achieve.
… structure chart
Question 1:
Develop a structure chart for a program
that is meant to obtain two numbers
from a user, multiply the numbers and
show the result on screen.
Solution?
Multiply 2
numbers
Program
Print ResultCalculate
Product
Input first &
second
numbers
Pseudocode
 Is an English-like statement; part of program logic.
 It describes what the program will do in precise
algorithmic detail e.g.
Pseudocode
English-like statements that follow a loosely defined syntax
and are used to convey the design of an algorithm.
Question 2:
Write a pseudocode for a program for calculating the
amount of tax (at 15% of value for property worth Kshs
100,000 and above, and 12% otherwise) of a property.
Assume that the user wants to determine taxes for more
than one property.
Question 3:
Write a pseudocode for a program for calculating
the cost of flooring the living areas (slide 33).
Reading:
Do a literature search in the Library or on the Internet about pseudocode
as a design and documentation tool. Read and attempt the questions
above.
Flowchart
Program design tool that uses standard
graphical symbols to represent logical
flow of data thru a function/program.
Its primary purpose is to show the design
of an algorithm.
… Flowchart
It frees a programmer from the syntax and
details of programming to concentrate on
details of the problem to be solved.
It gives a pictorial representation of an
algorithm – helps one to think of a
problem pictorially.
example Startv
Stop
Read
Length
Read
Width
Print Area
Calculate
Area = Length X
Width
example
Flowcharting Symbols:
Two basic categories:
1) Auxiliary symbols
 enhance readability or functionality of a
flowchart.
 They do not directly show instructions or
commands.
a) Terminators:
START STOP
b) Flow lines:
Rule: One entry/exit!
Rule: Start/Stop has one
Exiting/entering line!
… auxiliary symbols
c) Connectors:
n
Circle with number
in it.
2) Primary Symbols:
 Show instructions or actions needed a problem presented in
the algorithm.
 They show all three structured programming constructs:
sequence, decision, and repetition.
a) Sequence Symbols:
Sum ← x + y
i) Assignment
Statement:
ii) Input/Output
Statement:
Read x
Startv
Stop
Read
Length
Read
Width
Print Area
Calculate
Area = Length X
Width
… sequence symbols:
iii) Module-call statement:
AVRG(ave, a, b, c)
Startv
Stop
Read (a)
Read (b)
Print
Average
Read (c)
AVRG(ave, a, b, c)
Flowchart for this
is elsewhere (below)
AVRG(rslt, x, y, z)v
Return
sum ← x + y + z
rslt ← sum/3
b) Selection statement symbols
 Those for specifying conditional statements (that
allow execution of selected statements and
skipping of others).
 There are 2 selection statements (decisions):
 Two-way selection;
 Multiway selection.
Condition Number > 10
TF
T – to the right;
F – to the left;
NB: Not good practice to have any to bottom!
2-way:
… selection Startv
Stop
Read (a)
a > 10
TF
Write
(newnum)
newnum ← a - 10
NOTE: Only one statement (or
null) in each branch is allowed & it
may be a compound statement
… selection
Multiway selection:
Example (multiway selection)
Question 4:
Design an algorithm (flowchart) that reads an integer. If
the integer value is greater than 10, it subtracts 10 and
writes the original number and the result. If the number
is less than 10, it displays the message “That number is
less than 10”.
Question 5:
Design a flowchart for a program that reads a mark
between 0 and 100 and prints a corresponding letter
grade.
c) Looping Statements symbols
 Iteration/repetition (for, while, do..while)
a) for
- Counting loop.
- pre-test, so body may
never be executed.
- good when number of
times to loop is known.
… for loop actions
Question 6:
Design a flowchart (or algorithm) for a program that
reads 20 numbers and print their sum.
? answer…
b) while
• Not a counting loop;
•Also pre-test loop – body
may not be executed.
•Good when number of
times to loop is not known.
Question 7:
Design a flowchart for a program that reads numbers from
the keyboard and prints their total. We don‟t know how
many numbers the user will input. However, all numbers
are positive numbers.
NOTE: first number is
read before the loop (i.e.
priming the loop)
c) do...while
• this is a post-test loop i.e. the
condition is tested at the end of
the loop.
•Body of the loop is executed at
least once
Question 8:
Design a flowchart for a program that reads and
processes numbers between 1 and 5. How it processes
the numbers is not important at this stage.
(num > 1)
&& (num < 5)
So far in Program Development …
 Multistep process that requires that we:
 Understand the problem – output required; input
available; steps to follow in processing (algorithm).
 Plan the logic of the solution (or program). Three tools
will help in this task:
 Flowcharts;
 Pseudocode; and
 Structure charts.
 Code or write program statements in a programming
language e.g. BASIC, C, Pascal. This may be done on
paper.
 Key the program into the computer (use text editor).
 Test and debug the program.
 Complete the documentation: charts, listings, manuals.
Exercises
Write a pseudocode and develop a flowchart for each of
the following problems:
1) Calculate the circumference and area of a circle (PI =
3.142).
2) Compute and display the letter grade of a student‟s
mark in a certain course.
3) Compute and print the net pay of an employee given
the number of hours worked and the hourly rate of
pay.
4) Convert the temperature given in degrees fahrenheit
to 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 and
syntax.
 Choice: C
structured programming Introduction to c fundamentals

structured programming Introduction to c fundamentals

  • 1.
    INF 130 STRUCTURED PROGRAMMING (3UNITS) Instructor: Dr. H. Bii / Mr. J Sigei
  • 2.
    INTRODUCTION  Programming isa required skill today, just like English and Maths.  It teaches a variety of skills that are important in all kinds of professions:  critical reading,  analytical thinking,  creative synthesis, and  attention to detail.  It provides immediate feedback, leading to exploration, experimentation, and self- evaluation.
  • 3.
    What is programming? Process of coming up with computer programs.  But what is a program?  A PROGRAM is a set of instructions that a computer can follow to do something.  Programming = process of coming up with instructions that a computer can follow to do something.
  • 4.
    … What isprogramming?  As a process, it involves: Understanding a problem for which a solution is required; Designing a solution; Writing or coding the program in a programming language; Testing the code; Correcting any errors (debugging); and Maintaining the program.
  • 5.
    … and Structuredprogramming?  Programming that:  Enforces a logical structure on the program to make it efficient and easier to maintain/modify.  Implements modules (procedures / functions), each fulfilling some function.  Uses basic programming constructs - sequence, selection and iteration (no goto statements in „spaghetti code‟).
  • 6.
    Programming Language  Programmingrequires a programming language:  a set of words, codes, and symbols that allow a programmer to give instructions to the computer.  Each language has rules (or syntax) for writing the instructions.
  • 7.
    … Programming Language There are many programming languages – so many! (like human languages)  They may be classified (in many ways, including) into THREE broad categories:  Machine Language;  Assembly Language; and  High-level Languages.
  • 8.
  • 9.
    Machine Language Made upof streams of 1s and 0s. Programs written as series of 1s and 0s is said to be in machine language:
  • 10.
    … Machine Language Machine language is the only language understood by computer hardware.  Writing programs in machine language is difficult and cumbersome – instructions are difficult to remember. The only language understood by computer hardware is machine language.
  • 11.
    … Machine Language Each computer has its own machine language; rules of language differ from one computer hardware to another.  Note: Machine language is also referred to as First Generation programming language. First generation programming Language; also low-level languages
  • 12.
    Symbolic / AssemblyLanguage  Developed in 1950s to reduce programmers‟ burden – by Grace Murray Hopper, US naval officer.  She developed the concept of a special computer program that would convert programs into machine language.
  • 13.
    … Symbolic /Assembly Language The program mirrored the machine languages using symbols, or mnemonics, to represent the various machine instructions. The languages developed in this manner were known as symbolic languages. An assembler translates symbolic code into machine language – thus Assembly Language.
  • 14.
  • 15.
    High-Level Languages  Symboliclanguage improved programming efficiency, but still tedious and hardware focused.  High-level languages were developed to further improve efficiency and change focus from computer 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.
  • 17.
    … example  Programswritten in high-level languages have English-like statements (and familiar math symbols) and must be converted to machine language (1s and 0s).  The process of converting them is called compilation.  Examples of high-level languages are FORTRAN, COBOL, C, BASIC, Pascal, ALGOL, and many others.
  • 18.
    Overview of somehigh-level languages a) BASIC  Beginners‟ All-purpose Symbolic Instruction Code.  Developed by John Kemeny & Thomas Kurtz in 1964 – for beginners – easy to learn.  Example: 5 REM Program to compute sum of 10 numbers 10 LET s = 0 20 FOR i=1 TO 10 30 READ n 40 LET s = s + n 50 NEXT i 60 PRINT "The sum of the given numbers ="; s 70 DATA 4, 20, 15, 32, 48 80 DATA 12, 3, 9, 14, 44 100 END
  • 19.
    b) Pascal  Introducedin 1971 by Niklaus Wirth in Zurich becoming the first language to fully embody structured programming concepts.  Example: PROGRAM SUMNUM(INPUT, OUTPUT); (* Program to Compute the sum of 10 numbers *) (* Declaration of variables *) VAR Sum, N :REAL; VAR i :INTEGER; BEGIN Sum := 0; FOR i := 1 TO 10 DO BEGIN READ (N); Sum := Sum + N; END; WRITELN ('THE SUM OF GIVEN NUMBERS =', SUM); END
  • 20.
    Assignment 1: Read aboutand write short notes on the following high-level languages:  FORTRAN;  COBOL;  ADA;  ALGOL; and  PL/1.
  • 21.
    System and ProgramDevelopment
  • 23.
    System Development An oldprogramming proverb: Resist the temptation to code. Note
  • 24.
    Program Development Multistep processthat requires that we: Understand the problem – output required; input available; steps to follow in processing (algorithm). Plan the logic of the solution (or program). Three tools will help in this task:  Flowcharts;  Pseudocode; and  Structure charts.
  • 25.
    … Program Development Codeor write program statements in a programming 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.
  • 26.
    ... Programming Steps– 1) Understand the Problem Read the problem or talk to & listen to the person who posed the problem. Identify the problem inputs, outputs, and any additional requirements or constraints:  Inputs – data to work with;  Outputs – desired results;  Other Requirements/Constraints – Relationships between variables, format of results e.g. Table.
  • 27.
    ... Understand theProblem Example: Compute and display the total cost of oranges given the weight of oranges purchased and the cost per 1000g of oranges.
  • 28.
    ... Understand theProblem From the problem, we identify: Compute and display the total cost of oranges given the weight of oranges purchased and the cost per 1000g of oranges. Inputs: Quantity of oranges purchased (in Kgs); Unit cost of oranges (in Kshs.).
  • 29.
    ... Understand theProblem From the problem, we identify: Compute and display the total cost of oranges given the weight of oranges purchased and the cost per 1000g of oranges. Outputs: Total cost of oranges (in Kshs).
  • 30.
    ... Understand theProblem Other requirements/constraints: Total cost = Weight (Kgs) X Unit Cost (Kshs). The process we went thru (extracting essential variables and their relationships) is called ABSTRACTION.
  • 31.
    ... Understand theProblem Exercises:  Read two numbers from the keyboard, sum them up, and display the result.  Eldy surveyors want a program that converts distances in miles to kilometres and showing the result on screen.
  • 32.
    2) Plan thelogic 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 important here: Structure charts; Pseudocode; and Flowcharts.
  • 33.
    Structure Chart Also calledhierarchy chart. It shows the functional flow through a program – parts (modules) of a program and how they are related e.g.
  • 34.
    … structure chart Itis drawn before a program is written – thus acting as an architectural blueprint – more like a house plan. In business world, once a structure chart is completed, a structured walkthrough is conducted – where a review panel is taken through the structure to understand how programmers plan to solve the problem and attain the objectives they set out to achieve.
  • 35.
    … structure chart Question1: Develop a structure chart for a program that is meant to obtain two numbers from a user, multiply the numbers and show the result on screen.
  • 36.
  • 37.
    Pseudocode  Is anEnglish-like statement; part of program logic.  It describes what the program will do in precise algorithmic detail e.g. Pseudocode English-like statements that follow a loosely defined syntax and are used to convey the design of an algorithm.
  • 38.
    Question 2: Write apseudocode for a program for calculating the amount of tax (at 15% of value for property worth Kshs 100,000 and above, and 12% otherwise) of a property. Assume that the user wants to determine taxes for more than one property. Question 3: Write a pseudocode for a program for calculating the cost of flooring the living areas (slide 33). Reading: Do a literature search in the Library or on the Internet about pseudocode as a design and documentation tool. Read and attempt the questions above.
  • 39.
    Flowchart Program design toolthat uses standard graphical symbols to represent logical flow of data thru a function/program. Its primary purpose is to show the design of an algorithm.
  • 40.
    … Flowchart It freesa programmer from the syntax and details of programming to concentrate on details of the problem to be solved. It gives a pictorial representation of an algorithm – helps one to think of a problem pictorially.
  • 41.
  • 42.
  • 43.
    Flowcharting Symbols: Two basiccategories: 1) Auxiliary symbols  enhance readability or functionality of a flowchart.  They do not directly show instructions or commands. a) Terminators: START STOP b) Flow lines: Rule: One entry/exit! Rule: Start/Stop has one Exiting/entering line!
  • 44.
    … auxiliary symbols c)Connectors: n Circle with number in it.
  • 46.
    2) Primary Symbols: Show instructions or actions needed a problem presented in the algorithm.  They show all three structured programming constructs: sequence, decision, and repetition. a) Sequence Symbols: Sum ← x + y i) Assignment Statement: ii) Input/Output Statement: Read x
  • 47.
  • 48.
    … sequence symbols: iii)Module-call statement: AVRG(ave, a, b, c) Startv Stop Read (a) Read (b) Print Average Read (c) AVRG(ave, a, b, c) Flowchart for this is elsewhere (below)
  • 49.
    AVRG(rslt, x, y,z)v Return sum ← x + y + z rslt ← sum/3
  • 50.
    b) Selection statementsymbols  Those for specifying conditional statements (that allow execution of selected statements and skipping of others).  There are 2 selection statements (decisions):  Two-way selection;  Multiway selection. Condition Number > 10 TF T – to the right; F – to the left; NB: Not good practice to have any to bottom! 2-way:
  • 51.
    … selection Startv Stop Read(a) a > 10 TF Write (newnum) newnum ← a - 10 NOTE: Only one statement (or null) in each branch is allowed & it may be a compound statement
  • 52.
  • 53.
  • 54.
    Question 4: Design analgorithm (flowchart) that reads an integer. If the integer value is greater than 10, it subtracts 10 and writes the original number and the result. If the number is less than 10, it displays the message “That number is less than 10”. Question 5: Design a flowchart for a program that reads a mark between 0 and 100 and prints a corresponding letter grade.
  • 55.
    c) Looping Statementssymbols  Iteration/repetition (for, while, do..while) a) for - Counting loop. - pre-test, so body may never be executed. - good when number of times to loop is known.
  • 56.
    … for loopactions Question 6: Design a flowchart (or algorithm) for a program that reads 20 numbers and print their sum.
  • 57.
  • 58.
    b) while • Nota counting loop; •Also pre-test loop – body may not be executed. •Good when number of times to loop is not known. Question 7: Design a flowchart for a program that reads numbers from the keyboard and prints their total. We don‟t know how many numbers the user will input. However, all numbers are positive numbers.
  • 59.
    NOTE: first numberis read before the loop (i.e. priming the loop)
  • 60.
    c) do...while • thisis a post-test loop i.e. the condition is tested at the end of the loop. •Body of the loop is executed at least once Question 8: Design a flowchart for a program that reads and processes numbers between 1 and 5. How it processes the numbers is not important at this stage.
  • 61.
    (num > 1) &&(num < 5)
  • 62.
    So far inProgram Development …  Multistep process that requires that we:  Understand the problem – output required; input available; steps to follow in processing (algorithm).  Plan the logic of the solution (or program). Three tools will help in this task:  Flowcharts;  Pseudocode; and  Structure charts.  Code or write program statements in a programming language e.g. BASIC, C, Pascal. This may be done on paper.  Key the program into the computer (use text editor).  Test and debug the program.  Complete the documentation: charts, listings, manuals.
  • 63.
    Exercises Write a pseudocodeand develop a flowchart for each of the following problems: 1) Calculate the circumference and area of a circle (PI = 3.142). 2) Compute and display the letter grade of a student‟s mark in a certain course. 3) Compute and print the net pay of an employee given the number of hours worked and the hourly rate of pay. 4) Convert the temperature given in degrees fahrenheit to degrees celcius given that: Degrees Celcius = (Degrees Fahrenheit – 32) * 5/9
  • 64.
    Coding  Writing instructionsin a programming language – high-level language.  So we need to learn the language, its structure and syntax.  Choice: C