Dr Tripty Singh Tutorial for Fuctions

Slides:



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

Chapter 7: User-Defined Functions II
Chapter 7: User-Defined Functions II Instructor: Mohammad Mojaddam.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 5 - Functions Outline 5.1Introduction 5.2Program.
Chapter 6. 2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single Value Pass by Reference Variable Scope.
 2003 Prentice Hall, Inc. All rights reserved. 1 Functions Modules: functions and classes Programs use new and “prepackaged” modules –New: programmer-defined.
1 Functions Modules: functions and classes Programs use new and “prepackaged” modules –New: programmer-defined functions, classes –Prepackaged: from the.
CMSC 104, Version 8/061L18Functions1.ppt Functions, Part 1 of 4 Topics Using Predefined Functions Programmer-Defined Functions Using Input Parameters Function.
Functions in C. Function Terminology Identifier scope Function declaration, definition, and use Parameters and arguments Parameter order, number, and.
Chapter 4:Functions| SCP1103 Programming Technique C | Jumail, FSKSM, UTM, 2005 | Last Updated: September 2005 Slide 1 Functions Lecture 4 by Jumail Bin.
C Functions Programmer-defined functions – Functions written by the programmer to define specific tasks. Functions are invoked by a function call. The.
18-2 Understand “Scope” of an Identifier Know the Storage Classes of variables and functions Related Chapter: ABC 5.10, 5.11.
A First Book of C++: From Here To There, Third Edition2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single.
MAHENDRAN CHAPTER 6. Session Objectives Explain Type of Functions Discuss category of Functions Declaration & Prototypes Explain User Defined Functions.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. C How To Program - 4th edition Deitels Class 05 University.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition, Fifth Edition Chapter 7: User-Defined Functions II.
Functions Top-down design Breaking a complex problem into smaller parts that we can understand is a common practice. The process of subdividing a problem.
UniMAP SemI-09/10EKT120: Computer Programming1 Week 5 – Functions (1)
Lecture 05 Functions II, Storage Class, Scope, rand() METU Dept. of Computer Eng. Summer 2002 Ceng230 - Section 01 Introduction To C Programming by Ahmet.
FUNCTIONS. Funtions  The heart of effective problem solving is problem decomposition.  breaking a problem into small, manageable pieces  In C, the.
CSCI 171 Presentation 6 Functions and Variable Scope.
Lecture 10: Modular Programming (functions) B Burlingame 13 April 2015.
Functions: Part 2 of /11/10: Lecture 16 CMSC 104, Section 0101 John Y. Park 1.
Functions Math library functions Function definition Function invocation Argument passing Scope of an variable Programming 1 DCT 1033.
Tarik Booker CS 242. What we will cover…  Functions  Function Syntax  Local Variables  Global Variables  The Scope of Variables  Making Functions.
C Part 2 Computer Organization I 1 August 2009 © McQuain, Feng & Ribbens The Three Attributes of an Identifier Identifiers have three essential.
BIL 104E Introduction to Scientific and Engineering Computing Lecture 4.
UMBC CMSC 104 – Section 01, Fall 2016
Chapter 9: Value-Returning Functions
EKT120: Computer Programming
Functions Course conducted by: Md.Raihan ul Masood
Chapter 6: User-Defined Functions I
Chapter 7: User-Defined Functions II
INC 161 , CPE 100 Computer Programming
TMF1414 Introduction to Programming
Functions, Part 2 of 2 Topics Functions That Return a Value
Functions and Structured Programming
The Three Attributes of an Identifier
C-language Lecture By B.S.S.Tejesh, S.Neeraja Asst.Prof.
CSC113: Computer Programming (Theory = 03, Lab = 01)
PGT 106: Computer Programming
Week 5 – Functions (1) EKT120: Computer Programming.
EKT120: Computer Programming
Programmazione I a.a. 2017/2018.
Chapter 5 - Functions Outline 5.1 Introduction
Chapter 5 - Functions Outline 5.1 Introduction
Functions.
User-Defined Functions
2008/11/10: Lecture 16 CMSC 104, Section 0101 John Y. Park
Formatted and Unformatted Input/Output Functions
Computer Science 210 Computer Organization
Chapter 5 - Functions Outline 5.1 Introduction
Scope, Parameter Passing, Storage Specifiers
Arrays, For loop While loop Do while loop
Chapter 6 - Functions Outline 5.1 Introduction
Functions, Part 2 of 3 Topics Functions That Return a Value
A function with one argument
C Storage classes.
Function In this lesson, you will learn about Introduction to Function
Chapter 6: User-Defined Functions I
In C Programming Language
Introduction to Problem Solving and Programming
In C Programming Language
Functions, Part 2 of 3 Topics Functions That Return a Value
Functions, Part 2 of 3 Topics Functions That Return a Value
CPS125.
Functions that return a value
Presentation transcript:

