Structured Programming. Functions and Structured Programming. Functions. Variables

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

8. Structures, File I/O, Recursion. 18 th October IIT Kanpur

Unit 7. Functions. Need of User Defined Functions

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

PROGRAMMAZIONE I A.A. 2017/2018

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

Dynamic memory allocation

15 FUNCTIONS IN C 15.1 INTRODUCTION

CSE 230 Intermediate Programming in C and C++ Functions

Flow of Control. Selection. if statement. True and False in C False is represented by any zero value. switch

Declaration Syntax. Declarations. Declarators. Declaration Specifiers. Declaration Examples. Declaration Examples. Declarators include:

Chapter 13. Functions and Parameter Passing (Part 2)

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

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

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

United States Naval Academy Electrical and Computer Engineering Department EC310-6 Week Midterm Spring AY2017

Arrays and Pointers. CSE 2031 Fall November 11, 2013

Modifiers. int foo(int x) { static int y=0; /* value of y is saved */ y = x + y + 7; /* across invocations of foo */ return y; }

Introduction to Programming

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

Functions. Chapter 5

Today's Topics. CISC 458 Winter J.R. Cordy

IMPORTANT QUESTIONS IN C FOR THE INTERVIEW

Arrays and Pointers. Arrays. Arrays: Example. Arrays: Definition and Access. Arrays Stored in Memory. Initialization. EECS 2031 Fall 2014.

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

CS-211 Fall 2017 Test 1 Version Practice For Test on Oct. 2, Name:

Overview (1A) Young Won Lim 9/14/17

ESC101N: Fundamentals of Computing End-sem st semester


Overview (1A) Young Won Lim 9/9/17

Introduction to Computer Science Midterm 3 Fall, Points

COP 3223 Introduction to Programming with C - Study Union - Fall 2017

UNIT 3 FUNCTIONS AND ARRAYS

Functions. Arash Rafiey. September 26, 2017

CS 261 Fall C Introduction. Variables, Memory Model, Pointers, and Debugging. Mike Lam, Professor

Pointers and scanf() Steven R. Bagley

Overview (1A) Young Won Lim 9/25/17

Fundamental of Programming (C)

Compiler Design. Spring Run-Time Environments. Sample Exercises and Solutions. Prof. Pedro C. Diniz

Memory Allocation in C

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

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

ECE264 Fall 2013 Exam 1, September 24, 2013

Functions and Recursion

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

CS 0449 Sample Midterm

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

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

Arrays and Pointers (part 2) Be extra careful with pointers!

COMP26120: Algorithms and Imperative Programming. Lecture 5: Program structuring, Java vs. C, and common mistakes

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

Functions BCA-105. Few Facts About Functions:

Multiple Choice Questions ( 1 mark)

CSCI 2132 Software Development. Lecture 17: Functions and Recursion

C: How to Program. Week /Apr/23

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

High Performance Programming Programming in C part 1

Variation of Pointers

UNIVERSITY OF WINDSOR Fall 2006 QUIZ # 1. Examiner:Ritu Chaturvedi Dated : Oct 3rd, Student Name: Student Number:

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

COP 3223 Introduction to Programming with C - Study Union - Fall 2017

C Introduction. Comparison w/ Java, Memory Model, and Pointers

CENG 447/547 Embedded and Real-Time Systems. Review of C coding and Soft Eng Concepts

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

C BOOTCAMP DAY 2. CS3600, Northeastern University. Alan Mislove. Slides adapted from Anandha Gopalan s CS132 course at Univ.

Computer Science & Engineering 150A Problem Solving Using Computers

THEORY OF COMPILATION

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

Solutions to Assessment

Arrays and Pointers (part 2) Be extra careful with pointers!

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

ITEC114 Structured Programming Midterm Exam, Spring 2015/ April Instructor: Akile Oday Research Assistant: Mohammed Abubakar SOLUTIONS

CSCI565 Compiler Design

Introduction to C. Systems Programming Concepts

Flow Control. CSC215 Lecture

High-performance computing and programming Intro to C on Unix/Linux. Uppsala universitet

Procedural programming with C

CSCI 2132 Software Development. Lecture 20: Program Organization

