Pemrograman Dasar

Download as pdf or txt
Download as pdf or txt
You are on page 1of 50

PEMROGRAMAN DASAR Ahmad Nasikun

7 MODULARITAS Warsun Najib


THIS WEEK Ahmad Nasikun
ahmad.nasikun@ugm.ac.id
REVIEW OF
STRUCTURED PROGRAMMING
Structured programming is a problem solving strategy and a
programming methodology that includes the following
guidelines:
 The program uses only the sequence, selection, and repetition control
structures.
 The flow of control in the program should be as simple as possible.
 The construction of a program embodies top-down design.
INTRODUCTION TO
MODULAR PROGRAMMING
Several programmers work together in teams on the same
project.
In addition, there is the problem of software maintenance.
In general, a software system is a just another complex
artificial system. In developing it we use a similar strategy,
namely, the divide-and-conquer approach.
INTRODUCTION TO
MODULAR PROGRAMMING

Modular programming is defined as organizing a


program into small, independent modules that are
separately named and individually invoke-able
program elements. These modules are integrated to
become a software system that satisfies the problem
requirements.
EXAMPLE PROGRAM 1

A Modular C Program that Draws Geometrical Figures (Use of


Functions that Do Not Receive or Send Data)
We will assign a name to each module and combine the named
modules in a program structure under the control of a main
program. Such a program structure consists of a set of modules
and an order of execution.
STRATEGY (1)
This strategy is essentially based on the divide-and-conquer
approach to problem solving and has many advantages over
developing a monolithic program for the entire problem.
1. When we modularize a problem, we end up with a set of smaller
and simpler problems, which can be assigned to different teams.
2. Converting simple problems to individual programs facilitates
programming, program debugging, testing, expansion, repair, and
maintenance.
STRATEGY (2)

3. We can change the modules easily because they are


relatively small. Thus modular programs improve program
portability.
4. Some general-purpose modules of a modular program
can be used without any change in other software
development projects.
Now we have a main program and three subprograms.
Together, they make up a modular program.
HIERARCHY CHART
The main program appears at the top of the chart.
A line connecting a module to a module below it means that
the top module calls the one that is at a lower level of
hierarchy. Also, that the modules print_menu, draw_rectangle,
and draw_triangle are drawn in this order, from left to right,
means that the main program calls them in this order.
HIERARCHY CHART

Main_program

Print_menu Draw_rectangle Draw_triangle


DEVELOPMENT

If there is only one programmer, he or she may develop the entire


program, one module at a time, starting with the modules at the
lowest level of hierarchy in the structure chart and moving up from
there. This implementation strategy is referred to as bottom-up
implementation.
These functions require three elements:
1. Function definitions
2. Function calls
3. Function declarations
ELEMENTS OF MODULAR PROGRAMS

C requires that function names be unique in a source program file.


Program execution always begins and eventually terminates in the
main function.
A function definition consists of
1. A function type
2. A function name
3. An optional list of formal parameters enclosed in parentheses
4. A compound statement.
REVIEW OF TOP-DOWN DESIGN

Involves repeatedly decomposing a problem into smaller


problems
Eventually leads to a collection of small problems or tasks each
of which can be easily coded
The function construct in C is used to write code for these small,
simple problems.
FUNCTIONS
A C program is made up of one or more functions, one of which is main( ).
Execution always begins with main( ), no matter where it is placed in the
program. By convention, main( ) is located before all other functions.
When program control encounters a function name, the function is called
(invoked).
Program control passes to the function.
The function is executed.
Control is passed back to the calling function.
SAMPLE FUNCTION CALL
#include <stdio.h>

int main ( ) printf is the name of a predefined


{ function in the stdio library

printf (“Hello World!\n”) ; this statement is


return 0 ; is known as a
} function call
this is a string we are passing
as an argument (parameter) to
the printf function
PREDEFINED FUNCTIONS
You can use the manual pages for help with using the predefined
functions.
Some of the functions are also Linux commands or system calls, so to
get the information on how to use them in your program, use:
man 3 abs
You will also need to use the man page to find out what you have to
#include. There are over 900 libraries, so don’t expect to learn them all!
The man page will also tell you what the arguments and return type are.
FUNCTIONS (CON’T)
We have used three predefined functions so far:
printf
scanf
getchar
There are 3723 predefined functions on the gl system.
Don’t worry, nobody knows them all!
MAN PAGE EXAMPLE
ABS(3) Linux Programmer's Manual ABS(3)

NAME
abs, labs, llabs, imaxabs - compute the absolute value of an integer.

SYNOPSIS
#include <stdlib.h>

=======================================================
To use the library function abs( ), you must include the stdlib.h file.
MAN PAGE EXAMPLE (CONT’D)

In the case of the abs function, you will see:

int abs(int j);


This means that you must give it one integer argument and it will return an integer value.
PROGRAMMER-DEFINED FUNCTIONS

Programmers can write their own functions.


