Chapter 5 C Functions

Size: px
Start display at page:

Download "Chapter 5 C Functions"

Transcription

1 Chapter 5 C Functions

2 Objectives of this chapter: To construct programs from small pieces called functions. Common math functions in math.h the C Standard Library. sin( ), cos( ), tan( ), atan( ), sqrt( ) and pow(, ) To create new functions. The mechanisms used to pass information between functions. Simulation techniques using random number generation. rand(), srand( ) and time(null) Recursive Functions: How to write and use functions that call themselves.

3 Introduction to Functions/Modules Most of the complicated programs are formed from piece of function/modules. Function are helpful in organization of large programs. Functions help us to write the programs in easier way Making maintenance and modification/debugging easier manageable Helps us to organize the program in a better way Most importantly increases the mobility of the program avoid repetitions In this chapter, you will learn Some of the available functions available in C Libraries Also you will learn how to write a function Creating your own library file.h files

4 Program Modules in C Modules in C programming are called functions Piece of program that accomplishes a specific task Combination of these modules are the C libraries (stdio.h conio.h) We have been using functions as much as we need from the first day of writing program as an example: scanf printf getch Even main() is a function, but it is the main function There are many more functions prepackaged in C libraries to be used by the programmers (called Library Files or Header Files)

5 Daily Life Example to Concept of Functions A function can be called by as many times as needed. The function accomplish the task then return feedback or not. Good analogy to functions is hierarchal form of management Page 174

6 As an engineer we deal with mathematical calculations. Math Library (math.h) includes many mathematical operational functions. sin( ), cos( ), tan( ), sin( ), atan( ), sqrt( ) and pow(, ) Example: Square Root Function (sqrt) printf( %.2f,sqrt(900.0)); ==> 30.0 Page 174 Many more functions are available under Math Library.

7 Commonly used mathematical operations included in Math Library Page 174 * Trigonometric functions works in Radians 2π Radian = 360 Degree

8 Example: Pythagorean Theorem Write a C program which takes the components of a two dimensional vector then prints out the magnitude and direction of the vector. (you may use π= )

9 All programs include a main program also called main function. Page 176 Functions are defined to be called by main program or other functions. Functions are called by their names by the caller. Example: Program Writes to Screen Programming is fun! #include <stdio.h> void printmessage(void); /*** function prototype ***/ int main (void) { /***Main Program Starts ***/ printmessage(); // Calling function by it s name } /***Main Program Ends ***/ void printmessage(void){ /*** Function Starts ***/ printf( Programming is fun! ); } /*** Function Ends ***/

10 General Form of Function Definitions A function in C has the following form Page 176 return value type function_name (parameter list) { definitions statements } Functions with no return value are also called void functions. Note: Parameter list also referred as argument input values Example: Some function prototypes void prnt( void ); // Receives nothing and returns nothing void prnt( int x ); // Receives an integer and returns nothing int cube( int a); // Receives one int variable and returns int int findmax ( int a, int b); // Receives two int variables and returns int float area ( int radious); // Receives one float variable and returns float And many other function can be created for any purpose.

11 Page 176 Example: Write a program that uses a function called square to take the square of an integer number and prints the squares of the numbers from 1 to 10.

12 Example: Pythagorean Theorem Rewrite the C program which takes the components of a two dimensional vector then prints out the magnitude and direction of the vector. In this program define a function that calculate the magnitude and define another one that calculates the direction.

13 Example: Maximum of Three Integer Numbers Page 179 Write a C program that find the maximum of three integer values. In the program define a function that accepts three integer parameters then returns the maximum of the three numbers.

14 Page 183 Each standard library has a corresponding header containing the function prototypes this prototypes explains to the compiler parameters to be entered and return values for specific function. In other words, header files hold the prepackaged functions. Example: Standard Input/Output Library header file is stdio.h also conio.h stdlib.h There are many more C standard library headers.

15 In order to use the functions defined in these libraries, we need to include them at the beginning of the program with the statement #include<library_name.h> Page 184

16 Can we make our own header file? like mine.h We can make our custom headers. Put the functions to be included in your library into a text file. Save the file as mine.h then we are ready to go We can call these functions from any program after including #include mine.h if mine.h is placed into the same directory #include <mine.h> if it mine.h placed into standard library directory

17 There are two ways to invoke functions in many programming languages CALL BY VALUE: Argument passed to variable as a value, so the function can t change the value of the argument. In this method, the function creates a copy of the variable and even if you change this variable, the argument passed to function remains the same. CALL BY REFERENCE: Argument passed as reference (as like memory address), in this method the function can change the value of the argument. This way only should be used on trusted functions. Page 185 So far we have used call by value method to pass argument to function and for now we will stick with this. We will learn the second method when we study Pointers in Chapter 7 so then the function can also change the sent value if needed.

18 Example: Call By Value Calling a Function by a Value What will be the output of the following program when executed?*

19 Example: Factorial Function Write a program that lists the factorial of even number starting from 2 to 12 in a tabular form. In your program define a fact( ) function that takes an integer as argument then determines and return the factorial of the argument. Below is the output of the program when executed:

20 Page 219

21 Page 219

22 rand() : function is used to generate a random positive integer number. rand() function is hold in stglib.h library file. It generates number within range of 0 to In many games of chance, you might want to guess a number in a range or throw a dice. In such programs rand() function can be used to generate a random number Rolling a dice: A dice has six faces including one of 1, 2, 3, 4, 5, or 6 How can we generate a number within this range? Assume we would like to write a dice program (Hint: Think of using modulus operator.) Page 185