Chapter 6: User-Defined Functions. Objectives (cont d.) Objectives. Introduction. Predefined Functions 12/2/2016


are all acceptable. With the right compiler flags, Java/C++ style comments are also acceptable.

CSE 333 Midterm Exam 7/29/13

Friday, February 3, Lab Notes. Functions in C Arrays as parameters Pass by value vs pass by reference Programs 1 and 2

Arrays. Example: Run the below program, it will crash in Windows (TurboC Compiler)

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

Introduction to Computing Lecture 08: Functions (Part I)

Outline. Lecture 1 C primer What we will cover. If-statements and blocks in Python and C. Operators in Python and C

Lecture07: Strings, Variable Scope, Memory Model 4/8/2013

2. Which of the following will print the value 2 for the above code?

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

Common Misunderstandings from Exam 1 Material

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

DECLARAING AND INITIALIZING POINTERS

Kurt Schmidt. October 30, 2018

Lecture 3. Variables. Variables

Pointers, Arrays, and Strings. CS449 Spring 2016

G Programming Languages - Fall 2012

Array Initialization

Topic 6: A Quick Intro To C

Run-time Environments - 2

Transcription:

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 of the overall problem into finite subtasks. Each subtask can be coded directly as a function. 1 These functions can be used in main to solve the overall problem. 2 Functions Functions are the building blocks of C and the place where all program activity occurs. Function topics include: Function types Function variables Function arguments Function scopes Return values Function prototypes General syntax: ret-type function-name (parameter list) body of the function return (expression) A function may return any type of data except an array. The parameters receive the values of the arguments when the function is called. Recursion 3 4 VOID used to indicate: A. - No Return Value. B. - No Parameters or Arguments. * This allows Type compatibility to be handled by the compiler. void Fname (void) Variables A variable is a named location in memory that is used to hold a value that can be modified by the program. All variables must be declared before they can be used. 5 6 1

Where variables are declared: - Inside functions: local variables - Outside of all functions: global variables - In the function heading: formal parameters Local Variable Declared inside a function. Can be used only by statements that are inside the block in which the variables are declared. A local variable is created upon entry into its block and destroyed upon exit. void func1(void) int x; x = 10; void func2(void) int x; x = -199; 7 8 void f(void) int t; scanf("%d", &t); if(t==l) char s[80]; /* created only upon entry into this block */ /* s not known here */ int x; x = 10; if(x == 10) int x; /* this masks the outer x */ x = 99; printf("inner x: %d\n", x); 99 printf("outer x: %d\n", x); 10 9 10 Local variables are allocated in the Run-time stack. void f(void); int i; for(i=0; i<10; i++) f(); A valid call? void f(void) int j = 10; printf("%d ", j); j++; Prints What? Global Variables They are known throughout the program in which they are defined. They are declared outside of any function Storage for global variables is in a fixed region (Global Storage Area) and not the run-time stack. 11 12 2

int count; /* GLOBAL */ void func1(void); void func2(void); count = 100; func1(); printf("count is %d", count); void func1(void) int temp; temp = count; func2(); printf("count is %d", count); void func2(void) int count; /* LOCAL */ for(count=l; count<10; count++) putchar('.'); printf("count is %d", count); 13 Avoid using unnecessary global variables. They take up memory the entire time your program is executing. Using a global variable where a local variable will do makes a function less general. Using a large number of global variables can lead to program errors. 14 Function Parameters General form: fun-name( type varname1, type varname2,. ) All function parameters must be declared individually, each including both the type and name. void f(int i, int k, int j) /*correct*/ void f(int i, k, float j) /* wrong */ The Scope of a Function Each function is a discrete block of code. A function's code is private to that function and cannot be accessed by any statement in any other function except through a call to that function. Parameters behave like any other local variable. 15 16 Variables that are defined within a Function are local variables. Such variables are freed from memory when their function completes execution. The formal parameters to a function also fall within the function's scope. A parameter is known throughout the entire function. Therefore, a local variable cannot hold its value between function calls. A global variable has extern storage class. We will see the impact of this later. 17 A parameter comes into existence when the function is called and is destroyed when the function is exited,( I.e., the Extent of the variable). A function cannot be defined within a function (no nested-functions). 18 3

