Lesson 5: Functions and Libraries. EE3490E: Programming S1 2018/2019 Dr. Đào Trung Kiên Hanoi Univ. of Science and Technology

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

P.G.TRB - COMPUTER SCIENCE. c) data processing language d) none of the above

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

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


CSCI 171 Chapter Outlines

CSE123. Program Design and Modular Programming Functions 1-1

Writing an ANSI C Program Getting Ready to Program A First Program Variables, Expressions, and Assignments Initialization The Use of #define and

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

Procedural programming with C

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

IMPORTANT QUESTIONS IN C FOR THE INTERVIEW

EL6483: Brief Overview of C Programming Language

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

Applied Programming and Computer Science, DD2325/appcs15 PODF, Programmering och datalogi för fysiker, DA7011

Functions in C C Programming and Software Tools

Signals, Instruments, and Systems W2. C Programming (continued)

Functions. Systems Programming Concepts

Lecture 04 FUNCTIONS AND ARRAYS

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

Multiple Choice Questions ( 1 mark)

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

Chapter 4 Functions By C.K. Liang

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

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

CSCI-243 Exam 1 Review February 22, 2015 Presented by the RIT Computer Science Community

Programming and Data Structure

COMP322 - Introduction to C++ Lecture 02 - Basics of C++

CS3157: Advanced Programming. Outline

Chapter 7: Preprocessing Directives

Fundamentals of Programming

The University of Calgary. ENCM 339 Programming Fundamentals Fall 2016

Basic C Programming (2) Bin Li Assistant Professor Dept. of Electrical, Computer and Biomedical Engineering University of Rhode Island

A Fast Review of C Essentials Part I

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

cs3157: another C lecture (mon-21-feb-2005) C pre-processor (3).

EMBEDDED SYSTEMS PROGRAMMING Language Basics

BLM2031 Structured Programming. Zeyneb KURT

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

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

C programming basics T3-1 -

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

Informatica e Sistemi in Tempo Reale

Control flow and string example. C and C++ Functions. Function type-system nasties. 2. Functions Preprocessor. Alastair R. Beresford.

OBJECTIVE QUESTIONS: Choose the correct alternative:

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

Basic C Programming. Bin Li Assistant Professor Dept. of Electrical, Computer and Biomedical Engineering University of Rhode Island

Kurt Schmidt. October 30, 2018

G52CPP C++ Programming Lecture 6. Dr Jason Atkin

Midterm Exam 2 Solutions C Programming Dr. Beeson, Spring 2009

Approximately a Test II CPSC 206

Function Call Stack and Activation Records

Language Design COMS W4115. Prof. Stephen A. Edwards Spring 2003 Columbia University Department of Computer Science

Procedures, Parameters, Values and Variables. Steven R. Bagley

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

Object Oriented Design

Unit 4 Preprocessor Directives

C and C++ 2. Functions Preprocessor. Alan Mycroft

Dynamic memory allocation

Chapter 5 C Functions

LAB 6 FUNCTIONS I School of Computer and Communication Engineering

Introduction to Programming Block Tutorial C/C++

Motor Industry Software Reliability Association (MISRA) C:2012 Standard Mapping of MISRA C:2012 items to Goanna checks

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

CSE 333 Autumn 2013 Midterm

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

CS 326 Operating Systems C Programming. Greg Benson Department of Computer Science University of San Francisco

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

C Review. MaxMSP Developers Workshop Summer 2009 CNMAT

Tutorial 1: Introduction to C Computer Architecture and Systems Programming ( )

Fundamentals of Programming & Procedural Programming

Lecture 9 - C Functions

#include. Practical C Issues: #define. #define Macros. Example. #if

Variables Data types Variable I/O. C introduction. Variables. Variables 1 / 14

CS201 Some Important Definitions

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

CODE TIME TECHNOLOGIES. Abassi RTOS MISRA-C:2004. Compliance Report

When you add a number to a pointer, that number is added, but first it is multiplied by the sizeof the type the pointer points to.

Chapter 14 - Advanced C Topics

COMP322 - Introduction to C++

PROGRAMMAZIONE I A.A. 2017/2018

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

Memory Allocation in C

Gabriel Hugh Elkaim Spring CMPE 013/L: C Programming. CMPE 013/L: C Programming

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

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

The C standard library

Chapter 3 - Functions

C Functions. 5.2 Program Modules in C

A506 / C201 Computer Programming II Placement Exam Sample Questions. For each of the following, choose the most appropriate answer (2pts each).

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

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

