Eastern Mediterranean University School of Computing and Technology Information Technology Lecture2 Functions

Similar documents
CS1150 Principles of Computer Science Methods

Lab 4. Name: Checked: Objectives:

Lab 1 - Calculator. K&R All of Chapter 1, 7.4, and Appendix B1.2

LAB 7 (June 29/July 4) Structures, Stream I/O, Self-referential structures (Linked list) in C

INSTALLING CCRQINVOICE

CS1150 Principles of Computer Science Introduction (Part II)

Lab 1 - Calculator. K&R All of Chapter 1, 7.4, and Appendix B1.2 Iterative Code Design handout Style Guidelines handout

CS1150 Principles of Computer Science Midterm Review

CS1150 Principles of Computer Science Methods

COP2800 Homework #3 Assignment Spring 2013

DECISION CONTROL CONSTRUCTS IN JAVA

CS1150 Principles of Computer Science Loops

Test Pilot User Guide

C++ Reference Material Programming Style Conventions

CS1150 Principles of Computer Science Boolean, Selection Statements (Part II)

Adverse Action Letters

Faculty Textbook Adoption Instructions

Project #1 - Fraction Calculator

Laboratory #13: Trigger

1 Version Spaces. CS 478 Homework 1 SOLUTION

TRAINING GUIDE. Overview of Lucity Spatial

Chapter-10 INHERITANCE

Assignment #5: Rootkit. ECE 650 Fall 2018

Using SPLAY Tree s for state-full packet classification

Web of Science Institutional authored and cited papers

Eastern Mediterranean University School of Computing and Technology Information Technology Lecture3 Arrays

Reading and writing data in files

The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL

Technical Paper. Installing and Configuring SAS Environment Manager in a SAS Grid Environment with a Shared Configuration Directory

Getting Started with the Web Designer Suite

Iteration Part 2. Review: Iteration [Part 1] Flow charts for two loop constructs. Review: Syntax of loops. while continuation_condition : statement1

The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL

CS1150 Principles of Computer Science Introduction

ROCK-POND REPORTING 2.1

Municode Website Instructions

UiPath Automation. Walkthrough. Walkthrough Calculate Client Security Hash

Because of security on the site, you cannot create a bookmark through the usual means. In order to create a bookmark that will work consistently:


$ARCSIGHT_HOME/current/user/agent/map. The files are named in sequential order such as:

Systems & Operating Systems

CISC-103: Web Applications using Computer Science

Lab 0: Compiling, Running, and Debugging

1 Binary Trees and Adaptive Data Compression

Dashboard Extension for Enterprise Architect

- Replacement of a single statement with a sequence of statements(promotes regularity)

ClassFlow Administrator User Guide

Importing data. Import file format

CSE 361S Intro to Systems Software Lab #2

Preparation: Follow the instructions on the course website to install Java JDK and jgrasp on your laptop.

CS5530 Mobile/Wireless Systems Swift

Data Structure Interview Questions

Using the Swiftpage Connect List Manager

Computer Organization and Architecture

UiPath Automation. Walkthrough. Walkthrough Calculate Client Security Hash

Report Writing Guidelines Writing Support Services

Relius Documents ASP Checklist Entry

EASTERN ARIZONA COLLEGE Java Programming I

CS1150 Principles of Computer Science Final Review

Interfacing to MATLAB. You can download the interface developed in this tutorial. It exists as a collection of 3 MATLAB files.

Overview of OPC Alarms and Events

Proper Document Usage and Document Distribution. TIP! How to Use the Guide. Managing the News Page

Programming Project: Building a Web Server

MyUni Adding Content. Date: 29 May 2014 TRIM Reference: D2013/ Version: 1

Workflow Exception Routing for edocs

SUB-USER ADMINISTRATION HELP GUIDE

Xilinx Answer Xilinx PCI Express DMA Drivers and Software Guide

Ascii Art Capstone project in C

The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL

Structure Query Language (SQL)

These tasks can now be performed by a special program called FTP clients.

Integrating QuickBooks with TimePro

Configuring Database & SQL Query Monitoring With Sentry-go Quick & Plus! monitors