Typically, each module in a program’s design hierarchy chart is
implemented as a function.
C function names follow the same naming rules as C variables.
All non-trivial programs use functions.
You define all the parts of a programmer-defined function, the name, the
behavior, the parameters (or arguments) and the return type.
SAMPLE PROGRAMMER-DEFINED FUNCTION
#include <stdio.h>
void printMessage ( void ) ;
int main ( void ){
printMessage ( ) ;
return 0 ;
}

void printMessage ( void ){


printf (“A message for you:\n\n”) ;
printf (“Have a nice day!\n”) ;
}
EXAMINING PRINTMESSAGE
#include <stdio.h>

void printMessage ( void ) ; function prototype

int main ( void )


{
printMessage ( ) ; function call
return 0 ;
}

void printMessage ( void ) function header


{
printf (“A message for you:\n\n”) ; function
printf (“Have a nice day!\n”) ; body
}

function definition
THE FUNCTION PROTOTYPE
Informs the compiler that there will be a function defined later that:

returns this type


has this name
takes these arguments

void printMessage (void) ;

Needed because the function call is made before the definition -- the
compiler uses it to see if the call is made properly
THE FUNCTION CALL
Passes program control to the function
Must match the prototype in name, number of arguments, and types of
arguments

void printMessage (void) ;

int main ( void ) same name no arguments


{
printMessage ( ) ;
return 0 ;
}
THE FUNCTION DEFINITION
Control is passed to the function by the function call. The statements within
the function body will then be executed.
void printMessage ( void )
{
printf (“A message for you:\n\n”) ;
printf (“Have a nice day!\n”) ;
}

After the statements in the function have completed, control is passed back
to the calling function, in this case main( ) . Note that the calling function
does not have to be main( ) .
GENERAL FUNCTION DEFINITION SYNTAX
type functionName ( parameter1, . . . , parametern )
{
variable declaration(s)
statement(s)
}
If there are no parameters, either functionName( ) OR functionName(void) is acceptable.
There may be no variable declarations.
If the function type (return type) is void, a return statement is not required, but the following
are permitted: return ; OR return( ) ;
POSSIBILITIES

A function may:
Have no arguments and return nothing.
Have arguments and return nothing.
Have arguments and return one value.
Have no arguments and return one value.
A function can never return more than one value
PARAMETER LIST
A function can have more than one parameter:
int functionA( int a, int b, float c )
When the function is invoked, the parameters can be a
variable, constant, or expression:
result = functionA( 7, 3 + a, dollars);
The value 7 is put into to local variable a, 3 + a is put into
local variable b, and a copy of the value in dollars is put into
c in this example.
USING PARAMETERS
void printMessage (int counter) ;

int main ( void )

int num;

printf (“Enter an integer: “) ;

scanf (“%d”, &num) ;

printMessage (num) ; one argument matches the one formal parameter

return 0 ; of type int of type int

void printMessage (int counter)

int i ;

for ( i = 0; i < counter; i++ )

printf (“Have a nice day!\n”) ;

}
USING PARAMETERS (CONT’D)

In this example, we do not know in advance what the user will


enter for the value of num, however, it is copied into the
variable counter in the function printMessage( ).
Both the variables counter and i are considered to be local
variable, because they are only visible inside (or local to) the
function printMessage( ).
FINAL CLEAN C CODE
#include <stdio.h>
void printMessage (int counter) ; /*****************************************************************
** printMessage - prints a message a specified number of times
int main ( void ) ** Inputs: counter - the number of times the message will be printed
** Outputs: None
{ /*************************************************************************/
int num ; void printMessage ( int counter )
/* number of times to print message */ {
int i ; /* loop counter */
printf (“Enter an integer: “) ;
scanf (“%d”, &num) ; for ( i = 0; i < counter; i++ )
{
printMessage (num) ; printf (“Have a nice day!\n”) ;
return 0 ; }
}
}
GOOD PROGRAMMING PRACTICE
Notice the function header comment before the definition of function
printMessage.
This is a good practice and is required by the 104 C Coding Standards.
Your header comments should be neatly formatted and contain the
following information:
 function name
 function description (what it does)
 a list of any input parameters and their meanings
 a list of any output parameters and their meanings
 a description of any special conditions
HEADER FILES

Header files contain function prototypes for all of the functions


