Downloaded from

Similar documents
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.

Chapter-13 USER DEFINED FUNCTIONS

Downloaded from

CSE202-Lec#4. CSE202 C++ Programming

Chapter 6 - Notes User-Defined Functions I

Fundamentals of Computer Programming Using C

Multiple Choice Questions ( 1 mark)

C++ PROGRAMMING SKILLS Part 3 User-Defined Functions

Functions. Introduction :

A. Introduction to Function 1. Modular Programming input processing output functions library functions 2. Function 1. Benefit of Using Functions

CHAPTER 4 FUNCTIONS. 4.1 Introduction

C++ Programming Lecture 11 Functions Part I

Part II Answer to all the questions (2 Marks):

CAMBRIDGE SCHOOL, NOIDA ASSIGNMENT 1, TOPIC: C++ PROGRAMMING CLASS VIII, COMPUTER SCIENCE

Functions. Lecture 6 COP 3014 Spring February 11, 2018

3. Functions. Modular programming is the dividing of the entire problem into small sub problems that can be solved by writing separate programs.

CISC 1110 (CIS 1.5) Introduc2on to Programming Using C++

b) Give the output of the following program: 6,70,70 2,70 210,282,59290

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

Introduction to C++ Introduction and History. Characteristics of C++

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

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

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

Strings and Library Functions

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 6: User-Defined Functions. Objectives (cont d.) Objectives. Introduction. Predefined Functions 12/2/2016

ANSI C Programming Simple Programs

Lab Instructor : Jean Lai

Subject: Fundamental of Computer Programming 2068

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

Chapter-11 POINTERS. Important 3 Marks. Introduction: Memory Utilization of Pointer: Pointer:

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

6. C++ Subprograms David Keil CS I slides 7/03 1

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

Introduction to Programming

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

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

KENDRIYA VIDYALAYA SANGATHAN, GUWAHATI REGION HALF-YEARLY EXAMINATION-2015 CLASS XI : COMPUTER SCIENCE Time Allotted : 3 hrs. Max.

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

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

UEE1302(1066) F12: Introduction to Computers and Programming Function (II) - Parameter

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

C++ Programming: Functions

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

Laboratory 0 Week 0 Advanced Structured Programming An Introduction to Visual Studio and C++

Engineering Problem Solving with C++, Etter/Ingber

WT I (SET-I) Date: Class XI Sec. Time: 1 Hr. 10 min. Computer Science M.M.: 30

DELHI PUBLIC SCHOOL TAPI

C Functions. 5.2 Program Modules in C

VOLUME II CHAPTER 9 INTRODUCTION TO C++ HANDS ON PRACTICE PROGRAMS

BITG 1113: Function (Part 2) LECTURE 5

AIR FORCE SCHOOL,BAMRAULI COMPUTER SCIENCE (083) CLASS XI Split up Syllabus (Session ) Contents

vinodsrivastava.wordpress.com Question Bank Term-1

EECS402 Lecture 02. Functions. Function Prototype

It is necessary to have a single function main in every C program, along with other functions used/defined by the programmer.

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

Introduction to Algorithms and Data Structures. Lecture 6 - Stringing Along - Character and String Manipulation

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

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

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

Basic Source Character Set for C++ Language:

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

Chapter 2. Outline. Simple C++ Programs

m) sin() n) endl o) getch() p) cout

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

Creating a C++ Program

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

Chapter 1. Computer Overview

Computer Programming & Problem Solving ( CPPS ) Turbo C Programming For The PC (Revised Edition ) By Robert Lafore

ADARSH VIDYA KENDRA NAGERCOIL COMPUTER SCIENCE. Grade: IX C++ PROGRAMMING. Department of Computer Science 1

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

Lecture 2:- Functions. Introduction

Functions. Lab 4. Introduction: A function : is a collection of statements that are grouped together to perform an operation.

AMCAT Automata Coding Sample Questions And Answers

