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

Size: px
Start display at page:

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

Transcription

1 CSE 2421: Systems I Low-Level Programming and Computer Organization Functions Read/Study: Reek Chapters 7 Gojko Babić Predefined Functions C comes with libraries of predefined functions E.g.: sqrt function computes and returns the square root root = sqrt(9.0); The number 9.0 is called the argument and root will contain 3.0 The argument can also be a variable or an expression sqrt(9.0) is a function call and it invokes the sqrt function A function usually return a value but it doesn t have to A function call can be used in any expression bonus = sqrt(sales) / 10; printf( The side of a square with area %d is %f, area, sqrt(area)); Function call syntax: Function_name (Argument_1, Argument_2,, Argument_N) g. babic 2 1

2 Function Libraries Predefined functions are found in libraries The library must be included in a program to make the functions available An include directive tells the compiler which library file to include. To include the math library containing sqrt(): #include <math.h> Some of absolute value functions are in the library with header stdlib, so any program that uses them must contain the following directive #include <stdlib.h> Reek Section 16.1 and Section 16.2 contain a number of predefined integer and floating point functions g. babic 3 Some Predefined Functions math.h math.h stdlib.h stdlib.h math.h math.h math.h g. babic 4 2

3 Programmer-Defined Functions Two components of a programmer-defined function: function declaration (or function prototype) and function definition Function declaration shows how the function is to be called it must appear before the function can be called and it is usually declared outside main function syntax: type_returned Function_Name(Parameter_List); Parameter list tells types of the arguments and the formal parameter names (optional) Formal parameters are like placeholders for the actual arguments used when the function is called Example: float total_cost(int number, float price); or this is identical float total_cost(int, float); g. babic 5 Function Declaration and Definition Syntax g. babic 6 3

