Fundamental of Programming (C)

Size: px
Start display at page:

Download "Fundamental of Programming (C)"

Transcription

1 Borrowed from lecturer notes by Omid Jafarinezhad Fundamental of Programming (C) Lecturer: Vahid Khodabakhshi Lecture 6 Modular programming Department of Computer Engineering

2 Outline Introduction to pointer Introduction to function User define function Function prototype (declaration) Function definition Function call and return Formal and Actual Parameters Scope of Identifiers Storage classes Recursion Department of Computer Engineering 2/77

3 Pointer Fundamentals When a variable is defined the compiler (linker/loader actually) allocates a real memory address for the variable int x; x When a value is assigned to a variable, the value is actually placed to the memory that was allocated x=3; Department of Computer Engineering 3/77

4 Pointers When the value of a variable is used, the contents in the memory are used y=x; will read the contents in the 4 bytes of memory, and then assign it to variable y &x can get the address of x (referencing operator &) The address can be passed to a function: scanf("%d", &x); The address can also be stored in a variable Department of Computer Engineering 4/77

5 Pointers To declare a pointer variable type * pointername; For example: int x, k; int * p1; // (or p1 is a int pointer) char *p2; p1 = &x; /* Store the address in p1 */ Department of Computer Engineering 5/77

6 Using Pointers You can use pointers to access the values of other variables, i.e. the contents of the memory for other variables To do this, use the * operator (dereferencing operator) Depending on different context, * has different meanings For example: int n, m=3, *p; p=&m; n=*p; printf("%d\n", n); // 3 printf("%d\n",*p); // 3 Department of Computer Engineering 6/77

7 Using Pointers int i1; int i2; int *ptr1; 0x1014 ptr2: 0x1000 int *ptr2; 0x1010 i1 = 1; 0x100C ptr1: 0x1000 i2 = 2; 0x1008 ptr1 = &i1; ptr2 = ptr1; 0x1004 0x1000 i2: i1: *ptr1 = 3; i2 = *ptr2; Department of Computer Engineering 7/77

8 An Example int m=3, n=100, *p, *q; p=&m; printf("m is %d\n",*p); // 3 m++; printf("now m is %d\n",*p); // 4 m 3 m 3 m n 100 n 100 n p? p p q? q? q p=&n; printf("n is %d\n",*p); // 100 *p=500; printf("now n is %d\n", n); // 500 q=&m; *q = *p; printf("now m is %d\n", m); // m 4 m *p n 100 n 500 *p p p? q? q Department of Computer Engineering 8/77

9 Modular Programming Break a large problem into smaller pieces Smaller pieces sometimes called functions Why? Helps manage complexity Smaller blocks of code Easier to read Encourages re-use of code Divide and Conquer Within a particular program or across different programs Allows independent development of code Provides a layer of abstraction Department of Computer Engineering 9/77

10 Functions - Mathematical View f ( x) x 2 2x 3 What is f(2)? f (2) (2) 2 2(2) f (2) is 11 X Function Returned value 2 f (x) 11 Department of Computer Engineering 10/77

11 Functions Every C program starts with main() function Functions could be Pre-defined library functions e.g., printf, sin, tan Programmer-defined functions e.g., my_printf, area int main() Department of Computer Engineering 11/77

12 Pre-defined library functions The C standard library is a standardized collection of header files and library functions, which are used to implement common operations Department of Computer Engineering 12/77

13 Pre-defined library functions <math.h> Defines common mathematical functions e.g. sin, cos. sqrt, pow <stdio.h> Defines core input and output functions e.g. printf, scanf, puts, gets <time.h> Defines date and time handling functions e.g. time, clock <stdlib.h> Defines pseudo-random numbers generation functions e.g. rand, srand Department of Computer Engineering 13/77