23 Terminal Output Page 185

24 Example : Game of Chance Rolling Dices and Scoring Point Write a C program which throws dices. The program rolls as many as dices we want and prints the results in a tabular form. Furthermore, it reports the points collected (sum of the numbers from each dice). Below is the output of the program when executed: How Many Dices to throw: 4 Dice Face You have scored 22

25 Example : Game of Change Rolling Dice 6000 Times Write a C program which throws dice 6000 times (or throws 6000 dices). Then it determines how frequently (how many times) 1, 2, 3 6 faces appears. Below is the output of the program when executed: Face Frequency Page 186

26 Page 185 rand() : Even though it seems to generates numbers randomly, when you write a program and run it, each time it gives the same sequence of different numbers. So it is not completely random, it works and generates the numbers depending on an algorithm. In order to randomize it we use srand( ); function this will allows us to pick different sequence of numbers to be generated. srand() : Seed Random function is also available under stglib.h and accepts unsigned integer input. 10 numbers generated after srand(5): In order semi fully randomize the program we can use the seeding parameter from the current time on the computer. 10 numbers generated after srand(67): srand(time(null)); time(null) function call produces time available under time.h

27 5.12 Storage Classes: Storage Duration and Scope Rules Identifiers (int, float, char, ) are used to declare variables and functions int a; float pi= ; char c= A ; float square ( float x ); int factorial ( int number ); In C programming, variable identifiers may have other attributes beside the type depending on the way and the place where they are defined. These attributes; Page Storage Class: Used to express the class/category of the variable definition. Automatic variables, static variables, external variables, or variables held in the registers. Storage Duration: The period during which the variable is stored. Variables are created and destroyed in the memory. Local and Global Variables. Scope: The boundaries where the variable can be referenced. Function scope, block scope, or file scope. Linkage: Express the usage of a variable from another file. When compiling multiple files, external variables are used to link variable between files.

28 Storage Classes: auto, register, static, and extern Page Additional four storage class specifiers can be used to control the determine the such properties of the variables. Automatic Variables: auto int a; All variables defined in a function or in the main program are automatic variables by default. They are created in the memory and destroyed at the end. Register Variables: register int a; Normally all variables are held on the memory (RAM). Register variables may be held in the registers of the processor for faster access. If not enough register available then it is held in RAM as like other variables. Static Variables: static int a; Unlike automatic variables, static variables are not destroyed at the end. Especially, when a variable is defined as static variable. This variable is declared only once and kept in RAM with the same memory address. External Variables: extern int a; The variables which is used from a different file when a big program is made in small pieces of program and held in different files. Extern variables can t be changed within a function, only the main function can change the value of an external variable.

29 Local and Global Variables Local Variables: Page These are the variables, which are defined under the main or other under any function. These variables can be referenced within the function or the main. All local variables are normally automatic variables by default. These variables defined under a function are only accessible within the function and the program creates and forget them every time upon completion. Additional Static identifier can be used to define the variable as static variable in a function, which means this variable has a static class storage, it is only defined for one in the first time and it has a specific memory address. Global Variables: These variables are defined at the beginning of the program before the main program. These variables can be accessed from main or from a function if desired. All global variables are static variables by default. Created only once and uses the same memory address all through the program. Using Global variables are not recommended in large programs, because having one variable accessible by many functions may be dangerous and may be cause of some bugs in the program.

30 5.13 Scope Rules Page 196 Scope of an identifier is the portion of program in which the variable can be referenced. In other words, range of visibility of the variable. The following are the commonly known identifier scopes Function Scope: Variables defined in a function has a function scope. They can be only visible within the function. All local variables have a function scope. File Scope: Variables defined outside a functions and main have a file scope. They can be referenced from anywhere in the file/program. Global variables have a file scope. Block Scope: Variables defined within a block a block scope. They can be referenced within the block { } in which they are defined.

31 Example 1: Local Variables What will be the output of the following program; #include<stdio.h> void function (void); int main(){ int x=5,y=3,z; for (z=1;z<=3;z++){ function(); printf("under Main (x,y,z):%d,%d,%d\n",x,y,z);} return 0; } void function(void) { int x=1,y=2,z=3; x++; y++; z++; printf("under Function (x,y,z):%d,%d,%d\n",x,y,z); }

32 Example 2: Local Variables and Using Static Under Function What will be the output of the following program; #include<stdio.h> void function (void); int main(void){ int x=5,y=3,z; for (z=1;z<=3;z++){ function(); printf("under Main (x,y,z):%d,%d,%d\n",x,y,z);} return 0; } void function (void){ static int x=1,y=2; int z=3; x++; y++; z++; printf("under Function (x,y,z):%d,%d,%d\n",x,y,z); }

33 Example 3: Global Variables What will be the output of the following program; #include<stdio.h> int x=1; void function (void); int main(void){ int y=3,z; for (z=1;z<=3;z++){ function(); x+=2; printf("under Main (x,y,z):%d,%d,%d\n",x,y,z);} return 0; } void function (void){ static y=2; int z=3; x++; y++; z++; printf("under Function (x,y,z):%d,%d,%d\n",x,y,z); } *

34 Example: Block Scope What will be the output of the following programs; * See also at Page 197

35 Recursive Functions: A function calls itself is called recursive function. In programming, using recursive functions simplifies task to be accomplished. Each recursive function has recursive relation and a base case. Example: Most common examples are Factorial calculation Fibonacci numbers Also power calculation, even sum of numbers and many more can be done by using recursive functions easily. In order to understand the concept of the recursive functions let s consider common example, the factorial concept from mathematical point of view. 5! = ! = ! = 5. 4! This expression can be generalized as n! = n. (n 1)! called recursive relation. This can be considered as a recursive function: fact (n) = n. fact(n 1) This recursive operation will continue until fact(1) = 1 to the base case.

