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

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

Computer Programming: 7th Week Functions, Recursive Functions, Introduction to Pointers

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

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

C Functions. 5.2 Program Modules in C

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

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

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

Functions. Systems Programming Concepts

CSE123. Program Design and Modular Programming Functions 1-1

today cs3157-fall2002-sklar-lect05 1

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

ECET 264 C Programming Language with Applications

Chapter 4 Functions By C.K. Liang

Chapter 5 C Functions

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

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

Main Program. C Programming Notes. #include <stdio.h> main() { printf( Hello ); } Comments: /* comment */ //comment. Dr. Karne Towson University

cs3157: another C lecture (mon-21-feb-2005) C pre-processor (3).

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

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

C Programs: Simple Statements and Expressions

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

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

CS3157: Advanced Programming. Outline

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

Computer Programming 3 th Week Variables, constant, and expressions

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

Fundamental Data Types. CSE 130: Introduction to Programming in C Stony Brook University

Fundamentals of Programming & Procedural Programming

Introduction to C Language

Computer Programming: 8th Week Pointers

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

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

Multiple Choice Questions ( 1 mark)

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

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

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

C Tutorial: Part 1. Dr. Charalampos C. Tsimenidis. Newcastle University School of Electrical and Electronic Engineering.

OBJECTIVE QUESTIONS: Choose the correct alternative:

LAB 7 FUNCTION PART 2

1001ICT Introduction To Programming Lecture Notes

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

C Functions Pearson Education, Inc. All rights reserved.

from Appendix B: Some C Essentials

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

C Programming Multiple. Choice

Fundamentals of Programming & Procedural Programming

PESIT Bangalore South Campus Hosur road, 1km before Electronic City, Bengaluru -100 Department of Basic Science and Humanities

C Programming Language

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

C++ PROGRAMMING SKILLS Part 3 User-Defined Functions

Pointers and scanf() Steven R. Bagley

ALGORITHM 2-1 Solution for Exercise 4

A function is a named group of statements developed to solve a sub-problem and returns a value to other functions when it is called.

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

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

Programming in C. Part 1: Introduction

Functions in C C Programming and Software Tools

C introduction: part 1

Chapter 3 - Functions

Government Polytechnic Muzaffarpur.

COP 3223 Introduction to Programming with C - Study Union - Fall 2017

Dynamic memory allocation

Lecture 04 FUNCTIONS AND ARRAYS

BSM540 Basics of C Language

Introduction to Programming

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

UNIT-I Input/ Output functions and other library functions

School of Computer Science Introduction to Algorithms and Programming Winter Midterm Examination # 1 Wednesday, February 11, 2015

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

Programming and Data Structure

Visual Studio. Visual Studio is an extremely complex interactive development environment capable of handling many languages and tools.

BSM540 Basics of C Language

Fundamental of Programming (C)

C Program Structures

Procedural Programming & Fundamentals of Programming

Functions. Chapter 5

MODULE 3: Arrays, Functions and Strings

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

Basic memory model Using functions Writing functions. Basics Prototypes Parameters Return types Functions and memory Names and namespaces

2. Numbers In, Numbers Out

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

File IO and command line input CSE 2451

Structured Programming. Functions and Structured Programming. Functions. Variables

C Review. SWE2004: Principles in Programming Spring 2014 Euiseong Seo

Subject: Fundamental of Computer Programming 2068

Integer Representation. Variables. Real Representation. Integer Overflow/Underflow

Fundamentals of Computer Programming Using C

Standard Library Functions Outline

C: How to Program. Week /Apr/23

CpSc 1111 Lab 6 Conditional Statements, Loops, the Math Library, and Random Numbers What s the Point?

COP 3223 Introduction to Programming with C - Study Union - Fall 2017

Chapter 1 Getting Started Structured Programming 1

CS16 Exam #1 7/17/ Minutes 100 Points total

Function a block of statements grouped together, to perform some specific task

SWEN-250 Personal SE. Introduction to C

LESSON 5 FUNDAMENTAL DATA TYPES. char short int long unsigned char unsigned short unsigned unsigned long