Dr Tripty Singh Tutorial for Fuctions FUNCTIONS Dr Tripty Singh Tutorial for Fuctions

Function definitions return_type function_name (formal parameter list) { local declarations .... statements ..... } A function in C can have a return value, side effect or both. The functions value is the value in the expression of the return statement. A function side effect is an action that results in the change in the state of the program. The side effect occurs before the value is returned

void functions without parameters #include <stdio.h> void greeting( void) { printf(“Hello world”); return; } int main(void) greetings(); return 0; This function receives nothing and returns nothing

void functions parameters #include <stdio.h> void printone( int x) // x is formal parameter { printf(“%d\n”,x); return; } int main(void) int a; a = 5; printone(a); // a is actual parameter printone(20); // a value can be directly passed return 0;

void functions with parameters #include <stdio.h> void area( int x),int y) { int area; area = x * y; printf(“rea is %\dn”,area; return; } int main(void) int a=5, b=10; area(a,b); return 0; Output is area is 50 X,y is formal parameter Output is area is 50 a ,b is actual parameter

functions without parameters that returns a value; /*A functions that gets an option from user and returns it */ char get_option(void) { chat ch; printf(“Enter operation \n”); printf(“ * for multiplication\n”); printf(“ + for addition\n”); printf(“ – for subtraction\n”); printf(“ / for division\n”); printf(“ q to quit\n”); scanf(“ %c”, &ch); return ch; }

Sample program #include <stdio.h> //include function definition here int main(void) { int num1, num2, result; char option; option = get_option(); while (option != ‘q’) printf(“Enter the numbers”); scanf((“%d%d”, &num1, &num2); switch (option) { case ‘+’: result = num1+num2; break; case ‘*’: result = num1*num2; break; case ‘-’: result = num1-num2; break; case ‘/’: result = num1/num2; }