36 Example: Recursive Function Factorial Calculator Write a recursive function that inputs an integer argument and returns factorial of the number. Below is and output of an example run: Enter a Number: 10 10! Is Note that int has limited upper value, better to use long integer for the numbers.

37 Another most commonly known example to recursive functions is the calculations of Fibonacci numbers. Fibonacci Numbers are defined as below: 0 th Fibonacci Number : Fibonacci (0) = 0 1 th Fibonacci Number : Fibonacci (1) = 1 2 nd Fibonacci Number : Fibonacci (2) = 1 3 rd Fibonacci Number : Fibonacci (3) = 2 4 th Fibonacci Number : Fibonacci (4) = 3 5 th Fibonacci Number : Fibonacci (5) = 5 6 th Fibonacci Number : Fibonacci (6) = 8.. n th Fibonacci Number: Fibonacci (n )= Fibonacci (n 1) + Fibonacci (n 2) Page 202 In conclusion, any Fibonacci number is the sum of two previous Fibonacci numbers. This operation can be considered as recursive function with base value of 1.

38 Example: Recursive Function Fibonacci Number Write a recursive function that inputs an integer argument and returns n th order of Fibonacci number. Below is and output of an example run: Enter an integer: 10 Fibonacci (10) = 55 Note that int has limited upper value, better to use long integer for the numbers in case, high order of Fibonacci numbers are considered.

39 Page 218

40 Page 220

41 Page 221

42 Modified Page 221

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

Functions. Computer System and programming in C Prentice Hall, Inc. All rights reserved. Functions In general, functions are blocks of code that perform a number of pre-defined commands to accomplish something productive. You can either use the built-in library functions or you can create

More information

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

Dr M Kasim A Jalil. Faculty of Mechanical Engineering UTM (source: Deitel Associates & Pearson) Lecture 9 Functions Dr M Kasim A Jalil Faculty of Mechanical Engineering UTM (source: Deitel Associates & Pearson) Objectives In this chapter, you will learn: To understand how to construct programs modularly

More information

C Functions. 5.2 Program Modules in C

C Functions. 5.2 Program Modules in C 1 5 C Functions 5.2 Program Modules in C 2 Functions Modules in C Programs combine user-defined functions with library functions - C standard library has a wide variety of functions Function calls Invoking

More information

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

Functions. Angela Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan. Functions Angela Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan 2009 Fall Outline 5.1 Introduction 5.3 Math Library Functions 5.4 Functions 5.5

More information

Lecture 04 FUNCTIONS AND ARRAYS

Lecture 04 FUNCTIONS AND ARRAYS Lecture 04 FUNCTIONS AND ARRAYS 1 Motivations Divide hug tasks to blocks: divide programs up into sets of cooperating functions. Define new functions with function calls and parameter passing. Use functions

More information

CSE123. Program Design and Modular Programming Functions 1-1

CSE123. Program Design and Modular Programming Functions 1-1 CSE123 Program Design and Modular Programming Functions 1-1 5.1 Introduction A function in C is a small sub-program performs a particular task, supports the concept of modular programming design techniques.

More information

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

Functions in C++ Problem-Solving Procedure With Modular Design C ++ Function Definition: a single Functions in C++ Problem-Solving Procedure With Modular Design: Program development steps: Analyze the problem Develop a solution Code the solution Test/Debug the program C ++ Function Definition: A module

More information

Programming for Engineers Functions

Programming for Engineers Functions Programming for Engineers Functions ICEN 200 Spring 2018 Prof. Dola Saha 1 Introduction Real world problems are larger, more complex Top down approach Modularize divide and control Easier to track smaller

More information

Functions. Systems Programming Concepts

Functions. Systems Programming Concepts Functions Systems Programming Concepts Functions Simple Function Example Function Prototype and Declaration Math Library Functions Function Definition Header Files Random Number Generator Call by Value

More information

Chapter 3 - Functions

Chapter 3 - Functions Chapter 3 - Functions 1 Outline 3.1 Introduction 3.2 Program Components in C++ 3.3 Math Library Functions 3.4 Functions 3.5 Function Definitions 3.6 Function Prototypes 3.7 Header Files 3.8 Random Number

More information

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

BIL 104E Introduction to Scientific and Engineering Computing. Lecture 4 BIL 104E Introduction to Scientific and Engineering Computing Lecture 4 Introduction Divide and Conquer Construct a program from smaller pieces or components These smaller pieces are called modules Functions

More information

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

6-1 (Function). (Function) !*+!#!, Function Description Example. natural logarithm of x (base e) rounds x to smallest integer not less than x (Function) -1.1 Math Library Function!"#! $%&!'(#) preprocessor directive #include !*+!"#!, Function Description Example sqrt(x) square root of x sqrt(900.0) is 30.0 sqrt(9.0) is 3.0 exp(x) log(x)

More information

Lecture 04 FUNCTIONS AND ARRAYS

Lecture 04 FUNCTIONS AND ARRAYS Lecture 04 FUNCTIONS AND ARRAYS 1 Motivations Divide hug tasks to blocks: divide programs up into sets of cooperating functions. Define new functions with function calls and parameter passing. Use functions

More information

Function Call Stack and Activation Records

Function Call Stack and Activation Records 71 Function Call Stack and Activation Records To understand how C performs function calls, we first need to consider a data structure (i.e., collection of related data items) known as a stack. Students