14 C mathematical functions double fmod( double x, double y ); Computes the remainder of the division operation x/y double exp( double arg ); Computes the e (Euler's number, ) raised to the given power arg double log( double arg ); Computes the natural (base e) logarithm of arg double log10( double arg ); Computes the common (base 10) logarithm of arg double sqrt( double arg ); Computes square root of arg double pow( double base, double exp); Computes the value of base raised to the power exp Department of Computer Engineering 14/77

15 C mathematical functions double sin( double arg ); Computes sine of arg (representing angle in radians) double cos( double arg ); Computes cosine of arg (representing angle in radians) double tan( double arg ); Computes tangent of arg (representing angle in radians) overview of math functions in s#stdlib.h Department of Computer Engineering 15/77

16 An example #include <stdio.h> #include <math.h> int main(void) double angle; printf("input angle in radians: \n"); scanf("%lf", &angle); printf("the sine of the angle is %f\n", sin(angle) ); return 0; Department of Computer Engineering 16/77

17 An example #include <stdio.h> #include <math.h> int main(void) double x1,y1,x2,y2, dist; printf("enter x1 y1 x2 y2 :"); scanf("%lf %lf %lf %lf", &x1, &y1, &x2, &y2); dist = sqrt(pow((x2-x1),2) + pow((y2-y1),2)); // printf("distance is %lf\n", dist); return 0; Department of Computer Engineering 17/77

18 Random numbers generation functions int rand(); Returns a uniformly distributed pseudo-random integral value between 0 and RAND_MAX (0 and RAND_MAX included) RAND_MAX : Expands to an integer constant expression equal to the maximum value returned by the function rand(). This value is implementation dependent. #define RAND_MAX /*implementation defined*/ srand() should be called before any calls to rand() to initialize the random number generator void srand( unsigned seed ); Initializes the built-in random number generator used to generate values for rand() with the seed value seed Department of Computer Engineering 18/77

19 An Example #include <stdio.h> #include <stdlib.h> int main(void) unsigned int seed; /* Declare variables. */ int k; /* Get seed value from the user. */ printf("enter a positive integer seed value: \n"); scanf("%u",&seed); srand(seed); /* Generate and print ten random numbers. */ printf("random Numbers: \n"); for (k=1; k<=10; k++) printf("%i ", rand()); printf("\n"); return 0; /* Exit program. */ Department of Computer Engineering 19/77

20 An Example #include <stdio.h> #include <stdlib.h> #include <time.h> int main(void) srand(time(0)); //use current time as seed for random generator /* Generate and print ten random numbers. */ printf("random Numbers: \n"); for (k=1; k<=10; k++) printf("%i ", rand()); printf("\n"); return 0; /* Exit program. */ Department of Computer Engineering 20/77

21 Random Numbers in [a b] Generate a random number [0.. 7] x = rand() % 8; Generate a random number [10..17] x = 10 + rand() % 8; rand() % (b-a+1) + a; Department of Computer Engineering 21/77 Sharif University of 21 Technology

22 User- defined OR Programmer-defined function Department of Computer Engineering 22/77

23 Functions - Definition Structure Function 'header' Return data type (if any) Name Descriptive Arguments (or parameter list) Notice: data type and name Statements Variable declaration Operations Return value (if any) type function_name (type arg1, type arg2 ) statements; double product(double x, double y) double result; result = x * y; return result; A function that calculates the product of two numbers Department of Computer Engineering 23/77

24 An Example Function prototype Like a variable declaration Tells compiler that the function will be defined later Helps detect program errors Note semicolon!! Function definition See previous slide Note, NO semicolon Function return return statement terminates execution of the current function Control returns to the calling function if return expression; then value of expression is returned as the value of the function call Only one value can be returned this way Function call main() is the 'calling function' product() is the 'called function' Control transferred to the function code Code in function definition is executed #include <stdio.h> /* function prototype */ double product(double x, double y); int main() double var1 = 3.0, var2 = 5.0; double ans; ans = product(var1, var2); printf("var1 = %.2f\n" "var2 = %.2f\n",var1,var2); printf("var1*var2 = %g\n", ans); return 0; /* function definition */ double product(double x, double y) double result; result = x * y; return result; Department of Computer Engineering 24/77

25 Function An Example Write a function named 'sum' sums two integers returns the sum Steps 1. Function header return data type function name argument list with data types 2. Statements in function definition variable declaration operations return value int sum_int(int x, int y) int result; result = x + y; return result; Department of Computer Engineering 25/77

26 Formal and Actual Parameters Formal parameter Variables declared in the formal list of the function header (written in function prototype & function definition) Actual parameter Constants, variables, or expression in a function call that correspond to its formal parameter The number of actual parameters in a function call must be the same as the number of formal parameters in the function definition A one-to-one correspondence must occur among the actual and formal parameters. The first actual parameter must correspond to the first formal parameter and the second to the second formal parameter, an so on The type of each actual parameter must be the same as that of the corresponding formal parameter Department of Computer Engineering 26/77

27 An Example #include <stdio.h> int calsum(int,int); Formal Parameters int main(void).... sum = calsum(num1,num2); /* function call */.. int calsum(int val1, int val2) /*function header*/ Formal Parameters /*function prototype*/ Actual Parameters Department of Computer Engineering 27/77

28 An Example If the function requires some arguments to be passed along, then the arguments need to be listed in the bracket ( ) according to the specified order void Calc(int, double, char, int); int main(void) int a, b; double c; char d; Calc(a, c, d, b); return (0); Function Call Department of Computer Engineering 28/77

29 Functions that do not return a value Use the return type of void void functionname( DataType arg_1, ) void functionname() void functionname( void) Department of Computer Engineering 29/77

30 Function Call An Example #include <stdio.h> //function prototype //global variable declaration int main(void) local variable declaration; statements; fn1( ); fn2( ); return (0); void fn1(void) local variable declaration; statements; void fn2(void) local variable declaration; statements; return; Department of Computer Engineering 30/77

31 Function Call An Example If the function returns a value, then the returned value need to be assigned to a variable so that it can be stored int GetUserInput (void); /* function prototype*/ int main(void) int input; input = GetUserInput( ); return(0); /* return 0; */ However, it is perfectly okay (syntax wise) to just call the function without assigning it to any variable if we want to ignore the returned value We can also call a function inside another function printf("user input is: %d", GetUserInput( )); Department of Computer Engineering 31/77

32 Receive nothing and return nothing #include <stdio.h> void greeting(void); /* function prototype */ int main(void) greeting( ); greeting( ); return(0); // return 0; Have fun!! Have fun!! Press any key to continue void greeting(void) printf("have fun!! \n"); Department of Computer Engineering 32/77

33 Receive nothing and return nothing #include <stdio.h> int getinput(void) /* ignore function prototype */ int number; printf("enter a number:"); scanf("%d",&number); return number; int main(void) int num1, num2, sum; num1 = getinput( ); num2 = getinput( ); sum = num1 + num2; printf("sum is %d\n",sum); return(0); Enter a number: 5 Enter a number: 4 Sum is 9 Press any key to continue Department of Computer Engineering 33/77

34 Receive parameter(s) and return nothing #include <stdio.h> int getinput(void); void displayoutput(int); int main(void) int num1, num2, sum; num1 = getinput(); num2 = getinput(); sum = num1 + num2; displayoutput(sum); return(0); int getinput(void) int number; printf("enter a number:"); scanf("%d",&number); return number; void displayoutput(int sum) printf("sum is %d \n",sum); Department of Computer Engineering 34/77 Enter a number: 5 Enter a number: 4 Sum is 9 Press any key to continue

35 Call by value And Call by reference Call by value In this method, only the copy of variable s value (copy of actual parameter s value) is passed to the function. Any modification to the passed value inside the function will not affect the actual value In all the examples that we have seen so far, this is the method that has been used Call by reference In this method, the reference (memory address) of the variable is passed to the function. Any modification passed done to the variable inside the function will affect the actual value To do this, we need to have knowledge about pointers and arrays Department of Computer Engineering 35/77

36 Call by value An Example How are the arguments passed into functions? 'Pass by value' function arguments are expressions In the function call: Expressions are evaluated and copies of their values are put into temporary memory locations The names of the corresponding parameters in the function definition are made to be the names of the copies The values of the expressions in the function call are not changed Department of Computer Engineering 36/77 #include <stdio.h> double product(double x, double y); int main() int a = 10; double var1 = 3.0, var2 = 5.0; double ans; ans = product(var1, var2); printf("var1 = %.2f\n" "var2 = %.2f\n",var1,var2); printf("var1*var2 = %g\n", ans); /* function definition */ double product(double A, double B) double result; result = A * B; return result;

37 Call by value An Example #include <stdio.h> int calsum(int,int); int main(void) int sum, num1, num2; /*function protototype*/ printf("enter two numbers to calculate its sum:\n"); scanf("%d%d",&num1,&num2); sum = calsum(num1,num2); /* function call */ printf("\n %d + %d = %d", num1, num2, sum); return(0); int calsum(int val1, int val2) /*function definition*/ int sum; sum = val1 + val2; val2 = 100; return sum; Department of Computer Engineering 37/77 num2 num1 sum val2 val1 sum Enter two numbers to calculate its sum: = 13 Press any key to continue 4? 9? 13? ?

38 Array and String Lecture 6 Call by reference #include <stdio.h> void CalByVal(a, b) a = 0; b = 10; void CalByRef(int *a, int *b) // CalByRef(int *p, int *q) *a = 0; *b = -5; // a = 0;!!!! int main(void) int a = 1, b = 5; printf("before cal CalByVal: a = %d, b = %d\n", a, b); CalByVal(a, b); printf("after cal CalByVal: a = %d, b = %d\n", a, b); b a b a b a CalByVal CalByRef main printf("before cal CalByRef: a = %d, b = %d\n", a, b); CalByRef(&a, &b); printf("after cal CalByRef: a = %d, b = %d\n", a, b); getch(); return 0; /* Exit program. */ Department of Computer Engineering 38

39 Array and String Lecture 6 Call by reference Instead of product() prod_sum() How can I get the function to give both product and sum? put * in front of variable name in prototype and function definition put & in front of variable names in function call Department of Computer Engineering 39 #include <stdio.h> void prod_sum(double x, double y, double *ptr1, double *ptr2); int main() double var1 = 3.0, var2 = 5.0; double prod, sum; prod_sum(var1, var2, &prod, &sum); printf("var1= %g\n" "var2= %g\n",var1, var2); printf("prod= %g\n" "sum= %g\n", prod, sum); /* function definition */ void prod_sum(double A, double B, double *rslt_prod, double *rslt_sum) *rslt_prod = A * B; *rslt_sum = A + B;

40 Array and String Lecture 6 Pointers and Arrays Recall that the value of an array name is also an address void main() int x[10]; ReOrder(x); // ReOrder(&x); void ReOrder(int *x) int i, j, t; for(i = 0; i < 9; i++) for(j = i + 1; i < 10; ++j) if(x[i] < x[j]) t = x[i]; x[i] = x[j]; x[j] = t; Department of Computer Engineering 40

41 Array and String Lecture 6 Organizing Multi-File Programs A large C program should be divided into multiple files // main.c #include <stdio.h> void Test() // int main() // return 0; // math.c double mathvar; double sin() double tempsin; // return tempsin; Department of Computer Engineering 41

42 Array and String Lecture 6 Identifiers and Scope Identifier The name of a variable, function, label, etc. int my_var1; /* a variable */ pow_table();/* a function */ start: /* a label */ Question: Does it make a difference where in a program an identifier is declared? YES! --> concept of scope Department of Computer Engineering 42

43 Array and String Lecture 6 Scope of Identifiers Scope of a declaration of an identifier The region of the program that the declaration is active (i.e., can access the variable, function, label, etc.) Five types of scope: Program (global scope) File Function prototype Function Block ("between the scope") Department of Computer Engineering 43

44 Scope of Identifiers - Program Scope Program (global) scope if declared outside of all functions "Visible" to all functions from point of declaration Visible to functions in other source files Use only when necessary and then very carefully!! If there exist a local variable and a global variable with the same name, the compiler will refer to the local variable #include <stdio.h> int a = 10; double product(double x, double y); int main() double var1 = 3.0, var2 = 5.0; double ans; ans = product(var1, var2); // /* function definition */ double product(double x, double y) double result; a = 20; result = x * y; return result; a = 10 a = 20 Department of Computer Engineering 44/77

45 An Example // File name: main.c #include <stdio.h> int a = 10; // File name: ExternFile.c extern int a = 10; /* function definition */ void TestExtern() // a = 90; // /* function definition */ double product(double x, double y) double result; // a = 70; return result; int main() a = 80; Department of Computer Engineering 45/77

46 Scope of Identifiers - File Scope File scope Keyword static Makes variable a visible only within this source file Use file scope to avoid naming conflict if multiple source files are used #include <stdio.h> static int a = 10; double product(double x, double y); int main() double var1 = 3.0, var2 = 5.0; double ans; ans = product(var1, var2); // /* function definition */ double product(double x, double y) double result; result = x * y; return result; Department of Computer Engineering 46/77

47 An Example // File name: main.c #include <stdio.h> static int a = 10; // File name: ExternFile.c extern int a = 10; /* function definition */ void TestExtern() // a = 90; // /* function definition */ double product(double x, double y) double result; // a = 70; return result; int main() a = 80; Department of Computer Engineering 47/77

48 Scope of Identifiers - Function Prototype Scope Function prototype scope Identifiers x and y are not visible outside the prototype Thus, names in the prototype do not have to match names in the function definition MUST match types, however! #include <stdio.h> double product(double x, double y); int main() int a = 10; double var1 = 3.0, var2 = 5.0; double ans; ans = product(var1, var2); printf("var1 = %.2f\n" "var2 = %.2f\n",var1,var2); printf("var1*var2 = %g\n", ans); /* function definition */ double product(double A, double B) double result; result = A * B; return result; Department of Computer Engineering 48/77

49 Scope of Identifiers - Function Scope Function scope Active from the beginning to the end of a function #include <stdio.h> int main() int a; // return 0; int FunctionScopeTest() int b; // return 0; Department of Computer Engineering 49/77

50 Scope of Identifiers - Block Scope Block (local) scope A block is a series of statements enclosed in braces The identifier scope is active from the point of declaration to the end of the block ( ) Nested blocks can both declare the same variable name and not interfere #include <stdio.h> double product(double x, double y); int main() int a = 10; double var1 = 3.0, var2 = 5.0; double ans; ans = product(var1, var2); // /* function definition */ double product(double x, double y) double result; // a = 60; Error result = x * y; return result; Department of Computer Engineering 50/77

51 An Example #include <stdio.h> int a = 10; int f1() int a; a = 70; int a; a = 100; return a; void main() a = 80; f1(); a =? a = 70 a = 100 a = 70 a = 10 a = 80 Department of Computer Engineering 51/77

52 Storage Classes Refers to the lifetime of a variable Local variables only exist within a function by default. When calling a function repeatedly, we might want to Start from scratch reinitialize the variables The storage class is auto Continue where we left off remember the last value The storage class is static Another two storage classes (seldomly used) register (ask to use hardware registers if available) extern (global variables are external) Department of Computer Engineering 52/77

53 Auto storage class Variables with automatic storage duration are created when the block in which they are declared is entered, exist when the block is active and destroyed when the block is exited. The keyword auto explicitly declares variables of automatic storage duration. It is rarely used because when we declare a local variable, by default it has class storage of type auto. int a, b; // is the same as auto int a, b; Department of Computer Engineering 53/77

54 Static storage class However the static keyword can be applied to a local variable so that the variable still exist even though the program has gone out of the function. As a result, whenever the program enters the function again, the value in the static variable still holds Department of Computer Engineering 54/77

55 Auto - Example #include <stdio.h> void auto_example(void); int main(void) int i; printf("auto example:\n"); auto_example( ); auto_example( ); auto_example( ); return(0); Auto example: Press any key to continue void auto_example(void) auto int num = 1; printf(" %d\n",num); num = num + 2; Department of Computer Engineering 55/77

56 Static - Example #include <stdio.h> void auto_example(void); int main(void) int i; printf("static example:\n"); static_example( ); static_example( ); static_example( ); return(0); void static_example(void) static int num = 1; Static example: Press any key to continue printf(" %d\n",num); num = num + 2; Department of Computer Engineering 56/77

57 Recursion Recursion is a technique that solves a problem by solving a smaller problem of the same type A recursive function is a function invoking itself, either directly or indirectly Recursion: A B C D A Concept of recursive function (generally): A recursive function is called to solve a problem The function only knows how to solve the simplest case of the problem. When the simplest case is given as an input, the function will immediately return with an answer However, if a more complex input is given, a recursive function will divide the problem into 2 (or more) pieces: a part that it knows how to solve and another part that it does not know how to solve if (stopping case) solve it else reduce the problem using recursion Department of Computer Engineering 57/77

58 Recursion Any problem that can be solved recursively can also be solved iteratively (using loop) Recursive functions are slow and takes a lot of memory space compared to iterative functions So why bother with recursion? There are 2 reasons: Recursion approach more naturally resembles the problem and therefore the program is easier to understand and debug Iterative solution might not be apparent Department of Computer Engineering 58/77

59 An Example: x y In this example, we want to calculate x to the power of y i.e. x y If we analyze the formula for x y, we could see that x y could be written as (x being multiplied to itself, y times) An example is 2 4, which can be written as 2 4 = 2 x 2 x 2 x 2 (in this case, x = 2, y = 4) 2 4 could also be rewritten as 2 4 = 2 1 x 2 3 where 2 1 = 2 (i.e the number itself) Therefore, we could divide the problem into two stage: Simplest case: when y = 1, the answer is x Recursive case, we need to solve for x * x (y-1) Department of Computer Engineering 59/77

60 Recursion solution of x y #include <stdio.h> double XpowerY(double, int); int main(void) double power, x; int y; printf("enter the value of x and y:\n"); scanf("%lf%d", &x, &y); power = XpowerY(x, y); printf("%.2f to the power of %d is %.2f\n\n", x, y, power); return(0); double XpowerY(double x, int y) if (y ==1) else return x; return x * XpowerY(x, y-1); Enter the value of x and y: to the power of 3 is 8.00 Press any key to continue Department of Computer Engineering 60/77

61 How C Maintains the Recursive Steps C keeps track of the values of variables by the stack data structure. Recall that stack is a data structure where the last item added is the first item processed There are two operations (push and pop) associated with stack a b c pop b c push d d b c Department of Computer Engineering 61/77 Sharif University of Technology

62 How C Maintains the Recursive Steps Each time a function is called, the execution state of the caller function (e.g., parameters, local variables, and memory address) are pushed onto the stack When the execution of the called function is finished, the execution can be restored by popping up the execution state from the stack Department of Computer Engineering 62/77

63 Recursive Steps of x y #include <stdio.h> double XpowerY(double, int); int main(void) double power, x; int y; printf("enter the value of x and y:\n"); scanf("%lf%d", &x, &y); power = XpowerY(x, y); printf("%.2f to the power of %d is %.2f\n\n", x, y, power); return(0); double XpowerY(double x, int y) if (y ==1) else return x; return x * XpowerY(x, y-1); 2 2 * 2 2 * 4 2 * 8 x = 2; y = 2; return x; x = 2; y = 2; x * XpowerY(2, 1) x = 2; y = 3; x * XpowerY(2, 2) x = 2; y = 4; x * XpowerY(2, 3) Department of Computer Engineering 63/77

64 Factorial Analysis: n!= n * (n-1) * (n-2) * (n-3) * (n-4) * 1 n! could be rewritten as n * (n-1)! Example: 5! = 5 * 4 * 3 * 2 * 1 = 5 * (4)!, where n = 5 Fact: 0! Or 1! is equal to 1 Therefore, we could divide this problem into two stages for n!: Simplest case: if (n <= 1), answer is 1 Recursive case: we need to solve for n * (n-1)! Department of Computer Engineering 64/77

65 Factorial #include <stdio.h> double fact(double); int main(void) double n, result; printf("please enter the value of n:"); scanf("%lf", &n); result = fact(n); printf(" %.f! = %.2f\n", n, result); return(0); double fact(double n) if (n <= 1) return 1; else return n * fact(n-1); int fact(int n) int factres = 1; while(n>1) factres = factres*n; n--; return (factres); Enter the value of n: 3 3! = 6.00 Press any key to continue Department of Computer Engineering 65/77

66 Reuse of factorial function Write a statement to compute y X! Z!*5 K! D! // Enter X, Z, K, D y = (fact(x) + fact(z) * 5) / (fact(k) - fact(d)); Department of Computer Engineering 66/77

67 Reuse of factorial function Write a select function that takes n and k and computes "n choose k" where n k ( n n! k)! k! int select(int n, int k) return fact(n) / (fact(n-k) * fact(k)); Department of Computer Engineering 67/77

68 Fibonacci Fibonacci Sequence 1, 1, 2, 3, 5, 8, 13, 21, 1 st 2 nd 3 rd 4 th 5 th 6 th 7 th 8 th Fib(1) = 1 defined base case Fib(2) = 1 defined base case Fib(3) = 2 = Fib(2) + Fib(1) Fib(7) = 13 = Fib(6) + Fib(5) Fib(n) = Fib(n-1) + Fib(n-2) Department of Computer Engineering 68/77

69 Fibonacci int Fib (int n) int temp = 1; /* handles base cases */ if (n > 2) temp = Fib(n-1) + Fib(n-2); return temp; /* Iterative Version */ int fibonacci(int k) int a,b,c,i; if (k <= 1) return 1; else a = 1; b = 1; i = 2; while (i <= k) c = a + b; a = b; b = c; i++; return(c); Department of Computer Engineering 69/77

70 Fibonacci x = 1; temp = 1; return temp; x = 1; temp = 1; return temp; x = 1; temp = 1; return temp; x = 1; temp = 1; return temp; x = 5; temp = 1; temp = Fib(2) 1 + Fib(1); 1; + Fib(1); return temp; int Fib (int x) /* handles base cases of */ /* Fib(1) and Fib(2) */ int temp = 1; if (x > 2) /* other cases */ temp = Fib(x-1) + Fib(x-2); return temp; x = 1; temp = 1; return temp; x = 4; temp = 1; temp = Fib(3) 2 + 1; Fib(2); + Fib(2); return temp; x = 5; temp = 1; temp = Fib(2) 1 + Fib(1); 1; + Fib(1); return temp; x = 5; temp = 1; temp = Fib(4) 3 + 2; Fib(3); + Fib(3); return temp; Department of Computer Engineering 70/77

71 Fibonacci int Fib (int n) /* handles base cases of */ /* Fib(1) and Fib(2) */ int temp = 1; if (n > 2) /* other cases */ temp = Fib(n-1) + Fib(n-2); return temp; fib(4) fib(5) 3 2 fib(3) 1 1 fib(3) fib(2) fib(2) fib(1) 1 fib(2) 1 fib(1) Department of Computer Engineering 71/77

72 Exercise Write a function to compute log b a log b a log log a b # include <math.h> double log_any_base(double a, double b) return log(a) / log(b); Department of Computer Engineering 72/77

73 Exercise #include <stdio.h> int function1(int x) x = 2; return(x+1); int function2(int *x) *x = 2; return(*x+1); int main() int x = 4, y1, y2; y1 = x + function1(++x); // y1? y2 = ++x + function2(&x); // y2? return 0; Department of Computer Engineering 73/77

74 Exercise What is the output of the following program #include <stdio.h> // function prototypes void function3() printf("in function 3\n"); function2(); int main() function1(); function3(); return 0; Department of Computer Engineering 74/77 void function2() printf("in function 2\n"); void function1() function2(); printf("in function 1\n"); In function 2 In function 1 In function 3 In function 2

75 Exercise Given radius and height of a cylinder. Write a function to compute the surface area A = 2*pi*r*(r*h) #define PI 3.14 double area(double radius, double height) return 2 * PI * radius * (radius+height); Department of Computer Engineering 75/77

76 Exercise Write a function to compute the median of 3 numbers x, y and z Possible order of numbers x<y<z -> median y x<z<y -> median z y<x<z -> median x y<z<x -> median z z<x<y -> median x z<y<x -> median y int median(int x, int y, int z) if (((x < y) && (y < z)) ((z < y) && (y < x))) return y; else if (((y < x) && (x < z)) ((z < x) && (x < y))) return x; return z; Department of Computer Engineering 76/77

77 Exercise Recursive Definitions of gcd A: Euclid s algorithm makes use of the fact that gcd(x,y ) = gcd(y, x mod y) gcd( x, y) x, if y 0 gcd( y, x mod y), int gcd (unsigned int x, unsigned int y) if (y == 0 ) return x; return gcd(y, x % y); otherwise Department of Computer Engineering 77/77

Chapter 8: Function. In this chapter, you will learn about

Chapter 8: Function. In this chapter, you will learn about Principles of Programming Chapter 8: Function In this chapter, you will learn about Introduction to function User-defined function Formal and Actual Parameters Parameter passing by value Parameter passing

More information

Functions. Systems Programming Concepts

Functions. Systems Programming Concepts Functions Systems Programming Concepts Functions Simple Function Example Function Prototype and Declaration Math Library Functions Function Definition Header Files Random Number Generator Call by Value

More information

Functions. Functions are everywhere in C. Pallab Dasgupta Professor, Dept. of Computer Sc & Engg INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR

Functions. Functions are everywhere in C. Pallab Dasgupta Professor, Dept. of Computer Sc & Engg INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR 1 Functions Functions are everywhere in C Pallab Dasgupta Professor, Dept. of Computer Sc & Engg INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR Introduction Function A self-contained program segment that carries

More information

Dr M Kasim A Jalil. Faculty of Mechanical Engineering UTM (source: Deitel Associates & Pearson)

Dr M Kasim A Jalil. Faculty of Mechanical Engineering UTM (source: Deitel Associates & Pearson) Lecture 9 Functions Dr M Kasim A Jalil Faculty of Mechanical Engineering UTM (source: Deitel Associates & Pearson) Objectives In this chapter, you will learn: To understand how to construct programs modularly

More information

C Functions. 5.2 Program Modules in C

C Functions. 5.2 Program Modules in C 1 5 C Functions 5.2 Program Modules in C 2 Functions Modules in C Programs combine user-defined functions with library functions - C standard library has a wide variety of functions Function calls Invoking

More information

Functions. Autumn Semester 2009 Programming and Data Structure 1. Courtsey: University of Pittsburgh-CSD-Khalifa

Functions. Autumn Semester 2009 Programming and Data Structure 1. Courtsey: University of Pittsburgh-CSD-Khalifa Functions Autumn Semester 2009 Programming and Data Structure 1 Courtsey: University of Pittsburgh-CSD-Khalifa Introduction Function A self-contained program segment that carries out some specific, well-defined

More information

Functions. Prof. Indranil Sen Gupta. Dept. of Computer Science & Engg. Indian Institute t of Technology Kharagpur. Introduction

Functions. Prof. Indranil Sen Gupta. Dept. of Computer Science & Engg. Indian Institute t of Technology Kharagpur. Introduction Functions Prof. Indranil Sen Gupta Dept. of Computer Science & Engg. Indian Institute t of Technology Kharagpur Programming and Data Structure 1 Function Introduction A self-contained program segment that

More information

BIL 104E Introduction to Scientific and Engineering Computing. Lecture 4

BIL 104E Introduction to Scientific and Engineering Computing. Lecture 4 BIL 104E Introduction to Scientific and Engineering Computing Lecture 4 Introduction Divide and Conquer Construct a program from smaller pieces or components These smaller pieces are called modules Functions

More information

Functions. Computer System and programming in C Prentice Hall, Inc. All rights reserved.

Functions. Computer System and programming in C Prentice Hall, Inc. All rights reserved. Functions In general, functions are blocks of code that perform a number of pre-defined commands to accomplish something productive. You can either use the built-in library functions or you can create

More information

Chapter 5 C Functions

Chapter 5 C Functions Chapter 5 C Functions Objectives of this chapter: To construct programs from small pieces called functions. Common math functions in math.h the C Standard Library. sin( ), cos( ), tan( ), atan( ), sqrt(

More information

Chapter 3 - Functions

Chapter 3 - Functions Chapter 3 - Functions 1 Outline 3.1 Introduction 3.2 Program Components in C++ 3.3 Math Library Functions 3.4 Functions 3.5 Function Definitions 3.6 Function Prototypes 3.7 Header Files 3.8 Random Number

More information

CSE123. Program Design and Modular Programming Functions 1-1

CSE123. Program Design and Modular Programming Functions 1-1 CSE123 Program Design and Modular Programming Functions 1-1 5.1 Introduction A function in C is a small sub-program performs a particular task, supports the concept of modular programming design techniques.

More information

Function. specific, well-defined task. whenever it is called or invoked. A function to add two numbers A function to find the largest of n numbers

Function. specific, well-defined task. whenever it is called or invoked. A function to add two numbers A function to find the largest of n numbers Functions 1 Function n A program segment that carries out some specific, well-defined task n Example A function to add two numbers A function to find the largest of n numbers n A function will carry out

More information

Functions. Angela Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan.

Functions. Angela Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan. Functions Angela Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan 2009 Fall Outline 5.1 Introduction 5.3 Math Library Functions 5.4 Functions 5.5

More information

Lecture 04 FUNCTIONS AND ARRAYS

Lecture 04 FUNCTIONS AND ARRAYS Lecture 04 FUNCTIONS AND ARRAYS 1 Motivations Divide hug tasks to blocks: divide programs up into sets of cooperating functions. Define new functions with function calls and parameter passing. Use functions

More information

Chapter 4 Functions By C.K. Liang

Chapter 4 Functions By C.K. Liang 1 Chapter 4 Functions By C.K. Liang What you should learn? 2 To construct programs modularly from small pieces called functions Math functions in C standard library Create new functions Pass information

More information

INTRODUCTION TO C++ FUNCTIONS. Dept. of Electronic Engineering, NCHU. Original slides are from

INTRODUCTION TO C++ FUNCTIONS. Dept. of Electronic Engineering, NCHU. Original slides are from INTRODUCTION TO C++ FUNCTIONS Original slides are from http://sites.google.com/site/progntut/ Dept. of Electronic Engineering, NCHU Outline 2 Functions: Program modules in C Function Definitions Function

More information

C Functions. CS 2060 Week 4. Prof. Jonathan Ventura

C Functions. CS 2060 Week 4. Prof. Jonathan Ventura CS 2060 Week 4 1 Modularizing Programs Modularizing programs in C Writing custom functions Header files 2 Function Call Stack The function call stack Stack frames 3 Pass-by-value Pass-by-value and pass-by-reference

More information

Function Call Stack and Activation Records

Function Call Stack and Activation Records 71 Function Call Stack and Activation Records To understand how C performs function calls, we first need to consider a data structure (i.e., collection of related data items) known as a stack. Students

More information

Programming Fundamentals for Engineers Functions. Muntaser Abulafi Yacoub Sabatin Omar Qaraeen. Modular programming.

Programming Fundamentals for Engineers Functions. Muntaser Abulafi Yacoub Sabatin Omar Qaraeen. Modular programming. Programming Fundamentals for Engineers - 0702113 7. Functions Muntaser Abulafi Yacoub Sabatin Omar Qaraeen 1 Modular programming Your program main() function Calls AnotherFunction1() Returns the results

More information

Function Example. Function Definition. C Programming. Syntax. A small program(subroutine) that performs a particular task. Modular programming design

Function Example. Function Definition. C Programming. Syntax. A small program(subroutine) that performs a particular task. Modular programming design What is a Function? C Programming Lecture 8-1 : Function (Basic) A small program(subroutine) that performs a particular task Input : parameter / argument Perform what? : function body Output t : return

More information

엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University COPYRIGHTS 2017 EOM, HYEONSANG ALL RIGHTS RESERVED

엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University COPYRIGHTS 2017 EOM, HYEONSANG ALL RIGHTS RESERVED 엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University COPYRIGHTS 2017 EOM, HYEONSANG ALL RIGHTS RESERVED Outline - Function Definitions - Function Prototypes - Data

More information

Functions in C C Programming and Software Tools

Functions in C C Programming and Software Tools Functions in C C Programming and Software Tools N.C. State Department of Computer Science Functions in C Functions are also called subroutines or procedures One part of a program calls (or invokes the

More information

Functions in C C Programming and Software Tools. N.C. State Department of Computer Science

Functions in C C Programming and Software Tools. N.C. State Department of Computer Science Functions in C C Programming and Software Tools N.C. State Department of Computer Science Functions in C Functions are also called subroutines or procedures One part of a program calls (or invokes the

More information

CS11001/CS11002 Programming and Data Structures (PDS) (Theory: 3-0-0)

CS11001/CS11002 Programming and Data Structures (PDS) (Theory: 3-0-0) CS11001/CS11002 Programming and Data Structures (PDS) (Theory: 3-0-0) Class Teacher: Pralay Mitra Department of Computer Science and Engineering Indian Institute of Technology Kharagpur An Example: Random

More information

Functions in C. Lecture Topics. Lecture materials. Homework. Machine problem. Announcements. ECE 190 Lecture 16 March 9, 2011

Functions in C. Lecture Topics. Lecture materials. Homework. Machine problem. Announcements. ECE 190 Lecture 16 March 9, 2011 Functions in C Lecture Topics Introduction to using functions in C Syntax Examples Memory allocation for variables Lecture materials Textbook 14.1-14.2, 12.5 Homework Machine problem MP3.2 due March 18,

More information

CSE 2421: Systems I Low-Level Programming and Computer Organization. Functions. Presentation C. Predefined Functions

CSE 2421: Systems I Low-Level Programming and Computer Organization. Functions. Presentation C. Predefined Functions CSE 2421: Systems I Low-Level Programming and Computer Organization Functions Read/Study: Reek Chapters 7 Gojko Babić 01-22-2018 Predefined Functions C comes with libraries of predefined functions E.g.:

More information

6-1 (Function). (Function) !*+!"#!, Function Description Example. natural logarithm of x (base e) rounds x to smallest integer not less than x

6-1 (Function). (Function) !*+!#!, Function Description Example. natural logarithm of x (base e) rounds x to smallest integer not less than x (Function) -1.1 Math Library Function!"#! $%&!'(#) preprocessor directive #include !*+!"#!, Function Description Example sqrt(x) square root of x sqrt(900.0) is 30.0 sqrt(9.0) is 3.0 exp(x) log(x)

More information

Lecture 3. Review. CS 141 Lecture 3 By Ziad Kobti -Control Structures Examples -Built-in functions. Conditions: Loops: if( ) / else switch

Lecture 3. Review. CS 141 Lecture 3 By Ziad Kobti -Control Structures Examples -Built-in functions. Conditions: Loops: if( ) / else switch Lecture 3 CS 141 Lecture 3 By Ziad Kobti -Control Structures Examples -Built-in functions Review Conditions: if( ) / else switch Loops: for( ) do...while( ) while( )... 1 Examples Display the first 10

More information

Lecture 9 - C Functions

Lecture 9 - C Functions ECET 264 C Programming Language with Applications Lecture 9 C Functions Paul I. Lin Professor of Electrical & Computer Engineering Technology http://www.etcs.ipfw.edu/~lin Lecture 9- Prof. Paul I. Lin

More information

Calling Prewritten Functions in C

Calling Prewritten Functions in C Calling Prewritten Functions in C We've already called two prewritten functions that are found in the C library stdio.h: printf, scanf. The function specifications for these two are complicated (they allow

More information

AN OVERVIEW OF C, PART 3. CSE 130: Introduction to Programming in C Stony Brook University

AN OVERVIEW OF C, PART 3. CSE 130: Introduction to Programming in C Stony Brook University AN OVERVIEW OF C, PART 3 CSE 130: Introduction to Programming in C Stony Brook University FANCIER OUTPUT FORMATTING Recall that you can insert a text field width value into a printf() format specifier:

More information

Unit 7. Functions. Need of User Defined Functions

Unit 7. Functions. Need of User Defined Functions Unit 7 Functions Functions are the building blocks where every program activity occurs. They are self contained program segments that carry out some specific, well defined task. Every C program must have

More information

Functions in C++ Problem-Solving Procedure With Modular Design C ++ Function Definition: a single

Functions in C++ Problem-Solving Procedure With Modular Design C ++ Function Definition: a single Functions in C++ Problem-Solving Procedure With Modular Design: Program development steps: Analyze the problem Develop a solution Code the solution Test/Debug the program C ++ Function Definition: A module

More information

Functions. (transfer of parameters, returned values, recursion, function pointers).

Functions. (transfer of parameters, returned values, recursion, function pointers). Functions (transfer of parameters, returned values, recursion, function pointers). A function is a named, independent section of C/C++ code that performs a specific task and optionally returns a value

More information

Fundamental of Programming (C)

Fundamental of Programming (C) Borrowed from lecturer notes by Omid Jafarinezhad Fundamental of Programming (C) Lecturer: Vahid Khodabakhshi Lecture 9 Pointer Department of Computer Engineering 1/46 Outline Defining and using Pointers

More information

Lecture 04 FUNCTIONS AND ARRAYS

Lecture 04 FUNCTIONS AND ARRAYS Lecture 04 FUNCTIONS AND ARRAYS 1 Motivations Divide hug tasks to blocks: divide programs up into sets of cooperating functions. Define new functions with function calls and parameter passing. Use functions

More information

Fundamentals of Programming & Procedural Programming

Fundamentals of Programming & Procedural Programming Universität Duisburg-Essen PRACTICAL TRAINING TO THE LECTURE Fundamentals of Programming & Procedural Programming Session Eight: Math Functions, Linked Lists, and Binary Trees Name: First Name: Tutor:

More information

BSM540 Basics of C Language

BSM540 Basics of C Language BSM540 Basics of C Language Chapter 9: Functions I Prof. Manar Mohaisen Department of EEC Engineering Review of the Precedent Lecture Introduce the switch and goto statements Introduce the arrays in C

More information

Functions. CS10001: Programming & Data Structures. Sudeshna Sarkar Professor, Dept. of Computer Sc. & Engg., Indian Institute of Technology Kharagpur

Functions. CS10001: Programming & Data Structures. Sudeshna Sarkar Professor, Dept. of Computer Sc. & Engg., Indian Institute of Technology Kharagpur Functions CS10001: Programming & Data Structures Sudeshna Sarkar Professor, Dept. of Computer Sc. & Engg., Indian Institute of Technology Kharagpur 1 Recursion A process by which a function calls itself

More information

Functions and Recursion

Functions and Recursion Functions and Recursion 1 Outline Introduction Program Components in C++ Math Library Functions Functions Function Definitions Function Prototypes Header Files Random Number Generation Example: A Game

More information

LAB 7 FUNCTION PART 2

LAB 7 FUNCTION PART 2 LAB 7 FUNCTION PART 2 School of Computer and Communication Engineering Universiti Malaysia Perlis 1 OBJECTIVES 1. To differentiate the file scope and block scope. 2. To write recursive function. 3. To

More information

Introduction to Programming

Introduction to Programming Introduction to Programming session 9 Instructor: Reza Entezari-Maleki Email: entezari@ce.sharif.edu 1 Fall 2010 These slides are created using Deitel s slides Sahrif University of Technology Outlines

More information

Chapter 3 - Functions

Chapter 3 - Functions Chapter 3 - Functions 1 3.1 Introduction 3.2 Program Components in C++ 3.3 Math Library Functions 3.4 Functions 3.5 Function Definitions 3.6 Function Prototypes 3.7 Header Files 3.8 Random Number Generation

More information

FUNCTIONS. Without return With return Without return With return. Example: function with arguments and with return value

FUNCTIONS. Without return With return Without return With return. Example: function with arguments and with return value FUNCTIONS Definition: A is a set of instructions under a name that carries out a specific task, assigned to it. CLASSIFICATION of s: 1. User defined s (UDF) 2. Library s USER DEFINED FUNCTIONS Without

More information

C Functions Pearson Education, Inc. All rights reserved.

C Functions Pearson Education, Inc. All rights reserved. 1 5 C Functions 2 Form ever follows function. Louis Henri Sullivan E pluribus unum. (One composed of many.) Virgil O! call back yesterday, bid time return. William Shakespeare Call me Ishmael. Herman Melville

More information

Chapter 3 - Functions. Chapter 3 - Functions. 3.1 Introduction. 3.2 Program Components in C++

Chapter 3 - Functions. Chapter 3 - Functions. 3.1 Introduction. 3.2 Program Components in C++ Chapter 3 - Functions 1 Chapter 3 - Functions 2 3.1 Introduction 3.2 Program Components in C++ 3.3 Math Library Functions 3. Functions 3.5 Function Definitions 3.6 Function Prototypes 3. Header Files 3.8

More information

C++ PROGRAMMING SKILLS Part 3 User-Defined Functions

C++ PROGRAMMING SKILLS Part 3 User-Defined Functions C++ PROGRAMMING SKILLS Part 3 User-Defined Functions Introduction Function Definition Void function Global Vs Local variables Random Number Generator Recursion Function Overloading Sample Code 1 Functions

More information

Computer Programming 5th Week loops (do-while, for), Arrays, array operations, C libraries

Computer Programming 5th Week loops (do-while, for), Arrays, array operations, C libraries Computer Programming 5th Week loops (do-while, for), Arrays, array operations, C libraries Hazırlayan Asst. Prof. Dr. Tansu Filik Computer Programming Previously on Bil 200 Low-Level I/O getchar, putchar,

More information

CHAPTER 4 FUNCTIONS. 4.1 Introduction

CHAPTER 4 FUNCTIONS. 4.1 Introduction CHAPTER 4 FUNCTIONS 4.1 Introduction Functions are the building blocks of C++ programs. Functions are also the executable segments in a program. The starting point for the execution of a program is main

More information

Unit 3 Functions. 1 What is user defined function? Explain with example. Define the syntax of function in C.

Unit 3 Functions. 1 What is user defined function? Explain with example. Define the syntax of function in C. 1 What is user defined function? Explain with example. Define the syntax of function in C. A function is a block of code that performs a specific task. The functions which are created by programmer are

More information

C Programs: Simple Statements and Expressions

C Programs: Simple Statements and Expressions .. Cal Poly CPE 101: Fundamentals of Computer Science I Alexander Dekhtyar.. C Programs: Simple Statements and Expressions C Program Structure A C program that consists of only one function has the following

More information

UNIT III (PART-II) & UNIT IV(PART-I)

UNIT III (PART-II) & UNIT IV(PART-I) UNIT III (PART-II) & UNIT IV(PART-I) Function: it is defined as self contained block of code to perform a task. Functions can be categorized to system-defined functions and user-defined functions. System

More information

Functions. Functions. Identify Repeated Code. Identify Repeated Code. Identify Similar Code. Use Parameters to Customize 2/25/14

Functions. Functions. Identify Repeated Code. Identify Repeated Code. Identify Similar Code. Use Parameters to Customize 2/25/14 Functions Functions Based on slides from K. N. King and Dianna Xu Bryn Mawr College CS246 Programming Paradigm Function: Unit of operation o A series of statements grouped together with a given name Must

More information

Programming in C. main. Level 2. Level 2 Level 2. Level 3 Level 3

Programming in C. main. Level 2. Level 2 Level 2. Level 3 Level 3 Programming in C main Level 2 Level 2 Level 2 Level 3 Level 3 1 Programmer-Defined Functions Modularize with building blocks of programs Divide and Conquer Construct a program from smaller pieces or components

More information

Introduction to Computers II Lecture 4. Dr Ali Ziya Alkar Dr Mehmet Demirer

Introduction to Computers II Lecture 4. Dr Ali Ziya Alkar Dr Mehmet Demirer Introduction to Computers II Lecture 4 Dr Ali Ziya Alkar Dr Mehmet Demirer 1 Contents: Utilizing the existing information Top-down design Start with the broadest statement of the problem Works down to

More information

Functions. Chapter 5

Functions. Chapter 5 Functions Chapter 5 Function Definition type function_name ( parameter list ) declarations statements For example int factorial(int n) int i, product = 1; for (i = 2; I

More information

Functions and Recursion

Functions and Recursion Functions and Recursion CSE 130: Introduction to Programming in C Stony Brook University Software Reuse Laziness is a virtue among programmers Often, a given task must be performed multiple times Instead

More information

Fundamentals of Programming Session 13

Fundamentals of Programming Session 13 Fundamentals of Programming Session 13 Instructor: Reza Entezari-Maleki Email: entezari@ce.sharif.edu 1 Fall 2014 These slides have been created using Deitel s slides Sharif University of Technology Outlines

More information

Methods: A Deeper Look

Methods: A Deeper Look 1 2 7 Methods: A Deeper Look OBJECTIVES In this chapter you will learn: How static methods and variables are associated with an entire class rather than specific instances of the class. How to use random-number

More information

CSE101-lec#12. Designing Structured Programs Introduction to Functions. Created By: Amanpreet Kaur & Sanjeev Kumar SME (CSE) LPU

CSE101-lec#12. Designing Structured Programs Introduction to Functions. Created By: Amanpreet Kaur & Sanjeev Kumar SME (CSE) LPU CSE101-lec#12 Designing Structured Programs Introduction to Functions Created By: Amanpreet Kaur & Sanjeev Kumar SME (CSE) LPU Outline Designing structured programs in C: Counter-controlled repetition

More information

& Technology. G) Functions. void. Argument2, Example: (Argument1, Syllabus for 1. 1 What. has a unique. 2) Function name. passed to.

& Technology. G) Functions. void. Argument2, Example: (Argument1, Syllabus for 1. 1 What. has a unique. 2) Function name. passed to. Computer Programming and Utilization (CPU) 110003 G) Functions 1 What is user defined function? Explain with example. Define the syntax of function in C. A function is a block of code that performs a specific

More information

C++, How to Program. Spring 2016 CISC1600 Yanjun Li 1

C++, How to Program. Spring 2016 CISC1600 Yanjun Li 1 Chapter 6 Function C++, How to Program Deitel & Deitel Spring 2016 CISC1600 Yanjun Li 1 Function A function is a collection of statements that performs a specific task - a single, well-defined task. Divide

More information

Fundamentals of Programming & Procedural Programming

Fundamentals of Programming & Procedural Programming Universität Duisburg-Essen PRACTICAL TRAINING TO THE LECTURE Fundamentals of Programming & Procedural Programming Session Four: Functions: Built-in, Parameters and Arguments, Fruitful and Void Functions

More information

Introduction to Functions in C. Dr. Ahmed Telba King Saud University College of Engineering Electrical Engineering Department

Introduction to Functions in C. Dr. Ahmed Telba King Saud University College of Engineering Electrical Engineering Department Introduction to Functions in C Dr. Ahmed Telba King Saud University College of Engineering Electrical Engineering Department Function definition For example Pythagoras(x,y,z) double x,y,z; { double d;

More information

UNIT 3 FUNCTIONS AND ARRAYS

UNIT 3 FUNCTIONS AND ARRAYS UNIT 3 FUNCTIONS AND ARRAYS Functions Function definitions and Prototypes Calling Functions Accessing functions Passing arguments to a function - Storage Classes Scope rules Arrays Defining an array processing

More information

Functions. Introduction :

Functions. Introduction : Functions Introduction : To develop a large program effectively, it is divided into smaller pieces or modules called as functions. A function is defined by one or more statements to perform a task. In

More information

Subject: Fundamental of Computer Programming 2068

Subject: Fundamental of Computer Programming 2068 Subject: Fundamental of Computer Programming 2068 1 Write an algorithm and flowchart to determine whether a given integer is odd or even and explain it. Algorithm Step 1: Start Step 2: Read a Step 3: Find

More information

C Language Part 2 Digital Computer Concept and Practice Copyright 2012 by Jaejin Lee

C Language Part 2 Digital Computer Concept and Practice Copyright 2012 by Jaejin Lee C Language Part 2 (Minor modifications by the instructor) 1 Scope Rules A variable declared inside a function is a local variable Each local variable in a function comes into existence when the function

More information

To declare an array in C, a programmer specifies the type of the elements and the number of elements required by an array as follows

To declare an array in C, a programmer specifies the type of the elements and the number of elements required by an array as follows Unti 4: C Arrays Arrays a kind of data structure that can store a fixed-size sequential collection of elements of the same type An array is used to store a collection of data, but it is often more useful

More information

CSE 230 Intermediate Programming in C and C++ Functions

CSE 230 Intermediate Programming in C and C++ Functions CSE 230 Intermediate Programming in C and C++ Functions Fall 2017 Stony Brook University Instructor: Shebuti Rayana shebuti.rayana@stonybrook.edu http://www3.cs.stonybrook.edu/~cse230/ Concept of Functions

More information

Procedural programming with C

Procedural programming with C Procedural programming with C Dr. C. Constantinides Department of Computer Science and Software Engineering Concordia University Montreal, Canada August 11, 2016 1 / 77 Functions Similarly to its mathematical

More information

More Flow Control Functions in C++ CS 16: Solving Problems with Computers I Lecture #4

More Flow Control Functions in C++ CS 16: Solving Problems with Computers I Lecture #4 More Flow Control Functions in C++ CS 16: Solving Problems with Computers I Lecture #4 Ziad Matni Dept. of Computer Science, UCSB Administrative CHANGED T.A. OFFICE/OPEN LAB HOURS! Thursday, 10 AM 12 PM

More information

Computer Science & Engineering 150A Problem Solving Using Computers

Computer Science & Engineering 150A Problem Solving Using Computers Computer Science & Engineering 150A Problem Solving Using Computers Lecture 03 - Stephen Scott (Adapted from Christopher M. Bourke) 1 / 41 Fall 2009 Chapter 3 3.1 Building Programs from Existing Information

More information

Methods (Deitel chapter 6)

Methods (Deitel chapter 6) Methods (Deitel chapter 6) 1 Plan 2 Introduction Program Modules in Java Math-Class Methods Method Declarations Argument Promotion Java API Packages Random-Number Generation Scope of Declarations Methods

More information

CS113: Lecture 4. Topics: Functions. Function Activation Records

CS113: Lecture 4. Topics: Functions. Function Activation Records CS113: Lecture 4 Topics: Functions Function Activation Records 1 Why functions? Functions add no expressive power to the C language in a formal sense. Why have them? Breaking tasks into smaller ones make

More information

Programming for Engineers Functions

Programming for Engineers Functions Programming for Engineers Functions ICEN 200 Spring 2018 Prof. Dola Saha 1 Introduction Real world problems are larger, more complex Top down approach Modularize divide and control Easier to track smaller

More information

Computer Science & Engineering 150A Problem Solving Using Computers. Chapter 3. Existing Information. Notes. Notes. Notes. Lecture 03 - Functions

Computer Science & Engineering 150A Problem Solving Using Computers. Chapter 3. Existing Information. Notes. Notes. Notes. Lecture 03 - Functions Computer Science & Engineering 150A Problem Solving Using Computers Lecture 03 - Functions Stephen Scott (Adapted from Christopher M. Bourke) Fall 2009 1 / 1 cbourke@cse.unl.edu Chapter 3 3.1 Building

More information

Fundamentals of Programming Session 12

Fundamentals of Programming Session 12 Fundamentals of Programming Session 12 Instructor: Reza Entezari-Maleki Email: entezari@ce.sharif.edu 1 Fall 2014 These slides have been created using Deitel s slides Sharif University of Technology Outlines

More information

ECET 264 C Programming Language with Applications

ECET 264 C Programming Language with Applications ECET 264 C Programming Language with Applications Lecture 10 C Standard Library Functions Paul I. Lin Professor of Electrical & Computer Engineering Technology http://www.etcs.ipfw.edu/~lin Lecture 10

More information

Methods (Deitel chapter 6)

Methods (Deitel chapter 6) 1 Plan 2 Methods (Deitel chapter ) Introduction Program Modules in Java Math-Class Methods Method Declarations Argument Promotion Java API Packages Random-Number Generation Scope of Declarations Methods

More information

Fundamental of Programming (C)

Fundamental of Programming (C) Borrowed from lecturer notes by Omid Jafarinezhad Fundamental of Programming (C) Lecturer: Vahid Khodabakhshi Lecture 3 Constants, Variables, Data Types, And Operations Department of Computer Engineering

More information

Technical Questions. Q 1) What are the key features in C programming language?

Technical Questions. Q 1) What are the key features in C programming language? Technical Questions Q 1) What are the key features in C programming language? Portability Platform independent language. Modularity Possibility to break down large programs into small modules. Flexibility

