Presentation is loading. Please wait.

Presentation is loading. Please wait.

BBS514 Structured Programming (Yapısal Programlama)1 Functions and Structured Programming.

Similar presentations

Presentation on theme: "BBS514 Structured Programming (Yapısal Programlama)1 Functions and Structured Programming."— Presentation transcript:

1 BBS514 Structured Programming (Yapısal Programlama)1 Functions and Structured Programming

2 BBS514 Structured Programming (Yapısal Programlama)2 Introduction Structured Programming is a problem-solving strategy and a programming methodology that includes the following two guidelines: The flow of control in a program should be as simple as possible. The construction of a program should embody top-down design.

3 BBS514 Structured Programming (Yapısal Programlama)3 Top-down Design Top-down design, also referred to as stepwise refinement, or divide and conquer, consists of repeatedly decomposing a problem into smaller problems. In other words: –Construct a program from smaller pieces or components These smaller pieces are called modules –Each piece more manageable than the original program

4 BBS514 Structured Programming (Yapısal Programlama)4 Program Modules in C Functions –Modules in C –Programs combine user-defined functions with library functions C standard library has a wide variety of functions Function calls –Invoking functions Provide function name and arguments (data) Function performs operations or manipulations Function returns results –Function call analogy: Boss asks worker to complete task –Worker gets information, does task, returns result –Information hiding: boss does not know details

5 BBS514 Structured Programming (Yapısal Programlama)5 Math Library Functions Math library functions –perform common mathematical calculations –#include Format for calling functions –FunctionName( argument ); If multiple arguments, use comma-separated list –y = sqrt( ); Calls function sqrt, which returns the square root of its argument –Arguments may be constants, variables, or expressions

6 BBS514 Structured Programming (Yapısal Programlama)6 Available Mathematical functions Function HeaderDescription int abs(int num)Returns the absolute value of an integer element. double fabs(double num)Returns the absolute value of a double precision element. double pow(double x,double y)Returns x raised to the power of y. int rand(void)returns a random number double sin(double angle)Returns the sine of an angle; the angle should be in Radius. double cos(double angle)Returns the cosine of an angle; the angle should be in Radius. double sqrt(double num)Returns the the square root of a double

7 BBS514 Structured Programming (Yapısal Programlama)7 Using Library Functions Calculate the square root of (x1 - x2) 2 + (y1 - y2) 2 a = x1 – x2; b = y1 – y2; c = pow(a,2) + pow(b, 2); d = sqrt(d); OR just: d=sqrt( pow( (x1-x2), 2) + pow( (y1-y2), 2)); What is the value of: sqrt(floor(fabs(-16.8)))

8 BBS514 Structured Programming (Yapısal Programlama)8 Functions  We have already written our own functions and used library functions: –main is a function that must exist in every C program. –printf, scanf are library functions which we have already used in our programs.  We need to do two things with functions: –Create Functions –Call Functions (Function invocation)

9 BBS514 Structured Programming (Yapısal Programlama)9 Functions Functions can be categorized by their return types: Function returning a value – A function that performs some subtask that requires returning some value to the calling function. Void function – A function that performs some subtask that does not require a single value to be returned to the calling function.

10 BBS514 Structured Programming (Yapısal Programlama)10 Function Definition A function definition has the following form: return_type function name (formal parameter list) { declarations statements } function prototype return_type - the type of value returned by the function void – indicates that the function returns nothing. function name – any valid identifier formal parameter list – comma separated list, describes the number and types of the arguments that get passed into the function when its invoked.

11 BBS514 Structured Programming (Yapısal Programlama)11 Example: Function returning a value Let’s define a function to compute the cube of a number: int cube ( int num ) { int result; result = num * num * num; return result; } This function can be called as: n = cube(5);

12 BBS514 Structured Programming (Yapısal Programlama)12 void prn_message() /* function definition */ { printf(“A message for you: ”); printf(“Have a nice day!\n”); } int main () { prn_message ( ); /* function invocation */ return 0; } Example: Void Function

13 BBS514 Structured Programming (Yapısal Programlama)13 General Structure of a C Program preprocessor directives function prototypes int main () {. } function-1 function-2. function-n

14 BBS514 Structured Programming (Yapısal Programlama)14 Function Invocation A program is made up of one or more functions, one of them being main ( ). When a program encounters a function, the function is called or invoked. After the function does its work, program control is passed back to the calling environment, where program execution continues. Main Func 1 Func 2