More information

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

Functions. Functions are everywhere in C. Pallab Dasgupta Professor, Dept. of Computer Sc & Engg INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR 1 Functions Functions are everywhere in C Pallab Dasgupta Professor, Dept. of Computer Sc & Engg INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR Introduction Function A self-contained program segment that carries

More information

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

Functions. Prof. Indranil Sen Gupta. Dept. of Computer Science & Engg. Indian Institute t of Technology Kharagpur. Introduction Functions Prof. Indranil Sen Gupta Dept. of Computer Science & Engg. Indian Institute t of Technology Kharagpur Programming and Data Structure 1 Function Introduction A self-contained program segment that

More information

Chapter 4 Functions By C.K. Liang

Chapter 4 Functions By C.K. Liang 1 Chapter 4 Functions By C.K. Liang What you should learn? 2 To construct programs modularly from small pieces called functions Math functions in C standard library Create new functions Pass information

More information

Chapter 3 - Functions

Chapter 3 - Functions Chapter 3 - Functions 1 3.1 Introduction 3.2 Program Components in C++ 3.3 Math Library Functions 3.4 Functions 3.5 Function Definitions 3.6 Function Prototypes 3.7 Header Files 3.8 Random Number Generation

More information

C Functions. CS 2060 Week 4. Prof. Jonathan Ventura

C Functions. CS 2060 Week 4. Prof. Jonathan Ventura CS 2060 Week 4 1 Modularizing Programs Modularizing programs in C Writing custom functions Header files 2 Function Call Stack The function call stack Stack frames 3 Pass-by-value Pass-by-value and pass-by-reference

More information

Functions and Recursion

Functions and Recursion Functions and Recursion 1 Outline Introduction Program Components in C++ Math Library Functions Functions Function Definitions Function Prototypes Header Files Random Number Generation Example: A Game

More information

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

Chapter 3 - Functions. Chapter 3 - Functions. 3.1 Introduction. 3.2 Program Components in C++ Chapter 3 - Functions 1 Chapter 3 - Functions 2 3.1 Introduction 3.2 Program Components in C++ 3.3 Math Library Functions 3. Functions 3.5 Function Definitions 3.6 Function Prototypes 3. Header Files 3.8

More information

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

Computer Programming 5th Week loops (do-while, for), Arrays, array operations, C libraries Computer Programming 5th Week loops (do-while, for), Arrays, array operations, C libraries Hazırlayan Asst. Prof. Dr. Tansu Filik Computer Programming Previously on Bil 200 Low-Level I/O getchar, putchar,

More information

Functions in C C Programming and Software Tools. N.C. State Department of Computer Science