CS102: Standard I/O. %<flag(s)><width><precision><size>conversion-code

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

Transcription:

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, C libraries

Computer Programming C Libraries C Liabraries "math.h", "stdlib.h", "string.h"

Computer Programming C Libraries The main C language only consists of expressions and grammar rules. C, itself, has NO built in function! Most C compilers come with the standard libraries containing several useful functions. In order to be able to use these functions, you must use #include directive to include the associated library containing the useful function.

Computer Programming C Libraries Function Libraries <stdio.h> - printf(), fprintf(), scanf(), fscanf(), fopen(), putchar(), getchar(),... <math.h> - pow(), sqrt(), fabs()... <ctype.h> - toupper(), tolower(), isalpha(), isdigit(),... <stdlib.h> - rand(), srand(), exit(),...

Introduction to Programming Languages C Libraries Function Libraries : math.h Many mathematical function (prototypes) exist here. fabs (x) : absolute value of float x sqrt (x) : square root of x exp (x) : e to the power x (e = 2.71828) log (x) : ln x log10 (x) : base-10 logarithm pow(x, y) : x to the power y sin (x) : sine (radians) cos (x) : cosine (radians) tan (x) : tangent fmod (a, b) : remainder of a/b ceil (x) : least integer >= x floor (x) : greatest integer <= x

Introduction to Programming Languages C Libraries Function Libraries : stdlib.h exit(val) : used for terminating program. if (fp == NULL) exit(1); /* if file cannot open, quit*/ rand(void) : generates a random number for(i=0; i < 100; ++i) /* 100 random numbers*/ printf("%d ", rand()); srand(value) : seed for the randomizer srand(100); /* starting point of random sequence*/

Introduction to Programming Languages C Libraries Function Libraries : time.h time(null): Numbe of seconds passed since 01/01/1970. int secs; secs = time(null);

Introduction to Programming Languages C Libraries Example: Approximate pi value Pi is a very commonly used constant in mathematical expressions. This number has infinite decimal points. Special applications require as many of these decimals as possible. Simple applications may be OK with 22/7. In the following example, we will see how near to pi the value 22/7 is. In C, asin(1) is approximately equal to pi.

Approximate value of pi #include <stdio.h> #include <math.h> int main(void) double pi, yak, hata; asin, is the arc-sine function. pi = 2 * asin(1); /* realistic pi value*/ yak = (double) 22 / 7; /* approximate pi */ hata = fabs(yak pi) / pi; /* find error */ printf("pi = %.15f\n", pi); /* write result */ printf("yaklaşık = %.15f\n", yak); printf("hata = %.5f", hata * 100); return 0;

pi = 3.141592653589793 yaklaşık = 3.142857142857143 hata = 0.04025 Press any key to continue

time(null) Gives number of seconds since 01/01/1970 At 13:40 on 17/11/2015, its value was. zaman: 1447760273 #include<stdio.h> #include<time.h> void main() int t; t = time(null); printf("zaman: %d \n", t);

time(null) Before using you should write: #include <time.h> Usage: int t; t = time(null); Since each time instant is different, it is a good randomization seed.

Clock: tik-tak #include <stdio.h> #include <time.h> void main(void) int i, t; for(i=0; i <= 10; ++i) /* just for 10 sec */ t = time(null) + 1; /* t next sec */ while (time(null) < t); /* wait */ printf("tik\n"); /* write tik */ t = time(null) + 1; /* wait 1 sac */ while(time(null) < t); /* wait */ printf("tak\n"); /* write tak */

Introduction to Programming Languages Functions Functions The modules that are written by the programmer

Introduction to Programming Languages Functions Function Calls Calling a function means returning the value of a named list of commands that do a specific task. We may call functions that we write ourselves. We may call functions that already exist in the standard C library. Ex: printf, scanf, sqrt

