Functions Chapter 5. Function A set of instructions that are designed to perform specific task. A complete and independent program. It is executed by.

Slides:



Advertisements
Similar presentations
Etter/Ingber Engineering Problem Solving with C Fundamental Concepts Chapter 4 Modular Programming with Functions.
Advertisements

Spring Semester 2013 Lecture 5
Functions in C++. Functions  Groups a number of program statements into a unit & gives it a name.  Is a complete and independent program.  Divides.
Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
Chapter 7: User-Defined Functions II Instructor: Mohammad Mojaddam.
Lecture 2 Introduction to C Programming
1 CS 161 Introduction to Programming and Problem Solving Chapter 9 C++ Program Components Herbert G. Mayer, PSU Status 10/20/2014.
Introduction to C Programming
 2006 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
Structure of a C program
C Programming Language 4 Developed in 1972 by Dennis Ritchie at AT&T Bell Laboratories 4 Used to rewrite the UNIX operating system 4 Widely used on UNIX.
CS1061 C Programming Lecture 2: A Few Simple Programs A. O’Riordan, 2004.
ספטמבר 04Copyright Meir Kalech1 C programming Language Chapter 3: Functions.
 2007 Pearson Education, Inc. All rights reserved Introduction to C Programming.
1 Key Concepts:  Why C?  Life Cycle Of a C program,  What is a computer program?  A program statement?  Basic parts of a C program,  Printf() function?
CS 201 Functions Debzani Deb.
Guide To UNIX Using Linux Third Edition
Introduction to C Programming
Chapter 3: Introduction to C Programming Language C development environment A simple program example Characters and tokens Structure of a C program –comment.
Program A computer program (also software, or just a program) is a sequence of instructions written in a sequence to perform a specified task with a computer.
Lecture 5: Modular Programming (functions – part 1 BJ Furman 27FEB2012.
 Introduction Introduction  Types of Function Types of Function  Library function Library function  User defined function User defined function 
By: Mr. Baha Hanene Chapter 3. Learning Outcomes We will cover the learning outcome 02 in this chapter i.e. Use basic data-types and input / output in.
Goals of Course Introduction to the programming language C Learn how to program Learn ‘good’ programming practices.
© The McGraw-Hill Companies, 2006 Chapter 4 Implementing methods.
Program A computer program (also software, or just a program) is a sequence of instructions written in a sequence to perform a specified task with a computer.
Copyright © 2012 Pearson Education, Inc. Chapter 6: Functions.
Chapter 06 (Part I) Functions and an Introduction to Recursion.
Week 1 Algorithmization and Programming Languages.
Constants Numeric Constants Integer Constants Floating Point Constants Character Constants Expressions Arithmetic Operators Assignment Operators Relational.
Structure of a C program Preprocessor directive (header file) Program statement } Preprocessor directive Global variable declaration Comments Local variable.
Fundamentals of C and C++ Programming. EEL 3801 – Lotzi Bölöni Sub-Topics  Basic Program Structure  Variables - Types and Declarations  Basic Program.
Java™ How to Program, 10/e © Copyright by Pearson Education, Inc. All Rights Reserved.
Built-In and user-Defined functions Software Design Concepts Lecture IV Dr. Sothy Vignarajah.
1 Remember: Examination is a chance not ability. By ILTAF MEHDI, IT LECTURER, MIHE, KATR-E-PARWAN BRANCH, KABUL.
Engineering Problem Solving with C Fundamental Concepts Chapter 4 Modular Programming with Functions.
Chapter 6 Functions 6.1 Modular Design A valuable strategy when writing complex programs is to break down the program into several smaller modules. A module.
Principles of Programming - NI Chapter 6: Function In this chapter, you will learn about Introduction to function User define function Function prototype.
CSC141 Introduction to Computer Programming Teacher: AHMED MUMTAZ MUSTEHSAN Lecture - 6.
Chapter 3 Top-Down Design with Functions Part II J. H. Wang ( 王正豪 ), Ph. D. Assistant Professor Dept. Computer Science and Information Engineering National.
CSCI 3133 Programming with C Instructor: Bindra Shrestha University of Houston – Clear Lake.
Lecture 10: Modular Programming (functions) B Burlingame 13 April 2015.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 6: User-Defined Functions I.
Chapter Functions 6. Modular Programming 6.1 Modular Programming Modular programming: breaking a program up into smaller, manageable functions or modules.
Functions Math library functions Function definition Function invocation Argument passing Scope of an variable Programming 1 DCT 1033.
 2008 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