More information

EC 413 Computer Organization

EC 413 Computer Organization EC 413 Computer Organization C/C++ Language Review Prof. Michel A. Kinsy Programming Languages There are many programming languages available: Pascal, C, C++, Java, Ada, Perl and Python All of these languages

More information

Government Polytechnic Muzaffarpur.

Government Polytechnic Muzaffarpur. Government Polytechnic Muzaffarpur. Name of the Lab: COMPUTER PROGRAMMING LAB (MECH. ENGG. GROUP) Subject Code: 1625408 Experiment: 1 Aim: Programming exercise on executing a C program. If you are looking

More information

Assoc. Prof. Dr. Tansu FİLİK

Assoc. Prof. Dr. Tansu FİLİK Assoc. Prof. Dr. Tansu FİLİK Computer Programming Previously on Bil 200 Midterm Exam - 1 Midterm Exam - 1 126 students Curve: 49,78 Computer Programming Arrays Arrays List of variables: [ ] Computer Programming

More information

Introduction to C Language

Introduction to C Language Introduction to C Language Instructor: Professor I. Charles Ume ME 6405 Introduction to Mechatronics Fall 2006 Instructor: Professor Charles Ume Introduction to C Language History of C Language In 1972,

More information

Chapter 3. Computer Science & Engineering 155E Computer Science I: Systems Engineering Focus. Existing Information.