FORM 1 (Please put your name and form # on the scantron!!!!) CS 161 Exam I: True (A)/False(B) (2 pts each):

5. Assuming gooddata is a Boolean variable, the following two tests are logically equivalent. if (gooddata == false) if (!

Chapter 3 - Functions

Sample Paper Class XI Subject Computer Sience UNIT TEST II

The University Of Michigan. EECS402 Lecture 02. Andrew M. Morgan. Savitch Ch. 3-4 Functions Value and Reference Parameters.


UNIT - I. Introduction to C Programming. BY A. Vijay Bharath

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

OBJECTIVE QUESTIONS: Choose the correct alternative:

I Internal Examination Sept Class: - BCA I Subject: - Principles of Programming Lang. (BCA 104) MM: 40 Set: A Time: 1 ½ Hrs.

Lecture 4. 1 Statements: 2 Getting Started with C++: LESSON FOUR

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

Functions. Arash Rafiey. September 26, 2017

Faculty of Engineering Computer Engineering Department Islamic University of Gaza C++ Programming Language Lab # 6 Functions

Unit 7. Functions. Need of User Defined Functions

today cs3157-fall2002-sklar-lect05 1

Darshan Institute of Engineering & Technology for Diploma Studies

Variable x is created and assigned a value 35. Variable is y created as a copy of x. Variables x and y are two separate memory locations.

FUNCTIONS OMPAL SINGH

CS201- Introduction to Programming Current Quizzes

PROGRAMMING IN C++ COURSE CONTENT

Chapter 6: Functions

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

Methods CSC 121 Fall 2016 Howard Rosenthal

6.1. Chapter 6: What Is A Function? Why Functions? Introduction to Functions

Transcription:

Function: A function is a named unit of a group of statements that can be invoked from other parts of the program. The advantages of using functions are: Functions enable us to break a program down into a number of smaller and smaller and simpler units. This makes the program more organized and structured and easier to debug. It helps in reusability of code and thus reduces program size. If similar code is required at several places in the program, the use of a function allows this code to be written just once, and to be called wherever it is required. It helps to execute the same set of statements with different set of values. Function Declaration/Prototype: Just as any variable is declare before it is used in a program, it is necessary to declare a function to inform the compiler that the function would be referenced at a later point in the program. Function declaration is also called function prototype. Syntax for function declaration: <return type> <function name> ( <data type of parameter> [<parameter name>],. ); Example: int sum ( int, int); A declaration (prototype) tells the compiler that later on in our program we are going to write a particular function. It also informs the compiler about: 1. the type of result to be returned; 2. the identifier of the function; 3. the number and types of parameters; It is terminated by a semicolon. <return type>: It is the data type of the value that is returned to the calling function after the function is executed. It can be any of the data types, available in C++. <function name>: It is the name of the function, which is given with accordance to the naming conventions used for naming an identifier. A function is called with the help of it s name. <data type of parameter>: These are the data types of the parameters/inputs that the function receives when it is called. In function declaration it is optional to give the name of the parameters. The different data types specify to the compiler, the total number of parameters, and the data type of these parameters that the function will receive, when it is called (invoked). Function definition: The function definition contains the function header and the function body i.e. the set of statements which are executed when the function is called. Syntax for function definition: <return type> <function name> (<data type of parameter> <name of <parameter>,. ) Statement 1; Statement 2; : return ( value / variable / expression );

Example: int sum ( int a, int b) int s = a + b; return s; Note: The return statement is used to return a value to the calling function. It is always the last statement in the function definition (if the function has return type). The data type of the value returned should match with the return type of the function. // Example 1 // Program to find the factorial of a number using a function Fact () #include<conio.h> long Fact( long); // Function Prototype long num; clrscr(); cout<< \n\tenter a No. : ; cin>>num; cout<<num<<! = <<Fact(num); // Function call with num as an actual parameter getch(); // Definition of function long Fact (long N) // Function header with N as a Formal parameter long I, f=1; for( i=1; i<=n; i++) f = f * i; return f; Function Body Order of Execution in the above program main() // Execution starts from the main() Function call to Fact() // Control is passed to the function definition of Fact() Execution of the Fact() // All the statements in the function Definition of Fact() are executed Execution of statement getch() // Control returns to the main(), to the statement which follows the function call statement of Fact() Function Header: It is the first line of the function definition, which specifies the following: Return type of the function Name of the function Name of the parameters, along with their data types Note: It is not terminated with semicolon.

Function Body: It is the set of statements, which are executed when the function is called. Function Call: It is the statement in the calling function, through which the control is passed to the function definition of another function. This will execute the statements is the called function and then the control is returned back to the statement in the calling function, which follows the function call statement. The function call consists of the function name, followed by actual parameters, if any, enclosed in parentheses. Calling Function: The function, which calls a function is called the calling function. In the above example main() is the calling function. Called Function: The function which is called by anther function is known as the called function. Formal Parameter: The parameters mentioned in the function header are called formal parameter. Actual Parameter: Values/Variables which are used while making a call to the function are called actual parameter. Difference between call by value and call by reference Call by Reference 1) The changes made to the formal parameters are reflected back to the actual parameters. 2) It provides a mechanism of returning more than one value. 3) The reference parameters require an 3) Not Available ampersand (&) sign before their name. 4) The Formal and Actual parameters share the same memory location. 5) void Swap(int & a, int & b) int temp = a; a = b; b = temp; // Program to illustrate the invoking of a function using call by value // and call by reference methods #include<conio.h> // Function to swap the values of two variables, // where both the parameters are value parameters void swapv ( int a, int b) int temp = a; a = b; b = temp; Call by Value 1) The changes made to the formal parameters are not reflected back to the actual parameters. 2) Not Available 4) The formal and actual parameters have different memory location. 5) void Swap(int a, int b) int temp = a; a = b; b = temp; cout<< Displaying the formal parameters of swapv () function <<endl; cout<<a<< \t <<b<<endl; // Function to swap the values of two variables, // where both the parameters are variable parameters void swapr( int&b, int&b)