Introduction to Programming Languages Functions Example Write a program which obtains and prints out the square-root of an entered number. #include <stdio.h> #include <math.h> /* Ekrandan girilen bir sayının karekökünü yazar. */ int main() float x, sonuc; printf("bir sayi giriniz"); scanf("%f", &x); sonuc = sqrt(x); printf("sonuc = %f", sonuc); return 0;

Introduction to Programming Languages Functions Until now, we wrote our program using a single function: main(). The sytax was: void main ( ) /* definitions */ /* expressions */ The term void indicates that this function returns NOTHING.

Introduction to Programming Languages Functions The () parantheses indicate that main is a function. Inside these parantheses, you send parameters to the function. For this particular case, we do not send anything to the function, so the parantheses are empty. Normally, functions require a list of parameters to be sent to them for processing and generating a result. That result may be returned to the function calling place.

Introduction to Programming Languages Functions A function can be written is three steps: 1. Function prototype declaration 2. The function itself (declaration + commands inside) 3. The expression that calls the function.

Introduction to Programming Languages Functions 1. Function prototypes Compilers trace the program from top to bottom. If you write a program which tries to use your functions, the compiler needs to know how the function is called. The prototypes are listed at the top to show the parametric interface of functions. void, char, int, float, double semicolon

Introduction to Programming Languages Functions 1. Function prototypes: Parameters Parameter list is a list of types that will enter to the function. float toplam(int a,int b,int c) ;

Introduction to Programming Languages Functions 2. Function definition In the real declaration of function, do not put ; at the end of first line. float toplam(int a,int b, int c) Here, the function toplam takes three variables: a, b and c. The return type is float. a, b and c values are sent by the place where the function is called.

Introduction to Programming Languages Functions 2. Function definition Function definition consists of a declaration line similar to the prototype, followed by a list of commands bounded by curly parantheses: float toplam( int a, int b, int c) float t; t = a + b + c ; return t; Note: The function returns a value using the return keyword. If the return type is void, you do not need to use a return line.

Introduction to Programming Languages Functions 2. Function definition float toplam( int a, int b, int c) float t; t = a + b + c ; return t; The variables a, b and c are valid only inside the function toplam. The variable t is also valid only inside the function, and its memory location is freed when the function finished.

Introduction to Programming Languages Functions 3. Function calls While calling a function, it must be compatible with the prototype and the return type. The sent parameters must also be compatible with the types. You may send proper variables, expressions, or values to a function. For this case: deger = toplam( i, j, k ) ; or deger = toplam( 5, x, 2.7 ) ;

Introduction to Programming Languages Functions 3. Function calls Inside the main() function, the function toplam() is called. In that case, the parameter values are copied into the parameter list variables of the function.

Introduction to Programming Languages Functions 3. Function calls main() data memory i 12 j 25 copied copied toplam() data memory a 12 25 b 45 k copied c 45

#include<stdio.h> void func1(void); int func2(int n, char ch); void main(void) int i=1,j=2; char ch= 0 ; printf( %d %d\n,i,j); func1(); j=func2(i,ch); printf( %d %d\n,i,j); void func1(void) printf( selam!\n );... FUNCTIONS- review Prototype declarations. Before using in main or other functions, declare their names like this. Their bodies will be written later. Calling a void-type function. Result is not assigned to anything. There is no input (void). Function generates an int type output. Therefore, its output can be assigned to some variable. Inputs are an int and a char. One of the functions whose prototype was declared. It is fully defined here. The I/O style of this and its prototype are compatible.

... int func2(int x, char y) int z; printf( Basta: x=%d, y=%c\n,x,y); z=x*y; printf( Simdi: z=%d\n,z); return z; Since function generates an int......an int variable is declared inside......and a value is assigned to it......and variable is returned (function value produced). /* As a result, this function adopts a value at the place where it is called. */

Introduction to Programming Languages Functions Prototypes are necessary if you plant to write functions at the end of the program. In this way, you can safely use functions within functions. If you write functions before main, or before other functions which call them, you do not need to use prototypes. In this case, if a function (a) is used in function (b), then (a) must be written on top of (b).

Introduction to Programming Languages Functions General function syntax