Chapter 3. Computer Science & Engineering 155E Computer Science I: Systems Engineering Focus. Existing Information. Chapter 3 Computer Science & Engineering 155E Computer Science I: Systems Engineering Focus Lecture 03 - Introduction To Functions Christopher M. Bourke cbourke@cse.unl.edu 3.1 Building Programs from Existing

More information

C Programming Lecture V

C Programming Lecture V C Programming Lecture V Instructor Özgür ZEYDAN http://cevre.beun.edu.tr/ Modular Programming A function in C is a small sub-program that performs a particular task, and supports the concept of modular

More information

from Appendix B: Some C Essentials

from Appendix B: Some C Essentials from Appendix B: Some C Essentials tw rev. 22.9.16 If you use or reference these slides or the associated textbook, please cite the original authors work as follows: Toulson, R. & Wilmshurst, T. (2016).

More information

MODULE 3: Arrays, Functions and Strings

MODULE 3: Arrays, Functions and Strings MODULE 3: Arrays, Functions and Strings Contents covered in this module I. Using an Array II. Functions in C III. Argument Passing IV. Functions and Program Structure, locations of functions V. Function

More information

Programming & Data Structure Laboratory. Day 2, July 24, 2014

Programming & Data Structure Laboratory. Day 2, July 24, 2014 Programming & Data Structure Laboratory Day 2, July 24, 2014 Loops Pre and post test loops for while do-while switch-case Pre-test loop and post-test loop Condition checking True Loop Body False Loop Body