Functions in C C Programming and Software Tools. N.C. State Department of Computer Science Functions in C C Programming and Software Tools N.C. State Department of Computer Science Functions in C Functions are also called subroutines or procedures One part of a program calls (or invokes the

More information

C Functions Pearson Education, Inc. All rights reserved.

C Functions Pearson Education, Inc. All rights reserved. 1 5 C Functions 2 Form ever follows function. Louis Henri Sullivan E pluribus unum. (One composed of many.) Virgil O! call back yesterday, bid time return. William Shakespeare Call me Ishmael. Herman Melville

More information

Lecture 3. Review. CS 141 Lecture 3 By Ziad Kobti -Control Structures Examples -Built-in functions. Conditions: Loops: if( ) / else switch

Lecture 3. Review. CS 141 Lecture 3 By Ziad Kobti -Control Structures Examples -Built-in functions. Conditions: Loops: if( ) / else switch Lecture 3 CS 141 Lecture 3 By Ziad Kobti -Control Structures Examples -Built-in functions Review Conditions: if( ) / else switch Loops: for( ) do...while( ) while( )... 1 Examples Display the first 10

More information

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

Functions. Autumn Semester 2009 Programming and Data Structure 1. Courtsey: University of Pittsburgh-CSD-Khalifa Functions Autumn Semester 2009 Programming and Data Structure 1 Courtsey: University of Pittsburgh-CSD-Khalifa Introduction Function A self-contained program segment that carries out some specific, well-defined

More information

Functions in C C Programming and Software Tools

Functions in C C Programming and Software Tools Functions in C C Programming and Software Tools N.C. State Department of Computer Science Functions in C Functions are also called subroutines or procedures One part of a program calls (or invokes the

More information

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

INTRODUCTION TO C++ FUNCTIONS. Dept. of Electronic Engineering, NCHU. Original slides are from INTRODUCTION TO C++ FUNCTIONS Original slides are from http://sites.google.com/site/progntut/ Dept. of Electronic Engineering, NCHU Outline 2 Functions: Program modules in C Function Definitions Function

More information

Unit 7. Functions. Need of User Defined Functions

Unit 7. Functions. Need of User Defined Functions Unit 7 Functions Functions are the building blocks where every program activity occurs. They are self contained program segments that carry out some specific, well defined task. Every C program must have

More information

ECET 264 C Programming Language with Applications

ECET 264 C Programming Language with Applications ECET 264 C Programming Language with Applications Lecture 10 C Standard Library Functions Paul I. Lin Professor of Electrical & Computer Engineering Technology http://www.etcs.ipfw.edu/~lin Lecture 10

More information

Programming Assignment #4 Arrays and Pointers

Programming Assignment #4 Arrays and Pointers CS-2301, System Programming for Non-majors, B-term 2013 Project 4 (30 points) Assigned: Tuesday, November 19, 2013 Due: Tuesday, November 26, Noon Abstract Programming Assignment #4 Arrays and Pointers

More information

Visual Studio. Visual Studio is an extremely complex interactive development environment capable of handling many languages and tools.

Visual Studio. Visual Studio is an extremely complex interactive development environment capable of handling many languages and tools. Tips and Tricks Topics Visual Studio Handling Output to the Screen Handling Input from the Keyboard Simple Text Menus When to use a For Loop When to use a While Loop Reviewing a Function Visual Studio

More information

Assoc. Prof. Dr. Tansu FİLİK

Assoc. Prof. Dr. Tansu FİLİK Assoc. Prof. Dr. Tansu FİLİK Computer Programming Previously on Bil 200 Midterm Exam - 1 Midterm Exam - 1 126 students Curve: 49,78 Computer Programming Arrays Arrays List of variables: [ ] Computer Programming

More information

C++ PROGRAMMING SKILLS Part 3 User-Defined Functions

C++ PROGRAMMING SKILLS Part 3 User-Defined Functions C++ PROGRAMMING SKILLS Part 3 User-Defined Functions Introduction Function Definition Void function Global Vs Local variables Random Number Generator Recursion Function Overloading Sample Code 1 Functions

More information

AN OVERVIEW OF C, PART 3. CSE 130: Introduction to Programming in C Stony Brook University

AN OVERVIEW OF C, PART 3. CSE 130: Introduction to Programming in C Stony Brook University AN OVERVIEW OF C, PART 3 CSE 130: Introduction to Programming in C Stony Brook University FANCIER OUTPUT FORMATTING Recall that you can insert a text field width value into a printf() format specifier:

More information

Introduction to Programming

Introduction to Programming Introduction to Programming session 9 Instructor: Reza Entezari-Maleki Email: entezari@ce.sharif.edu 1 Fall 2010 These slides are created using Deitel s slides Sahrif University of Technology Outlines

More information

C++ Programming Lecture 11 Functions Part I

C++ Programming Lecture 11 Functions Part I C++ Programming Lecture 11 Functions Part I By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department Introduction Till now we have learned the basic concepts of C++. All the programs

More information

Programming Fundamentals for Engineers Functions. Muntaser Abulafi Yacoub Sabatin Omar Qaraeen. Modular programming.

Programming Fundamentals for Engineers Functions. Muntaser Abulafi Yacoub Sabatin Omar Qaraeen. Modular programming. Programming Fundamentals for Engineers - 0702113 7. Functions Muntaser Abulafi Yacoub Sabatin Omar Qaraeen 1 Modular programming Your program main() function Calls AnotherFunction1() Returns the results

More information

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

C++ How to Program, 9/e by Pearson Education, Inc. All Rights Reserved. C++ How to Program, 9/e 1992-2014 by Pearson Education, Inc. Experience has shown that the best way to develop and maintain a large program is to construct it from small, simple pieces, or components.

More information

Chapter 8: Function. In this chapter, you will learn about

Chapter 8: Function. In this chapter, you will learn about Principles of Programming Chapter 8: Function In this chapter, you will learn about Introduction to function User-defined function Formal and Actual Parameters Parameter passing by value Parameter passing

More information

Introduction to Computers II Lecture 4. Dr Ali Ziya Alkar Dr Mehmet Demirer

Introduction to Computers II Lecture 4. Dr Ali Ziya Alkar Dr Mehmet Demirer Introduction to Computers II Lecture 4 Dr Ali Ziya Alkar Dr Mehmet Demirer 1 Contents: Utilizing the existing information Top-down design Start with the broadest statement of the problem Works down to

More information

Chapter 7 Functions. Now consider a more advanced example:

Chapter 7 Functions. Now consider a more advanced example: Chapter 7 Functions 7.1 Chapter Overview Functions are logical groupings of code, a series of steps, that are given a name. Functions are especially useful when these series of steps will need to be done

More information

C: How to Program. Week /Apr/16

C: How to Program. Week /Apr/16 C: How to Program Week 8 2006/Apr/16 1 Storage class specifiers 5.11 Storage Classes Storage duration how long an object exists in memory Scope where object can be referenced in program Linkage specifies

More information

Objectives of This Chapter

Objectives of This Chapter Chapter 6 C Arrays Objectives of This Chapter Array data structures to represent the set of values. Defining and initializing arrays. Defining symbolic constant in a program. Using arrays to store, list,

More information

Chapter 3 - Functions

Chapter 3 - Functions Chapter 3 - Functions 1 Outline 3.1 Introduction 3.2 Progra m Components in C++ 3.3 Ma th Libra ry Func tions 3.4 Func tions 3.5 Func tion De finitions 3.6 Func tion Prototypes 3.7 He a de r File s 3.8

More information

C Programming for Engineers Functions

C Programming for Engineers Functions C Programming for Engineers Functions ICEN 360 Spring 2017 Prof. Dola Saha 1 Introduction Real world problems are larger, more complex Top down approach Modularize divide and control Easier to track smaller

More information

CSE 2421: Systems I Low-Level Programming and Computer Organization. Functions. Presentation C. Predefined Functions

CSE 2421: Systems I Low-Level Programming and Computer Organization. Functions. Presentation C. Predefined Functions CSE 2421: Systems I Low-Level Programming and Computer Organization Functions Read/Study: Reek Chapters 7 Gojko Babić 01-22-2018 Predefined Functions C comes with libraries of predefined functions E.g.:

More information

C Programming Lecture V

C Programming Lecture V C Programming Lecture V Instructor Özgür ZEYDAN http://cevre.beun.edu.tr/ Modular Programming A function in C is a small sub-program that performs a particular task, and supports the concept of modular

More information

C Tutorial: Part 1. Dr. Charalampos C. Tsimenidis. Newcastle University School of Electrical and Electronic Engineering.

C Tutorial: Part 1. Dr. Charalampos C. Tsimenidis. Newcastle University School of Electrical and Electronic Engineering. C Tutorial: Part 1 Dr. Charalampos C. Tsimenidis Newcastle University School of Electrical and Electronic Engineering September 2013 Why C? Small (32 keywords) Stable Existing code base Fast Low-level

More information

Functions. Introduction :

Functions. Introduction : 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

More information

Functions and Recursion

Functions and Recursion Functions and Recursion CSE 130: Introduction to Programming in C Stony Brook University Software Reuse Laziness is a virtue among programmers Often, a given task must be performed multiple times Instead

More information

Fundamental Data Types. CSE 130: Introduction to Programming in C Stony Brook University

Fundamental Data Types. CSE 130: Introduction to Programming in C Stony Brook University Fundamental Data Types CSE 130: Introduction to Programming in C Stony Brook University Program Organization in C The C System C consists of several parts: The C language The preprocessor The compiler

More information

CpSc 1111 Lab 6 Conditional Statements, Loops, the Math Library, and Random Numbers What s the Point?

CpSc 1111 Lab 6 Conditional Statements, Loops, the Math Library, and Random Numbers What s the Point? CpSc 1111 Lab 6 Conditional Statements, Loops, the Math Library, and Random Numbers What s the Point? Overview For this lab, you will use: one or more of the conditional statements explained below scanf()

More information

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

C++, How to Program. Spring 2016 CISC1600 Yanjun Li 1 Chapter 6 Function C++, How to Program Deitel & Deitel Spring 2016 CISC1600 Yanjun Li 1 Function A function is a collection of statements that performs a specific task - a single, well-defined task. Divide

More information

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

C Functions. Object created and destroyed within its block auto: default for local variables 1 5 C Functions 5.12 Storage Classes 2 Automatic storage Object created and destroyed within its block auto: default for local variables auto double x, y; Static storage Variables exist for entire program

More information

CHAPTER 4 FUNCTIONS. Dr. Shady Yehia Elmashad

CHAPTER 4 FUNCTIONS. Dr. Shady Yehia Elmashad CHAPTER 4 FUNCTIONS Dr. Shady Yehia Elmashad Outline 1. Introduction 2. Program Components in C++ 3. Math Library Functions 4. Functions 5. Function Definitions 6. Function Prototypes 7. Header Files 8.

More information

Methods (Deitel chapter 6)

Methods (Deitel chapter 6) Methods (Deitel chapter 6) 1 Plan 2 Introduction Program Modules in Java Math-Class Methods Method Declarations Argument Promotion Java API Packages Random-Number Generation Scope of Declarations Methods

More information

Methods (Deitel chapter 6)

Methods (Deitel chapter 6) 1 Plan 2 Methods (Deitel chapter ) Introduction Program Modules in Java Math-Class Methods Method Declarations Argument Promotion Java API Packages Random-Number Generation Scope of Declarations Methods

More information

Beginning C Programming for Engineers

Beginning C Programming for Engineers Beginning Programming for Engineers R. Lindsay Todd Lecture 2: onditionals, Logic, and Repetition R. Lindsay Todd () Beginning Programming for Engineers Beg 2 1 / 50 Outline Outline 1 Math Operators 2

More information

C Program Structures

C Program Structures Review-1 Structure of C program Variable types and Naming Input and output Arithmetic operation 85-132 Introduction to C-Programming 9-1 C Program Structures #include void main (void) { } declaration

More information

CSE101-lec#12. Designing Structured Programs Introduction to Functions. Created By: Amanpreet Kaur & Sanjeev Kumar SME (CSE) LPU

CSE101-lec#12. Designing Structured Programs Introduction to Functions. Created By: Amanpreet Kaur & Sanjeev Kumar SME (CSE) LPU CSE101-lec#12 Designing Structured Programs Introduction to Functions Created By: Amanpreet Kaur & Sanjeev Kumar SME (CSE) LPU Outline Designing structured programs in C: Counter-controlled repetition

More information

Subject: Fundamental of Computer Programming 2068

Subject: Fundamental of Computer Programming 2068 Subject: Fundamental of Computer Programming 2068 1 Write an algorithm and flowchart to determine whether a given integer is odd or even and explain it. Algorithm Step 1: Start Step 2: Read a Step 3: Find

More information

Computer Science & Engineering 150A Problem Solving Using Computers

Computer Science & Engineering 150A Problem Solving Using Computers Computer Science & Engineering 150A Problem Solving Using Computers Lecture 03 - Stephen Scott (Adapted from Christopher M. Bourke) 1 / 41 Fall 2009 Chapter 3 3.1 Building Programs from Existing Information

More information

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

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 Functions 1 Function n A program segment that carries out some specific, well-defined task n Example A function to add two numbers A function to find the largest of n numbers n A function will carry out

More information

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

Lesson #3. Variables, Operators, and Expressions. 3. Variables, Operators and Expressions - Copyright Denis Hamelin - Ryerson University Lesson #3 Variables, Operators, and Expressions Variables We already know the three main types of variables in C: int, char, and double. There is also the float type which is similar to double with only

More information

BSM540 Basics of C Language

BSM540 Basics of C Language BSM540 Basics of C Language Chapter 9: Functions I Prof. Manar Mohaisen Department of EEC Engineering Review of the Precedent Lecture Introduce the switch and goto statements Introduce the arrays in C

More information

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

Faculty of Engineering Computer Engineering Department Islamic University of Gaza C++ Programming Language Lab # 6 Functions Faculty of Engineering Computer Engineering Department Islamic University of Gaza 2013 C++ Programming Language Lab # 6 Functions C++ Programming Language Lab # 6 Functions Objective: To be familiar with

More information

Computer Science & Engineering 150A Problem Solving Using Computers. Chapter 3. Existing Information. Notes. Notes. Notes. Lecture 03 - Functions

Computer Science & Engineering 150A Problem Solving Using Computers. Chapter 3. Existing Information. Notes. Notes. Notes. Lecture 03 - Functions Computer Science & Engineering 150A Problem Solving Using Computers Lecture 03 - Functions Stephen Scott (Adapted from Christopher M. Bourke) Fall 2009 1 / 1 cbourke@cse.unl.edu Chapter 3 3.1 Building

More information

Methods: A Deeper Look

Methods: A Deeper Look 1 2 7 Methods: A Deeper Look OBJECTIVES In this chapter you will learn: How static methods and variables are associated with an entire class rather than specific instances of the class. How to use random-number

More information

Multiple Choice Questions ( 1 mark)

Multiple Choice Questions ( 1 mark) Multiple Choice Questions ( 1 mark) Unit-1 1. is a step by step approach to solve any problem.. a) Process b) Programming Language c) Algorithm d) Compiler 2. The process of walking through a program s

