Fundamentals of Programming & Procedural Programming

Similar documents
Procedural Programming

Fundamentals of Programming & Procedural Programming

Chapter 7 Functions. Now consider a more advanced example:

Fundamentals of Programming & Procedural Programming

EK131 E5 Introduction to Engineering

Unit 7. Functions. Need of User Defined Functions

Subject: Fundamental of Computer Programming 2068

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

EC 413 Computer Organization

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

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

BSM540 Basics of C Language

Functions BCA-105. Few Facts About Functions:

Lecture 05 I/O statements Printf, Scanf Simple statements, Compound statements

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

Pointers and scanf() Steven R. Bagley

Lecture 9 - C Functions

Lecture 16. Daily Puzzle. Functions II they re back and they re not happy. If it is raining at midnight - will we have sunny weather in 72 hours?

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

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

Lecture 6. Statements

Functions. Arash Rafiey. September 26, 2017

C Functions. 5.2 Program Modules in C

Fundamentals of Programming Session 4

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

Functions. Systems Programming Concepts

Chapter 5 C Functions

ALGORITHM 2-1 Solution for Exercise 4

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

Module 4: Decision-making and forming loops

Fundamentals of Programming. Lecture 3: Introduction to C Programming

EXAMINATION FOR THE BSC (HONS) INFORMATION SYSTEMS; BSC (HONS) INFORMATION TECHNOLOGY & BSC (HONS) COMPUTER SCIENCE; YEAR 1

Slide Set 1. for ENCM 339 Fall Steve Norman, PhD, PEng. Electrical & Computer Engineering Schulich School of Engineering University of Calgary

15 FUNCTIONS IN C 15.1 INTRODUCTION

Fundamentals of Programming Session 13

MA 511: Computer Programming Lecture 2: Partha Sarathi Mandal

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

Fundamentals of Programming Session 8

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

Scheme G. Sample Test Paper-I. Course Name : Computer Engineering Group Course Code : CO/CD/CM/CW/IF Semester : Second Subject Tile : Programming in C

Lecture 2: C Programming Basic

CSE123. Program Design and Modular Programming Functions 1-1

OBJECTIVE QUESTIONS: Choose the correct alternative:

بسم اهلل الرمحن الرحيم

A PROBLEM can be solved easily if it is decomposed into parts. Similarly a C program decomposes a program into its component functions.

Module 10A Lecture - 20 What is a function? Why use functions Example: power (base, n)

M.EC201 Programming language

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

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

QUIZ Lesson 4. Exercise 4: Write an if statement that assigns the value of x to the variable y if x is in between 1 and 20, otherwise y is unchanged.

4. C++ functions. 1. Library Function 2. User-defined Function

Procedural programming with C

Lecture 04 FUNCTIONS AND ARRAYS

Computer Science & Engineering 150A Problem Solving Using Computers

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

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

Wipro Technical Interview Questions

Fundamentals of Programming Session 14

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

Func%ons. CS449 Fall 2017

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

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

User Defined Functions

Lecture 12 Modular Programming with Functions

Programming for Engineers Introduction to C

AMCAT Automata Coding Sample Questions And Answers

WARM UP LESSONS BARE BASICS

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

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

C Programming Language

Loops / Repetition Statements

FUNCTIONS OMPAL SINGH

C Programming for Engineers Functions

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

Fundamental of Programming (C)

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

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

M.CS201 Programming language

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

Materials covered in this lecture are: A. Completing Ch. 2 Objectives: Example of 6 steps (RCMACT) for solving a problem.

6 Functions. 6.1 Focus on Software Engineering: Modular Programming TOPICS. CONCEPT: A program may be broken up into manageable functions.

C++ PROGRAMMING SKILLS Part 3 User-Defined Functions

EL6483: Brief Overview of C Programming Language

UNIVERSITY OF TORONTO FACULTY OF APPLIED SCIENCE AND ENGINEERING