More information

Bil 104 Intiroduction To Scientific And Engineering Computing. Lecture 5. Playing with Data Modifiers and Math Functions Getting Controls

Bil 104 Intiroduction To Scientific And Engineering Computing. Lecture 5. Playing with Data Modifiers and Math Functions Getting Controls Readin from and Writint to Standart I/O BIL104E: Introduction to Scientific and Engineering Computing Lecture 5 Playing with Data Modifiers and Math Functions Getting Controls Pointers What Is a Pointer?

More information

Computer Programming 6th Week Functions (Function definition, function calls),

Computer Programming 6th Week Functions (Function definition, function calls), Computer Programming 6th Week Functions (Function definition, function calls), Hazırlayan Asst. Prof. Dr. Tansu Filik Computer Programming Previously on Bil-200 loops (do-while, for), Arrays, array operations,

More information

Lesson #3. Variables, Operators, and Expressions. 3. Variables, Operators and Expressions - Copyright Denis Hamelin - Ryerson University

Lesson #3. Variables, Operators, and Expressions. 3. Variables, Operators and Expressions - Copyright Denis Hamelin - Ryerson University Lesson #3 Variables, Operators, and Expressions Variables We already know the three main types of variables in C: int, char, and double. There is also the float type which is similar to double with only

More information