int temp = a; a = b; b = temp; cout<< Displaying the formal parameters of swapr () function <<endl; cout<<a<< \t <<b<<endl; clrscr(); int x=5, y=7; swapv(x,y); cout<< The values of actual parameters after calling the swapv() function <<endl; cout<<x<< \t <<y<<endl; swapr(x,y); cout<< The values of actual parameters after calling the swapr() function <<endl; cout<<x<< \t <<y<<endl; getch(); Returning values from Functions: When a function completes its execution it can return a single value to the calling function. // Program to explain return statement int Sum(int x, int y) int z; z = x+y; return z; clrscr(); int a,b,c; cout<< \n Enter 2 numbers : ; cin>>a>>b; OUTPUT Displaying the formal parameters of swapv() function 7 5 The values of actual parameters after calling the swapv() function 5 7 Displaying the formal parameters of swapr() function 7 5 The values of actual parameters after calling the swapr() function 7 5 OR int Sum(int x, int y) return(x+y); c = Sum(a,b); // Function call statement, the returned value is stored in the variable c cout<< \n Sum = <<c;

Default Parameters: A function can assign a parameter a default value. So, a function can be called with less number of parameters than that defined if values have been set. These default values are used when no value corresponding to these parameters are specified in the call to that function. The default values have to be specified in the function prototype, and not in the function definition. For example: int Change(int, int &, int c=9); The following points should be considered while using the default parameters: If a function consists of value, reference and default parameters, then the default parameters are specified in the end of the parameter list, i.e. If a parameter has a default value, then all the parameters appearing to it s right must have a default value. Reference parameter cannot have a default value. // Program to show the usage of default parameters int Calculate(int, int b=20); int x=5, y=15; cout<<calculate(x); cout<<endl; cout<<calculate(x,y); int Calculate(int a, int b) return(b/a); Difference between Local and Global Variables Local Variables Global Variables 1) They are declared outside all the functions, and can be used in all the functions after its declaration. 1) They are declared in a function, and can be used only in the function in which they are declared. 2) If a local variable has the same name as that of a global variable, then the local variable is given preference. 3) For example void Show () int m =5; // Local Variable cout<<m<<endl; 2) To access the global variable explicitly, scope resolution operator(::), is used. 3) For example int m = 50; // Global Variable void Show () int m =5; // Local Variable cout<<m<<::m<<endl; In-Built functions in Header File <math.h> Function Usage Example Result 1. fabs(x) Calculates the absolute value of the floating point number x. 2. abs(x) Calculates the absolute value of the integer x. Output 4 3 cout<<fabs(-7.5); cout<<fabs(8.25); cout<<abs(-12); cout<<abs(25); cout<<abs(-17.25); cout<<abs(25.77); 3. log(y) Calculates natural logarithm of cout<<log(100); y. cout<<log(2); 4. log10(y) Calculates the base 10 cout<<log10(100); 2 7.5 8.25 12 25 17 25 4.60517 0.693147