4 Function definition describes how the function does its task and it can appear before or after the function is called Syntax: type_returned Function_Name(Formal_Parameter_List) { Example: Function Definition //code to make the function work float total_cost(int number_par, float price_par) { const float TAX_RATE = ; //6.75% tax float subtotal; subtotal = price_par * number_par; return (subtotal + subtotal * TAX_RATE); Function header has to have identical types of parameters as in the function declaration. Function body return statement returns the value calculated by the function g. babic 7 The RETURN Statement Every function except those returning void should have at least one return; each return shows what value is supposed to be returned at that point. Although it is possible to return from a function by falling through the last, unless the function returns void, an unknown value will be returned, resulting in undefined behavior. The type of expression returned must match the type of the function, or be capable of being converted to it as if an assignment statement were in use. Following the return keyword with an expression is not permitted if the function returns void. 8 4

5 Function Call Tells the name of the function to use and lists the arguments May be used in a statement where the returned value makes sense Example: float bill = total_cost(number, price); The values of the arguments are plugged into the formal parameters (call-by-value mechanism) The first argument is used for the first formal parameter, the second argument for the second formal parameter, and so forth. Compiler checks that the types of the arguments are correct and in the correct sequence. The value plugged into the formal parameter is used in all instances of the formal parameter in the function body g. babic 9 Program: FunctionPrice.c #include<stdio.h> //Function definition #define TAX_RATE //This code usually follows the main function float total_cost(int num_par, float price_par) // Function declaration { float subtotal; float total_cost(int, float); subtotal = price_par * num_par; int main() return (subtotal + subtotal * TAX_RATE); { float price, bill; int number; printf("enter number of items purchased:"); scanf("%d", &number); //remember to include & in scanf printf("enter the price per items $:"); scanf("%f",&price); printf("number= %d price= %.2f", number, price); bill = total_cost(number, price); // Function call printf("\nfinal bill including %.2f%% tax: %.2f",TAX_RATE*100, bill); return 0; 10 5

6 Program: pmax void pmax(int first, int second); /* function declaration prototype */ int main () If main function is in file ProgA.c, and pmax { function is in file ProgB.c, then the command: int i,j; gcc o x ProgA.c ProgB.c for(i = -10; i <= 10; i++) produces executable in file x. for(j = -10; j <= 10; j++) pmax(i,j); //function call return 0; void pmax (int a1, int a2) //function definition starts*/ { //prints larger of its two arguments. int bigger; if (a1==a2) printf( Numbers %d and %d are equal, a1, a2); else {if (a1 > a2) bigger = a1; else bigger = a2; printf("larger of %d and %d is %d\n", a1, a2, bigger); 11 Syntax of void Function A void-function implements a subtask that returns no value Optional return statement does not include value to return Is a return ever needed in a void-function since no value is returned? g. babic 12 6

7 Pass by Value Pass by value makes a copy of varibales in a function call before passing them into a called function. This means that when you modify those values inside a function, you will modify values only inside the function. Once the function returns, the variables you passed will have the same value they had before you passed them into the function. Pass by value is the only passing mechanism C supports. Pass by reference modifies the value of the passed variable locally inside the called function and the value of the variable in the calling function as well. C doesn t have pass by reference but the same effect can be made passing pointers. When a pointer is passed, a copy is made so two variables point to the same address, one from the called function and one from the calling function. g. babic 13 Functions: Summary Two forms for function declarations list formal parameter names and their types list types of formal parameters, but not names Examples: float total_cost(int num_par, float pri_par); float total_cost(int, float); Within a function definition function headers must always list formal parameter names! variables must be declared before they are used and variables are typically declared before the executable statements Except for void functions, at least one return statement must end the function g. babic 14 7

8 Functions: Summary (cont.) A function call must be preceded by either the functions declaration or the functions definition Placing the function declaration prior to the main function and the function definition after the main function leads naturally to building your own libraries in the future. Variables declared in a function are local variables to that function and they have the function as their scope they cannot be used from outside the function Formal parameters in function headers are also variables that are local to the function definition they are used just as if they were declared in the function body do not re-declare the formal parameters in the function body, since they are declared in the function header g. babic 15 Function Summary (cont.) It is recommended to always use function declarations (prototypes). The values of the arguments in a function call are converted to the types of the formal parameters exactly as if they had been assigned using the = operator. Functions can return any type that you can declare, except for arrays and functions you get around that restriction by using pointers. Functions returning no value should return void. Functions taking no arguments should have a prototype with void as the argument specification. Functions can call another functions and they can be called recursively, directly or indirectly. 16 8

9 Recursive Factorial Function n! = n * (n-1) * (n-2) * * 3 * 2 * 1 The definition of a factorial is often stated recursively, like this n! = 1 if n<=0 n * (n-1)! if n > 0 long factorial (int n) { if (n<=0) return 1; else return n* factorial (n-1); Note that factorial function can be implemented without recursion. 17 Scope of Variables Scope is a region of a program where a defined variable can have its existence, thus can be accessed, and beyond that, the variable can not be accessed. Three places where variables can be declared: Inside a function (or block) local variable A block is a list of statement enclosed in braces Outside any function global variable Definition of a function parameter formal parameter The location where an identifier is declared determines its scope. 18 9

10 Scope of Variables (cont.) The local variable or the variable with block scope is any identifier declared (usually) at the beginning of the block and it is accessible to all statements inside the block (after point of its declaration), and can t be accessed from outside the block. The formal parameter of a function definition also has a block scope in the function s body and could be viewed as local variables. The global variable is identifier declared outside of all blocks and it has the program scope, which also means they are visible among different files. These files are the entire source files that make up an executable program. 19 Statement Blocks A block is a section of code enclosed by braces variables declared within a block are local to the block and have the block as their scope. variable names declared in the block can be reused outside the block Statement blocks can be nested in other statement blocks If a single identifier is declared as a variable in each of two blocks, one within the other, then these are two different variables with the same name one of the variables exists only within the inner block and cannot be accessed outside the inner block the other variable exists only in the outer block and cannot be accessed in the inner block g. babic 20 10

11 // File: NestedBlocks.c int main() { int x=1; printf("outer x= %d\n", x); { printf("outer x inside= %d\n", x); int x=2; printf("inside x= %d\n", x); printf("again Outer x= %d\n", x); Nested Blocks What is the output of this code? ~/Cse2421> NestedBlocks Outer x= 1 Outer x inside= 1 Inside x= 2 Again Outer x= 1 Nesting statement blocks can make code difficult to read, and it is generally better to avoid them and to create function instead. g. babic 21 Local and Global Variables Variables declared in the main part of a program are also local variables to the main function of the program cannot be used from outside the main and have the main as their scope. Global variables (as well as global constants) are declared outside the main function body. Global variables and global constants are available to any function in the program including the main. Example: #define PI // PI is global constant double x, y, z; // x, y, and z are global variables int main() { int func1( ) { g. babic 22 11

12 Storage Class: auto The storage class defines life time of a variable, i.e. determines when the variable is created and then destroyed, and how long it will retain its value. The storage class specifier precedes the variable type and define its storage class: auto automatic is default for all local variables; they are stored on the stack (usually) or in registers after entering a block (or a function) and discarded on exit from a block (or a function), e.g. int number; or auto int number; register this specifier is very rarely if ever used, and here it is mentioned only for completeness. g. babic 23 Storage Class: static static changes storage class of a local variable from automatic to static, e.g. static int number; a static variable declaration keeps a local variable in existence during the lifetime of the program, instead of creating and destroying it each time it comes into and goes out of scope; it exists and retains its value even after the control is transferred to the calling function; there is only one copy of static local variable in memory the changing of the storage class of a local variable does not change its scope, a static variables may be initialized during compilation, static is default for global variables global variable with static specifier changes its scope to a file where it s declared. function formal parameters cannot be declared static. g. babic 24 12

13 Local Variable With Static Specifier #include <stdio.h> /* the add_two function */ int add_two(int x, int y) {static int counter = 1; printf( Call No. %d,\n, counter++); return (x + y); main() { int i, j; for (i=0, j=5; i<5; i++, j--) printf( %d+%d =%d.\n\n", i, j, add_two(i, j)); return 0; Output: Call No =5 Call No =5 Call No =5 Call No =5 Call No =5 25 Same Example: No Static Specifier #include <stdio.h> /* the add_two function */ int add_two(int x, int y) {/*static*/ int counter = 1; printf( Call No. %d,\n, counter++); return (x + y); main() { int i, j; for (i=0, j=5; i<5; i++, j--) printf( %d+%d =%d.\n\n", i, j, add_two(i, j)); return 0; Output: Call No =5 Call No =5 Call No =5 Call No =5 Call No =

14 Variable type Global Local Formal parameter Scope and Storage Class Summary Where declared Outside of all blocks Inside a block (usually beginning) Function header Stored on stack or in registers No (1) Yes (2) Yes (2) Scope All source file(s) Throughout the block (3) Throughout the function (3) If declared static Prevents access from other source files Not stored on the stack or in registers, kept its value for the entire execution (1) Not allowed (1) Variables not stored on the stack (or in registers) are created and their memory is allocated when the program begins executing and they exist and retain their values throughout execution, regardless of whether they are local or global (2) Variables stored on stack (or in registers) exist and retain their values only while the block they are local is active; when execution leaves the block, their allocations and the values are lost (3) Except in a nested block that declares identical names 27 14

Chapter 4. Procedural Abstraction and Functions That Return a Value. Copyright 2014 Pearson Addison-Wesley. All rights reserved.

Chapter 4. Procedural Abstraction and Functions That Return a Value. Copyright 2014 Pearson Addison-Wesley. All rights reserved. Chapter 4 Procedural Abstraction and Functions That Return a Value 1 Overview 4.1 Top-Down Design 4.2 Predefined Functions 4.3 Programmer-Defined Functions 4.4 Procedural Abstraction 4.5 Local Variables

More information

Top-Down Design Predefined Functions Programmer-Defined Functions Procedural Abstraction Local Variables Overloading Function Names

Top-Down Design Predefined Functions Programmer-Defined Functions Procedural Abstraction Local Variables Overloading Function Names Chapter 4 In this chapter, you will learn about: Top-Down Design Predefined Functions Programmer-Defined Functions Procedural Abstraction Local Variables Overloading Function Names Top-Down Design Top-Down

More information

Chapter Procedural Abstraction and Functions That Return a Value. Overview. Top-Down Design. Benefits of Top Down Design.

Chapter Procedural Abstraction and Functions That Return a Value. Overview. Top-Down Design. Benefits of Top Down Design. Chapter 4 Procedural Abstraction and Functions That Return a Value Overview 4.1 Top-Down Design 4.2 Predefined Functions 4.3 Programmer-Defined Functions 4.4 Procedural Abstraction 4.5 Local Variables

More information

Chapter 4. Procedural Abstraction and Functions That Return a Value

Chapter 4. Procedural Abstraction and Functions That Return a Value Chapter 4 Procedural Abstraction and Functions That Return a Value Overview 4.1 Top-Down Design 4.2 Predefined Functions 4.3 Programmer-Defined Functions 4.4 Procedural Abstraction 4.5 Local Variables

More information

Programmer-Defined Functions

Programmer-Defined Functions Functions Programmer-Defined Functions Local Variables in Functions Overloading Function Names void Functions, Call-By-Reference Parameters in Functions Programmer-Defined Functions function declaration

More information

Chapter 4. Procedural Abstraction and Functions That Return a Value. Copyright 2015 Pearson Education, Ltd.. All rights reserved.

Chapter 4. Procedural Abstraction and Functions That Return a Value. Copyright 2015 Pearson Education, Ltd.. All rights reserved. Chapter 4 Procedural Abstraction and Functions That Return a Value Overview 4.1 Top-Down Design 4.2 Predefined Functions 4.3 Programmer-Defined Functions 4.4 Procedural Abstraction 4.5 Local Variables

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

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

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

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

/* EXAMPLE 1 */ #include<stdio.h> int main() { float i=10, *j; void *k; k=&i; j=k; printf("%f\n", *j);

/* EXAMPLE 1 */ #include<stdio.h> int main() { float i=10, *j; void *k; k=&i; j=k; printf(%f\n, *j); You try /* EXAMPLE 3 */ #include int main(void) { char ch = 'c'; char *chptr = &ch; int i = 20; int *intptr = &i; float f = 1.20000; float *fptr = &f; char *ptr = "I am a string"; /* EXAMPLE

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

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

CSE 230 Intermediate Programming in C and C++ Functions

CSE 230 Intermediate Programming in C and C++ Functions CSE 230 Intermediate Programming in C and C++ Functions Fall 2017 Stony Brook University Instructor: Shebuti Rayana shebuti.rayana@stonybrook.edu http://www3.cs.stonybrook.edu/~cse230/ Concept of Functions

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

Structured Programming. Functions and Structured Programming. Functions. Variables

Structured Programming. Functions and Structured Programming. Functions. Variables Structured Programming Functions and Structured Programming Structured programming is a problem-solving strategy and a programming methodology. The construction of a program should embody topdown design

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

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

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

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

Technical Questions. Q 1) What are the key features in C programming language? Technical Questions Q 1) What are the key features in C programming language? Portability Platform independent language. Modularity Possibility to break down large programs into small modules. Flexibility

More information

Computer Science & Information Technology (CS) Rank under AIR 100. Examination Oriented Theory, Practice Set Key concepts, Analysis & Summary

Computer Science & Information Technology (CS) Rank under AIR 100. Examination Oriented Theory, Practice Set Key concepts, Analysis & Summary GATE- 2016-17 Postal Correspondence 1 C-Programming Computer Science & Information Technology (CS) 20 Rank under AIR 100 Postal Correspondence Examination Oriented Theory, Practice Set Key concepts, Analysis

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

Functions. (transfer of parameters, returned values, recursion, function pointers).

Functions. (transfer of parameters, returned values, recursion, function pointers). Functions (transfer of parameters, returned values, recursion, function pointers). A function is a named, independent section of C/C++ code that performs a specific task and optionally returns a value

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

Iterative Languages. Scoping

Iterative Languages. Scoping Iterative Languages Scoping Sample Languages C: static-scoping Perl: static and dynamic-scoping (use to be only dynamic scoping) Both gcc (to run C programs), and perl (to run Perl programs) are installed

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

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

Why Pointers. Pointers. Pointer Declaration. Two Pointer Operators. What Are Pointers? Memory address POINTERVariable Contents ...

Why Pointers. Pointers. Pointer Declaration. Two Pointer Operators. What Are Pointers? Memory address POINTERVariable Contents ... Why Pointers Pointers They provide the means by which functions can modify arguments in the calling function. They support dynamic memory allocation. They provide support for dynamic data structures, such

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

Chapter 3 Function Basics

Chapter 3 Function Basics Chapter 3 Function Basics Learning Objectives Predefined Functions Those that return a value and those that don t Programmer-defined Functions Defining, Declaring, Calling Recursive Functions Scope Rules

More information

3.2 Predefined Functions Libraries. 3.1 Top Down Design. 3.2 Predefined Functions Libraries. 3.2 Function call. Display 3.

3.2 Predefined Functions Libraries. 3.1 Top Down Design. 3.2 Predefined Functions Libraries. 3.2 Function call. Display 3. 3.1 Top Down Design 3.2 Predefined Functions Libraries Step wise refinement, also known as divide and conquer, means dividing the problem into subproblems such that once each has been solved, the big problem

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

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

A Fast Review of C Essentials Part II

A Fast Review of C Essentials Part II A Fast Review of C Essentials Part II Structural Programming by Z. Cihan TAYSI Outline Fixed vs. Automatic duration Scope Global variables The register specifier Storage classes Dynamic memory allocation

More information

Functions and Recursion

Functions and Recursion Functions and Recursion 1 Storage Classes Scope Rules Functions with Empty Parameter Lists Inline Functions References and Reference Parameters Default Arguments Unary Scope Resolution Operator Function

More information

PROGRAMMAZIONE I A.A. 2017/2018

PROGRAMMAZIONE I A.A. 2017/2018 PROGRAMMAZIONE I A.A. 2017/2018 FUNCTIONS INTRODUCTION AND MAIN All the instructions of a C program are contained in functions. üc is a procedural language üeach function performs a certain task A special

More information

Programming in C. main. Level 2. Level 2 Level 2. Level 3 Level 3

Programming in C. main. Level 2. Level 2 Level 2. Level 3 Level 3 Programming in C main Level 2 Level 2 Level 2 Level 3 Level 3 1 Programmer-Defined Functions Modularize with building blocks of programs Divide and Conquer Construct a program from smaller pieces or components

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

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

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

M.EC201 Programming language

M.EC201 Programming language Power Engineering School M.EC201 Programming language Lecture 13 Lecturer: Prof. Dr. T.Uranchimeg Agenda The union Keyword typedef and Structures What Is Scope? External Variables 2 The union Keyword The

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

University of Kelaniya Sri Lanka

University of Kelaniya Sri Lanka University of Kelaniya Sri Lanka Scope, Lifetime and Storage Class of a Variable COSC 12533/ COST 12533 SACHINTHA PITIGALA 2017 - Sachintha Pitigala < 1 What is Scope? Scope of Identifier: The scope of

More information

CS113: Lecture 4. Topics: Functions. Function Activation Records

CS113: Lecture 4. Topics: Functions. Function Activation Records CS113: Lecture 4 Topics: Functions Function Activation Records 1 Why functions? Functions add no expressive power to the C language in a formal sense. Why have them? Breaking tasks into smaller ones make

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

Chapter 5 C Functions

Chapter 5 C Functions Chapter 5 C Functions 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(

More information

Functions in C. Lecture Topics. Lecture materials. Homework. Machine problem. Announcements. ECE 190 Lecture 16 March 9, 2011

Functions in C. Lecture Topics. Lecture materials. Homework. Machine problem. Announcements. ECE 190 Lecture 16 March 9, 2011 Functions in C Lecture Topics Introduction to using functions in C Syntax Examples Memory allocation for variables Lecture materials Textbook 14.1-14.2, 12.5 Homework Machine problem MP3.2 due March 18,

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

15 FUNCTIONS IN C 15.1 INTRODUCTION

15 FUNCTIONS IN C 15.1 INTRODUCTION 15 FUNCTIONS IN C 15.1 INTRODUCTION In the earlier lessons we have already seen that C supports the use of library functions, which are used to carry out a number of commonly used operations or calculations.

More information

C: How to Program. Week /Mar/05

C: How to Program. Week /Mar/05 1 C: How to Program Week 2 2007/Mar/05 Chapter 2 - Introduction to C Programming 2 Outline 2.1 Introduction 2.2 A Simple C Program: Printing a Line of Text 2.3 Another Simple C Program: Adding Two Integers

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

C Programming Language

C Programming Language Department of Electrical, Electronics, and Communication Engineering C Programming Language Storage Classes, Linkage, and Memory Management Manar Mohaisen Office: F208 Email: manar.subhi@kut.ac.kr Department

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

Procedural programming with C

Procedural programming with C Procedural programming with C Dr. C. Constantinides Department of Computer Science and Software Engineering Concordia University Montreal, Canada August 11, 2016 1 / 77 Functions Similarly to its mathematical

More information

Compiling and Running a C Program in Unix

Compiling and Running a C Program in Unix CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 95 ] Compiling and Running a C Program in Unix Simple scenario in which your program is in a single file: Suppose you want to name

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

Storage class in C. Automatic variables External variables Static variables Register variables Scopes and longevity of above types of variables.

Storage class in C. Automatic variables External variables Static variables Register variables Scopes and longevity of above types of variables. 1 Storage class in C Automatic variables External variables Static variables Register variables Scopes and longevity of above types of variables. 2 Few terms 1. Scope: the scope of a variable determines

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

Chapter 7: User Defined Functions and Stack Mechanics

Chapter 7: User Defined Functions and Stack Mechanics Chapter 7: User Defined Functions and Stack Mechanics Objectives: (a) Demonstrate the ability to analyze simple programs that use library and user defined functions. (b) Describe the organization and contents

More information

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

UNIT III (PART-II) & UNIT IV(PART-I) UNIT III (PART-II) & UNIT IV(PART-I) Function: it is defined as self contained block of code to perform a task. Functions can be categorized to system-defined functions and user-defined functions. System

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

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

Pointers and scanf() Steven R. Bagley

Pointers and scanf() Steven R. Bagley Pointers and scanf() Steven R. Bagley Recap Programs are a series of statements Defined in functions Can call functions to alter program flow if statement can determine whether code gets run Loops can

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

B.V. Patel Institute of Business Management, Computer & Information Technology, Uka Tarsadia University

B.V. Patel Institute of Business Management, Computer & Information Technology, Uka Tarsadia University Unit 1 Programming Language and Overview of C 1. State whether the following statements are true or false. a. Every line in a C program should end with a semicolon. b. In C language lowercase letters are

More information

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

Functions. Lab 4. Introduction: A function : is a collection of statements that are grouped together to perform an operation. Lab 4 Functions Introduction: A function : is a collection of statements that are grouped together to perform an operation. The following is its format: type name ( parameter1, parameter2,...) { statements

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

Programming Languages

Programming Languages Programming Languages Recitation Summer 2014 Recitation Leader Joanna Gilberti Email: jlg204@cs.nyu.edu Office: WWH, Room 328 Web site: http://cims.nyu.edu/~jlg204/courses/pl/index.html Homework Submission

More information

OBJECTIVE QUESTIONS: Choose the correct alternative:

OBJECTIVE QUESTIONS: Choose the correct alternative: OBJECTIVE QUESTIONS: Choose the correct alternative: 1. Function is data type a) Primary b) user defined c) derived d) none 2. The declaration of function is called a) function prototype b) function call

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