15 BBS514 Structured Programming (Yapısal Programlama)15 #include void print_message (int k); /*function prototype */ int main () { int n; printf(“There is a message for you.\n”); printf(“How many times do you want to see it? ”); scanf(“%d”, &n); print_message(n); return 0; } void print_message (int k) /* function definition */ { int i; printf(“\nHere is the message.\n”); for (i=0; i < k; ++i) printf(“Have a nice day!\n”); }

16 BBS514 Structured Programming (Yapısal Programlama)16 /* An example demonstrating local variables */ #include void func1 (); int main () { int i = 5; printf(“%d \n”, i); func1( ); printf(“%d \n”,i); return 0; } void func1 () { int i = 5; printf(“%d\n”, i); i++; printf(“%d\n”, i); }

17 BBS514 Structured Programming (Yapısal Programlama)17 The return statement When a return statement is executed, program control is immediately passed back to the calling environment. If an expression follows the keyword return, the value of the expression is returned to the calling environment as well. A return statement has one of the following two forms: return; if return type is void return expression;otherwise

18 BBS514 Structured Programming (Yapısal Programlama)18 Examples return; return 77; return ++a; return (a+b+c);

19 BBS514 Structured Programming (Yapısal Programlama)19 Example int IsLeapYear(int year) { return ( ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0) ); } This function may be called as: if (IsLeapYear(2005)) printf(“29 days in February.\n”); else printf(“28 days in February.\n”);

20 BBS514 Structured Programming (Yapısal Programlama)20 #include int min (int a, int b); int main () { int j, k, m; printf(“Input two integers: ”); scanf(“%d %d”, &j, &k); m = min(j,k); printf(“\nThe minimum is %d.\n”, m); return 0; } int min(int a, int b) { if (a < b) return a; else return b; } Input two integers: 5 6 The minimum is 5. Input two integers: 11 3 The mininum is 3.

21 BBS514 Structured Programming (Yapısal Programlama)21 Parameters A function can have zero or more parameters. In declaration header: int f (int x, double y, char c); In function calling: value = f(age, score, initial); the formal parameter list (parameter variables and their types are declared here) actual parameter list (cannot tell what their type are from here)

22 BBS514 Structured Programming (Yapısal Programlama)22 Rules for Parameter Lists The number of parameters in the actual and formal parameter lists must be consistent Parameter association is positional: the first actual parameter matches the first formal parameter, the second matches the second, and so on Actual parameters and formal parameters must be of compatible data types Actual parameters may be a variable, constant, any expression matching the type of the corresponding formal parameter

23 BBS514 Structured Programming (Yapısal Programlama)23 Invocation and Call-by-Value Each argument is evaluated, and its value is used locally in place of the corresponding formal parameter. If a variable is passed to a function, the stored value of that variable in the calling environment will not be changed. In C, all calls are call-by-value.

24 BBS514 Structured Programming (Yapısal Programlama)24 #include int compute_sum (int n); int main () { int n, sum; n = 3; printf(“%d\n”, n); sum=compute_sum(n); printf(“%d\n”,n); printf(“%d\n”, sum); return 0; } int compute_sum (int n) { int sum; sum = 0; for ( ; n > 0; --n) sum += n; printf(“%d\n”, n); return sum; }

25 BBS514 Structured Programming (Yapısal Programlama)25 1/* Finding the maximum of three integers */ 2 3#include 4 5int maximum( int, int, int ); /* function prototype */ 6 7int main() 8{8{ 9 int a, b, c; printf( "Enter three integers: " ); 12 scanf( "%d%d%d", &a, &b, &c ); 13 printf( "Maximum is: %d\n", maximum( a, b, c ) ); return 0; 16} 17 18/* Function maximum definition */ 19int maximum( int x, int y, int z ) 20{ 21 int max = x; if ( y > max ) 24 max = y; if ( z > max ) 27 max = z; return max; 30} Enter three integers: Maximum is: 85

26 BBS514 Structured Programming (Yapısal Programlama)26 Function Prototypes Function prototype –Function name –Parameters – what the function takes in –Return type – data type function returns (default int ) Used to validate functions –Prototype only needed if function definition comes after use in program The function with the prototype int maximum( int, int, int ); Takes in 3 int s Returns an int

27 BBS514 Structured Programming (Yapısal Programlama)27 Alternative styles for function definition order #include int max(int,int); int min(int,int); int main() { min(x,y); max(u,v);... } int max (int a, int b) {... } int min (int a, int b) {... } #include int max (int a, int b) {... } int min (int a, int b) {... } int main() {... min(x,y); max(u,v);... }