More information

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

It is necessary to have a single function main in every C program, along with other functions used/defined by the programmer. Functions A number of statements grouped into a single logical unit are called a function. The use of function makes programming easier since repeated statements can be grouped into functions. Splitting

More information

Function Example. Function Definition. C Programming. Syntax. A small program(subroutine) that performs a particular task. Modular programming design

Function Example. Function Definition. C Programming. Syntax. A small program(subroutine) that performs a particular task. Modular programming design What is a Function? C Programming Lecture 8-1 : Function (Basic) A small program(subroutine) that performs a particular task Input : parameter / argument Perform what? : function body Output t : return

More information

Calling Prewritten Functions in C

Calling Prewritten Functions in C Calling Prewritten Functions in C We've already called two prewritten functions that are found in the C library stdio.h: printf, scanf. The function specifications for these two are complicated (they allow

More information

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

Computer Programming & Problem Solving ( CPPS ) Turbo C Programming For The PC (Revised Edition ) By Robert Lafore Sir Syed University of Engineering and Technology. Computer ming & Problem Solving ( CPPS ) Functions Chapter No 1 Compiled By: Sir Syed University of Engineering & Technology Computer Engineering Department

More information

CHAPTER 4 FUNCTIONS. 4.1 Introduction

CHAPTER 4 FUNCTIONS. 4.1 Introduction CHAPTER 4 FUNCTIONS 4.1 Introduction Functions are the building blocks of C++ programs. Functions are also the executable segments in a program. The starting point for the execution of a program is main

