LAB 7 FUNCTION PART 2

Similar documents
LAB 6 FUNCTIONS I School of Computer and Communication Engineering

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

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

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

C Functions. 5.2 Program Modules in C

Functions. Systems Programming Concepts

C Programming Lecture V

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

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

ECET 264 C Programming Language with Applications

CSE123. Program Design and Modular Programming Functions 1-1

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

Fundamentals of Programming & Procedural Programming

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

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

Chapter 4 Functions By C.K. Liang

LOOPS. 1- Write a program that prompts user to enter an integer N and determines and prints the sum of cubes from 5 to N (i.e. sum of 5 3 to N 3 ).

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

C Programs: Simple Statements and Expressions

Procedural Programming

CpSc 1011 Lab 4 Formatting and Flow Control Windchill Temps

Introduction to C Language

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

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

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

'C' Programming Language

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

Chapter 5 C Functions

Programming & Data Structure Laboratory. Day 2, July 24, 2014

UNIVERSITY OF TORONTO FACULTY OF APPLIED SCIENCE AND ENGINEERING

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

1001ICT Introduction To Programming Lecture Notes

Unit 7. Functions. Need of User Defined Functions

PROGRAMMING IN C LAB MANUAL FOR DIPLOMA IN ECE/EEE

Chapter 3 - Functions

Computer Programming

Loops / Repetition Statements

ECE15: Introduction to Computer Programming Using the C Language. Lecture Unit 4: Flow of Control

Methods: A Deeper Look

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

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

CS 108 Computing Fundamentals. October/November Array Bootcamp

Introduction to Programming

Chapter 1 Getting Started Structured Programming 1

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

Procedural Programming & Fundamentals of Programming

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

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

Multiple Choice Questions ( 1 mark)

Refraction of Light. c = m / s. n = c v. The index of refraction is never less than 1. Some common indices of refraction are listed below.

Built-in Types of Data

Arithmetic and Logic Blocks

EC 413 Computer Organization

COP 4516: Math for Programming Contest Notes

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

Chapter 9: Functions. Chapter 9. Functions. Copyright 2008 W. W. Norton & Company. All rights reserved.

Chapter 7 Functions. Now consider a more advanced example:

Mentor Graphics Predefined Packages

Home Lab 7 Refraction, Ray Tracing, and Snell s Law

15 FUNCTIONS IN C 15.1 INTRODUCTION

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

speed of light in vacuum = speed of light in the material

Main Program. C Programming Notes. #include <stdio.h> main() { printf( Hello ); } Comments: /* comment */ //comment. Dr. Karne Towson University

CT 229 Java Syntax Continued

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

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

OBJECTIVE QUESTIONS: Choose the correct alternative:

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

UNIVERSITY OF TORONTO FACULTY OF APPLIED SCIENCE AND ENGINEERING

Functions. Arash Rafiey. September 26, 2017

Carleton University Department of Systems and Computer Engineering SYSC Foundations of Imperative Programming - Winter 2012

Function Calls. 1 Administrivia. Tom Kelliher, CS 240. Feb. 13, Announcements. Collect homework. Assignment. Read

Investigation 21A: Refraction of light

Computational Physics

UEE1302(1066) F12: Introduction to Computers and Programming Function (II) - Parameter

from Appendix B: Some C Essentials

Fixed point algorithmic math package user s guide By David Bishop

I2204 ImperativeProgramming Semester: 1 Academic Year: 2018/2019 Credits: 5 Dr Antoun Yaacoub

Functions Introduction to Algorithms and Programming II School of Computer Science Term: Summer 2013 Instructor: Dr. Asish Mukhopadhyay

MA 511: Computer Programming Lecture 2: Partha Sarathi Mandal

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

Programming for Engineers in Python. Recitation 2

C Functions Pearson Education, Inc. All rights reserved.

UNIVERSITY OF WINDSOR Fall 2007 QUIZ # 2 Solution. Examiner : Ritu Chaturvedi Dated :November 27th, Student Name: Student Number:

CS1100 Introduction to Programming

UNIT 3 FUNCTIONS AND ARRAYS

Structured programming

Computing and Statistical Data Analysis Lecture 3

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


There are three steps involved in converting your idea of what is to be done to a working program

ME 172. C Programming Language Sessional Lecture 8

BSM540 Basics of C Language