PERIYAR CENTENARY POLYTECHNIC COLLEGE Periyar Nagar- Vallam Thanjavur

Questions Bank. 14) State any four advantages of using flow-chart

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #16 Loops: Matrix Using Nested for Loop

C: How to Program. Week /Mar/05

SUHAIL T A

Programming and Data Structure

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

PROGRAMMAZIONE I A.A. 2017/2018

Lecture 3: C Programm

Computer Science & Engineering 150A Problem Solving Using Computers

Control Structure: Loop

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

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

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

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

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

Transcription:

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 Name: First Name: Tutor: Matriculation-Number: Group-Number: Date: Prof. Dr.Ing. Axel Hunger Dipl.-Ing. Joachim Zumbrägel Universität Duisburg-Essen Faculty of Engineering, Department Electrical Engineering and Information Technology Computer Engineering Procedural Programming/Lab4 1

Getting familiar with Functions A function is a self contained program that carries out some specific purpose. Every C program consists of one or more functions, and if you recall from the first section one of these functions is the int main() function. Execution of a C program always begins with the int main() function. Any other functions used will be subordinate to the int main() function, and perhaps to one another. So, why should we actually use functions? Well, one of the main advantages of using functions is that they are used to divide up a program code into easy manageable sized portions. So they basically work like subtasks within a program. They can be executed (i.e. when it is called ) as many times as required from various points of the program. Once a function has carried out its intended action, control will be returned back to the point of the program from where it was accessed. Therefore, without the ability to use functions within our programs, our code would end up being much larger. Every function has a name which not only identifies it but is also used to call it for execution in a program. The name is global, but may not necessarily be unique in C. Nevertheless, functions with different actions should be supposed to have different names in general. The rules governing the name of a function are same as those used for a variable. The name of a function can be a sequence of letters and digits and should reflect its action in general, for example, you might name a function as CountUpper() which counts all upper case letters. Functions can either be user defined or they can be built in in a standard library file, such as the pow() function used to raise a number to a certain power in the math.h library file. Note: To use the functions which are located in a C library file, you must include the corresponding header file at the start of the program. Procedural Programming/Lab4 2

Declaring a Function We already know that we need to declare a variable prior to using it. Similarly, you can t use a function without declaring it first. Functions are declared by first telling the compiler about its some characteristics, i.e. the name of the function, the return type of the function, the number of arguments and their data types. Syntax: return-type function-name(type1 argument1,.,typen argumentn); For example, double pow(double x, double y); Explanation: The function pow() returns a value of type double. It has two arguments, x and y. The first argument x, should be of data type double, the second argument y, should also be of data type double. Exercise 4.1: Write a function declaration for a function named afunc() which returns a value of type integer and has two arguments of type double. Function Definition The function definition consists of a function definition header, followed by the function body. The function body is composed of statements that make up the function, delimited by braces. Syntax: return-type function-name(type1 argument1,.,typen argumentn) function body (statements and declarations) The function body consists of statements and declarations which allow the function to carry out its necessary task. The body of a user defined function is programmed very much similarly as the body of the main() function. Procedural Programming/Lab4 3

Explanation: return type: This defines the data type a function returns. A function might or might not return a value. If a function returns a value, that should be of a valid data type. The return data type can be of integer, float, character or any other valid data type. A returning variable data type should have a matching return type data type. There can be functions which don t return a value. For such type of functions, the return type is void. void is a keyword of C language. If a return type is not mentioned with a function, the default return type value is of int data type i.e. it will return an integer value. function name: Like naming variables, same rules apply while naming functions. It s generally a good practice to use function names which are self explanatory such as square, squareroot, circlearea etc. argument list: The argument list consists of information needed to pass to a function. Some functions don t need any type of information to perform the task. Consequently, the argument list will be empty for such functions. Arguments to a function should be of a valid data type e.g. double radius, int number etc. function body: The body of the function consists of declarations and statements. The task of the function is performed within the body of the function. Calling a Function within a Program In order to call a function, the calling program needs to reference the function name along with its arguments. When a function is called within a program, the control is immediately passed on to the function. The parameters are then substituted with values and the function is executed. The control is then transferred back to the called function, along with the returned values. For example, the statement within a program in the main() function outcome = factorial(num); calls the function factorial() and passes a copy of the value stored in the variable num from the function factorial(). Note: While calling a function, we don t need to mention the return value data type or the data types of arguments. Procedural Programming/Lab4 4