void face(void) printf( :-) ); void next_line(void) printf( \n ); void faces(int n) if(i<=0) return; else for(i=1;i<=n;i++) face(); next_line(); void main(void) faces(3); faces(2); faces(1); :-):-):-) :-):-) :-)

Introduction to Programming Languages Functions Exercise: function factorial() Write a function to evaluate the factorial of a number. For parameters less than zero, the return value will be 0. For zero and one, the return value is 1, for larger numbers, use a loop to evaluate. In the main function, write a loop to evaluate factorials of numbers from 0 to 10, and print on the screen. Do not forget to write the prototype.

Introduction to Programming Languages Functions Exercise: factorial program #include <stdio.h> int factorial( int x); for (i = 0 ; i < 10 ; i++ ) printf("%d! = %d\n", i, factorial(i)); void main() int i;

Introduction to Programming Languages Functions Exercise: factorial program int factorial ( int x ) int f = 1, k; for ( k = 2 ; k <= x ; k++ ) f *= k ; return f ; if ( x < 0 ) return 0; else if ( x==0 x==1 ) return 1; /* Return 1 for 0 or 1 */

Introduction to Programming Languages Functions Exercise: Write a function which takes two parameters and returns the factorial of the difference. Function must start as: int factorial_diff(int a, int b) This function may call the function factorial() which was previously implemented. Do not forget to write the prototypes.

Introduction to Programming Languages Functions Class Exercise: Main Program #include <...> printf("fark= %d\n", factorial_diff(a,b)); /* prototype */ int factorial_diff(int a, int b); void main() int a,b; printf("farkın alinacagi sayilari girin: "); scanf("%d %d", &a, &b);

Introduction to Programming Languages Functions - Phylosophy For early programming languages, procedural structure was a great improvement... Instead of a single big and nasty program; Intelligible and easily written blocks are preferable. Then, which parts should be made a function? How do we decide on the structure? How do functions communicate with each other and with main? There must be an interface standard.

Introduction to Programming Languages Recursion Some mathematical problems and graph theoretical questions are inherently recursive : n! = n * (n-1)!... (n-1)! =(n-1) * (n-2)! Fibonacci series: 0, 1, 1, 2, 3, 5, 8... fib( n ) = fib( n - 1 ) + fib( n 2 ) In this case, the function must call itself! (n-2)! = (n-2)*(n-3)!

long fibonacci( long n ) if (n == 0 n == 1) /* en alt */ return n; else return fibonacci( n - 1) + fibonacci( n 2 ); f( 3 ) return f( 2 ) + f( 1 ) return f( 1 ) + f( 0 ) return 1 return 1 return 0

long fibonacci( long n ) printf("%d\n",n); if (n == 0 n == 1) /* en alt */ return n; else return fibonacci( n - 1) + fibonacci( n 2 ); f( 3 ) return f( 2 ) + f( 1 ) return f( 1 ) + f( 0 ) return 1 3 2 1 0 1 return 1 return 0

int factorial(int a) if(a<0) fprintf(stderr, Gecersiz sayi\n ); return; else if ((a==0) (a==1)) return 1; else return (a*factorial(a-1));

Exercise: tanh 1 x 3 5 7 x x x x 3 5 7 Evaluate the above expression until the added numbers become smaller than a determined threshold.

void a(void) int x=10; printf( %d\n,x); x++; printf( %d\n,x); void b(void) static int x=10; printf( %d\n,x); x++; printf( %d\n,x); The value of this variable is assigned to 10 for the first call of function. Then, each time the function is called, the previous value is remembered. void main(void) a(); a(); a(); a(); b(); b(); b(); b(); a: 10 11 10 11 10 11 10 11 b: 10 11 11 12 12 13 13 14

Exercises: What's wrong with the following listing? #include <stdio.h> void print_msg( void ); main() print_msg( "This is a message to print" ); return 0; void print_msg( void ) puts( "This is a message to print" ); return 0; What's wrong with the following function definition? int twice(int y); return (2 * y);

