Functions. Introduction :

Similar documents
Lab Instructor : Jean Lai

Pointers and Strings Prentice Hall, Inc. All rights reserved.

Chapter 3 - Functions

CHAPTER 4 FUNCTIONS. Dr. Shady Yehia Elmashad

C++ PROGRAMMING SKILLS Part 3 User-Defined Functions

by Pearson Education, Inc. All Rights Reserved.

Programming for Engineers Pointers

UNIT- 3 Introduction to C++

Chapter 6 - Pointers

Chapter-13 USER DEFINED FUNCTIONS

KOM3191 Object Oriented Programming Dr Muharrem Mercimek ARRAYS ~ VECTORS. KOM3191 Object-Oriented Computer Programming

calling a function - function-name(argument list); y = square ( z ); include parentheses even if parameter list is empty!

Chapter 3 - Functions

CHAPTER 4 FUNCTIONS. Dr. Shady Yehia Elmashad

Introduction to C++ Systems Programming

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

Lecture 04 FUNCTIONS AND ARRAYS

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

C++ Programming Chapter 7 Pointers


Lecture 05 POINTERS 1

C++ PROGRAMMING SKILLS Part 4: Arrays

Content. In this chapter, you will learn:

Functions and Recursion

CHAPTER 4 FUNCTIONS. 4.1 Introduction

C Pointers Pearson Education, Inc. All rights reserved.

C Pointers. sizeof Returns size of operand in bytes For arrays: size of 1 element * number of elements if sizeof( int ) equals 4 bytes, then

C++ How to Program, 9/e by Pearson Education, Inc. All Rights Reserved.

Fundamentals of Programming Session 20

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

Arrays. Comp Sci 1570 Introduction to C++ Array basics. arrays. Arrays as parameters to functions. Sorting arrays. Random stuff

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

IS 0020 Program Design and Software Tools

Chapter 7 Array. Array. C++, How to Program

MODULE 3: Arrays, Functions and Strings

Chapter 6: User-Defined Functions. Objectives (cont d.) Objectives. Introduction. Predefined Functions 12/2/2016


CSE202-Lec#4. CSE202 C++ Programming

Downloaded from

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

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

Introduction to C++ Introduction to C++ 1

by Pearson Education, Inc. All Rights Reserved. 2

Chapter 15 - C++ As A "Better C"

Chapter 5 - Pointers and Strings

Chapter 5 - Pointers and Strings