CSE 333 Midterm Exam July 24, Name UW ID#

Introduction to C++ Systems Programming

Lectures 5-6: Introduction to C

LAB 6 FUNCTION PART 1 School of Computer and Communication Engineering Universiti Malaysia Perlis

C Programming for Engineers Functions

EL2310 Scientific Programming

#include <stdio.h> int main() { char s[] = Hsjodi, *p; for (p = s + 5; p >= s; p--) --*p; puts(s); return 0;

Model Viva Questions for Programming in C lab

Transcription:

Lesson 5: Functions and Libraries 1

Functions 2

Overview Function is a block of statements which performs a specific task, and can be called by others Each function has a name (not identical to any other), parameters (or arguments), and a return type Benefits: Break down a program into smaller problems Reuse in multiple places or in multiple programs Syntax: <return type> <function name>(<list of parameters>) { Declaration of local variables Statements return statement used to exit a function and return a value 3

Example Function to calculate the sum of two numbers double sum(double x, double y) { double z = x+y; return z; int main() { double x = 10, y = sum(2,3); printf("x + y = %g", sum(x,y)); return 0; Parameters and local variables are valid only in the scope of the function 4

Scopes of variables, constants 5 Global variables/constants: declared outside of all functions, have program scope, accessible from anywhere in program, and only destroyed when program ends Local: declared inside a function or block, exist only in that function/block, and destroyed when exit that function/block Local variables/constants of same names hide those from a wider scope In C, local variables/constants must be declared on top of functions/blocks Ex: int x = 10, y = 20; int sum() { int z = x+y; return z; int main() { int x = 1, y = 2; int z = sum(); /* returns: 10+20 */ return 0;

Variables/constants in blocks 6 Variables/constants can be declared in statement blocks {, and exists only in those blocks Ex: int x = 1, y = 2; int sum(int x, int y) { return x+y; int a = 1000, b = 2000; int main() { int x = 10, y = 20; { int x = 100, y = 200; x+y; x+y; sum(a,b); return 0;

Variables/constants in blocks: loops Exist only in one iteration of the loop, and will be recreated and reinitialized on next iteration Ex: int x = 20; for (i=0; i<10; i++) { int y = 20; x++; y++; printf("%d %d\n", x, y); 7

Static variables Local static variables: variables with local scope but exist during all the runtime of program, even when before entering and after exiting the function/block Declared by static keyword int callcount() { static int count = 0; count++; return count; Global static variables: are local variables of a source file static int tic_time = 0; void tic() { tic_time = clock(); int toc() { return clock() - tic_time; Static functions: self-study 8

return statement Terminates a function and returns a value to the caller int find(int number, int a[], int n) { int i; for (i=0; i<n; i++) if (number == a[i]) return i; return -1; Void functions: do not return values void copy(int *a, int *b, int n) { if (a==null b==null a==b n==0) return; for (; n>0; n--) *a++ = *b++; return statement without parameter return statement at the end of function is not required 9

Passing parameters by value and by reference Function parameters are temporary variables created on function calls and destroyed when functions end assigning values to parameters does not have effect on original variables void assign10(int x) { x = 10; x (int) int main() { int a = 20; assign10(a); copy printf("a = %d", a); return 0; a User pointers if desire to modify value of original variables 10 void assign10(int *x) { *x = 10; int a = 20; assign10(&a); x (int*) Pointer parameters are often used as an alternative way to return values to callers, as each function has only one real return value &a copy a

Pointers returned from functions Issue of returning address of local variables: int* sum(int x, int y) { int z = x+y; int* sum() { z return &z; copy address 11 int* p = sum(2, 3); /* error */ Solution: allocate memory inside function int* sum(int x, int y) { int* z = (int*)malloc(sizeof(int)); *z = x+y; return z; int* p = sum(2, 3); /*... */ free(p); int* sum() { z p copy p *z

Function prototype & forward declaration Function prototype: used to declare functions before calls, but the their definitions are put lower usually declared on top of source files or in header files (.h files) Ex: 12 double sum(double x, double y); double prod(double x, double y); int main() { double x = 5., y = 10.; sum(x, y); prod(x, y); return 0; double sum(double x, double y) { return x+y; double prod(double x, double y) { return x*y;

Recursive functions Are functions that calls themselves Example 1: factorial of an integer n unsigned int factorial(unsigned int n) { if (n <= 1) return 1; return n * factorial(n-1); Example 2: x to the power of n double power(double x, unsigned int n) { double y; if (n == 0) return 1; y = power(x, n/2); if (n%2 == 0) return y*y; return y*y*x; Might be ineffective if too many calls do not abuse 13

Function pointers Are pointers to functions a data type in C, usually used to call functions that are unspecified at writing time double (*SomeOpt)(double, double); typedef double (*OptFunc)(double, double); OptFunc SomeOpt; Ex: double sum(double x, double y) { return x+y; double prod(double x, double y) { return x*y; int main() { double (*SomeOpt)(double, double) = SomeOpt(2., 5.); /* same as: sum(2., 5.); */ SomeOpt = prod; (*SomeOpt)(2., 5.); /* same as: prod(2., 5.); */ return 0; Attn: using & in assignments and * in calls is optional 14

Macros Macros are named code fragments. Whenever the name is used, it is replaced by the contents of the macro. #define ERROR { printf("error, exit now!"); exit(-1); int main(int argc, char* argv[]) { if (argc!= 3) ERROR /* */ return 0; Macros are replaced when other macros of the same names is defined Remove (undefine) macros: #undef ERROR Check if a macro is defined or not: #ifdef ERROR /*... */ #else /*... */ #endif 15

Macros (cont.) Macros can accept parameters resemble to functions in usage #define MIN(x,y) x<y? x:y z = MIN(2,4); /* z = 2<4? 2:4; */ #define PI 3.1415 #define AREA(R) R*R*PI z = AREA(5); /* z = 5*5*3.1415; */ Attention to side effects #define MUL(x,y) x*y z = MUL(2,4); /* z = 2*4; */ z = MUL(2+1,4); /* z = 2+1*4; */ z = 8/MUL(1+1,2); /* z = 8/1+1*2; */ #define MUL(x,y) ((x)*(y)) z = MUL(2+1,4); /* z = ((2+1)*(4)); */ z = 8/MUL(1+1,2); /* z = 8/((1+1)*(2)); */ #define SQR(x) ((x)*(x)) z = SQR(i); /* z = ((i)*(i)); */ z = SQR(i++); /* z = ((i++)*(i++)); */ 16

Libraries 17

Overview A program may be broken into many source files, each one contains a group of functions that realize a certain part of the program, and can be used in multiple places Certain functions can be used by many other programs function libraries A function library has 2 parts: A header file with.h extension including prototype of usable functions of the library A source file with.c extension including function implementations, or.obj,.lib files for compiled source Using a library: #include <header_file.h> /* in default folders */ #include "header_file.h" /* in the same folder */ #include directive replaces the content of the file at the declared position 18

Remarks for.h files Ex: writing abcd.h file To avoid #include the same file many times, add the following lines to the beginning and end of that file #ifndef ABCD_H #define ABCD_H /* Content of abcd.h file */ #endif Global variables must be declared in.c file, and a extern declaration must be added to the.h file if the variables need to be exported: extern int global_variable; Using abcd.h file #include "abcd.h" /*.h in same folder */ #include <abcd.h> /*.h in folders of libary */ 19

Example: Library to calculate area of shapes 20 area.h #ifndef AREA_H #define AREA_H extern const double PI; double circle_area(double r); double ellipse_area(double r1, double r2); double square_area(double l); double rect_area(double l1, double l2); #endif area.c const double PI = 3.1415; double circle_area(double r) { return r*r*pi; double ellipse_area(double r1, double r2) { return r1*r2*pi; double square_area(double l) { return l*l; double rect_area(double l1, double l2) { return l1*l2;

Some useful standard libraries Filename Description stdio.h ctype.h string.h Input, output with screen, files, keyboard, Check for character class (digit, letter, ) Character string processing memory.h Dynamic memory management math.h stdlib.h time.h Mathematic functions and constants Data conversion between numeric types and string, dynamic memory allocation, Time and date 21

Problems 1. Write a function to allocate memory and input values to an array of integers, then return the pointer to that array and n o of elements 2. Write prime( ) function that returns array of primes smaller than n 3. Define an array of struct MenuItem { title, task function, print a menu to screen, read user s choice then execute the corresponding task 4. Write a function to calculate the n th Fibonacci number defined as: Fib 0 = 0, Fib 1 = 1 Fib n = Fib n-1 + Fib n-2 (n 2) 5. Define String type and write a library including some functions: initialization, copy, concatenation, search, 6. Define a struct Shape then write a library including functions to calculate perimeter and area of shapes based on their types (circle, square, rectangle). Give two solutions: using switch structure and function pointer 22