The values of local variables are unknown to outside the function. Different functions may have local variables with same names. Their values have nothing to do with other functions variables. The variables (parameters) that are sent to the function can change their values inside the function. BUT!!! The variable which is inside the function call does not change. The function makes a copy of the variable, and uses it. It does not use the original variable.

!! Example!! Write a function which swaps the values of its two parameters: int a=6, b=4; printf("%d %d\n", a, b); degistir(a, b); printf("%d %d\n", a, b); The first printf should write "6 4", the next should "4 6".

void degistir ( int a, int b ) int gecici; Solution (?) gecici = a; a = b; b = gecici; a and b are local variables, specific to the function only. The function is unable to change the values.

Why doesn t it work? Because you may send parameters to functions in two ways: by value by reference By value: While calling function, a copy of the variable value is sent. The original variable is not sent. By reference: While calling function, the real address of the variable is sent to the function. Inside the function, the values at that address can be changed. So the variable value also changes! (Remember scanf())

Function calls Remember function: toplam(). When it is called, the loal variables work, and when the function finishes, the local variables are lost. So how can we send parameters by reference? By address-pointer syntax. main() memory area i 12 j 25? copied copied toplam() memory area a 12 b 25

Two-way communication with functions #include <stdio.h> void swap(int *a,int *b); void main() int i = 1, j = 2; &i and &j, are memory locations of i and j. We send addresses to the swap() function. swap(&i, &j); void swap(int *a, int *b) int t; a and b are address (pointer) variables. t = *a; *a = *b; *b = t; By writing *a and *b, we can rach to the values in the given address.

Sending addresses to functions main() memory area &i toplam() memory area a 12 i 100 &j 100 b 25 104 104 j This is the memory location of variable j

We already use such functions Remember scanf(); fscanf(); fopen(); etc... Think of function scanf(). What is critical here? Why do we send addresses of variables: scanf( %d, &i); Because we want to change the value of variable i. Why do we use scanf( %s, str);? We have not seen yet, but str is already an address!

scanf(&num) illustration &num &num 2 byte Read from keyboard: (Assume 10 is entered) 0 A

If you send the variable with & (address) sign - just like doing in scanf() we can change its value inside the function by writing thing to its memory location. Since the memory location corresponds to the container of the original variable, its value automatically changes.. So, what is the syntax (format) of a function that accepts addresses? We use *variable notation.

void my_func(int *num) This part is just like other functions. The argument listing part is different. int *num; is a variable whose address is num. We call the above function as: my_func(&i);

Example: If we want to print out the value of the parameter which was sent: void my_func(int *num) printf("\n%d", num); printf("\n%d\n", *num); 1245048 1 void main(void) int *num; int i = 1; my_func(&i);

void my_func(int *num) printf( %d\n,*num); *num = 2; printf( %d\n,*num); void main(void) int a=3; printf( %d\n,a); my_func(&a); printf( %d\n,a); This is the int variable; num is not int! If you call the function like this (with address)...then the function argument must be declared with * (a pointer) indicator.

void degis(int *n, int *m) int k; printf( Degismeden once, n=%d, m=%d,,*n,*m); k=*n; *n=*m; *m=*k; printf( Degistikten sonra, n=%d, m=%d,,*n,*m); void main(void) int n1=10,n2=20; printf( Fonksiyon oncesi n1=%d, n2=%d,n1,n2); degis(&n1,&n2); printf( Fonksiyon sonrasi n1=%d, n2=%d,n1,n2);

= &n1 = n *n=10 &n2 m *m=10 10 20

If you want to use address/pointer convention, but keep the value unchanged, then use const int *const num; /* for instance... */

Class Exercise Write a function which reads three float variables from the user, and returns them. The name would be: read_return(). The main program must be like: #include <stdio.h> main() float a, b, c; read_return(&a, &b, &c); printf( The numbers: %f %f %f\n",a,b,c);

Alternative uses void getnum(int *num) int k; printf( bir sayi girin: ); scanf( %d,&k); num=k; void getnum(int *num) printf( bir sayi girin: ); scanf( %d,num); void main(void) int k; getnum(&k); scanf( %d,k);