logarithm of y cout<<log10(2); 0.30103 5. pow(x, y) Calculates the power x to y. cout<<pow(10,2); cout<<pow(125,1/3.0); 100 5 6. sqrt(x) Calculates the square root of x cout<<sqrt(25); cout<<sqrt(144); 5 12 7. sin(x) Computes the sine of x. The angle is specified in radians. cout<<sin(90); cout<<sin(90/(22/7.0)); 0.893997 0.540834 8. cos(x) Computes the cosine of x. The angle is specified in radians. cout<<cos(270); cout<<sin(90/(22/7.0)); 0.984382 0.841129 In-Built functions in Header File <ctype.h> Function Usage Example Result 1. isalpha( x) Check if character x is A-Z or a-z char x= B ; if(isalpha(x)) Albhabet cout<< Alphabet ; cout<< Not alphabet ; 2. isdigit( x) Check if character x is 0-9 char x= 9 ; if(isdigit(x)) cout<< Digit ; cout<< Not digit ; 3. islower( x) Check if character x is lower case alphabet a-z 4. isupper( x) Check if character x is Upper case alphabet A-Z 5. Isalnum( x) Check if character x is an alphanumeric i.e. A-Z, a-z, 0-9 6. tolower(x) Converts the character x to its lower case value i.e. if character is A-Z then it convert it to a-z. All other characters are left unchanged. It return ASCII of the lower case equivalent. 7. toupper(x) Converts the character x to its upper case value i.e. if character is a-z then it convert it to A-Z. All other characters are left unchanged. It return ASCII of the upper case char x= b ; if(islower(x)) cout<< Lowercase ; cout<< Not lowercase ; char x= B ; if(isupper(x)) cout<< Uppercase ; cout<< Not uppercase ; char x= b ; if(isalnum(x)) cout<< alphabet/digit ; cout<< other ; char x= H ; if(isupper(x)) cout<<(char)tolower(x); char x= h ; if(islower(x)) cout<<(char)toupper(x); Digit Lowercase Uppercase alphabet/ digit h H

equivalent. In-Built functions in Header File <conio.h> Function Usage Example Result 1. clrscr() To clear the screen clrscr(); Places the text cursor at first row, and first column on the screen 2. getch() Wait for a character input getch(); 3. gotoxy(c,r) To place the text cursor at column c and row r on the screen. gotoxy(3,6); Places the text cursor at third column and sixth row on the screen In-Built functions in Header File <stdlib.h> Function Usage Example Result 1. randomize() It is used to initialize the random number generator, so that each time a new random number is generated. randomize(); 2. random(n) It returns a random integer cout<<random(7); Will display any between 0 to n-1, both integer number inclusive. between 0-6. // Program find LCM of two number using function. int LCM( int a, int b) int i, lcm; for(i=a*b; i>=a; i--) if(i%a==0 && i%b==0) lcm=i; return lcm; int GCD(int a, int b) int i, gcd; for(i=1; i<=a; i++) if(a%i ==0 && b%i==0) gcd=i; return gcd;

int a, b, l,g; cout<< \n Enter 2 number : ; cin>>a>>b; l = LCM(a,b); cout<< \n LCM = <<l; g = GCD(a,b); cout<< \n GCD = <<g;