Functions  A Function is a self contained block of one or more statements or a sub program which is designed for a particular task is called functions.
Course Title Object Oriented Programming with C++ instructor ADEEL ANJUM Chapter No: 06 FUNCTIONS 1 BY ADEEL ANJUM (MSc-cs, CCNA,WEB DEVELOPER) 1.
1 ICS103 Programming in C Lecture 8: Functions I.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 6: User-Defined Functions I.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 6: Functions.
© Oxford University Press All rights reserved. CHAPTER 10 THE PREPROCESSOR DIRECTIVE.
FUNCTIONS. Midterm questions (1-10) review 1. Every line in a C program should end with a semicolon. 2. In C language lowercase letters are significant.
Lecture 4 – Function (Part 1) FTMK, UTeM – Sem /2014.
Programming Fundamentals Enumerations and Functions.
Functions Skill Area 314 Part B. Lecture Overview Functions Function Prototypes Function Definitions Local Variables Global Variables Default Parameters.
Sudeshna Sarkar, IIT Kharagpur 1 Programming and Data Structure Sudeshna Sarkar Lecture 3.
User-Written Functions
C-language Lecture By B.S.S.Tejesh, S.Neeraja Asst.Prof.
User-Defined Functions
Chapter 3 Introduction to Classes, Objects Methods and Strings
Chapter 4 void Functions
6 Chapter Functions.
Introduction to Classes and Objects
C Programming Getting started Variables Basic C operators Conditionals
In C Programming Language
Course Outcomes of Programming In C (PIC) (17212, C203):
CPS125.
Getting Started With Coding
Presentation transcript:

Functions Chapter 5

Function A set of instructions that are designed to perform specific task. A complete and independent program. It is executed by the main function or any other function of the program to perform its task. Functions are identified by name and can return a single value. We need to tell the compiler the name of our function, what parameters it has, and the type of information it returns

What Do Function Do? Avoid unnecessary repetition – In large programs, one often has to execute a piece of code several times. Instead of writing the code several times, the code is written only once as a function and this function is called to execute it code. Program Organization – If the operation of a program could be divided into separate activities, and each activity placed in a separate subroutine, then each subroutine could be written and checked out more or less independently. Separating the code into modular functions also made programs easier to design and understand. Independence – There is an advantage in making subroutines as independent from the main program and from one another as possible. For instance, subroutines were invented that had their own "private" variables; that is variables that could not be accessed from the main program or the other subroutine. This meant that a programmer did not need to worry about accidentally using the same variable names in different subroutines; the variables in each subroutine were protected from inadvertent tampering by other subroutines.

Structure of Function Functions are of two types 1.Built-in functions Already defined as a part of the language and can be used in any program i.e. getch(), clrscr() 2.User defined functions Created by a user Program to perform specific task Structure of User define Function 1.Function Declaration(Prototype) 2.Function Definition 3.Function Calling

Function Declaration (PROTOTYPE) The function declaration is also called Prototype. Prototype means sample or model Only provide the model of the function In function declaration, the following information about the function is provided to compiler – Name of function – Type of data returned by the function – The number and types of arguments or parameters used in the function Semi colon indicate the end of function declaration void line(void); int Sum( int, int ); The prototype is written before the main ( ) function, This causes the prototype to be visible to all the functions in a file.

Function Definition The function itself is referred to as the function definition. The set of instructions that are written to perform a specific task Function definition is always outside the main() function. Can be written before or after the main() function but main () will be executed first Can be written in the separate file and include in the program by using #include directive Function definition consists of two parts – Declarator – Body of Function

Function Definition Declarator – Heading line function definition – Same as function declaration but it is not terminated by the semicolon(;) Body of Function – The set of statements enclosed in braces after the declaration are called the body of the function – The statement in the body of function performed specific task /* Function definition- Draw Line at the Screen*/ void line(void) { int j; for (j=1;j<=11;j++) printf("\xDB"); printf("\n"); }

Calling a Function Executing the statements of a function to perform a task is calling of the function The parentheses lets the compiler know that you are referring to a function and not to a variable or some thing else. e.g. prinf(), getch(), line() This function call causes control to be transferred to the code in the definition of the line(). This function execute the written statements in the function, and then returns to the main (), to the statement immediately following the function call.

Simple Function #include void line(void); /*Prototype of function line() */ void main (void) { clrscr(); line(); printf("\xDB Turbo C \xDB\n"); line(); getch(); } /* Function defination- Draw Line at the Screen*/ void line(void) { int j; for (j=1;j<=11;j++) printf("\xDB"); printf("\n"); }

Local Variables The variables that are declared inside the main function or inside any user-defined function are called local variables The lifetime of a variable is the time period between the creation and destruction of the variable. When the control is transferred to a function, the local variables or variables declared inside that function are automatically created and they occupy memory spaces to store data. When the control returns to the calling function, the variables of that function are destroyed and their data is lost Thus, Local variables can only be accessed from within the function in which they are declared. They are not available outside that function printf(“%d”,j); /*what happened, if this statement used in main()*/

A Sound Example This program uses the special character ‘\x7‘, which is called BELL in the standard ASCII code. On the PC, printing this character, instead of ringing a bell, causes a beeping sound. void beep (void) ; void main (void) { beep ( ) ; } void beep (void) { long count ; printf ( “ \x7 “) ; delay ( ) ; /* delay in mili-seconds*/ printf ( “ \x7 “ ) ; }

Delay function The delay function suspends execution for interval (milliseconds). With a call to delay, the current program is suspended from execution for the time specified by the argument milliseconds. void delay ( unsigned milliseconds ) ; For(j=1;j<100000;j++) /*delay*/ ; /*null statement*/