More information

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

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

More information

C Programs: Simple Statements and Expressions

C Programs: Simple Statements and Expressions .. Cal Poly CPE 101: Fundamentals of Computer Science I Alexander Dekhtyar.. C Programs: Simple Statements and Expressions C Program Structure A C program that consists of only one function has the following

More information

Matlab? Chapter 3-4 Matlab and IPT Basics. Working Environment. Matlab Demo. Array. Data Type. MATLAB Desktop:

Matlab? Chapter 3-4 Matlab and IPT Basics. Working Environment. Matlab Demo. Array. Data Type. MATLAB Desktop: Matlab? Lecture Slides ME 4060 Machine Vision and Vision-based Control Chapter 3-4 Matlab and IPT Basics By Dr. Debao Zhou 1 MATric LABoratory data analysis, prototype and visualization Matrix operation

More information

CS11001/CS11002 Programming and Data Structures (PDS) (Theory: 3-0-0)

CS11001/CS11002 Programming and Data Structures (PDS) (Theory: 3-0-0) CS11001/CS11002 Programming and Data Structures (PDS) (Theory: 3-0-0) Class Teacher: Pralay Mitra Department of Computer Science and Engineering Indian Institute of Technology Kharagpur An Example: Random

More information

Lab Instructor : Jean Lai

Lab Instructor : Jean Lai Lab Instructor : Jean Lai Group related statements to perform a specific task. Structure the program (No duplicate codes!) Must be declared before used. Can be invoked (called) as any number of times.

More information

6.5 Function Prototypes and Argument Coercion

6.5 Function Prototypes and Argument Coercion 6.5 Function Prototypes and Argument Coercion 32 Function prototype Also called a function declaration Indicates to the compiler: Name of the function Type of data returned by the function Parameters the

More information

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

C++ Programming: From Problem Analysis to Program Design, Fifth Edition. Chapter 6: User-Defined Functions I C++ Programming: From Problem Analysis to Program Design, Fifth Edition Chapter 6: User-Defined Functions I In this chapter, you will: Objectives Learn about standard (predefined) functions and discover

More information

Subject: PROBLEM SOLVING THROUGH C Time: 3 Hours Max. Marks: 100

Subject: PROBLEM SOLVING THROUGH C Time: 3 Hours Max. Marks: 100 Code: DC-05 Subject: PROBLEM SOLVING THROUGH C Time: 3 Hours Max. Marks: 100 NOTE: There are 11 Questions in all. Question 1 is compulsory and carries 16 marks. Answer to Q. 1. must be written in the space

