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

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

Computer Science & Engineering 150A Problem Solving Using Computers

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

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

C++ Programming Lecture 11 Functions Part I

Functions. Systems Programming Concepts

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

Object Oriented Programming Using C++ Mathematics & Computing IET, Katunayake

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

Week 2: Console I/O and Operators Arithmetic Operators. Integer Division. Arithmetic Operators. Gaddis: Chapter 3 (2.14,3.1-6,3.9-10,5.

C Functions. 5.2 Program Modules in C

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

Programming Fundamentals. With C++ Variable Declaration, Evaluation and Assignment 1

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

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

Functions. A function is a subprogram that performs a specific task. Functions you know: cout << Hi ; cin >> number;

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

Structured Programming. Dr. Mohamed Khedr Lecture 4

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

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

C Program Structures

Lecture 04 FUNCTIONS AND ARRAYS

BSM540 Basics of C Language

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

3.1. Chapter 3: The cin Object. Expressions and Interactivity

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

Data Type Fall 2014 Jinkyu Jeong

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

C Programs: Simple Statements and Expressions

ANSI C Programming Simple Programs

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

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur

C++ Programming: From Problem Analysis to Program Design, Third Edition

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

CSE202-Lec#4. CSE202 C++ Programming

Computers in Engineering. Moving From Fortran to C Michael A. Hawker

Calling Prewritten Functions in C

CSE123. Program Design and Modular Programming Functions 1-1

Operators and Expression. Dr Muhamad Zaini Yunos JKBR, FKMP

Chapter 5 C Functions

Outline. Functions. Functions. Predefined Functions. Example. Example. Predefined functions User-defined functions Actual parameters Formal parameters

WARM UP LESSONS BARE BASICS

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

C++ PROGRAMMING SKILLS Part 3 User-Defined Functions

Programming. C++ Basics

Lab Instructor : Jean Lai

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

Lecture 04 FUNCTIONS AND ARRAYS

GE U111 Engineering Problem Solving & Computation Lecture 6 February 2, 2004

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

Chapter 3 - Functions

2. Numbers In, Numbers Out

Programming Language A

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

ECET 264 C Programming Language with Applications

Introduction to Programming

Computer Programming: Skills & Concepts (CP) arithmetic, if and booleans (cont)

Chapter 2. Outline. Simple C++ Programs

2. Numbers In, Numbers Out

COMP 208 Computers in Engineering

Programming and Data Structure

Introduction. What is function? Multiple functions form a larger program Modular programming

Chapter 4. Procedural Abstraction and Functions That Return a Value. Copyright 2014 Pearson Addison-Wesley. All rights reserved.

Outline. Why do we write functions? Introduction to Functions. How do we write functions? Using Functions. Introduction to Functions March 21, 2006

Chapter 6 - Notes User-Defined Functions I

Using Free Functions

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

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

Standard Library Functions Outline

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.

Functions. Lecture 6 COP 3014 Spring February 11, 2018

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

Learning to Program with Haiku

C++ Programming: From Problem Analysis to Program Design, Fifth Edition. Chapter 6: User-Defined Functions I

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

Functions. Arash Rafiey. September 26, 2017

ET156 Introduction to C Programming

Chapter 4 Functions By C.K. Liang

Exam 2. CSI 201: Computer Science 1 Fall 2016 Professors: Shaun Ramsey and Kyle Wilson. Question Points Score Total: 80

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

Preview from Notesale.co.uk Page 2 of 79

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

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

4. C++ functions. 1. Library Function 2. User-defined Function

Downloaded from

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

Lecture 9 - C Functions

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

Conditional Expressions

Output of sample program: Size of a short is 2 Size of a int is 4 Size of a double is 8

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

Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

CS 151 Review #3. // More than one variable can be defined // in a statement. Multiple variables are // separated by a comma.

o Counter and sentinel controlled loops o Formatting output o Type casting o Top-down, stepwise refinement

from Appendix B: Some C Essentials

Summary of basic C++-commands

Engineering Problem Solving with C++, Etter/Ingber

Computer Programming for Engineering Applica4ons. Intro to Programming 10/2/13 ECE 175. Limita4ons of Reference by Value. The Concept of Pointers

Introduction to Scientific Programming with C++

Fundamentals of Programming & Procedural Programming

Transcription:

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; d = sqrt(x*x+y*y+z*z); printf("the distance to your point was %f\n",d); }