28 BBS514 Structured Programming (Yapısal Programlama)28 Correct the errors in the following program segments 1. int g () { printf (“Inside function g\n”); int h() { printf(“Inside function h\n”); } 2. int sum(int x, int y) { int result; result = x + y; }

29 BBS514 Structured Programming (Yapısal Programlama)29 Correct the errors in the following program segments 3. void f (float a); { float a; printf (“%f”, a); } 4. void product () { int a, b, c, result; printf(“Enter 3 integers: ”); scanf(“%d %d %d”, &a, &b, &c); result = a * b * c; printf(“Result is %d\n”, result); return result; }

30 BBS514 Structured Programming (Yapısal Programlama)30 Example Program /* This program finds the factorial value of a given * positive integer */ #include int factorial(int n); int main() { int num; printf(“Enter a positive integer: "); scanf(“%d”,&num); printf("Given positive integer: %d, “, num); printf(“its factorial value is : %d \n“, factorial(num)); return 0; }

31 BBS514 Structured Programming (Yapısal Programlama)31 Function factorial() /* Function: factorial * This function computes and returns the factorial * value of its parameter. The function assumes that * the parameter is a positive integer. */ int factorial (int num) { int counter = 2; int factVal = 1; while (counter <= num) { factVal = factVal * counter; counter = counter + 1; } return factVal; }

32 BBS514 Structured Programming (Yapısal Programlama)32 More Examples /* Function: comp_Grade * It returns a numerical value in between 0 and 4 corresponding to * a given letter grade. If the grade is invalid -1 will be returned. * Input: a single character. The character MUST BE one of the following: ‘A’,‘B’,’C’,’D’, or ‘F’. * Output: a numerical value. */ int comp_Grade(char grade) { if (grade == ‘A’) return 4; else if (grade == ‘B’) return 3; else if (grade == ‘C’) return 2; else if (grade == ‘D’) return 1; else if (grade == 'F') return 0; else return -1; }

33 BBS514 Structured Programming (Yapısal Programlama)33 Void functions A void function that prints out a menu: void menu() { printf("Please choose one of the following.\n"); printf(“\t 1. Square\n”); printf(“\t 2. Rectangle\n”); printf(“\t 3. Circle\n”); printf(“\t 4. Quit\n”); printf(“\n\n\t Enter your choice: “); } You can call this function as follows: menu();

34 BBS514 Structured Programming (Yapısal Programlama)34 Another situation where void functions might be useful is a menu driven program where the menu choices are completely unrelated. Here is a skeleton of the main program of such a function: int main() { int choice; menu(); scanf("%d", &choice); while (choice != 4) { if (choice == 1) function1(); else if (choice == 2) function2(); else if (choice == 3) function3(); else if (choice != 4) printf("Sorry, please enter your choice again.\n"); menu(); scanf("%d", &choice); }

35 BBS514 Structured Programming (Yapısal Programlama)35 Programming Exercise Write a program that that reads in the side of a square and then prints a hollow square.Your program should work for squares of all side sizes between 1 and 20. For example, if your program reads a size of 4, it should print: **** * ****

36 BBS514 Structured Programming (Yapısal Programlama)36 /* This program reads in the size of a square and draws * the square on the screen. The program validates that * the user enters a side size between 1 and 20. */ #include /* Function prototypes */ int GetSide(); void draw_square(int); int main() { int size; size = GetSide();/* Read the side length */ draw_square(size); /* Draw hallow square */ }

37 BBS514 Structured Programming (Yapısal Programlama)37 /* Function: GetSide * This function reads an integer representing the side * of a square. The function verifies that the input * value is between 1 and 20. Once input is correct * it is returned to the calling environment. */ int GetSide() { int side; printf("Enter the side of the square (1..20): "); do { scanf("%d",&side); if (side 20){ printf(“Invalid input.\n”); printf("Enter a number between 1 and 20:"); } } while (side 20); return side; }

38 BBS514 Structured Programming (Yapısal Programlama)38 /* Function: draw_square * This function draws a hallow square on the screen * given its side length. */ void draw_square(int number) { int i, j; for(i=1; i<=number; i++){ for(j=1; j<=number; j++){ if (j==1 || j== number || i==1 || i== number) printf("*"); else printf(" "); } printf("\n"); } return; }

Download ppt "BBS514 Structured Programming (Yapısal Programlama)1 Functions and Structured Programming."

Similar presentations

Ads by Google