FORM 2 (Please put your name and form # on the scantron!!!!)

C Functions. Object created and destroyed within its block auto: default for local variables

Downloaded from

Chapter 5 C Functions

OOP THROUGH C++(R16) int *x; float *f; char *c;

Relationship between Pointers and Arrays

Chapter 7 C Pointers

CS2255 HOMEWORK #1 Fall 2012

Pointers and Strings Chapters 10, Pointers and Arrays (10.3) 3.2 Pointers and Arrays (10.3) An array of ints can be declared as

Kingdom of Saudi Arabia Princes Nora bint Abdul Rahman University College of Computer Since and Information System CS242 ARRAYS

Cpt S 122 Data Structures. Introduction to C++ Part II

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

CS 345. Functions. Vitaly Shmatikov. slide 1

Functions and Recursion

Darshan Institute of Engineering & Technology for Diploma Studies

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

Pointer in C SHARDA UNIVERSITY. Presented By: Pushpendra K. Rajput Assistant Professor

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

Data type of a pointer must be same as the data type of the variable to which the pointer variable is pointing. Here are a few examples:

MYcsvtu Notes LECTURE 34. POINTERS

CSC 211 Intermediate Programming. Arrays & Pointers

Programming for Engineers Functions

Exam 3 Chapters 7 & 9

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

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

Chapter 2: Introduction to C++

Chapter 2: Special Characters. Parts of a C++ Program. Introduction to C++ Displays output on the computer screen

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

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

Solution: A pointer is a variable that holds the address of another object (data item) rather than a value.

Programming - 1. Computer Science Department 011COMP-3 لغة البرمجة 1 لطالب كلية الحاسب اآللي ونظم المعلومات 011 عال- 3

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

CSC 307 DATA STRUCTURES AND ALGORITHM ANALYSIS IN C++ SPRING 2011

6.5 Function Prototypes and Argument Coercion

CHRIST THE KING BOYS MATRIC HR. SEC. SCHOOL, KUMBAKONAM CHAPTER 9 C++

COMP26120: Pointers in C (2018/19) Lucas Cordeiro

INTRODUCTION TO PROGRAMMING

Arrays. Week 4. Assylbek Jumagaliyev

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

Chapter 3 - Functions

A First Book of ANSI C Fourth Edition. Chapter 8 Arrays

Pointers, Dynamic Data, and Reference Types

C++ is case sensitive language, meaning that the variable first_value, First_Value or FIRST_VALUE will be treated as different.

PART I. Part II Answer to all the questions 1. What is meant by a token? Name the token available in C++.

EL6483: Brief Overview of C Programming Language

C Functions. 5.2 Program Modules in C

Pointer Basics. Lecture 13 COP 3014 Spring March 28, 2018

Review. Outline. Array Pointer Object-Oriented Programming. Fall 2013 CISC2200 Yanjun Li 1. Fall 2013 CISC2200 Yanjun Li 2

Review. Outline. Array Pointer Object-Oriented Programming. Fall 2017 CISC2200 Yanjun Li 1. Fall 2017 CISC2200 Yanjun Li 2

11. Arrays. For example, an array containing 5 integer values of type int called foo could be represented as:

Introduction to C Final Review Chapters 1-6 & 13

DE122/DC106 Object Oriented Programming with C++ DEC 2014

Name MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.

C++ Programming Lecture 11 Functions Part I

Transcription:

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 C++, main( ) is also a function which is defined to do a particular task Functions are used for : Divide and conquer : A large program is divided into smaller pieces to build the program effectively. Code reusability: Avoid repeating code in the program and using existing functions as building blocks to create new programs. Math Library Functions Sometimes functions are not members of a class. Called global functions. Function prototypes for global functions are placed in header files, so that the global functions can be reused in any program that includes the header file and that can link to the function s object code. The <cmath> header file provides a collection of functions that enable you to perform common mathematical calculations. All functions in the <cmath> header file are global functions therefore, each is called simply by specifying the name of the function followed by parentheses containing the function s arguments. - 1 -

Generate random number: Returns a pseudo-random integral number in the range between 0 and RAND_MAX.(32767) This number is generated by an algorithm that returns a sequence of apparently non-related numbers each time it is called. This algorithm uses a seed to generate the series, which should be initialized to some distinctive value using function srand. Defined in header <cstdlib> int rand(); - Parameters (none) -Return value Pseudo-random integral value between 0 and RAND_MAX. - 2 -

-Scaling Random Numbers: - A typical way to generate trivial pseudo-random numbers in a determined range using rand is to use the modulo of the returned value by the range span and add the initial value of the range: To produce integers in the range 0 to 5, we use the modulus operator (%) with rand: rand() % 6 This is called scaling. The number 6 is called the scaling factor. Six values are produced. We can shift the range of numbers produced by adding a value. 1 v1 = rand() % 100; // v1 in the range 0 to 99 2 v2 = rand() % 100 + 1; // v2 in the range 1 to 100 3 v3 = rand() % 30 + 1985; // v3 in the range 1985-2014 Functions (Empty Parameter Lists): In C++, an empty parameter list is specified by writing either void or nothing at all in parentheses. The prototype void print(); specifies that function print does not take arguments and does not return a value. A function is implemented in three steps : 1) Function Prototype. 2) Calling the function. 3) Defining the function The general format of empty parameter list function definition is return-type function-name() statement1; statement2; - 3 -

return-type is the data type of the value returned by the function. If the return-type is void, the function return nothing. functionname is the name of the function. A function is invoked by calling the function and when the called function completes its task it returns a value. Function Prototype : A function prototype (also called a function declaration) tells the compiler the name of a function, the return-type, the number of arguments the function receive and the types of those arguments. 1- The following program uses a function to print "hello world". # include <iostream.h> void print(); // Function prototype void main( ) print(); // Function call void print() // Function Definition cout<<"hello World"; Functions (with Parameter Lists) The general format of function with parameter list definition is return-type function-name(argument1,argument2,.,argument n) - 4 -

statement1; statement2; The following program uses a function to add two numbers. # include <iostream.h> int sum( int, int); // Function prototype void main( ) int a,b; cout<< Enter two numbers ; cin>>a>>b; cout<< Sum of two numbers : << sum(a,b); // Function call int sum(int a, int b) int c; c = a + b; return(c); // Function Definition Here sum is the name of the function. This function adds the integers a and b passed as arguments and returns the result. two - 5 -

Scope of Variables : A variable declared inside the function definition is called a local variable. Its scope is within the function block. A variable declared outside any function is called a global variable. This variable can be accessed by any function in the program. The following example demonstrates the scope of variables: # include <iostream.h> int a; // global variable void function1(); void main() a =5; function1(); cout<< a = a; void function1() int b; // local variable cout<< b= b; a=a+1; Since a is declared outside the function, it is a global variable and is accessible by all functions. b is accessible only within the function1(). - 6 -

Reference Parameters : There are two ways to pass arguments to the functions : 1. Pass by value 2. Pass by reference When an argument is passed by value, a copy of the argument's value is passed to the called function. Changes to the copy do not affect the original variable's value in the caller. When an argument is passed by reference, an alias ( reference) of the argument is passed to the called function. Any changes made to the argument directly affect the original variable. To indicate that a function parameter is passed by reference, simply append the parameter's type by an ampersand (&). Eg : Consider the following program : # include <iostream.h> void swap(int&, int&); void main() int a,b; a=5 ; b=7; swap ( a,b); cout<< The values of a and b after swapping are ; cout<< a= a; cout<< b= b; void swap(int & x, int & y) Output : a=7 b=5 int temp; temp=x; x=y; y=temp; The values of x and y modified by the function swap() affects the original variables a and b. - 7 -

Default arguments : Default arguments are the arguments that have default values provided by the programmer,and when a default argument is ommited in a function call, the default value of that argument is automatically inserted by the compiler and passed in the call. Default arguments must be the rightmost arguments in a function s parameter list. When one is calling a function with 2 or more default arguments, if an ommited argument is not the rightmost argument in the argument list, all the argument to the right must be ommited. Default argument should be specified in the first occurrence of the function name typically,in the prototype. Eg : int volume(int l,int b, int h=1); void main() cout<< Volume of a box << volume(4,5); int volume(int l,int b,int h) return(l*b*h); The function call volume(4,5) omits the argument h, the default value of the argument h i.e 1 is passed. - 8 -

Function Overloading C++ enables several functions of the same name to be defined, as long as these functions have different sets of parameters. This capability is called function overloading. When an overloaded function is called, the C++ compiler selects the proper function by examining the number, types and order of the arguments in the call. Function overloading is commonly used to create several functions of the same name that perform similar tasks, but on different data types. Eg: // function square for int values int square( int x ) cout << "square of integer " << x << " is "; return x * x; // function square for double values double square( double y ) cout << "square of double " << y << " is "; return y * y; int main() cout << square( 7 ); // calls int version cout << endl; cout << square( 7.5 ); // calls double version cout << endl; return 0; - 9 -

Recursion : A recursive function is a function that calls itself, either directly, or indirectly. For example, to calculate the factorial of a number the recursive definition of a factorial is n! = n * (n-1)! 5! = 5 * 4 * 3 * 2 * 1 5! = 5 * (4*3*2*1) 5! = 5 * 4! 5! = 5 * 4 * 3!. #include <iostream.h> long int fact ( long int ); void main() for ( int i = 0; i <= 10; i++ ) cout << i << "! = " <<fact(i); long int fact(long int n) long int f; if ( n<=1) f=1; // base case else f = n * fact(n-1); // recursion step return (f); - 10 -

ARRAYS Introduction An array is a series of elements of the same data type. All the values are stored in contiguous memory locations. The values can be accessed by using the position of the stored value. An array is declared as follows : type arrayname [ arraysize ]; For eg : int a[10]; // array a of 10 integers The above declaration tells the compiler to reserve 10 elements for array a. The elements in the array a is accessed by using the position of the value i.e a[0], a[1] a[9]. a[0] refers to the first element. a[1] refers to the second element and so on. The following program demonstrates the use of arrays : # include <iostream.h> void main() int marks[5]; int total=0; cout<< Enter the marks ; for (int i=0; i<5;i++) cin>>marks[i]; for(i=0;i<5;i++) total=total+marks[i]; cout<< Total Marks : <<total; - 11 -

Arrays can be declared to contain elements of any data type. For example an array of type char can be used to store a character string. char c[20] // array c of 20 characters Initializing Arrays: The elements of an array also can be initialized in the array declaration by following the array name with an equals sign and a commaseparated list (enclosed in braces) of initializers. Eg: int a[5]= 20,12,6,4,9; Here a[0] refers to 20,a[1] refers to 12,a[2] refers to 6 and so on. Passing Arrays to functions: To pass an array argument to a function, specify the name of the array without any brackets. For example, if array X has been declared as int X[ 10 ]; the function call modifyarrayx( X, 10 ); passes array X and its size to function modifyarrayx. When passing an array to a function, the array size is also passed so that the function can process the specific number of elements in the array. Note: C++ passes arrays to function by reference. The called functions can modify the element values in the callers' original arrays. Eg : # include <iostream.h> # include <iomanip.h> void modifyarrayx(int [],int); void main() - 12 -

int X[5]=10,20,30,40,50; modifyarrayx(x,5); cout<< The array X after modify is \n ; for(int i=0;i<5;i++) cout<<a[i]<<endl; void modifyarrayx(int X[], int size); for(int i=0;i<size;i++) X[i]+=5; Output : The array X after modifying : 15 25 35 45 55 Multi Dimensional Arrays : Multidimensional arrays with two dimensions are often used to represent tables of values consisting of information arranged in rows and columns. To identify a particular table element, we must specify two subscripts. Arrays that require two subscripts to identify a particular element are called two-dimensional arrays. Eg : int M[3][3]; // A two dimensional array M with 3X3 elements. A multi dimensional array can also be initialized in its declaration. Eg : int P[2][2] = 1,2, 4,5 ; - 13 -

POINTERS Introduction: A pointer variable is a variable that stores the address of another variable. E.g.: Consider the following code: int *p; int a=5; p = &a; cout<< a = <<*p; // p is a pointer variable of type int // p points to a // a is accessed using pointer p p a 5 int *p; declares the variable to be of type int*. i.e. a pointer p points to an int variable. p = &a; assigns the address of the variable to pointer variable p. The variable p is said to point to variable a. & is called the address operator or reference operator. cout<< a = << *p; The * operator called indirection or dereference operator returns an alias for the object to which its pointer points. The above statement prints the value of a. - 14 -

Pointers should be initialized either when they are declared or in an assignment. A pointer may be initialized to 0, NULL or an address. A pointer with the value 0 or NULL points to nothing and is known as a null pointer. Relationship Between Pointers and Arrays Arrays and pointers are intimately related in C++ and may be used almost interchangeably. An array name can be thought of as a constant pointer. Pointers can be used to do any operation involving array subscripting. Assume the following declarations: int b[ 5 ]; // create 5-element int array b int *bptr; // create int pointer bptr Because the array name (without a subscript) is a (constant) pointer to the first element of the array, we can set bptr to the address of the first element in array b with the statement bptr = b; // assign address of array b to bptr This is equivalent to taking the address of the first element of the array as follows: bptr = &b[ 0 ]; // also assigns address of array b to bptr Array element b[ 3 ] can alternatively be referenced with the pointer expression *( bptr + 3 ) - 15 -

Just as the array element can be referenced with a pointer expression, the address &b[ 3 ] can be written with the pointer expression bptr + 3 Eg: int main() int b[] = 10, 20, 30, 40 ; // create 4-element array b int *bptr = b; // set bptr to point to array b // output array b using array subscript notation for ( int i = 0; i < 4; i++ ) cout << "b[" << i << "] = " << b[ i ] << '\n'; // output array b using the array name and pointer/offset notation for ( int i = 0; i < 4; i++ ) cout << *( b + i ) << '\n'; return 0; // indicates successful termination // end main - 16 -

Arrays of Pointers Arrays may contain pointers. Consider the declaration of string array suit that might be useful in representing a deck of cards: const char *suit[ 4 ] = "Hearts", "Diamonds", "Clubs", "Spades" ; The suit[4] portion of the declaration indicates an array of four elements. The const char * portion of the declaration indicates that each element of array suit is of type "pointer to char constant data." The four values to be placed in the array are "Hearts", "Diamonds", "Clubs" and "Spades". Each is stored in memory as a null-terminated character string that is one character longer than the number of characters between quotes. Each pointer points to the first character of its corresponding string. Thus, even though the suit array is fixed in size, it provides access to character strings of any length. - 17 -

sizeof Operators C++ provides the unary operator sizeof to determine the size of an array (or of any other data type, variable or constant) in bytes during program compilation. Eg: unsigned int getsize( double * ); // prototype int main() double array[ 20 ]; // 20 doubles occupies 160 bytes cout << "The number of bytes in the array is " << sizeof( array ); cout << "\nthe number of bytes returned by getsize is " << getsize( array ) << endl; return 0; // indicates successful termination // end main unsigned int getsize( double *ptr ) return sizeof( ptr ); - 18 -

Program -1. Write a program to generate and print numbers using random number generation function. #include<iostream.h> #include<stdlib.h> #include<conio.h> void main() for(int counter =1 ; counter <= 20; counter ++) cout<<( 1 + rand()%6); if ( counter % 5==0) cout<<endl; getch(); Output : 6 6 5 5 6 5 1 1 5 3 6 6 2 4 2 6 2 3 4 1 Program-2 Write a program to swap two numbers (Use function with pass by reference parameters) #include<iostream.h> #include<conio.h> Void swap(float &,float &); void main() float a,b; cout<< Enter the first value: <<endl; cin>>a; cout<< Enter the Second value: <<endl; cin>>b; - 19 -

swap(a,b); cout<< a= <<a<< b= <<b<<endl; getch(); void swap(float& x,float& y) float temp=x; x=y; y=temp; Program -3. Write C++ program computes the volume of a box.use a function with default arguments for length,width, and height. #include<iostream.h> int boxvolume(int length=1,int width=1,int height=1); int main() cout<< The default box volume is : <<boxvolume(); cout<< \n\n The volume of a box with length 10 \n << width 1 and height 1 is : <<boxvolume(10); cout<< \n\n The volume of a box with length 10 \n << width 5 and height 1 is : <<boxvolume(10,5); cout<< \n\n The volume of a box with length 10 \n << width 5 and height 2 is : <<boxvolume(10,5,2)<<endl; return 0; int boxvolume(int length,int width,int height) return length*width*height; Ouput: The default box volume is : 1 The volume of a box with length 10, Width 1 and height 1 is : 10 The volume of a box with length 10, - 20 -

Width 5 and height 1 is : 50 The volume of a box with length 10, Width 5 and height 2 is : 100 Program -4 Write C++ program to find the square of a number, integer or double.use overloaded function. #include<iostream.h> #include<conio.h> int square(int x) cout<< square of integer <<x<< is ; return x*x; double square(double y) cout<< square of double <<y<< is ; return y*y; void main() cout<<square(7); cout<<endl; cout<<square(7.5); cout<<endl; getch(); Output: Square of integer 7 is 49 Square of double 7.5 is 56.25-21 -

Program -5. Write C++ program to print the factorial of numbers from 0 to 10 using recursive function. #include<iostream.h> #include<conio.h> long factorial( long); void main() for(int i=0; i <= 10;i ++) cout<<i<<!= <<factorial(i)<<endl; getch(); long factorial(long number) if(number<=1) return 1; else return number*factorial(number-1); // end function factorial Output: 0! = 1 1! = 1 2! = 2 3! = 6 4! = 24 5! = 120 6! = 720 7! = 5040 8! = 40320 9! = 362880 10! = 3628800-22 -

Program -6. Write C++ program to find the sum of the elements in a given array. Also find the maximum and minimum among the elements. #include<iostream.h> #include<conio.h> void main() int a[20]; int n,sum=0; cout<< \nenter the size of array ; cin>>n; cout<< \nenter the elements ; for(int i=0;i<n;i++) cin>>a[i]; sum+=a[i]; int max,min; max=min=a[0]; for(i=0;i<n;i++) if(a[i]>max) max=a[i]; if(a[i]<min) min=a[i]; cout<< Sum of array elements: <<sum<<endl; cout<< Maximum : <<max<<endl; cout<< Minimum : <<min<<endl; getch(); - 23 -