Functions with parameters that returns value /*A functions that accepts three sides of a triangle as its parameters and returns the area of the triangle */ float t_area(float a, float b, float c) { float area, s; // local variables s = (a + b+ c) /2.0; area = s qrt(s * (s-a) * (s-b) * (s-c) ) return area } Main Program #include <stdio.h> //include function definition here int main(void) { float s1,s2,s3,ar; printf(“Enter three sides:”); scanf(“%f%f%f”, &s1, &s2, &s3); ar=t_area(s1,s2,s3); printf(“area is %f\n”,ar); }

Function name - usage Function declaration Function definition Function call

Function to find largest of three numbers What should be the function prototype of a function that returns the largest of three numbers passed to it?

Function to find largest of three numbers What should be the function prototype of a function that returns the largest of three numbers passed to it? int largest (int a, int b, int c);

Function to find largest of three numbers #include <stdio.h> int largest(int a, int b, int c); // function declaration main() { int l, i,j,k; printf("Enter three numbers"); scanf("%d%d%d", &i, &j, &k); l = largest(i,j,k); // Function call printf("largest is %d\n", l); } int largest(int a, int b, int c) // Function definition if (a>=b && a>=c) return a; else if (b>= a && b >=c) return b; else return c;

Function to find largest of three numbers #include <stdio.h> int largest(int , int , int ); // variable names can be omitted in declaration main() { int l, i,j,k; printf("Enter three numbers"); scanf("%d%d%d", &i, &j, &k); l = largest(i,j,k); printf("largest is %d\n", l); } int largest(int a, int b, int c) if (a>=b && a>=c) return a; else if (b>= a && b >=c) return b; else return c;

Function to check prime #include <stdio.h> #include <math.h> int prime(int num); main() { int l; printf("Enter a numbers"); scanf("%d", &i); if (prime(i)) printf("%d is prime \n", i); else printf("%d is not prime \n", i); } int prime(int n) int i = 1; int end = sqrt(n) + 1; while (++i < end) if (n%i == 0) return 0; return 1;

Number of prime numbers between two given numbers #include <stdio.h> int prime(int num); main() { int low, upper,i,count=0; printf("Enter the lower and upper range”); scanf("%d", &iower, &upper; for (i=lower; i<= upper; i++) if (prime(i)==1 ) count++; printf(“Number of prime numbers between “); printf(“ %d and %d is %d\n”, lower, upper, count); } int prime(int n) int i = 1, prime = 1; for (i=2; i<n; i++) if (n%i == 0) { prime =0; break; } // come out of loop as soon as a divisor is found return prime; // prime will be 1 if no divisor is found

Specifying function requirements We can see that a more general function might require arguments; but how do we know what the requirements are? A general method for specifying the requirements for a function call is called function declaration or function prototyping

C – Argument, return value All C functions can be called either with arguments or without arguments in a C program. These functions may or may not return values to the calling function. Now, we will see simple example C programs for each one of the below. C function with arguments (parameters) and with return value. C function with arguments (parameters) and without return value. C function without arguments (parameters) and without return value. C function without arguments (parameters) and with return value.

Function prototype Declaration statement for function Provides information necessary to call function Data type of function’s return value (if any) Data type(s) of any required argument(s), listed in the order required: this is called the parameter list Usually appears above main() or in a header file Function prototypes are declaration statements – each one ends with a semicolon

Function prototype examples The function prototypes for some familiar functions are listed below: int rand(); // appears in the stdlib.h header file double sqrt (double); // appears in math.h double pow (double, double); // also in math.h

Function prototypes A function prototype includes the following parts: The function’s return type; can be any data type, including void (meaning no return value) The function name (must be a valid C identifier – same rules apply for functions and variables) The function’s parameter list, which specifies the data type of each required argument, and optionally includes a name for each parameter

Examples int rand(); double pow (double, double); parameter list name of function type of value returned double pow (double, double); Note: a function’s parameter list may, but does not have to, include a name for each parameter; the parameters are not named in the examples above

More examples Previously, we considered 3 possible versions of a drawSquare function; the prototypes for each version are shown below: void drawSquare(); // draws a 4x4 square made of asterisks void drawSquare(int); // draws a square of the specified size, made of asterisks void drawSquare(int size, char pixel); // draws a square of the specified size using the specified // picture element Note that these are examples of overloaded functions – their prototypes differ only in their parameter lists

More examples Previously, we considered 3 possible versions of a drawSquare function; the prototypes for each version are shown below: void drawSquare(); // draws a 4x4 square made of asterisks void drawSquare(int); // draws a square of the specified size, made of asterisks void drawSquare(int size, char pixel); // draws a square of the specified size using the specified // picture element Note that these are examples of overloaded functions – their prototypes differ only in their parameter lists

C functions aspects syntax 1. With arguments and with return values function declaration: int function ( int ); function call: function ( a ); function definition:        int function( int a ) { statements; return a; } 2. With arguments and without return values function declaration: void function ( int ); function call: function( a ); function definition: void function( int a ) { statements; }

C functions aspects syntax 3. Without arguments and without return values function declaration: void function(); function call: function(); function definition: void function() { statements; } 4. Without arguments and with return values function declaration: int function ( ); function call: function ( ); function definition: int function( ) { statements; return a; }

#include<stdio.h> // function prototype, also called function declaration float square ( float x );                               // main function, program starts from here   int main( )               {     float m, n ;     printf ( "\nEnter some number for finding square \n");     scanf ( "%f", &m ) ;     // function call     n = square ( m ) ;                           printf ( "\nSquare of the given number %f is %f",m,n ); } float square ( float x )   // function definition     float p ;     p = x * x ;     return ( p ) ; Enter some number for finding square 2 Square of the given number 2.000000 is 4.000000

Function with no Arguments but Return Value In C

Function with no arguments and no Return Value In C

Note: If the return data type of a function is “void”, then, it can’t return any values to the calling function. If the return data type of the function is other than void such as “int, float, double etc”, then, it can return values to the calling function.

Function with argument and return type

Storage Classes auto static extern register Automatic. Also called local variable static extern External. Also called global variables register Storage class determines life time of a variable

Scope Scope /life / visibility of a variable starts from where it is declared and continues till the end of the block where it is declared. If a variable is declared outside of any block, such variables ( typically global variables) are visible till the end of the file.

auto storage class. Automatic variables are always declared within a function or a block. They are local to the function (i.e., their scope is confined to the function). Formal parameters are local to the function. Any variable declared within a block (pairs of { } ) without explicit storage class specifier is a local variable. Its scope is only up to the end of the block (variable gets destroyed at the end of the block and memory allocated for it is released) It is a common practice to omit storage class specifier when local variables are declared. Local variables can be initialized

auto storage class. Automatic variables are always declared within a function or a block. They are local to the function (i.e., their scope is confined to the function). Formal parameters are local to the function. Any variable declared within a block (pairs of { } ) without explicit storage class specifier is a local variable. Its scope is only up to the end of the block (variable gets destroyed at the end of the block and memory allocated for it is released). it is not available outside the block. It is a common practice to omit storage class specifier when local variables are declared.

auto storage class. int bigger( int a, int b) { int large; auto char option = ‘a’; if (a > b) large = a; else large = b; return large; } a, b , large and option are auto (also called local) variables. The value of a local variable is unspecified unless it is initialized or until a value a value is assigned to it.

#include <stdio.h> main() { int i=30,j, k; if (i > 20) int sum = 10; sum = sum +10; printf("sum is %d \n", sum); } printf("sum is %d \n", sum);// error

#include <stdio.h> main() { int i,j, k; int sum=20, i = 30; if (i > 10) int sum = 10; printf("sum is %d \n", sum); }

static storage class static storage class specifier causes a memory to be allocated to the variable till the end of program execution. Though the variable is not destroyed at the end of block, it is not visible outside the block. The value of the variable is retained.

#include <stdio.h> main() { int i,j, k,l; int sum=20; for (i = 0; i<=1; i++) int sum = 10; sum = sum + 2; printf("sum is %d \n", sum); }

#include <stdio.h> main() { int i,j, k,l; int sum=20; for (i = 0; i<=1; i++) static int sum = 10;//initialized only once sum = sum + 2; printf("sum is %d \n", sum); }

Global variables Variables declared outside of any function definition is a global variable The visibility of a global variable start from where it is declared and is visible till the end of the file. Life of the variable till the end of program execution If the variable not explicitly initialized, it gets an initial value of zero. Initialization, if done, has to be with a constant value (it cannot be an expression involving variables) Storage class specifier extern is used to declare a variable which is defined in another file (variable is external to the current file)

#include <stdio. h> int count; // global variable #include <stdio.h> int count; // global variable. initial value 0 int num = 1000; extern max; // max is defined in another file. void mesage(); int main() { printf("%d %d %d\n", count, num, max); num = num + 500; message(); printf("%d\n", count); } void message(void) printf(“num is %d\n", num); count++;

#include <stdio.h> int count; int num = 1000; void mesage(); int main() { printf("%d %d\n", count, num); // 0 1000 num = num + 500; message(); printf("%d\n", count); // 1 } void message(void) printf(“num is %d\n", num);// 1500 count++; 0 1000 num is 1500 1

register variables register storage class is same as auto class except that it contains a recommendation to the compiler to allocate a CPU register for the variable.

Some standard (builtin) functions Math functions To calculate absolute value int abs ( int number); // stdlib.h long labs (long number) // stdlib.h long long llabs (long long number) // stdlib.h double fabs (double number) //math.h float fabsf (float number) //math.h long double fabsl (long double number) //math.h

Additional math functions Ceiling functions (smallest integral value greater than or equal to number) double ceil ( double number) float ceilf ( float number) long double ceill ( long double number) floor functions (largest integral value smaller than or equal to number) double float( double number) float floatf( float number) long double floatl( long double number)

Additional math functions Truncate functions (returns the integer in the direction of zero) double trunc ( double number) float truncf ( float number) long double truncl( long double number) round functions (returns the nearest integral value) double round( double number) float roundf( float number) long double roundl( long double number)

Additional math functions Power function double pow ( double n1, double n2) float powf (float n1, float n2) long double powlf (long double n1, long double n2) Square root functions double sqrt( double number) float sqrtf( float number) long double sqrtlf( long double number)

Recursion A function calling itself A function calling some function higher in the calling hierarchy.

Recursion function1

Recursion function1 function2 function3

Recursion - Examples Fibonacci numbers Facttorial F(n) = F(n-1) + F(n-2) Facttorial n! = (n-1)! * n

Recursion