McGill University School of Computer Science COMP-206. Software Systems. Due: September 29, 2008 on WEB CT at 23:55.

TaiRox Mail Merge. Running Mail Merge

The following screens show some of the extra features provided by the Extended Order Entry screen:

Update: Users are updated when their information changes (examples: Job Title or Department). o

MATH PRACTICE EXAM 2 (Sections 2.6, , )

Using the Swiftpage Connect List Manager

Uploading Files with Multiple Loans

PAGE NAMING STRATEGIES

Quick Start Guide. Basic Concepts. DemoPad Designer - Quick Start Guide

MediaTek LinkIt Development Platform for RTOS Memory Layout Developer's Guide

Project 4: System Calls 1

CS1150 Principles of Computer Science Boolean, Selection Statements (Part II)

D e s i g n S c r i p t L a n g u a g e S u m m a r y P a g e 1

DesignScript summary:

CSCI L Topics in Computing Fall 2018 Web Page Project 50 points

MIPS Architecture and Assembly Language Overview

The Java if statement is used to test the condition. It checks Boolean condition: true or false. There are various types of if statement in java.

Please contact technical support if you have questions about the directory that your organization uses for user management.

Using the Turnpike Materials ProjectSolveSP System (Materials & ProjectSolveSP Admin)

CLIC ADMIN USER S GUIDE

InformationNOW Elementary Scheduling

Technical Paper. Installing and Configuring SAS Environment Manager in a SAS Grid Environment

Master Calendar Navigation

Populate and Extract Data from Your Database

The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL

WordPress Overview for School Webmasters

Using CppSim to Generate Neural Network Modules in Simulink using the simulink_neural_net_gen command

SOLA and Lifecycle Manager Integration Guide

Transcription:

Eastern Mediterranean University Schl f Cmputing and Technlgy Infrmatin Technlgy Lecture2 Functins User Defined Functins Why d we need functins? T make yur prgram readable and rganized T reduce repeated cde Define a functins nce and re use everywhere yu want. This will save yu frm sme time. In ther wrds, a C prgram can be mdularized via the sensible use f prgrammer-defined functins. In general, mdular prgrams are far easier t write and debug than mnlithic prgrams. C als allws prgrammers t define their wn functins. The use f prgrammer-defined functins permits a large prgram t be brken dwn int a number f smaller, self-cntained units. Functins: A functin is a self-cntained prgram segment that carries ut sme specific, well-defined task. Every C prgram cnsists f ne r mre functins. One f these functins must be called main. Executin f the prgram always begins by carrying ut the instructins cntained in main. The same functin can be accessed frm several different places within a prgram. Once the functin has carried ut its intended actin, cntrl is returned t the pint frm which the functin was accessed. Functin prcesses infrmatin passed t it frm the calling prtin f the prgram, and returns a single value. This is the same definitin f functins in mathematics. (fr each x in X there exist y in Y such that f(x)= y ). A functin in C language is a blck f cde that perfrms a specific task. It has a name and it is reusable i.e. it can be executed frm as many different parts in a C prgram as required. It als, ptinally, returns a value t the calling prgram. Sme functins, hwever, accept infrmatin but d nt return anything. 1