Outline Introduction to Functions Predefined Functions and Code Reuse User-defined void Functions without Arguments I. Function Prototypes II. Function Definitions III. Placement of Functions in a Program IV. Program Style 3

Function Declarations

Example

Example

Introduction to Functions Learning how to use operators, +, -, *, / and % to form simple arithmetic expressions. However, we are not yet able to write many other mathematical expressions we are used to. For example, we cannot yet represent any of the following expressions in C: C does not have operators for square root, absolute value, sine, log, etc. Instead, C provides program units called functions to carry out these and other mathematical operations. 16

Introduction to Functions A function can be thought of as a black box that takes one or more input arguments and produces a single output value. For example, the following shows how to use the sqrt function that is available in the standard math library: y = sqrt (x); If x is 16, the function computes the square root of 16. The result, 4, is then assigned to the variable y. The expression part of the assignment statement is called function call. Another example is: z = 5.7 + sqrt (w); If w = 9, z is assigned 5.7 + 3, which is 8.7. 17

Example /* Performs three square root computations */ #include <stdio.h> /* definitions of printf, scanf */ #include <math.h> /* definition of sqrt */ int main(void) { double first, second, /* input - two data values */ first_sqrt, /* output - square root of first input */ second_sqrt, /* output - square root of second input */ sum_sqrt; /* output - square root of sum */ printf("enter a number> "); scanf("%lf", &first); first_sqrt = sqrt(first); printf("square root of the number is %.2f\n", first_sqrt); printf("enter a second number> "); scanf("%lf", &second); second_sqrt = sqrt(second); printf("square root of the second number is %.2f\n", second_sqrt); } sum_sqrt = sqrt(first + second); printf("square root of the sum of the 2 numbers is %.2f\n",sum_sqrt); return (0); 18

Predefined Functions and Code Reuse The primary goal of software engineering is to write error-free code. Reusing code that has already been written & tested is one way to achieve this. --- Why reinvent the wheel? C promotes reuse by providing many predefined functions. e.g. Mathematical computations. Input/Output: e.g. printf, scanf 19

Predefined Functions and Code Reuse The next slide lists some commonly used mathematical functions (Table 3.6 in the book) Appendix B gives a more extensive lists of standard library functions. In order to use a function, you must use #include with the appropriate library. Example, to use function sqrt you must include math.h. If a functions is called with a numeric argument that is not of the argument type listed, the argument value is converted to the required type before it is used. Conversion of type int to type double cause no problems Conversion of type double to type int leads to the loss of any fractional part. Make sure you look at documentation for the function so you use it correctly. 20

Some Mathematical Library Functions Function Header File Purpose Arguments Result abs(x) <stdlib.h> Returns the absolute value of its integer argument x. sin(x),cos(x), tan(x) <math.h> Returns the sine, cosine, or tangent of angle x. log(x) <math.h> Returns the natural log of x. Log10(x) <math.h> Returns base 10 log of x int double (in radians) double (must be positive) Double (positive) int double double double pow(x, y) <math.h> Returns x y double, double double sqrt(x) <math.h> double (must be positive) x double 21

#include <iostream> using namespace std; int mult ( int x, int y ); int main() { int x; int y; } cout<<"please input two numbers to be multiplied: "; cin>> x >> y; cin.ignore(); cout<<"the product of your two numbers is "<< mult ( x, y ) <<"\n"; cin.get();

Example We can use C functions pow and sqrt to compute the roots of a quadratic equation in x of the form: If the discriminant (b 2 4ac) is greater than zero, the two roots are defined as: In C, these two roots are computed as: /* compute two roots, root_1 and root_2, for disc > 0.0 */ disc = pow(b, 2) - 4 * a * c; root_1 = (-b + sqrt(disc)) / (2 * a); root_2 = (-b - sqrt(disc)) / (2 * a); 23