Why Pointers. Pointers. Pointer Declaration. Two Pointer Operators. What Are Pointers? Memory address POINTERVariable Contents ...

Why Pointers. Pointers. Pointer Declaration. Two Pointer Operators. What Are Pointers? Memory address POINTERVariable Contents ... Why Pointers Pointers They provide the means by which functions can modify arguments in the calling function. They support dynamic memory allocation. They provide support for dynamic data structures, such

More information

15 FUNCTIONS IN C 15.1 INTRODUCTION

15 FUNCTIONS IN C 15.1 INTRODUCTION 15 FUNCTIONS IN C 15.1 INTRODUCTION In the earlier lessons we have already seen that C supports the use of library functions, which are used to carry out a number of commonly used operations or calculations.

More information

CS240: Programming in C

CS240: Programming in C CS240: Programming in C Lecture 5: Functions. Scope of variables. Program structure. Cristina Nita-Rotaru Lecture 5/ Fall 2013 1 Functions: Explicit declaration Declaration, definition, use, order matters.

More information

MA 511: Computer Programming Lecture 2: Partha Sarathi Mandal

MA 511: Computer Programming Lecture 2: Partha Sarathi Mandal MA 511: Computer Programming Lecture 2: http://www.iitg.ernet.in/psm/indexing_ma511/y10/index.html Partha Sarathi Mandal psm@iitg.ernet.ac.in Dept. of Mathematics, IIT Guwahati Semester 1, 2010-11 Largest

More information

A Fast Review of C Essentials Part II

A Fast Review of C Essentials Part II A Fast Review of C Essentials Part II Structural Programming by Z. Cihan TAYSI Outline Fixed vs. Automatic duration Scope Global variables The register specifier Storage classes Dynamic memory allocation

More information