S functin in a C prgram has sme prperties as discussed belw. Every functin has a unique name. This name is used: t be called frm main () functin. A functin can be called frm within anther functin. (Functin can call anther functin, r even can call itself (recursive). Remember that a C prgram must has at least ne functin called main (). A functin is independent and it can perfrm its task withut interventin frm r interfering with ther parts f the prgram. A functin perfrms a specific task. A task is a distinct jb that yur prgram must perfrm as a part f its verall peratin, such as adding tw r mre integer, srting an array int numerical rder, r calculating a cube rt etc. A functin returns a value t the calling prgram. This is ptinal and depends upn the task yur functin is ging t accmplish. Suppse yu want t just shw few lines thrugh functin, then it is nt necessary t return a value (as an example: a functin which prints string f characters nly as a heading). But if yu are calculating area f rectangle as an example, and wanted t use result smewhere in prgram, then yu have t send back (return) value t the calling functin. Nte that: Yu cannt imagine a C prgram withut functin. Structure f a Functin A general frm f a C functin lks like this: <return type> FunctinName (Argument1, Argument2, Argument3 ) Statement1; Statement2; Statement3; return value; return (value); r may be withut return statement (sme times) 2

User defined functins can be categrized as: Functin with n arguments and n return value Functin with n arguments and a return value Functin with arguments and n return value Functin with arguments and a return value When d we need functin prttype? Mst C prgrammers prefer t place the main() functin at the beginning f their prgrams. After all, main() is always the first part f a prgram t be executed. I recmmend yu t use this methd ( First place main functin then fllw all the functins after the main, and yu shuld apply the requirement as defined belw In such situatins, functin calls [within main()] are bund t precede the crrespnding functin definitins: frtunately, hwever, cmpilatin errrs can be avided by using a cnstruct knwn as a functin prttype. Functin prttypes are cnventinally placed at the beginning f a prgram (i.e., befre the main() functin) and are used t infrm the cmpiler f the name, data type, and number and data types f the arguments, f all userdefined functins emplyed in the prgram. The general frm f a functin prttype is data-type name(type 1, type 2,..., type n); ntice that semicln (;) must be cded as shwn abve in functin prttype where data-type represents the data type f the item returned by the referenced functin, name is the name f the functin, and type 1, type 2,..., type n are the data types f the arguments f the functin. Als, nte that it is nt necessary t specify the names f the arguments in a functin prttype. As an example: the functin prttype statement fr factrial functin can be written as: duble factrial ( int ); instead f duble factrial( int n); 3

Functins with n type. The use f vid What if we want t return n value? Imagine that we want t make a functin just t shw a message n the screen. We d nt need it t return any value. In this case we shuld use the vid type specifier fr the functin. This is a special specifier that indicates absence f type. vid printmessage;//func. prttype vid main () printmessage (); vid printmessage () printf("i'm a functin!"); The Arguments Argument1, Argument2, Argument3 are declared as: Type1 argument1, Type2 argument 2, Type 3 argument 3,..an s n. Example: int a, flat b, char d, int e; and s n. Ntice that cmma (,) must used t separate arguments and nt semicln (;). Functin Call: A functin can be accessed, r called, by specifying its name, fllwed by a list f arguments enclsed in parentheses and separated by cmmas. Nte that when yu call functin frm main then yu shuld nt include the type f the arguments. This mean that if yur functin declaratin is as fllws: int myfuncin(int A, flat B) then the call statement in main as fllws (as an example): 4

C= myfuncin(a,b); r as fllws: printf(" the value f C = %.3f\n", myfuncin(a,b)); If the functin call (call statement in main) des nt require any arguments then an empty pair f parentheses must fllw the name f the functin, as an example: func1 ( ). fr passing the value f an argument t a functin is called passing by value Example: int sum (int x, int y) int result; /* result is lcal variable */ result = x + y; return (result); /* r like: return result; */ In the abve: the returned value (result) is f type int, argument x is f type int, and argument y is f type int. Nte that: x and y are integer arguments t functin frm main ( r frm ther Functins). Als, the argument r variable (result) is called lcal variable. This mean that this variable is nly knwn with the functin (sum) defined abve. If main functin r any ther functin called by main has als anther variable with same name as result as an example, then they are ttally different and might have different values. vid main ( ) int x,y,v1; x=40;y=70; v1=sum(x,y); int sum(int k,int d) int R; R=k+d; return R; Value f R will be returned t main ( ) 5

Nte that the identifiers used t reference the arguments f a functin are lcal, in the sense that they are nt recgnized utside f the functin. Return statement: the bdy f the functins must include ne r mre return statements in rder t return a value t the calling prtin f the prgram. If the type f the functin is vid then functin has n return statement. A return statement causes the prgram lgic t return t the pint in the prgram frm which the functin was accessed. The general frm f a return statement is: return expressin; This statement causes the value f expressin t be returned t the calling part f the prgram. Of curse, the data type f expressin shuld match the declared data type f the functin. Fr a vid functin, which des nt return any value, the apprpriate return statement is simply: return; r even, dn t write the statement: return. A maximum f ne expressin can be included in a return statement. Thus, a functin can return a maximum f ne value t the calling part f the prgram. Hwever, a functin definitin can include multiple return statements, each cntaining a different expressin, which is cnditinally executed, depending n the prgram lgic. Example: int additin (int a, int b) int r; r=a+b; return (r); int main () int z; z = additin (5,3); printf("the result is %d \n",z); return 0; 6

1. Example prgram fr withut arguments & withut return value: In this prgram, n values are passed t the functin test and n values are returned frm this functin t main functin. vid test(); vid main() test(); vid test() int a = 50, b = 80; printf("\nvalues : \na = %d and b = %d\n\n", a, b); Output: values : a = 50 and b = 80 2. Example prgram fr withut arguments & with return value: In this prgram, n arguments are passed t the functin sum. But, values are returned frm this functin t main functin. Values f the variable a and b are summed up in the functin sum and the sum f these value is returned t the main functin. int sum(); vid main() int additin; additin = sum(); printf("\nsum f tw given values = %d\n\n", additin); int sum() int a = 50, b = 80; return a+b; Output: Sum f tw given values = 130 7

3. Example prgram fr with arguments & with return value: The value f m is passed as argument t the functin square. This value is multiplied by itself in this functin and multiplied value p is returned t main functin frm functin square. flat square ( flat x ); vid main( ) flat m ; printf ( "\nenter sme number fr finding square : "); scanf ( "%f", &m ) ; printf ( "\nsquare f the given number %.2f is %.2f\n\n",m,square(m) ); flat square ( flat x ) return x*x ; Output: Enter sme number fr finding square : 2 Square f the given number 2.00 is 4.00 4. Call by value: In call by value methd, the value f the variable is passed t the functin as parameter. The value f the actual parameter can nt be mdified by frmal parameter. Different Memry is allcated fr bth actual and frmal parameters. Because, value f actual parameter is cpied t frmal parameter. Nte: Actual parameter This is the argument which is used in functin call. Frmal parameter This is the argument which is used in functin definitin Example prgram fr C functin (using call by value): In this prgram, the values f the variables m and n are passed t the functin swap. These values are cpied t frmal parameters a and b in swap functin and used. vid swap(int a, int b); vid main() int m = 22, n = 44; printf("\nvalues befre swap m = %d nand n = %d\n", m, n); swap(m, n); vid swap(int a, int b) int tmp; tmp = a; 8

Output: a = b; b = tmp; printf("\nvalues after swap m = %d and n = %d\n\n", a, b); values befre swap m = 22 and n = 44 values after swap m = 44 and n = 22 5. Call by reference: In call by reference methd, the address f the variable is passed t the functin as parameter. The value f the actual parameter can be mdified by frmal parameter. Same memry is used fr bth actual and frmal parameters since nly address is used by bth parameters. Example prgram fr C functin (using call by reference): In this prgram, the address f the variables m and n are passed t the functin swap. These values are nt cpied t frmal parameters a and b in swap functin. Because, they are just hlding the address f thse variables. This address is used t access and change the values f the variables. vid swap(int &a, int &b); vid main() int m = 22, n = 44; printf("\nvalues befre swap m = %d and n = %d\n",m,n); swap(m, n); printf("\nvalues after swap a = %d nand b = %d\n\n",m,n); vid swap(int &a, int &b) int tmp; tmp = a; a = b; b = tmp; Output: values befre swap m = 22 and n = 44 values after swap a = 44 and b = 22 9

Randm Functin Generate randm number. It returns an integer value in the range between 0 and RAND_MAX Syntax: rand()% ttal number in the range + first number Ex: a in the range 12 t 25 a = rand() % (25-12+1) + 12 v1 = rand() % 100; // v1 in the range 0 t 99 v2 = rand() % 100 + 1; // v2 in the range 1 t 100 v3 = rand() % 30 + 1985; // v3 in the range 1985-2014 10