More information

C Programming Language

C Programming Language C Programming Language Arrays & Pointers I Dr. Manar Mohaisen Office: F208 Email: manar.subhi@kut.ac.kr Department of EECE Review of Precedent Class Explain How to Create Simple Functions Department of

More information

Lecture 9 - C Functions

Lecture 9 - C Functions ECET 264 C Programming Language with Applications Lecture 9 C Functions Paul I. Lin Professor of Electrical & Computer Engineering Technology http://www.etcs.ipfw.edu/~lin Lecture 9- Prof. Paul I. Lin

More information

Computer Programming 6th Week Functions (Function definition, function calls),

Computer Programming 6th Week Functions (Function definition, function calls), Computer Programming 6th Week Functions (Function definition, function calls), Hazırlayan Asst. Prof. Dr. Tansu Filik Computer Programming Previously on Bil-200 loops (do-while, for), Arrays, array operations,

More information

Functions and an Introduction to Recursion Pearson Education, Inc. All rights reserved.

Functions and an Introduction to Recursion Pearson Education, Inc. All rights reserved. 1 6 Functions and an Introduction to Recursion 2 Form ever follows function. Louis Henri Sullivan E pluribus unum. (One composed of many.) Virgil O! call back yesterday, bid time return. William Shakespeare

More information

1001ICT Introduction To Programming Lecture Notes

1001ICT Introduction To Programming Lecture Notes 1001ICT Introduction To Programming Lecture Notes School of Information and Communication Technology Griffith University Semester 1, 2015 1 M Environment console M.1 Purpose This environment supports programming

More information

UNIT 3 FUNCTIONS AND ARRAYS

UNIT 3 FUNCTIONS AND ARRAYS UNIT 3 FUNCTIONS AND ARRAYS Functions Function definitions and Prototypes Calling Functions Accessing functions Passing arguments to a function - Storage Classes Scope rules Arrays Defining an array processing

More information

Functions BCA-105. Few Facts About Functions:

Functions BCA-105. Few Facts About Functions: Functions When programs become too large and complex and as a result the task of debugging, testing, and maintaining becomes difficult then C provides a most striking feature known as user defined function

More information

CSCI 171 Chapter Outlines

CSCI 171 Chapter Outlines Contents CSCI 171 Chapter 1 Overview... 2 CSCI 171 Chapter 2 Programming Components... 3 CSCI 171 Chapter 3 (Sections 1 4) Selection Structures... 5 CSCI 171 Chapter 3 (Sections 5 & 6) Iteration Structures

More information

More loops Ch

More loops Ch More loops Ch 3.3-3.4 Announcements Quiz next week! -Covers up to (and including) HW1 (week 1-3) -Topics: cout/cin, types, scope, if/else, etc. Review: Loops We put a loop around code that we want to run

More information

C: How to Program. Week /Apr/23

C: How to Program. Week /Apr/23 C: How to Program Week 9 2007/Apr/23 1 Review of Chapters 1~5 Chapter 1: Basic Concepts on Computer and Programming Chapter 2: printf and scanf (Relational Operators) keywords Chapter 3: if (if else )

More information

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

Chapter 3. Computer Science & Engineering 155E Computer Science I: Systems Engineering Focus. Existing Information. Chapter 3 Computer Science & Engineering 155E Computer Science I: Systems Engineering Focus Lecture 03 - Introduction To Functions Christopher M. Bourke cbourke@cse.unl.edu 3.1 Building Programs from Existing

More information

Fundamentals of Programming & Procedural Programming

Fundamentals of Programming & Procedural Programming Universität Duisburg-Essen PRACTICAL TRAINING TO THE LECTURE Fundamentals of Programming & Procedural Programming Session Four: Functions: Built-in, Parameters and Arguments, Fruitful and Void Functions

More information

CS101 Introduction to computing Function, Scope Rules and Storage class

CS101 Introduction to computing Function, Scope Rules and Storage class CS101 Introduction to computing Function, Scope Rules and Storage class A. Sahu and S. V.Rao Dept of Comp. Sc. & Engg. Indian Institute of Technology Guwahati Outline Functions Modular d l Program Inbuilt

More information

Experiment 9: Using HI-TECH C Compiler in MPLAB

Experiment 9: Using HI-TECH C Compiler in MPLAB University of Jordan Faculty of Engineering and Technology Department of Computer Engineering Embedded Systems Laboratory 0907334 9 Experiment 9: Using HI-TECH C Compiler in MPLAB Objectives The main objectives

More information

Question 2. [5 points] Given the following symbolic constant definition

Question 2. [5 points] Given the following symbolic constant definition CS 101, Spring 2012 Mar 20th Exam 2 Name: Question 1. [5 points] Determine which of the following function calls are valid for a function with the prototype: void drawrect(int width, int height); Assume

More information

Fundamentals of Programming Session 12

Fundamentals of Programming Session 12 Fundamentals of Programming Session 12 Instructor: Reza Entezari-Maleki Email: entezari@ce.sharif.edu 1 Fall 2014 These slides have been created using Deitel s slides Sharif University of Technology Outlines

More information

More Flow Control Functions in C++ CS 16: Solving Problems with Computers I Lecture #4

More Flow Control Functions in C++ CS 16: Solving Problems with Computers I Lecture #4 More Flow Control Functions in C++ CS 16: Solving Problems with Computers I Lecture #4 Ziad Matni Dept. of Computer Science, UCSB Administrative CHANGED T.A. OFFICE/OPEN LAB HOURS! Thursday, 10 AM 12 PM

More information