Exercise 4.2: Considering the given function declaration void func(int x, char y); State which of the following calls to the function are correct calls, and if not then why not? a. func(22.4, 49); b. func(3.14159); c. func(19.5, a ); d. func(52.3, 19, b ); e. func(62, c ); Sending Information to a Function Passing Arguments Whether a function is user defined or a standard library function, they can be further classified depending on its definition as: 1. Those which return a value 2. Those which don t return a value Assume, we have a function which computes the square of an integer value such a function will return the square of the given integer value. Similarly, we might have a function to display some type of information on the standard output screen and such type of a function is not supposed to return any value to the calling program. Functions that don t return a value and use in the declaration If you don t want a function to return a value, use the keyword void as the return type in its prototype. This means the function has no arguments. As another example, consider the following int getchar(void); Procedural Programming/Lab4 5

The function getchar(void) is a function returning an integer type value but does not take any arguments. Exercise 4.3: Write a function declaration for a function named voidfunc() which does not return a value. The function should have two arguments. The first argument should be a double and the second an integer. The keyword void can be used as a type specifier when defining a function which is not supposed to return anything (example 1) or when a function definition does not include any arguments (example 2). It s not compulsory to write this key word, but it s usually a good programming practice to use this. Such functions are also commonly used to display instructions to a user. Example 1: /* example: using void functions */ #include<stdio.h> void add(int a, int b); int main() add(3,2); void add(int a,int b) int sum; sum = a + b; printf( sum: %d\n,sum); Procedural Programming/Lab4 6

Example 2: Following program shows us an example of the definition of the void function Display_Stars(): /* example: using void functions */ #include <stdio.h> void Display_Stars(); int main() printf( \n ); for (int x = 1; x <= 5; ++x) Display_Stars(); Printf( \n ); printf( \n ); void Display_Stars(void) for (int y = 1; y <= 10; ++y) printf( * ); Explanation: This function has no arguments and does not return a value. So, its definition header does not have a parameter list and specifies the return type as void. It displays ten stars * using a for loop. Each iteration prints one star *. The last statement of the function body, the return statement, passes control back to the point of the program where the function Display_Stars() was called or executed, namely the int main() function. Exercise 4.4: Trace the output of the above program example and write it down below. Procedural Programming/Lab4 7

Exercise 4.5: Write a function header for a function which does not have any arguments and does not return a value. Returning a Value from a Function Arguments are used to pass values to a called function. A return value can be used to pass a value from a called function back to the function that called it. Example: /* example: value returning functions */ #include <stdio.h> int addnums(int x, int y); int main() int n1, n2; int sum = 0; printf( Enter the first number:\n ); scanf( %d,n1); printf( Enter the second number:\n ); scanf( %d,n2); sum = addnums(n1, n2); printf( n1 + n2 = %d\n, sum); int addnums(int x, int y) return x + y; Explanation: The above program uses the function addnums() to add two numbers of type integer. The return value is added by indicating its data type, here an int, in front of the function name in both the function prototype and the header. Procedural Programming/Lab4 8

Exercise 4.6: Write a function header for a function inttofloat that takes an integer number as an argument, and returns the result in floating point. Exercise 4.7: Write a function named hypotenuse which takes two double precision, floatingpoint arguments, side1 and side2, and returns a double precision, floating point result. Exercise 4.8: Write a function named largest which takes three integers values a, b and c, and then returns an integer. Procedural Programming/Lab4 9