Simple User-defined Functions An advantage of using predefined functions is that the programmer needs to be concerned only with what the function does but not how it does it. In complex software systems, this principle of separating what from the how is an important aspect of managing the complexity of programs. C provides a mechanism for the programmer to define his own functions with the same advantages as the C s library functions. We now study the simplest type of user-defined functions those that display one or more lines of output. These are useful for tasks such as displaying instructions to the user on how to use a program. 24

Example /* Performs three square root computations */ #include <stdio.h> /* definitions of printf, scanf */ #include <math.h> /* definition of sqrt */ void instruct (void); //displays user instruction int main(void) { /* Display instrctions */ instruct(); double first, second, /* input - two data values */ first_sqrt, /* output - square root of first input */ second_sqrt, /* output - square root of second input */ sum_sqrt; /* output - square root of sum */ printf("enter a number> "); scanf("%lf", &first); first_sqrt = sqrt(first); printf("square root of the number is %.2f\n", first_sqrt); // continue next slide 25

// continue from previous slide Example printf("enter a second number> "); scanf("%lf", &second); second_sqrt = sqrt(second); printf("square root of the second number is %.2f\n", second_sqrt); sum_sqrt = sqrt(first + second); printf("square root of the sum of the 2 numbers is %.2f\n",sum_sqrt); return (0); } // end of main function /* displays user instructions */ void instruct(void) { printf("this program demostrates the use of the \n"); printf("math library function sqrt (square root). \n"); printf("you will be asked to enter two numbers -- \n"); printf("the program will display the square root of \n"); printf("each number and the square root of their sum. \n\n"); } 26

Function Prototypes Like other identifiers in C, a function must be declared before it can be used in a program. To do this, you can add a function prototype before main to tell the compiler what functions you are planning to use. A function prototype tells the C compiler: 1. The data type the function will return For example, the sqrt function returns a type of double. 2. The function name 3. Information about the arguments that the function expects. The sqrt function expects a double argument. So the function prototype for sqrt would be: double sqrt(double); 27

Function Prototypes : void Functions void instruct(void); is a void function Void function - does not return a value The function just does something without communicating anything back to its caller. If the arguments are void as well, it means the function doesn t take any arguments. Now, we can understand what our main function means: int main(void) This means that the function main takes no arguments, and returns an int 28

Function Definition The prototype tells the compiler what arguments the function takes and what it returns, but not what it does. We define our own functions just like we do the main function Function Header The same as the prototype, except it is not ended by the symbol ; Function Body A code block enclosed by {}, containing variable declarations and executable statements. In the function body, we define what actually the function does In this case, we call printf 5 times to display user instructions. Because it is a void function, we can omit the return statement. Control returns to main after the instructions are displayed. 29

