Sei sulla pagina 1di 39

C 05

“Modular
Programming
PROBLEM SOLVING AND PROGRAM DESIGN IN C BY HANLY AND KOFFMAN

Objectives:
 Be able to understand top-down designing principle
 Be able to grasp the concept of modular programming
 Be able to utilize recursion to solve iterative problems
 Be able to work with multiple source files
CLO_1

Programming
Fundamentals Contents:

Top-Down Design
Chapter 5
Problem Solving and Program Predefined Functions
Design in C by Hanly and Programmer defined Functions
Koffman Limitation of Function
Scope of Variables
Recursion
C 05

Lecture 13
TOP-DOWN DESIGN. PREDEFINED FUNCTIONS.
Top-Down Design
Building a program from existing Stones
resources. Bric ks
Mud
Modular Programming – dividing a
program in to multiple modules Sand Silica
(functions) Room 1

Decomposing a problem into smaller Silica


Floor 1 Room 2
problems.
C ement Carbonates
Eventually leads to a collection of Room 3
smaller problems or tasks, each of
Sulfates
which can be easily coded. Room 1

Example: Building Floor 2 Room 2

Construct a building Room 3


Consist of Floors
Room 1 Lego Blocks
Consist of Rooms
Bricks
Floor 3 Room 2
Sand
Cement
Room 3
Top-Down Design
Examples:
Predefined Functions
Procedural Language:
As the name implies, algorithms are implemented in snippet called procedures aka functions.
C is a pure procedural language.

Code Reusability:
Reusing program fragments that have already been written and tested whenever possible, is one way to
accomplish this goal.
Stated more simply, “Why reinvent thewheel?”

Example:
We can use the C functions pow( ) and sqrt( ) included in <math.h> header to compute the roots of a
quadratic equation in x of the form ax²+ bx +c =0
Compute two roots, root_1 and root_2
disc =pow(b,2) -4*a*c;
root_1 =(-b +sqrt(disc)) / (2*a);
root_2 =(-b - sqrt(disc)) / (2*a);
Library Functions in C
Library Functions in C
Predefined Functions
Example: Find Logarithm(base10)
Predefined Functions
Example: Find Absolute value.
Predefined Functions
Example: Find Ceiling value.
C 05

Lecture 14
PROGRAMMER DEFINED FUNCTIONS. LIMITATION OF FUNCTION.
Functions in C
C program is made up of one or more functions, one of them 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 isexecuted.
Control is passed back to the calling function.

Calling a function is analogous to asking a friend to perform an urgent task. You tell your friend what to do
(but not how to do it) and wait for your friend to report back that the task is finished. After hearing from your
friend, you can go on and do something else.

A function in C consists of following three parts


Function Declaration
Function Definition
Function Call
Bad Programming Practice
Example: Print same messages 4times

int main ( )
{
printf(“A message for you:\n\n”);
printf(“Have a nice day!\n”);

printf(“A message for you:\n\n”);


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

printf(“A message for you:\n\n”);


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

printf(“A message for you:\n\n”);


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

return 0; }
Good Programming Practice
Programmers can write their own functions as well.
Typically, each module in a program’s design hierarchy is implemented as a function.
C function names follow the same naming rules as C variables.

void printMessage(void); //Function Declaration

int main ( )
{ printMessage ( ); //Function Calling
printMessage ( ); //Function Calling
printMessage ( ); //Function Calling
printMessage ( ); //Function Calling
return 0; }

void printMessage(void) //Function Definition


{
printf(“A message for you:\n\n”);
printf(“Have a nice day!\n”);
}
The Function Declaration
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.
Also make programming with multiple files possible.
The Function Call
Passes program control to the function
Must match the prototype/declaration in name, number of arguments, and types of arguments

void printMessage (void);

int main ( ) same name, same arguments and same return type
{
printMessage( );
printMessage( );
printMessage( );
printMessage( );

return 0;
}
The Function Definition
Control is passed to the function definition by the function call.
The statements within the function body will then be executed.

void printMessage(void)
{
printf(“A message for you:\n\n”); Function Body
printf(“Have a nice day!\n”);
}

After the statements in the function body 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( ) always . It can be any other function.
General Function Syntax
Generally we have to deal with following things when working with functions.

type functionName(parameter1, . . . , parameterN)


{
variable declaration(s)
statement(s)
return;
}

Function can have any number of parameters.


Function can return only one value.

Following four possible combinations of function are possible.


void functionname (void);
void functionname (parameter1, . . . ., parameterN);
type functionname (void);
type functionname (parameter1, . . . .,parameterN);
Input Parameters
Example: Print the received value.

void printMessage(int);
int main( )
{
int num;
printf(“Enter an integer:”);
scanf(“%d”,&num);
printMessage(num); //matches the one formal parameter of type int
return 0;
}
void printMessage(int val)
{
printf(“Value passed by function is %d \n” , val);
}
Functions with Return Value
Example: Find Average of two numbers

float averageTwo(int, int);

int main(void)
{ float ave; int value1=5; int value2=8;
ave = averageTwo (value1, value2) ; //ave = 6.5;
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;
}
Passing Parameters
Actual parameters are the parameters that appear in the function call.
ave =averageTwo(value1, value2) ;

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

Actual and formal parameters are matched by position.


Each formal parameter receives the copy of value (aka pass by value) of its corresponding actual
parameter.
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.

Function –Pros and Cons:


Pros – Clean programming practice, allow team projects by providing modularity.
Cons – To much function calling leads to slower program execution.
C 05