Bil 104 Intiroduction To Scientific And Engineering Computing. Lecture 7

Bil 104 Intiroduction To Scientific And Engineering Computing. Lecture 7 Strings and Clases BIL104E: Introduction to Scientific and Engineering Computing Lecture 7 Manipulating Strings Scope and Storage Classes in C Strings Declaring a string The length of a string Copying

More information

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

UNIT - I. Introduction to C Programming. BY A. Vijay Bharath UNIT - I Introduction to C Programming Introduction to C C was originally developed in the year 1970s by Dennis Ritchie at Bell Laboratories, Inc. C is a general-purpose programming language. It has been

More information

Dynamic memory allocation

Dynamic memory allocation Dynamic memory allocation outline Memory allocation functions Array allocation Matrix allocation Examples Memory allocation functions (#include ) malloc() Allocates a specified number of bytes

More information

C Language Part 2 Digital Computer Concept and Practice Copyright 2012 by Jaejin Lee

C Language Part 2 Digital Computer Concept and Practice Copyright 2012 by Jaejin Lee C Language Part 2 (Minor modifications by the instructor) 1 Scope Rules A variable declared inside a function is a local variable Each local variable in a function comes into existence when the function

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

CS6202 - PROGRAMMING & DATA STRUCTURES UNIT I Part - A 1. W hat are Keywords? Keywords are certain reserved words that have standard and pre-defined meaning in C. These keywords can be used only for their

More information

C introduction: part 1

C introduction: part 1 What is C? C is a compiled language that gives the programmer maximum control and efficiency 1. 1 https://computer.howstuffworks.com/c1.htm 2 / 26 3 / 26 Outline Basic file structure Main function Compilation

More information

IECD Institute for Entrepreneurship and Career Development Bharathidasan University, Tiruchirappalli 23.

IECD Institute for Entrepreneurship and Career Development Bharathidasan University, Tiruchirappalli 23. Subject code - CCP01 Chapt Chapter 1 INTRODUCTION TO C 1. A group of software developed for certain purpose are referred as ---- a. Program b. Variable c. Software d. Data 2. Software is classified into

More information

CS201 Some Important Definitions

CS201 Some Important Definitions CS201 Some Important Definitions For Viva Preparation 1. What is a program? A program is a precise sequence of steps to solve a particular problem. 2. What is a class? We write a C++ program using data

More information

Functions. Lecture 6 COP 3014 Spring February 11, 2018

Functions. Lecture 6 COP 3014 Spring February 11, 2018 Functions Lecture 6 COP 3014 Spring 2018 February 11, 2018 Functions A function is a reusable portion of a program, sometimes called a procedure or subroutine. Like a mini-program (or subprogram) in its

More information

Computers Programming Course 5. Iulian Năstac

Computers Programming Course 5. Iulian Năstac Computers Programming Course 5 Iulian Năstac Recap from previous course Classification of the programming languages High level (Ada, Pascal, Fortran, etc.) programming languages with strong abstraction

More information

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

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 Unti 4: C Arrays Arrays a kind of data structure that can store a fixed-size sequential collection of elements of the same type An array is used to store a collection of data, but it is often more useful

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

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++ 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

About Codefrux While the current trends around the world are based on the internet, mobile and its applications, we try to make the most out of it. As for us, we are a well established IT professionals

More information

More Functions. Pass by Value. Example: Exchange two numbers. Storage Classes. Passing Parameters by Reference. Pass by value and by reference

More Functions. Pass by Value. Example: Exchange two numbers. Storage Classes. Passing Parameters by Reference. Pass by value and by reference Pass by Value More Functions Different location in memory Changes to the parameters inside the function body have no effect outside of the function. 2 Passing Parameters by Reference Example: Exchange

More information

Chapter 2 - Introduction to C Programming

Chapter 2 - Introduction to C Programming Chapter 2 - Introduction to C Programming 2 Outline 2.1 Introduction 2.2 A Simple C Program: Printing a Line of Text 2.3 Another Simple C Program: Adding Two Integers 2.4 Memory Concepts 2.5 Arithmetic

More information

EC 413 Computer Organization

EC 413 Computer Organization EC 413 Computer Organization C/C++ Language Review Prof. Michel A. Kinsy Programming Languages There are many programming languages available: Pascal, C, C++, Java, Ada, Perl and Python All of these languages

More information

Computer Programming. C Array is a collection of data belongings to the same data type. data_type array_name[array_size];

Computer Programming. C Array is a collection of data belongings to the same data type. data_type array_name[array_size]; Arrays An array is a collection of two or more adjacent memory cells, called array elements. Array is derived data type that is used to represent collection of data items. C Array is a collection of data

More information

Functions. Arash Rafiey. September 26, 2017

Functions. Arash Rafiey. September 26, 2017 September 26, 2017 are the basic building blocks of a C program. are the basic building blocks of a C program. A function can be defined as a set of instructions to perform a specific task. are the basic

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

M1-R4: Programing and Problem Solving using C (JAN 2019)

M1-R4: Programing and Problem Solving using C (JAN 2019) M1-R4: Programing and Problem Solving using C (JAN 2019) Max Marks: 100 M1-R4-07-18 DURATION: 03 Hrs 1. Each question below gives a multiple choice of answers. Choose the most appropriate one and enter

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

Computer Programming: Skills & Concepts (CP) arithmetic, if and booleans (cont)

Computer Programming: Skills & Concepts (CP) arithmetic, if and booleans (cont) CP Lect 5 slide 1 Monday 2 October 2017 Computer Programming: Skills & Concepts (CP) arithmetic, if and booleans (cont) Cristina Alexandru Monday 2 October 2017 Last Lecture Arithmetic Quadratic equation

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

Computer Programming Unit 3

Computer Programming Unit 3 POINTERS INTRODUCTION Pointers are important in c-language. Some tasks are performed more easily with pointers such as dynamic memory allocation, cannot be performed without using pointers. So it s very

More information

Government Polytechnic Muzaffarpur.

Government Polytechnic Muzaffarpur. Government Polytechnic Muzaffarpur. Name of the Lab: COMPUTER PROGRAMMING LAB (MECH. ENGG. GROUP) Subject Code: 1625408 Experiment: 1 Aim: Programming exercise on executing a C program. If you are looking

More information

Chapter 7 - Notes User-Defined Functions II

Chapter 7 - Notes User-Defined Functions II Chapter 7 - Notes User-Defined Functions II I. VOID Functions ( The use of a void function is done as a stand alone statement.) A. Void Functions without Parameters 1. Syntax: void functionname ( void

More information

M.CS201 Programming language

M.CS201 Programming language Power Engineering School M.CS201 Programming language Lecture 4 Lecturer: Prof. Dr. T.Uranchimeg Agenda How a Function Works Function Prototype Structured Programming Local Variables Return value 2 Function

More information