Learning to Program with Haiku

Purpose: To determine the index of refraction of glass, plastic and water.

Python. Olmo Zavala R. Python Exercises. Center of Atmospheric Sciences, UNAM. August 24, 2016

Unit III Functions. C functions can be classified into two categories, namely, library functions and user defined functions.

Refraction Ch. 29 in your text book

Computer Science & Engineering 150A Problem Solving Using Computers

FUNCTIONS. Without return With return Without return With return. Example: function with arguments and with return value

Transcription:

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

OBJECTIVES 1. To differentiate the file scope and block scope. 2. To write recursive function. 3. To use library functions in a C program. 4. To write user-defined library function. NOTES Part 1 Scope 1. An identifier declared outside any function has file scope. Such an identifier is known (i.e., accessible) in all functions from the point at which the identifier is declared until the end of the file. Global variables, function definitions, and function prototypes placed outside a function all have file scope. 2. Block Identifiers defined inside a block have block scope. Block scope ends at the terminating right brace () of the block. Local variables defined at the beginning of a function have block scope as do function parameters, which are considered local variables by the function. 3. Global variables are defined outside a function, usually on top of the program. Global variables hold their values throughout the lifetime of your program and they can be accessed inside any of the functions defined for the program. This can be illustrated in Figure 1. #include <stdio.h> int x; /* Global variable, declared outside any function. */ void funct(void); main() x = 0; /* x isn't declared in main()*/ x++; /* increment x */ printf("the value of x is %d\n", x); funct(); /* x will be different after funct() */ printf("the value of x is %d\n", x); void funct(void) x++; /* x isn't declared in funct()*/ x += 3; Figure 1 Global variable 2

Sample output: The value of x is 1 The value of x is 5 4. Variables that are declared inside a function or block are called local variables. They can be used only by statements that are inside that function or block of code. Local variables are not known to functions outside their own. This can be illustrated in Figure 2. #include <stdio.h> void funct(void); main() int x; /* Local variable, declared inside any function. */ x = 0; x++; /* increment x */ printf("the value of x is %d\n", x); funct(); /* x will be the same after funct() */ printf("the value of x is %d\n", x); void funct(void) int x; /* Local variable, declared inside any function. */ x++; x += 3; Sample output: The value of x is 1 The value of x is 1 Figure 2 Local variable 5. If we want a variable to persist throughout the running of the program. This is where the static type comes in. The use of the static variable allows the variable to be incremented and for the value to be remembered throughout the program. This can be illustrated in Figure 3. 3

#include <stdio.h> int times_called(void); main() int i; for (i = 0; i < 10; i++) printf("times_called() has been called %d times\n",times_called()); int times_called(void) /* The variable is declared and defined once*/ static int i = 0; ++i; /* Incrementing the variable */ return i; Figure 3 Static variable Sample output: times_called() has been called 1 times times_called() has been called 2 times times_called() has been called 3 times times_called() has been called 4 times times_called() has been called 5 times times_called() has been called 6 times times_called() has been called 7 times times_called() has been called 8 times times_called() has been called 9 times times_called() has been called 10 times Part 2 Recursive function 1. A recursive function is a function that called itself. 2. The recursive functions should be used very carefully because when a function called by itself it enters into infinite loop. And when a function enters into the infinite loop, the function execution never gets completed. We should define the condition to exit from the function call so that the recursive function gets terminated. 4

#include<stdio.h> int factorial(int); int main() int fact, n; printf("enter any positive integer:\n"); scanf("%d", &n); fact = factorial(n); printf("factorial of %d! is %d\n", n, fact); return 0; int factorial(int n) if (n == 0) return 1; else return(n * factorial(n-1)); Sample output: Enter any positive integer: 3 Factorial of 3! = 6 Figure 4 An example of a recursive function 3. In the above example program, the factorial() function call is initiated from main() function with the value 3. Inside the factorial() function, the function calls factorial(2), factorial(1) and factorial(0) are called recursively. The complete execution process of the program in Figure 4 is shown in Figure 5. 5

