You are on page 1of 30

NATIONAL ECONOMICS UNIVERSITY

SCHOOL OF INFORMATION TECHNOLOGY AND DIGITAL ECONOMICS

CHAPTER 3
TOP-DOWN DESIGN WITH FUNCTIONS
OUTLINE

¡ Top-Down Design
¡ Introduction to Function
¡ Function Design
¡ Library Function
TOP-DOWN DESIGN

¡ Top-down design: a problem-solving method in which:


¡ first break a problem up into its major subproblems
¡ solve the subproblems to derive the solution to the original problem

Big Problem

Smaller Smaller Smaller


Problem Problem Problem

Even Smaller Even Smaller Even Smaller


Problem Problem Problem

3
TOP-DOWN DESIGN

¡ Making a movie:

4
FUNCTIONS

¡ A function is a group of statements that together


perform a task.
¡ A function can be used to call or execute multiple
statements at one time
¡ Every C program has at least one function, which
is main()
¡ You can divide up your code into separate
functions.

5
ADVANTAGES OF USING FUNCTION SUBPROGRAMS

¡ Solve large complicated problems


¡ Keep our code simple and readable
¡ Reuse of Function Subprograms

main()

draw_circle() draw_triangle() draw_intersecting _line()

draw_intersecting _line() draw_based()


House Person
6
FUNCTIONS WITHOUT ARGUMENTS

¡ The empty parentheses after the function name indicate that this function requires
no arguments
¡ For example:

int main(void){
draw_circle(); // Draw a circle
draw_triangle(); // Draw a triangle
draw_intersect(); // Draw intersecting lines
return (0);
} Person
7
FUNCTION PROTOTYPES & DEFINITIONS

¡ You need to provide a prototype & a definition for each function:


void draw_circle(void) Function Prototype
main (void) {
draw_circle(); Invoke Function
}

void draw_circle(void) { Function Definitions


printf(" * * ");
printf(" * * ");
printf(" * * ");
printf(" * * ");
}
8
FUNCTIONS WITH INPUT ARGUMENTS

¡ Arguments
¡ Parameters
¡ Return parameter

double volumeOfSphere(double r){


return data type double v = 4.0/3.0*3.141592*r*r*r;
return v;
}

return statement volumeOfSphere(10.0)

argument 9
EXAMPLE

¡ Calculate volume of Moon:


#include <stdio.h>
double volumeOfSphere(double r){
return 4.0/3.0*3.141592*r*r*r;
}
int main(){
r ≈ 1.735 km
printf("Volume Of Moon %f",volumeOfSphere(1737.5));
return 0;
}
10
FUNCTION DESIGN

¡ You shouldn't output to the console


inside of a returned function
¡ Try to make the functions have one use
or one function basically

11
CREATING VOID FUNCTIONS

¡ void is used as a function return type, indicating that it doesn’t return a value:
void printInfo(char name[], double r){
printf("Volume of %s is %.1f cubic kilometers\n",name,volumeOfSphere(r));
}
int main(){
printInfo("Moon", 1737);
printInfo("Mars", 3393);
printInfo("Earth", 6378.8);
printInfo("Sun", 696340);
return 0;
}

12
LIBRARY FUNCTIONS

¡ The C standard library:


¡ stdio.h: core input and output functions
¡ stdlib.h: numeric conversion, random numbers…
¡ ctype.h: set of functions used to classify characters
¡ math.h: common mathematical functions
¡ stdbool.h: boolean data type
¡ time.h: date- and time-handling functions
¡ assert.h: the assert macro to assist detecting errors
¡ complex.h: functions for complex numbers
¡ …
13
STDIO.H

¡ Formatted input/output:
¡ printf() is used to print the character, string, float, integer, octal and hexadecimal values onto the
output screen
¡ scanf() is used to read a character, string, numeric data from keyboard.
¡ getchar() reads character from keyboard
¡ putchar() writes a character to screen
¡ gets() reads line from keyboard
¡ puts() writes line to o/p screen
¡ …

14
STDIO.H

¡ Operations on files:
¡ fopen() opens a file
¡ fclose() closes an opened file
¡ getw() reads an integer from file
¡ putw() writes an integer to file
¡ fgetc() reads a character from file
¡ fgets() reads string from a file, one line at a time
¡ fputs() writes string to a file
¡ feof() finds end of file
¡ …

15
MATH.H

¡ Trigonometric functions:
¡ cos(): Returns the cosine of a radian angle x
¡ sin(): Returns the sine of a radian angle x
¡ tan(): Returns the tangent of a radian angle x
¡ acos(): Returns the arc cosine of x in radians
¡ asin(): Returns the arc sine of x in radians
¡ atan(): Returns the arc tangent of x in radians

16
MATH.H

¡ Hyperbolic functions:
¡ acosh(): Returns the area hyperbolic cosine of x
¡ asinh(): Returns the area hyperbolic sine of x
¡ atanh(): Returns the area hyperbolic tangent of x
¡ sinh(): Returns the hyperbolic sine of x
¡ cosh(): Returns the hyperbolic cosine of x
¡ tanh(): Returns the hyperbolic tangent of x

17
MATH.H

¡ Exponential and logarithmic functions:


¡ exp(double x): Returns the value of e raised to the xth
power.
¡ log(double x); Returns the natural logarithm (base-e
logarithm) of x
¡ log10(double x); Returns the common logarithm (base-10
logarithm) of x.
¡ log2(double x); Returns the common logarithm (base-2
logarithm) of x.

18
MATH.H