found in the specified library.
They also contain definitions of constants and data types used
in that library.
COMMONLY USED HEADER FILES
Header File Contains Function Prototypes for:
<stdio.h> standard input/output library functions
and information used by them
<math.h> math library functions
<stdlib.h> conversion of numbers to text, text to
numbers, memory allocation, random
numbers, and other utility functions
<time.h> manipulating the time and date
<ctype.h> functions that test characters for certain
properties and that can convert case
<string.h> functions that manipulate character strings
others see Chapter 5 of text
USING HEADER FILES
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main ( ){
float side1, side2, hypotenuse ;
printf(“Enter the lengths of the right triangle sides: “) ;
scanf(“%f%f”, &side1, &side2) ;
if ( (side1 <= 0) || (side2 <= 0) {
exit (1) ;
}
hypotenuse = sqrt ( (side1 * side1) + (side2 * side2) ) ;
printf(“The hypotenuse = %f\n”, hypotenuse) ;
return 0 ;
}
Functions Can Return Values
/****************************************************************************
** averageTwo - calculates and returns the average of two numbers
** Inputs: num1 - an integer value
** num2 - an integer value
** Outputs: the floating point average of num1 and num2
*****************************************************************************/
float averageTwo (int num1, int num2)
{
float average ; /* average of the two numbers */

average = (num1 + num2) / 2.0 ;


return average ;
}
#include <stdio.h>
float averageTwo (int num1, int num2) ;
int main ( )

USING {

AVERAGETWO float ave ;


int value1 = 5, value2 = 8 ;
ave = averageTwo (value1, value2) ;
printf (“The average of %d and %d is %f\n”, value1, value2, ave) ;
return 0 ;
}
float averageTwo (int num1, int num2)
{
float average ;
average = (num1 + num2) / 2.0 ;
return average ;
}
PARAMETER PASSING
Actual parameters are the parameters that appear in the function call.
average = averageTwo (value1, value2) ;

Formal parameters are the parameters that appear in the function header.
float averageTwo (int num1, int num2)

Actual and formal parameters are matched by position. Each formal


parameter receives the value of its corresponding actual parameter.
PARAMETER PASSING (CON’T)

Corresponding actual and formal parameters do not have to


have the same name, but they may.
Corresponding actual and formal parameters must be of the
same data type, with some exceptions.
LOCAL VARIABLES
Functions only “see” (have access to) their own local variables.
This includes main( ) .
Formal parameters are declarations of local variables. The values
passed are assigned to those variables.
Other local variables can be declared within the function body.
There is another type of variable called a global variable. Do not
use them! They are a major source of errors!
SAMPLE PROGRAM
#include <stdio.h> printf( "result = %d\n", result );
int funcA(int a, int b, int c ); result = funcA( 2.1, 3.5, 4.0 );
printf( "result = %d\n", result );
int main( void ) return 0;
{ }
int x = 3, y = 4, z = 5; int funcA(int a, int b, int c )
int result; {
result = funcA( x, y, z ); printf(" a = %d b = %d c = %d\n", a, b, c );
printf( "result = %d\n", result ); return ( a + b + c );
result = funcA( 6 + 4, y + 2, 9 ); }
SAMPLE PROGRAM ANALYSIS (1 AND 2)
int x = 3, y = 4, z = 5; result = funcA( 6 + 4, y + 2, 9 );
result = funcA( x, y, z ); printf( "result = %d\n", result );
printf( "result = %d\n", result ); ===================
=================== a = 10 b = 6 c = 9

a=3 b=4 c=5 result = 25

result = 12 ===================
=================== 6 + 4 is 10, OK.

Looks good! y is 4 + 2 is 6, OK.


SAMPLE PROGRAM ANALYSIS (3)
result = funcA( 2.1, 3.5, 4.0 );
printf( "result = %d\n", result );
===================

a=2 b=3 c=4


result = 9
===================

Notice that 2.1 became 2, 3.5 became 3 and 4.0 became 4. This is called
truncation. The compiler tried to make the data fit the prototype! This is called
an implied conversion, and can be the source for errors that is hard to find.
Do not use implied conversions!
ANOTHER EXAMPLE
#include <stdio.h> In this example the expression was
#include <stdlib.h> the result of another function
multiplied by a constant.
int main( void )
{ Whatever the argument is, it is
int negNum = -3; evaluated to the proper data type
printf( "%d\n", abs( negNum ) * 2 ); and then the function is invoked that
that final version of the argument.
return 0;
}
GOOD PROGRAMMING STYLE:
SIMPLICITY
Functions should do one thing and do it well!
Functions can only return one thing! (You can use a data
structure as a simple variable => do not worry, let’s deal
with it later)
It is better to have more than one function than one
complicated function.
GOOD PROGRAMMING STYLE:

Function subprograms allow us to remove the the main


function the code that provides the detailed solutions to a
subproblem.
Never write the same code twice.
Limit your functions to a maximum of 50-100 lines of code
and comments.
Many functions have only one line of code.
GOOD PROGRAMMING STYLE (CONT’D)
Forgetting to return a value from a function that is
suppose to return a value can lead to unexpected errors.
Programs should be written as a collection of small
functions.
The function prototype, function header and function
calls should all agree in the number, type, and order of
arguments and parameters, and the type of the return
value.
QUIZ REVIEW Ahmad Nasikun
ahmad.nasikun@ugm.ac.id
QUIZ
4. p=3, q=2 5. a=10, b=1, c=3, k=30
a = p & q; n = a % ++b
p = k % (--c * c++)
6. k=5 q = (n<=p) ? n+p : n-p;
j=(k >> 2) << 2
TERIMA KASIH Ahmad Nasikun
ahmad.nasikun@ugm.ac.id

You might also like