Figure 5 Execution process of the program in Figure 4 (source: http://www.btechsmartclass.com) 6

Part 3 Library functions 1. C supports many built-in functions. Table 1 and Table 2 lists mathematical functions available in C. Most of the functions expect one or more type double arguments and return a type double result. Table 1 Some mathematical Library Functions 7

Table 2 More mathematical library functions 2. The program in Figure 6 shows how to use some of the mathematical functions in Table 1 and Table 2. 8

#include <stdio.h> #include <math.h> int main() double x,y; printf("acos(0.5)\t%f\n", acos(0.5)); printf("asin(0.5)\t%f\n", asin(0.5)); printf("cos(0.3)\t%f\n", cos(0.3)); printf("cosh(0.5)\t%f\n", cosh(0.5)); printf("sin(0.5)\t%f\n", sin(0.5)); printf("sinh(0.5)\t%f\n", sinh(0.5)); printf("tan(0.5)\t%f\n", tan(0.5)); printf("tanh(0.5)\t%f\n", tanh(0.5)); printf("abs(-7)\t\t%f\n", abs(-7)); printf("ceil(-3.3)\t%f\n", ceil(-3.3)); printf("exp(0.5)\t%f\n", exp(0.5)); printf("fabs(-3.3)\t%f\n", fabs(-3.3)); printf("floor(-3.3)\t%f\n", floor(-3.3)); printf("log(0.5)\t%f\n", log(0.5)); printf("log10(0.5)\t%f\n", log10(0.5)); printf("pow(2,3)\t%f\n", pow(2,3)); printf("sqrt(2)\t\t%f\n", sqrt(2)); return 0; Figure 6 Trigonometric and hyperbolic functions Sample output: acos(0.5) 1.047198 asin(0.5) 0.523599 cos(0.3) 0.955336 cosh(0.5) 1.127626 sin(0.5) 0.479426 sinh(0.5) 0.521095 tan(0.5) 0.546302 tanh(0.5) 0.462117 abs(-7) 0.462117 ceil(-3.3) -3.000000 exp(0.5) 1.648721 fabs(-3.3) 3.300000 floor(-3.3) -4.000000 log(0.5) -0.693147 log10(0.5) -0.301030 pow(2,3) 8.000000 sqrt(2) 1.414214 9

Part 4 User-defined library function 1. We have seen how the availability of C s standard libraries simplifies program development. However, the standard libraries are not extensive enough to handle every programming need. In fact, one can use the C preprocessor directive #include to make userdefined libraries as well. 2. To create a user-defined library, we must first make a header file (.h extension) a text file containing all the information about a library needed by the compiler when compiling a program that uses the facilities defined in the library. Precisely this type of data is found in system header files such as stdio.h, math.h, and string.h. 3. In Code Block, you must create a new project and put them in appropriate folders i.e. header files into header s folder and source files into source s folder as shown in Figure 7. Figure 7 A project with user-defined library function 4. Basically we will have 3 separate files in a project e.g. shapes.h (Figure 8), shapes.c (Figure 9) and main.c (Figure 10). /*shapes.h*/ void horizontalline();//function declaration(prototype) void triangle();//function declaration(prototype) Figure 8 shapes.h 10

EKT 120 Introduction to Computer Programming Laboratory Module /*shapes.c*/ void horizontalline() /*function definition*/ printf("\n*********\n"); void triangle()/*function definition*/ int i, space, rows=6, star=0; /* printing one row in every iteration */ for(i = 1; i <= rows; i++) /* Printing spaces */ for(space = 1; space <= rows-i; space++) printf(" "); /* Printing stars */ while(star!= (2*i - 1)) printf("*"); star++;; star=0; /* move to next row */ printf("\n"); Figure 9 shapes.c /*main.c*/ #include "shapes.h" int main() triangle(); /*function call*/ horizontalline(); /*function call*/ return 0; Sample output: Figure 10 main.c * *** ***** ******* ********* *********** ********* 11

EKT 120 Introduction to Computer Programming Laboratory Module PART 1 STRUCTURED QUESTIONS i. Predict and write the output for the program shown in Figure 11. #include <stdio.h> void function1(int, int); void function2(int *, int); int main() int a = 5; int b = 10; printf("\nbefore function1: a = %d function1(a, b); printf("\nafter function1: a = %d b = %d", a, b); b = %d", a, b); printf("\n\nbefore function2: a = %d b = %d", a, b); function2(&a, b); printf("\nafter function2: a = %d b = %d\n", a, b); return 0; void function1(int p, int q) p = p + 5; q = q + 5; printf("\nwithin function1: p = %d void function2(int *r, int s) *r = *r - 5; s = s -5; printf("\nwithin function2: *r = %d q = %d", p, q); s = %d", *r, s); Figure 11 12

EKT 120 Introduction to Computer Programming Laboratory Module ii. The following questions are based on Figure 12. #include <stdio.h> void fnfun1(int, int*); int main(void) int ia=3,ib=6; printf("before fun 1\n ); printf( ia = %d ib = %d \n,ia,ib); fnfun1(ia, &ib); printf( \n\nafter fun 1\n ); printf( ia = %d ib = %d \n,ia,ib); return 0; void fnfun1(int iaa,int *ibb) ++iaa; --*ibb; printf("\n\ninside fnfun1\n ); printf( iaa = %d ibb = %d \n,iaa,*ibb); Figure 12 a) Identify and state the parameter which is passed by value and by reference to function fnfun1(int, int*). b) State the difference between the passing parameter by value and by reference in functions. c) Predict the output of Figure 12. 13

EKT 120 Introduction to Computer Programming Laboratory Module PART 2 PROGRAMMING QUESTION i. Write and test a recursive function that finds the greatest common divisor of two integers m and n, using Euclid's algorithm: a) Find the integer remainder of min (m mod n). a) If the remainder is 0, then n is the largest integer divisor of both m and n. b) If the remainder is not 0, replace m with n and n with the integer remainder from the original division. Repeat the steps until the remainder is 0. For example, what is the greatest common divisor of 30 and 12? a) The integer remainder of 30/12 is 6. b) The remainder is not 0. c) The integer remainder of 12/6 is 0. Therefore, 6 is the largest integer divisor of both m and n. ii. Write and test a recursive function that returns 1 if an integer is prime and 0 if it is not. You can take advantage of the following facts: a) The integers 1, 2, and 3 are prime. b) Any even integer greater than 2 is not prime. c) If an integer has no divisor less than or equal to its square root, it must be prime. That is, if an integer has a divisor greater than or equal to its square root, it must also have a divisor less than or equal to its square root. Odd integers that are perfect squares, such as 49, have two divisors, each of which is equal to the square root. To implement this algorithm, it is helpful the use two separate functions, one of which has a single parameter associated with the integer to be tested. The prototypes should look like this: int Is_Prime(int n); int Get_Prime(int n,int m); where n is the integer to be tested and m is a trial divisor. Only the function Is_Prime is called directly. Then Is_Prime conducts some preliminary tests on n and calls Get_Prime only if the other tests cannot determine whether n is prime. Of these two functions, only Get_Prime is called recursively. 14

EKT 120 Introduction to Computer Programming Laboratory Module iii. Snell's Law describes the refraction (bending) of light as it passes from one medium to another. If the refractive index of the incident medium is n j and that of the refracting medium is n r, and the angle of incidence i and angle of refraction r of a ray of light, measured from the perpendicular to the boundary between the two mediums, are related by n i sin i = n r sin r Figure 13 illustrates the geometry of Snell s Law. Write a program that asks the user to provide two refractive indices and the angle of an incident ray and then calculates the angle of a refracted ray. Use mathematical library functions to construct the formula. Figure 13 Geometry for Snell s Law of refraction The formula to determine the angle of the refracted ray is: Table 3 gives the angles of refraction for some common materials when a light ray is directed from air, which has a refractive index equal to 1, into the material. Table 3 15

EKT 120 Introduction to Computer Programming Laboratory Module Sample output: Input indices of refraction for incident and refracting medium (water, glass or diamond) separated by spaces: 1 1.50 Input angle of incident: 20 Refracted angle = 13.8 degree iv. Create a project named calculator and write a header file named calculator.h, a function definition file, calculator.c and a main.c into the project. The program should take as input two integers and the operation to be performed. It should then output the numbers, the operator, and the result (For division, if the denominator is zero, output an appropriate message). Sample output : Please enter 2 integers: 4 2 Please enter an operator (+, -, *,/): * Result : 8 Do you want to continue : y or n?y Please enter 2 integers: 2 0 Please enter an operator (+, -, *,/): / ERROR denominator is zero!cannot divide by zero Do you want to continue : y or n?n Define function prototypes in calculator.h: a) double add(double,double); b) double multiply(double,double); c) double divide(double,double); d) double subtract(double,double); 16