¡ Round functions:
¡ ceil(): Returns the smallest integer value greater than or
equal to x
¡ round(): returns the nearest integer
¡ floor(): Returns the largest integer value less than or equal
to x
¡ trunc(): Returns nearest integral value that is not larger in
magnitude than x

19
MATH.H

¡ Other functions:
¡ double fabs(x): Returns the absolute value
¡ double fmax(x, y): Returns the larger of its arguments
¡ double fmin(x, y): Returns the smaller of its arguments
¡ double sqrt(x); Returns the square root of x.
¡ double cbrt(x); Returns the cubic root of x.

20
CTYPE.H

¡ Functions to classify and transform individual characters:


¡ isgraph(): Check if char has graphical representation
¡ ispunct(): Check if char is a punctuation character
¡ isxdigit(i): Check if char is hexadecimal digit
¡ iscntrl(): Check if char is a control character
¡ isupper(): Check if char is uppercase letter
¡ islower(): Check if char is lowercase letter
¡ isalnum(): Check if char is alphanumeric
¡ isspace(): Check if char is a white-space
¡ isdigit(): Check if char is decimal digit
¡ isalpha(): Check if char is alphabetic
¡ isprint(): Check if char is printable
¡ isblank(): Check if char is blank

21
STDLIB.H

¡ This header defines several general-purpose functions


¡ String conversion: atof(), atoi()
¡ Random generation: rand(), strand()
¡ Dynamic memory management: calloc(), free(), malloc(), realloc()
¡ Searching and sorting: bsearch(), qsort()
¡ Integer arithmetic: abs(), div(), labs(), ldiv()

22
STRING.H

¡ Copying: strcpy(), strncpy()


¡ Concatenation: strcat(), strncat()
¡ Comparison: strcmp(), strncmp()
¡ Searching: strchr(), strpbrk(), strstr(), strtok()

23
TIME.H

¡ Time manipulation:
¡ clock(): Clock program
¡ difftime(): Return difference between two times
¡ mktime(): Convert tm structure to time_t
¡ time(): Get current time
¡ Conversion:
¡ asctime(): Convert tm structure to string
¡ ctime(): Convert time_t value to string
¡ gmtime(): Convert time_t to tm as UTC time
¡ localtime(): Convert time_t to tm as local time
¡ strftime(): Format time as string
24
LIMITS.H

Name Expresses Value*


CHAR_BIT Number of bits in a char object (byte) 8 or greater*
SCHAR_MIN Minimum value for an object of type signed char -127 (-27+1) or less*
SCHAR_MAX Maximum value for an object of type signed char 127 (27-1) or greater*
UCHAR_MAX Maximum value for an object of type unsigned char 255 (28-1) or greater*
CHAR_MIN Minimum value for an object of type char either SCHAR_MIN or 0
CHAR_MAX Maximum value for an object of type char SCHAR_MAX or UCHAR_MAX
MB_LEN_MAX Maximum number of bytes in a multibyte character, for any local 1 or greater*
SHRT_MIN Minimum value for an object of type short int -32767 (-215+1) or less*
SHRT_MAX Maximum value for an object of type short int 32767 (215-1) or greater*
USHRT_MAX Maximum value for an object of type unsigned short int 65535 (216-1) or greater*
INT_MIN Minimum value for an object of type int -32767 (-215+1) or less*
INT_MAX Maximum value for an object of type int 32767 (215-1) or greater*
UINT_MAX Maximum value for an object of type unsigned int 65535 (216-1) or greater*
LONG_MIN Minimum value for an object of type long int -2147483647 (-231+1) or less*
LONG_MAX Maximum value for an object of type long int 2147483647 (231-1) or greater*
ULONG_MAX Maximum value for an object of type unsigned long int 4294967295 (232-1) or greater*
LLONG_MIN Minimum value for an object of type long long int -9223372036854775807 (-263+1)*
LLONG_MAX Maximum value for an object of type long long int 9223372036854775807 (263-1) *
ULLONG_MAX Maximum value for an object of type unsigned long long int 18446744073709551615 (264-1)* 25
EXERCISE 1

¡ Write this expression as a C assignment statement using functions exp, log, and pow:

𝑥 = 𝑒 !"#$% & + 𝑟 '

26
EXERCISE 2

¡ n! is defined as the product n*(n -1) *(n − 2) *… * 2 * 1


¡ An approximation can be used R.W. Gosper proposed the following such
approximation formula:

1
𝑛! ≈ 𝑛! 𝑒 "! 2𝑛 + 𝜋
3
¡ Write a C program, to calculate and display the result of 25! Should look something
like this:

25! equals approximately …


27
EXERCISE 3

¡ Write a function to find factorial of a given number.Your main() could be:

int main(){
int n;
printf("Enter an integer to find its factorial\n");
scanf("%d", &n);
float f = factorial(n);
printf("%d! equals approximately %f", n, f);
return 0;
}
28
EXERCISE 4

¡ A new strain of flu begins with a single case in a China. Three days later a second case is reported, and
in the following days the reported cases are as shown in the table below:

Day # 0 3 5 6 7 8 9 10 11
Total cases 1 2 3 4 5 7 9 11 15

¡ A math professor observes that the number of cases seems to be increasing by the following formula:
40000
𝐶𝑎𝑠𝑒𝑠 𝑥 =
1 + 39999(𝑒 !".$%&'( )
¡ Write a function that implements this model. Test your function by entering a day number and then
calculates the number of cases predicted

29
SUMMARY

¡ Top-Down Design
¡ Introduction to Function
¡ Function Design
¡ Library Function

30

You might also like