Exercise 4.9: Write a program which uses a function to calculate the square of a user entered number. The function should take the user entered number as an argument. Procedural Programming/Lab4 10

Passing Arguments to a Function There are two approaches to pass the information to a function through arguments: by Value by Reference Passing Arguments by Value In C, arguments are passed by value, by default. Passing by value means that an argument's value is passed to a function, and not to the argument itself. Example: The following program illustrates passing arguments by value: /* example: pass by value */ #include<stdio.h> void func(int a) printf( a is %d\n,a); a = 5; printf( a is %d\n,a); int main() int b = 8; printf( b is %d\n,b); func(b); printf( b is %d\n,b); Passing Arguments by Reference Passing by reference means that the function parameters are declared as references rather than the normal variables. As we saw in an earlier session, printf() function used this method of argument passing by using format specifiers, also known as conversion specifiers. Please take note, this topic will be covered later on in detail in the Session on Pointers. Procedural Programming/Lab4 11

Variable Scope in functions Local Variables A variable which is declared within a function has a local scope which means the variable is known only inside the function. Any statement outside that function in which the variable is declared cannot change the value of that variable. Example: The following program shows how the local variables are used within a program when defined locally in a function. Here in the int main() function. /* example: local variables */ #include <stdio.h> int main() int x = 5; int y = 20; x++; if (y > 0) printf("x is %d", x); // value of x defined in main() can be seen if (y > 0) int x = 50; // value of x is defined locally in this block printf("\nx is %d", x); // value of x (i.e. 50) dies here printf(" \nx is %d", x); // value of x is now visible Exercise 4.10: Trace the value of the variable x in the above program example and write down its value after each output statement. Procedural Programming/Lab4 12

Global Variables A variable which is declared outside a functions body has a global scope which means the variable is known to any function defined after the declaration of that variable. So, due to its globality, any function coming after the declaration of that global variable can change the value of that global variable.example: The following program shows how the global and local variables both are used within a program. /* example: global variables */ #include <stdio.h> int y = 5; // Global definition int func(); int main() int value = 0; y++; // Increment Global variable printf("global value of y is: %d",y); value = func(); printf("\nlocal value of y returned from the function is: %d", value); int func() int y = 10; y++; return y; // Internal declaration // Internal variable Exercise 4.11: Trace the value of the variable y in the above program example and write down its value after each output statement. Procedural Programming/Lab4 13

Exercise 4.12: Find and correct the errors in the following: a) int result(double i, double j) int sum; sum = i + j; b) int sum(int x) if (x == 0) else sum(x - 1) + x; c) void g(float i); double i; printf( i:%f,i); Procedural Programming/Lab4 14

Recursive Functions The programs we discussed so far were generally structured having functions which call one another in a disciplined, hierarchical manner. But sometimes it s useful to have functions call themselves, known as recursive functions. A recursive function is a function that calls itself, either directly or indirectly through another function. Recursive problem solving approaches have a number of elements in common. A recursive function is called to solve a problem. Example: The following example uses a recursive function to print the Fibonacci series. Except first two terms, every other term in a Fibonacci series, is the sum of two previous terms. First few numbers of series are 0, 1, 1, 2, 3, 5, 8 and so on. Here for example: 8 = 3 + 5. /* recursive fibonacci function */ #include<stdio.h> int fibonacci(int); main() int n, i = 0, x; printf("please enter number of fibonacci terms you want to print:\n"); scanf("%d",&n); printf("fibonacci series\n"); for ( x = 1 ; x <= n ; x++ ) printf("%d\n", Fibonacci(i)); i++; int Fibonacci(int n) if ( n == 0 ) else if ( n == 1 ) return 1; else return ( Fibonacci(n-1) + Fibonacci(n-2) ); Procedural Programming/Lab4 15

Exercise 4.13: Write a program which uses a fibonacci() function that uses a loop instead of recursion to print the Fibonacci series. Procedural Programming/Lab4 16