CSC 316 Structured Programming Update
CSC 316 Structured Programming Update
Programming
CSC 316
Heman A.M.
Course Outline
• Structured Programming elements
• structured design principles
• abstraction modularity
• stepwise refinement
• structured design techniques
What is a program
• A set of instructions written in a programming language for a
computer to perform a specific task
• It’s the structuring of a solution to a problem and the refine the
solution step-wise
Program types
• Application: a computer program designed to perform a group of
coordinated functions, tasks, or activities for the benefit of the user
• Utility: small program developed to carryout small task. Its not
maintained
• Service: any program that runs at the background of a computer that
enables the smooth running of the computer. No direct interaction
with the user
• System program: instructions the run a computer hardware or
application programs
Comparison between spaghetti
code and structured
MIP program that finds maximum,
program
minimum and average of numbers C program that finds maximum,
.data minimum and average of numbers
txt1: .asciiz "Enter number of terms : "
#include <stdio.h>
txt2: .asciiz "Please enter an integer : "
txt3: .asciiz "\nThe maximum value is : "
int main()
txt4: .asciiz "\nThe minimum value is : " {
txt5: .asciiz "\nThe average is : " int num[1000],i,n,min,max,sum = 0;
txt6: .asciiz " with remainder : " float avg;
.text printf("Enter number of terms : ");
.globl main #Enables the procedure accessible outside this file
scanf("%d",&n);
main:
printf("Enter the terms one by one: ");
addi $s0, $zero, 0
la $a0, txt1 #load the address ot txt1
for(i=0; i<n; i++)
li $v0, 4 {
syscall printf("\n%d. Enter a number: ", i + 1);
li $v0, 5 #Accept input (integer) value from the console scanf("%d",&num[i]);
syscall }
add $t1, $v0, 0
min=max=num[0];
Comparison between spaghetti code
and structured program Conn’d
loop:
for(i=1; i<n; i++)
la $a0, txt2 #load the address of txt2 to $a0
{
li $v0, 4 #Return the content of text1 to the console
if(min>num[i])
syscall
min=num[i];
beq $t1, $t0, average
if(max<num[i])
li $v0, 5 #Accepts input (integer) value from the console max=num[i];
syscall sum += num[i];
add $s0, $v0, 0 #Saves the value entered to $0 }
add $t0, $t0, 1 #auto increment value in the loop by 1 avg = sum/n;
add $t3, $t3, $s0 #Whatever taken be $s0 is added to the content of $t3 printf("The minimum value = %d",min);
beq $t0, 1, first #The First value should equal min and max printf("\nThe maximum value = %d",max);
blt $s0, $t2, min printf("\nAnd the average = %2f",avg);
bgt $s0, $t4, max return 0;
first: }
add $t2, $s0, 0 #The first value is assigned min
add $t4, $s0, 0 #The first value is assigned max
j loop #jump to pick the next value
min:
add $t2, $s0, 0 #Value less than $s0 is added to $t1
j loop
max:
add $t4, $s0, 0 #Value less greater than $s0 is put on t2
j loop
average:
div $t3, $t0 #divide sum by n
mflo $t7 #store quotient
mfhi $t6 # store reminder
print:
la $a0, txt3
li $v0, 4
syscall
add $a0, $t4, 0
li $v0, 1
syscall
la $a0, txt4
li $v0, 4
syscall
add $a0, $t2, 0
li $v0, 1
syscall
la $a0, txt5
li $v0, 4
syscall
add $a0, $t7, 0
li $v0, 1
syscall
exit:
li $v0, 10
syscall
unstructured
programming (Large
programs)
• Difficult to update/Modify
• More difficult to maintain
• More time consuming to develop
• A program could have more than one entry and exit points
• Tendency to have indefinite loop
• Have more lines of code
Structure
• A structure is a set of data that in someway it has an intermediary
relation
• A pre-state to classes within object oriented programming
Structured
Programming
• A programming paradigm aimed at improving the clarity, quality, and
development time of a computer program by making extensive use
of subroutines, block structures, for and while loops—in contrast to
using simple tests and jumps such as the goto statement which could
lead to "spaghetti code”
• Is base on refinement process – a method of problem decomposition
common to all engineering disciplines and the physical, chemical and
biological sciences
Structured program
example
Task
Task
1.1.1
Advantages of TopDown Analysis
• Reduces the complexity of problem solving
• Not limited to particular type of program
Steps for TopDown Analysis
1. Define complete scope of the problem
• Determination of input: what data to be processed
What to do on the input data
What type of processing is needed to be done
• Output: what information is expected
2. Division of problem
3. Divide the scope of each part and divide it into tasks
4. Repeat step 3 until a simple task is reached which can’t be further
divided (best solution is obtained)
Modular Programming
• Program broken into smaller independent units called modules
(functions)
Each module is developed independent of each other
Each module accomplish a function and contains all the source codes
Has entry point to which control is transferred from outside
Has only one exit point to which a control is return back to the calling function
• It is a solution to a very large program which is difficult to develop
and maintain
• Advantages
Modules can be assigned to groups of developers
It leads to reusable codes
Debugging and finding errors becomes easy
Structured Code
• Goto or Jump statement are replaced with if, if else, switch-
case, loop such as for and while and do-while statements
• Advantage
It improves the problem solving process
Better organization of program
Generalization programming methodology
Clear description of data and structure
Programs are made for easy documentation and modifications
Imperical
Bottom Up
• Bottom-up: is the composition (stepwise refinement) of smallest
components of a program that interlink to form a desired program
Building a language towards a program (low level language e.g. Lips,
Assembly language)
Larger language with more abstract operators
• Advantage
It’s the best approach when developing an application from an existing system
• Disadvantages of Bottom Top
It is risky to design and implement the base elements without having clear idea
of how these would be linked in the final system
Good vision is necessary to decide the functionality of a module
Disadvantages of
Structured
Programming
• Slower in compilation than assembly language
• Abstraction layer prevents programmers from handling use of hardware resources
directly
• The object code generated by a translator might be inefficient compared to an
equivalent assembly language program
• To update a datatype in a program with large source code can be time consuming
• Data is insecure as it could be accessed by any function
• It makes programmers lazy because it makes completion of program faster
C Language
• It’s a general-purpose, procedural, imperative computer
programming language
Procedural or imperative: list of instructions to be executed in a specified order
• Advantages
Easy to learn or at least, less complicated
Structured language
It produces efficient program
It can handle low-level activities
It comes with built-in headers
It can be compiled on variety of IDE
Areas of Application
• Operating Systems
• Language compilers
• Assemblers
• Text editors
• Print spoolers
• Network drivers
• Modern programs
• Databases
• Language interpreters
• Utilities
• Malware
Datatype
It is the classification of data which tells the compiler or interpreter how the
programmer wants to use the data
• Primitive:
Character
Integer
Floating point
• Enumerated type: is a user defined type which is used to assign names to
integral constants name which makes the program easier to read and maintain
• Void type: indicates that no value will be returned
• Derived types:
Pointer
Array
Structure
Union
Function
Running c on Linux
• Verify that gcc is install from the termimanal: gcc --version
• Create a file: touch <file_name>.c in the directory of your choice or
with any text editor, say gedit in the directory of your choice: gedit
/home/<username>/<dir> file_name
• Write code and save the file
• Compile the program: gcc <file_name>.c -o <binary_name>
• Run the program: /home/<username/<dir>/ ./<binary_name>
Similarly, you could use g++ to compile c++ (.cpp) files
Primitive types
Type Explanation Minimum size (bits) Format specifier
Smallest addressable unit of the machine that can contain basic character
char set. It is an integer type. Actual type can be either signed or unsigned. It 8 %c
contains CHAR_BIT bits.
Of the same size as char, but guaranteed to be signed. Capable of %c (or %hhi for numerical
signed char 8
containing at least the [−127, +127] range. output)
Of the same size as char, but guaranteed to be unsigned. Contains at least %c (or %hhu for numerical
unsigned char 8
the [0, 255] range. output)
Short signed integer type. Capable of containing at least the
signed short int 16 %hi or %hd
[−32,767, +32,767] range.
unsigned short int Short unsigned integer type. Contains at least the [0, 65,535] range. 16 %hu
unsigned int Basic unsigned integer type. Contains at least the [0, 65,535] range. 16 %u
if(employed == “Y”){
if(recentGrad==“Y”){
printf(“Your qualify”);
}
}
else{
printf(“Not qualified”);
}
Select Structure Conn’d
• if/else if statement: it tests series of statement where only one will
be executed. Example
if(score>=40){
printf(“You pass with E”,);
else if(score>=50){
printf(“You pass with D”);
}
else if(score>=60){
printf(“You pass with B”);
}
else if(score >=70){
printf(“You pass with A”);
}
else {
printf(“You fail”);
}
}
Select Structure Con
n’d
• Switch statement: it tests series of statement where only one of the statement will be selected to
execute just like the if/else if statement however it takes each of the expressions as a “case”.
switch(score){
case “1”:
printf(“N100 recharge is successful”);
break;
case “2”:
printf(“N200 recharge is successful”);
break;
case “3”:
printf(“N400 recharge is successful”);
break;
case “4”:
printf(“N500 recharge is successful”);
break;
case “5”:
printf(“N1000 recharge is successful”);
break
case “6”:
printf(“N1500 recharge is successful”);
break;
deafalt:
printf(“You quit. Bey…”);
}
Operations
• Operation it is the use of mathematics operators on operands
• An operator is a symbol that tells the compiler to perform a specific
mathematical operation on operands
• Types of operators include:
Arithmetic operators
Relational operators
Logical operators
Bitwise operators
Assignment operators
Misc operators
• An operand is a number string or character that mathematical
operator act upon
Operations Conn’d
• Arithmetic operators: arithmetic operators are binary unary
operators that act upon operands to produce a result. Arithmetic
operators supported in c assuming operand A=10 and operand B= 20
• NB:
and
Operations Conn’d
• Misc operator: is conditional operator which has 3 operands, the first operand is always
evaluated first. If nonzero, the second operand is evaluated, and that is the value of the
result.
1 #define
Substitutes a preprocessor macro.
2 #include
Inserts a particular header from another file.
3 #undef
Undefines a preprocessor macro.
4 #ifdef
Returns true if this macro is defined.
5 #ifndef
Returns true if this macro is not defined.
6 #if
Tests if a compile time condition is true.
7 #else
The alternative for #if.
8 #elif
#else and #if in one statement.
9 #endif
Ends preprocessor conditional.
Input and Output
• printf(): a function used for printing to the console
printf(“Hello world”);
• Scanf(): a function used for accepting input from the console
scanf(“%c”, &ch) : to accept character where “%c” is the format
specifier
scanf(“%d”, &ch) : to accept integer where “%c” is the format
specifier
Compilation in c
Escape sequences in
c
• It is a sequence of characters that does not represent itself when used inside a
character or string literal, but is translated into another character or a sequence of
characters that may be difficult or impossible to represent directly
Escape sequence Character represented
\a Alert (Beep, Bell)
\b Backspace
\e Escape character
\f Formfeed Page Break
\n Newline (Line Feed); see notes below
\r Carriage Return
\t Horizontal Tab
\v Vertical Tab
\\ Backslash
\' Apostrophe or single quotation mark
\" Double quotation mark
\? Question mark (used to avoid trigraphs)
Function
• A function is a set/block of programming statements for carrying out a specific
task enclosed withing curly brackets, { }.
• It can be called many time to carry out specific task (reusability)
• It enhance clarity of source code
• A system can be divided into component function and be assign to different
developers
• Function declaration: void rectangle(float l, float b);
• Types of function:
Library: inbuild, made up the header libraries e.g. scanf(), printf(), gets(), puts(),
ceil(), floor() etc.
User-define: defined by programmer e.g. void cuboid(float l, float b, float h)
Return: can be int, float char etc. e.g.
float get(){
return 10.2;
}
Void: does not return value
Function Conn’d
• A function may not accept argument e.g.
int circle (void){
float r, pi=3.14;
return r*pi;
}
Function Prototype
• It is a declaration of a function that specifies the name of the function, return
type and the type signature/parameter
int addNumbers(int a, int b);
parameter of the function addNumbers
int is the function
type
• The parameter of a function is variable that accept argument that is passed to
the function
• An argument is value that is passed to a function usually contained in a
variable
• Function definition contains a block of codes to perform a specific task
returnType functionName(type1 argument1, type2 argument2, ...)
{
//body of the function
}
Example of Function
Prototype
void findReactangleArea(float a, float b);
int main()
{
float x,y;
printf("Enter the length: ");
scanf("%f", &x);
printf("Enter the breadth: ");
scanf("%f", &y);
findReactangleArea(x, y);
return 0;
}
void findReactangleArea(float a, float b){
float res;
res = a*b;
printf("\n The area of this rectangle = %0.2f squared\n",res);
return;
}
Recursion
• Direct recursion: When a function calls itself it is said to be a
recursion
funct_one(){
funct_one();
}
• Indirect recursion: is when a function calls itself through another
function
void funct_one(){
funct_two();
}
void funct_two(){
funct_one();
}
Example: Fibonacci
Sequence
int fibbonacci(int n) {
if(n == 0){
return 0;
} else if(n == 1) {
return 1;
} else {
return (fibbonacci(n-1) + fibbonacci(n-2));
}
}
int main() {
int n;
printf("Enter the nth term: ");
scanf("%d", &n);
int i;
printf("Fibbonacci of %d: " , n);
for(i = 0;i<n;i++) {
printf("%d ",fibbonacci(i));
}
Array
• Arrays are kind of data structure that can store a fixed-size sequential collection of
elements/variables of the same type (primitive and derived)
• Declaration:
type arrayName [ arraySize ];
double balance[10];
• Array initialization:
double balance[5] = {1000.0, 2.0, 3.4, 7.0, 50.0};
double balance[] = {1000.0, 2.0, 3.4, 7.0, 50.0};
• Accessing array:
double salary = balance[9]; //accessing the 10th element of an array
Arrays Conn’d
• Array size
Array Conn’d
• Accessing array elements:
int main () {
int n[ 10 ]; /* n is an array of 10 integers */
int i,j;
/* initialize elements of array n to 0 */
for ( i = 0; i < 10; i++ ) {
n[ i ] = i + 100; /* set element at location i to i + 100 */
}
/* output each array element's value */
for (j = 0; j < 10; j++ ) {
printf("Element[%d] = %d\n", j, n[j] );
}
return 0;
}
Array Pointers
• Array pointers: is a data structure that stores a fixed-sized sequence
collection of pointers to primitive or derived datatypes
• Declaration
int *ptr[MAX];
Example:
int var[] = {10, 100, 200};
int i, *ptr[MAX];
int main( ) {
struct Books book1; /* Declare Book1 of type Book */
struct Books book2; /* Declare Book2 of type Book */
/* book 1 specification */
strcpy( Book1.title, "C Programming");
strcpy( Book1.author, "Nuha Ali");
strcpy( Book1.subject, "C Programming Tutorial");
book1.book_id = 6495407;
Structure with Function
Conn’d
/* book 2 specification */
strcpy( book2.title, "Telecom Billing");
strcpy( book2.author, "Zara Ali");
strcpy( book2.subject, "Telecom Billing Tutorial");
book2.book_id = 6495700;
/* print Book1 info */
printBook( book1 );
Bye…