Placement of Functions in a program In general, we will declare all of our function prototypes at the beginning (after #include or #define) This is followed by the main function After that, we define all of our functions. However, this is just a convention. As long as a function s prototype appears before it is used, it doesn t matter where in the file it is defined. The order we define them in does not have any impact on how they are executed 30

Execution Order of Functions Execution order of functions is determined by the order of execution of the function call statements. Because the prototypes for the function subprograms appear before the main function, the compiler processes the function prototypes before it translates the main function. The information in each prototype enables the compiler to correctly translate a call to that function. After compiling the main function, the compiler translates each function subprogram. At the end of a function, control always returns to the point where it was called. 31

Flow of Control Between the main Function and a Function Subprogram 32

Program Style Each function should begin with a comment that describes its purpose. If the function subprograms were more complex, we would include comments on each major algorithm step just as we do in function main. It is recommended that you put prototypes for all functions at the top, and then define them all after main. 33

#include <stdio.h> /* Program for Lesson 5_1 */ void function1(void); void function2(int n, double x); void main(void) { int m; double y ; m=15; y=308.24; printf ("The value of m in main is m=%d\n\n",m); function1( ); function2(m,y); } printf ("The value of m in main is still m=%d\n",m); void function1(void) { printf("function1 is a void function that does not receive\n\ \rvalues from main.\n\n"); } void function2(int n, double x) { int k,m; double z; k=2*n+2; m=5*n+37; z=4.0*x-58.4; printf("function2 is a void function that does receive\n\ \rvalues from main. The values received from main are:\n\ \r\t n=%d \n\r\t x=%lf\n\n",n,x); printf("function2 creates three new variables, k, m and z\n\ \rthese variables have the values:\n\ \r\t l=%d \n\r\t m=%d \n\r\t z=%lf\n\n",k,m,z);

/* Program for Lesson 5_2*/ #include <stdio.h> unsigned long int fact(int m); int main(void) { int n; unsigned long int g; double one_over_nfactorial; printf("this program calculates 1/nfactorial.\n\ \renter a positive integer less than or equal to 12:\n "); scanf ("%d",&n); g=fact(n); one_over_nfactorial=1.0/g; printf("1/%d! = %e",n,one_over_nfactorial); return (0); } unsigned long int fact(int m) { int i; unsigned long int product; } product = 1; for (i=m; i>=1; i--) { product*=i; } return(product);

/* Program for Lesson 5_3 */ #include <stdio.h> int m = 12; int function1 (int a, int b, int c, int d); void main(void) { int n = 30; int e,f,g,h,i; e=1; f=2; g=3; h=4; printf ("\n\n In main (before the call to function1): \n\ \r m = %d\n\ \r n = %d\n\ \r e = %d\n\n",m,n,e ); i=function1(e,f,g,h); } printf ("After returning to main: \n"); printf ("n = %d \n\ \r m = %d \n\ \r e = %d \n\ \r i = %d", n, m,e,i); int function1 (int a, int b, int c, int d) { int n = 400;

printf ("In function1:\n\ \r n = %d\n\ \r m = %d initially\n\ \r a = %d initially \n",n,m,a); m = 999; } if (a>=1) { a+=b+m+n; printf ("m = %d after being modified\n\ \r a = %d after being modified\n\n",m,a) ; return (a); } else { c+=d+m+n; return (c); }

/* Program for Lesson 5_4 */ #include <stdio.h> void function1 (int a, int b, double r,double s, int *c, double *t); void main (void) { int i=5, j=6, k; double x=10.6, y=22.3, z; } printf (" i = %d \n\r j = %d \n\r x = %lf \n\r y = %lf \n\n", i,j,x,y); function1 (i,j,x,y,&k,&z); printf (" k = %d \n\r z = %lf \n\n", k, z); void function1 (int a,int b,double r,double s,int *c,double *t) { *c = a+b; *t = r+s +(*c); } printf (" *c = %d \n\r *t = %lf \n\n", *c, *t );

* Program for Lesson 5_4 */ #include <stdio.h> void function1 (int a, int b, double r,double s, int *c, double *t); void main (void) { int i=5, j=6, k; double x=10.6, y=22.3, z; } printf (" i = %d \n\r j = %d \n\r x = %lf \n\r y = %lf \n\n", i,j,x,y); function1 (i,j,x,y,&k,&z); printf (" k = %d \n\r z = %lf \n\n", k, z); void function1 (int a,int b,double r,double s,int *c,double *t) { *c = a+b; *t = r+s +(*c); } printf (" *c = %d \n\r *t = %lf \n\n", *c, *t );

#include<iostream.h> int sum(int, int); int sub(int,int; int mul(int,int); int dev(int,int); int main() { int a,b,result; char op; cout << "pleas enter the first number" << endl; cin >> a; cout << "pleas enter the second number" << endl; cin >> b; cout << "type + for summing and - for subtracting and * for multiplaying>> " << endl; cin >> op; switch(op) { case '+': result = sum(a,b); cout << result; break; case '-': result = sub(a,b); cout << result; break; case '*': result = mul(a,b); cout << result; break; }} int sum(int x,int y) { return x+y; } int sub(int x,int y) { return x-y; } int mul(int x,int y) { return x*y; }