Functions that Return a Value A function that perform some function and returns a value. Similar like getche() - returns the value of the first character typed on the keyboard.

/* Implementation of lower case character using function */ char getlc (void) ; void main (void) { char chlc; printf ( “ Type ‘a’ for the selection, ‘b’ for the second: “ ) ; chlc = getlc ( ) ; switch ( chlc ) { case ‘ a ’ : printf (“ \n You typed an ‘ a ‘.“ ) ; break; case ‘ b ’ : printf (“ \n You typed a ‘ b ‘.“ ) ; break; default : printf (“ \n Non-existent selection.“ ) ; } getch ( ); } char getlc (void) { char ch; ch = getche ( ) ; if ( ch > 64 && ch < 91 ) ch = ch + 32 ; return ( ch ) ; } Output: Type ‘a’ for the selection, ‘b’ for the second: a You typed an ‘ a ‘. Type ‘a’ for the selection, ‘b’ for the second: A You typed an ‘ a ‘. Type ‘a’ for the selection, ‘b’ for the second: c You chose a non-existent selection.

The return Statement The return() statement has 2 purposes. 1.Executing it immediately transfer control from the function back to the calling program, 2.whatever is inside the parentheses following return is returned as a value to the calling program. The return() statement need not to be at the end of the function. It can occur anywhere in the function; as soon as it is encountered, control will return to the calling program. char getlc (void) { char ch; ch = getche ( ) ; if ( ch > 64 && ch < 91 ) return (ch + 32) ; else return ( ch ) ; }

Limitation of return ( ) statement Can only use it to return one value by a function.

Using Argument to pass data to a Function The mechanism used to convey information to a function is the argument. The argument in the calling program is referred to as the “Actual Argument”, while the argument in the called function is the “Formal Argument”. For example: printf() and scanf() functions; – the format strings and the values used inside the parentheses in these function are arguments.

Bar Graph Example /* Draws Bar-graph and Implementation of Function Arguments */ void bar ( int ) ; void main (void) { printf (“ Ali \t “) ; bar (10) ; printf (“ Babar \t “); bar (15) ; printf (“ Faraz \t “) ; bar (20) ; getch ( ); } void bar (int score) { int count ; for ( count =1 ; count < = score ; count ++ ) printf ( “ \xCD “ ) ; /*Draw double line*/ printf ( “ \n “ ) ; } Output: Ali ========== Babar =============== Faraz ====================

External Variable Variables that are declared outside the main() or any other function are called Global variables or External variables. /* Implementation of External Variables */ void oddeven ( void ) ; /* Function Prototype */ void negative ( void ) ; int keynum; /* External Variables */ void main (void) { printf ( “ Type Keynum: “ ) ; scanf ( “ %d ”, &keynum ) ; oddeven ( ); /* Function Call */ negative ( ); }

Preprocessor Directives Are the instructions to the compiler itself, Rather than being translated into machine language Preprocessor directives are instructions to the compiler. Preprocessor directives always start with a number # sign. The directives can be placed anywhere in a program, but are often used at the beginning of a file, before main (), or before the beginning of particular functions.

Example /* Implementation of define directive */ # define PI float area ( float ) ; /* Function Prototype */ void main (void) { float radius ; printf ( “ Enter radius of the sphere: “ ) ; scanf ( “ %f ”, &radius ) ; printf ( “ Area of the sphere is %.2f “, area (radius) ); } float area ( float rad ) { return ( 4 * PI * rad * rad ) ; }

Macros The additional power comes from # define is the ability to use arguments. A # define directive can take arguments, much as a function does. A Macro generates more code but executes more quickly than a functions. # define PR ( n ) printf ( “ %.2f \n “, n ) ; /* macro definition */ void main (void) { float num1 = ; float num2 ; num2 = 5.0 / 2.5 ; PR ( num1 ) ; PR ( num2 ) ; }

#include Directives The # include directive causes one source file to be included in another. Instead of having to rewrite all the macro every time you wrote a program that used them, you could insert them into the.cpp source file using the # include directive /* Implementation of the # include directive */ # include # include " c:\ tc\bin\ my.h " void main ( void ) { int a, b, ans = 0 ; printf ( " Enter any two numbers: \n " ) ; scanf ( " %d %d ", &a, &b ) ; mul ( a, b ) ; } /* Implementation header file my.h */ void mul ( int, int ) ; void mul ( int aa, int bb ) { int ans ; ans = aa * bb ; printf ( " Answer = %d ", ans ) ; }

#include Directives Two ways to include header files 1.The variation shown above # include ”my.h” shows the file name surrounded by quotes. This causes the preprocess or to start searching for the file in the directory containing the current source file. 2.The other approach is to use angle brackets # include. This format causes the preprocessor to start searching in the standard header directory.

Standard Header Files Each library function provided with Turbo C is associated with a header file: that is, – a file with the extension.h that is kept in the \ INCLUDE directory. – The prototype for the function is part of the corresponding header file.

Lab Write a program that prints out the larger of two numbers. Use a function to do the actual comparison of the two numbers. Pass the two numbers to the function as arguments and have the function return the answer with return() Implement the above function in separate header file and include in main program