Lecture 15
SCOPE OF VARIABLES. FUNCTION EXAMPLES.
Scope of Variables
Local Variables:
Local variables are declared within the body of a function or a block.
Local variable are created over stack.
It means as soon as the function execution ends, its LVs will self destruct.

The scope of local variables is limited to block enclosed in braces {}


where they are declared.
This means that if another function existed in addition to main(), the local
variables declared in main() could not be accessed from the other
function and vice versa.

Global Variables:
A global variable is a variable declared in the main body of the source
code, outside all functions.
Global variable are created over heap.
A Global variables can be referred from anywhere in the code, even
inside functions, whenever it is after itsdeclaration.
Local Variables
Example: Different names and different memory locations
value1 value2 ave
float averageTwo(int, int);
5 8 ?
int main(void)
{ float ave; int value1=5; int value2=8; int int float
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) num1 num2 average


{ float average;
average = (num1 + num2) / 2.0; ? ? ?
return average;
int int float
}
Local Variables
Example: Same names but still different memory locations
value1 value2 ave
float averageTwo(int, int);
5 8 ?
int main(void)
{ float ave; int value1=5; int value2=8; int int float
ave = averageTwo (value1, value2) ;
printf(“The average of %d and %d is %f \n”, value1, value2, ave);
return 0;
}

float averageTwo(int value1, int value2) value1 value2 ave

{ float ave;
ave = (value1 + value2) / 2.0; ? ? ?
return ave;
int int float
}
Local Variables
Example: Changes to local variables, do not change other(function’s) local variables.
value1 value2 ave
float averageTwo(int, int);
5 8 ?
int main(void)
{ float ave; int value1=5; int value2=8; int int float
ave = averageTwo (value1, value2) ;
printf(“The average of %d and %d is %f \n”, value1, value2, ave);
return 0;
}

float averageTwo(int value1, int value2) value1 value2 ave

{ float ave;
ave = (value1 + value2) / 2.0
22 9 6.5
value1 = 22; value2 = 9;
int int float
return ave; }
Functions
Example: Prime number or not a prime number.
Functions
Example: Find permutation and combination.
Functions
Example: Decimal/Binary Conversion
Functions
C 05

Lecture 16
RECURSION. HEADER FILES.
Recursion
Recursion is the property that function call itself(actually its clone) to solve iterative problems.

Example: Find factorial of a numbers


Recursion
Example: Find N Fibonacci terms in series
Header Files
Header files contain function prototypes/declaration for all of the functions found in the specified library.
They also contain definitions of constants and data types used in that library.

Example: Find hypotenuse ofrightangle triangle

#include <stdio.h>
#include <math.h>
int main ( )
{
float side1, side2, hypotenuse;
printf(“Enter the lengths of the right triangle sides:”);
scanf(“%f”,&side1);
scanf(“%f”,&side2);
hypotenuse = sqrt ((side1 * side1) + (side2 * side2));
printf(“The hypotenuse = %f” , hypotenuse);
return 0;
}
Storage Classes
Every variable in C programming has two properties: type and storage class.
Type refers to the data type of a variable and, storage class determines the scope and lifetime of a variable.

Auto: auto is the default storage class for all local variables.
auto can only be used within functions, i.e. local variables.

Register: register is used to define local variables that should be stored in a register instead of RAM.
Register should only be used for variables that require quick access - such as counters.

Static: static is the default storage class for global variables.


static can also be defined within a function. If this is done the variable is initialized at run time but is not reinitialized when
the function is called again. This means inside a function, static variable retains its value during various calls.

Extern: extern is used to give a reference of a global variable that is visible to ALL the program files.
When you use 'extern' the variable cannot be initialized as all it does is point the variable name at a storage location
that has been previously defined.
Task 1: C 05
 Write a complete C program that prompts the user for FIVE numbers at the
beginning of type float/double and the perform the following operations on each.
 Sine, Cosine, Tangent, Cosec, Sec, Cot, Exponent, Log, Log10, Square Root, Square, Cube,
Power10, Cube Root, Floor, Ceil, Absolute Value.
 Try to make use of programmer define function to save some of your typing efforts.
 Hint: function declaration looks like this - void math_function(float num);

Task 2:
 Write recursive function ArithmeticSeries( ) that will calculate the sum of odd
numbers from 1 to N.
 N must be entered by the user in main( ) and final result must be displayed by main( ).

Assignment 5
C 05
 Write complete C program to calculate grade and CGPA for 100 students.
 In main( ) function prompt the user for 5 subjects marks out of 100.
 Make another function named “tatalMarks” that takes 5 subjects as input from function
main( ) as parameters and return the totalMarks.
 Make second function named “cgpa” that takes totalMarks as input from main( ) and will
return CGPA .
 Then main( ) will print GRADE and CGPA. Make use of suitable data types.

 Write an interactive program that prompts the user for three inputs a, b, c in main( )
and then call a function roots to calculates it’s both roots using quadratic formula.
 Use google to learn how to return multiple result from a function.
 Your program must cover all cases of discriminant

Practice Problems
C 05
 Write a program that uses recursive function to convert decimal number to binary.
 Number must be entered by the user in main( ) and result must be displayed by main( ).

 Write a program that uses recursive function to calculate GCD of two numbers.
 Numbers must be entered by the user in main( ) and result must be displayed by main( ).

 Write a complete C program to calculate the value of side “a” of a triangle.


 In main ( ) function prompt the user for other two sides “b and c” and an angle “α” values.
 Make another function named side_of_tri( ) that take values of three inputs from function
main( ) as parameters and return value of “a”, and main( ) will print that value.

Practice Problems

Potrebbero piacerti anche