Communication with a Function Two ways that arguments can be passed to a function. Call by Value. Call by Reference. 19 Call by Value * When an Argument (variable, constant, or expression) is passed to a matching parameter (declared in Function Heading), A Copy of the Argument Value is made and is passed to the parameter. Arguments Parameters in calling in called Module. Module. * Changes made to the parameter have no effect on the argument. i.e., the parameter is implemented as a local variable which is initialized to the value passed from the Argument. 20 Call by Reference It is often convenient to have functions modify the values of the variables referred to in the Argument list. The address of an argument is copied into the parameter. Inside the subroutine, the address is used to access the actual argument used in the call. To effect call-by-reference we must use pointers in the Argument list & pass addresses of variables int sqr(int x); int t=10; printf("%d %d", sqr(t), t); What is output? int sqr(int t) t = t*t; return t; [see chap 8]. 21 22 Placement of Functions: Before the compiler sees a call to a function it wants to know the Number and Type of its Parameters and the type of the Return Value of the Function. Two methods of doing so: 1. Place Function Before main function 2. Provide Function Prototype Before the call. 23 void f(int a, int b) printf(''%d ", a%b); int main (void) f(10,3); Before Main 24 4

Function Prototypes A Function call can appear Before the function is Defined (i.e., code of function): * The called function can be defined later in the same file. * The called function can be in another file. Func Prototype is Heading of function. FP s - Can be placed at the top of the File - typically above any Function Definitions But below : #includes #defines IF the Function Prototype is provided Before the call. 25 This gives the FP s File Visibility. Know throughout the file. 26 Parameter Passing Call by Value /* This function returns the average of 3 exam scores which are passed call-by-value. */ double average(int, int, int); int test1, test2, test3; double avg; scanf( %d%d%d, &test1, &test2, &test3); avg = average(test1, test2, test3); printf( The average is: %f, avg); double average(int exam1, int exam2, int exam3) double testavg; testavg = (exam1 + exam2 + exam3)/ 3; return testavg; 27 28 Arguments to main( ) Information is passed into the main( ) function via command line arguments. Two special built-in arguments, argc and argv, are used to receive command line arguments. The argc parameter holds the number of arguments on the command line and is an integer. The argv parameter is a pointer to an array of character pointers. 29 #include <stdlib.h> int main( int argc, char *argv[] ) if(argc<2) printf(''you forgot to type your name.\n"); exit(1); printf("hello %s", argv[1] ); a.out John Input Hello John 30 5

Returning from a Function A function terminates execution and returns to the caller in two ways. 1. Occurs when the last statement in the function has executed. OR 2. Occurs when execute the return statement. return expression; It causes an immediate exit from the function. Returns program control to calling environment. Allows Returning of a value. The value of expression will become the return value of the function. 31 32 Return Rules You can use as many return statements as you like within a function. However, the function will stop executing as soon as it encounters the first return. /* Return 1 if c is part of string s; 0 otherwise. */ int is_in(char *s, char c) while (*s) if(*s==c) return 1; else s++; 33 The that ends a function also causes the function to return. It is the same as a return without any specified value. If this occurs within a non-void function, then the return value of the function is undefined. A function declared as void cannot contain a return statement that specifies a value. 34 A NON-VOID function can be used as an operand in an expression. The exit( ) Function General form void exit(int return_code); x = power(y); if(max(x,y) > 100) printf(''greater"); for(ch=getchar(); isdigit(ch); )... ; 35 This function causes immediate termination of the entire program, forcing a return to the operating system. The value of return_code is returned to the calling process, which is usually the operating system. 36 6

Programmers frequently use exit when a mandatory condition for program execution is not satisfied. #include <stdlib.h> if(!virtual_graphics()) exit(1); play();... 37 Recursion A function calls itself (circular definition). /* non-recursive */ int fact(int n) int t, answer; answer = 1; for(t=1; t<=n; t++) answer=answer*t; return answer; /* recursive */ int factr(int n) int answer; if(n==l) return 1; /* recursive call */ answer = factr(n-l)*n; return answer ; 38 7