Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
“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
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.
int main ( )
{
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.
int main ( )
{ printMessage ( ); //Function Calling
printMessage ( ); //Function Calling
printMessage ( ); //Function Calling
printMessage ( ); //Function Calling
return 0; }
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
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.
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
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;
}
Formal parameters are the parameters that appear in the function definition header.
float averageTwo(int num1, intnum2)
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.
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 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 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.
#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.
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( ).
Practice Problems