Copyright©1998 Angus Wu PROGRAMMING METHDOLODGY AND SOFTWARE ENGINEERING EE 31331 PROGRAMMING METHODOLOGY AND SOFTWARE ENGINEERING.

Slides:



Advertisements
Similar presentations
Etter/Ingber Engineering Problem Solving with C Fundamental Concepts Chapter 4 Modular Programming with Functions.
Advertisements

Programming Languages and Paradigms The C Programming Language.
C++ Programming: Program Design Including Data Structures, Third Edition Chapter 7: User-Defined Functions II.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 7: User-Defined Functions II.
Chapter 7: User-Defined Functions II
C++ Programming: Program Design Including Data Structures, Third Edition Chapter 7: User-Defined Functions II.
Chapter 7: User-Defined Functions II Instructor: Mohammad Mojaddam.
Kernighan/Ritchie: Kelley/Pohl:
1 Review of Class on Oct Outline  Pointer  Pointers to void  Call-by-Reference  Basic Scope Rules  Storage Classes  Default Initialization.
1 Functions and Structured Programming. 2 Structured Programming Structured programming is a problem-solving strategy and a programming methodology. –The.
ARRAYS AND POINTERS Although pointer types are not integer types, some integer arithmetic operators can be applied to pointers. The affect of this arithmetic.
Review on pointers and dynamic objects. Memory Management  Static Memory Allocation  Memory is allocated at compiling time  Dynamic Memory  Memory.
 2003 Prentice Hall, Inc. All rights reserved. 1 Functions Modules: functions and classes Programs use new and “prepackaged” modules –New: programmer-defined.
C Lecture Notes Functions (Cont...). C Lecture Notes 5.8Calling Functions: Call by Value and Call by Reference Used when invoking functions Call by value.
1 Chapter 8 Functions, Pointers, and Storage Classes  Pointer  Pointers to void  Call-by-Reference  Basic Scope Rules  Storage Classes  Default Initialization.
1 Chapter 9 Pointers. 2 Topics 8.1 Getting the Address of a Variable 8.2 Pointer Variables 8.3 Relationship Between Arrays and Pointers 8.4 Pointer Arithmetic.
1 Chapter 8 Scope, Lifetime, and More on Functions Dale/Weems/Headington.
1 Review of Chapter 6: The Fundamental Data Types.
1 Functions Modules: functions and classes Programs use new and “prepackaged” modules –New: programmer-defined functions, classes –Prepackaged: from the.
FunctionsFunctions Systems Programming Concepts. Functions   Simple Function Example   Function Prototype and Declaration   Math Library Functions.
1 COMP 2130 Introduction to Computer Systems Computing Science Thompson Rivers University.
1 Chapter 9 Scope, Lifetime, and More on Functions.
Operator Precedence First the contents of all parentheses are evaluated beginning with the innermost set of parenthesis. Second all multiplications, divisions,
C Functions Programmer-defined functions – Functions written by the programmer to define specific tasks. Functions are invoked by a function call. The.
18-2 Understand “Scope” of an Identifier Know the Storage Classes of variables and functions Related Chapter: ABC 5.10, 5.11.
MAHENDRAN CHAPTER 6. Session Objectives Explain Type of Functions Discuss category of Functions Declaration & Prototypes Explain User Defined Functions.
C++ for Engineers and Scientists Second Edition Chapter 6 Modularity Using Functions.
1 Chapter 8 Scope, Lifetime, and More on Functions Dale/Weems/Headington.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition, Fifth Edition Chapter 7: User-Defined Functions II.
PASSING VALUE TO A FUNCTION # CALL BY VALUECALL BY VALUE # CALL BY REFERENCECALL BY REFERENCE STORAGE CLASS # AUTOAUTO # EXTERNALEXTERNAL # STATICSTATIC.
18. DECLARATIONS.
Chapter 11: Pointers Copyright © 2008 W. W. Norton & Company. All rights reserved. 1 Chapter 11 Pointers.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Pointers.
Lecture 22: Reviews for Exam 2. Functions Arrays Pointers Strings C Files.
C Functions Three major differences between C and Java functions: –Functions are stand-alone entities, not part of objects they can be defined in a file.
Week 6: Functions - Part 2 BJ Furman 01OCT2012. The Plan for Today Comments on midterm exam (next week in lab!) Review of functions Scope of identifiers.
Dale Roberts CSCI 230 Functions Scope, Parameter Passing, Storage Specifiers Department of Computer and Information Science, School of Science, IUPUI Dale.
Topic 3: C Basics CSE 30: Computer Organization and Systems Programming Winter 2011 Prof. Ryan Kastner Dept. of Computer Science and Engineering University.
Engineering Problem Solving with C Fundamental Concepts Chapter 4 Modular Programming with Functions.
FUNCTIONS. Funtions  The heart of effective problem solving is problem decomposition.  breaking a problem into small, manageable pieces  In C, the.
Review 1 List Data Structure List operations List Implementation Array Linked List.
Functions Illustration of: Pass by value, reference Scope Allocation Reference: See your CS115/215 textbook.
POINTERS Introduction to Systems Programming - COMP 1002, 1402.
1 Chapter 9 Scope, Lifetime, and More on Functions.
142 L -1 Pointers Chapter 6 C uses a call BY VALUE for functions for example: void add_one(int x, int y) { x=x+1; y=y+1; } int main(void) { int a,b; a=4;
Building Programs from Existing Information Solutions for programs often can be developed from previously solved problems. Data requirements and solution.
A First Book of ANSI C Fourth Edition
Pointers Lecture: 5. Topics 1 Pointers and the Address Operator 2 Pointer Variables 3 The Relationship Between Arrays and Pointers 4 Pointer Arithmetic.
Gator Engineering Copyright © 2008 W. W. Norton & Company. All rights reserved. 1 Chapter 9 Functions.
Arrays and Pointers (part 1) CSE 2031 Fall July 2016.
C Part 2 Computer Organization I 1 August 2009 © McQuain, Feng & Ribbens The Three Attributes of an Identifier Identifiers have three essential.
Topic 5 Addresses, Pointers and Arrays. 2 Objectives (Textbook Chapter 14) You should be able to describe: Addresses and Pointers Pointer Operators Pointer.
Chapter 7: User-Defined Functions II
C Functions -Continue…-.
Friend Class Friend Class A friend class can access private and protected members of other class in which it is declared as friend. It is sometimes useful.
Functions and Structured Programming
Pointers.
Programmazione I a.a. 2017/2018.
Lecture 6 C++ Programming
User-Defined Functions
C++ for Engineers and Scientists Second Edition
Scope, Parameter Passing, Storage Specifiers
Chapter 9 Scope, Lifetime, and More on Functions
Object Oriented Programming COP3330 / CGS5409
Chapter 7: User-Defined Functions II
Pointers Chapter 11 Copyright © 2008 W. W. Norton & Company.
Pointers Chapter 11 Copyright © 2008 W. W. Norton & Company.
Pointers Chapter 11 Copyright © 2008 W. W. Norton & Company.
Scope of Identifier The Scope of an identifier (or named constant) means the region of program where it is legal to use that.
Presentation transcript:

Copyright©1998 Angus Wu PROGRAMMING METHDOLODGY AND SOFTWARE ENGINEERING EE PROGRAMMING METHODOLOGY AND SOFTWARE ENGINEERING

Copyright©1998 Angus Wu PROGRAMMING METHDOLODGY AND SOFTWARE ENGINEERING C Programming Review

Copyright©1998 Angus Wu PROGRAMMING METHDOLODGY AND SOFTWARE ENGINEERING Program Structure Local and Global Variable Storage Classes Pointers Function Call

Copyright©1998 Angus Wu PROGRAMMING METHDOLODGY AND SOFTWARE ENGINEERING Local Variable variables declared within a function body #include int main() { int next, n; /* next input, number of inputs */ long sum = 0; /* running total */ double avg; /* average of input values */ for (n = 0; scanf("%i", &next) == 1; n++) sum += next; avg = (n == 0) ? 0.0 : (double) sum / n; printf("Average of %i values is %f.\n", n, avg); return 0; } next, sum, avg are local variables of main

Copyright©1998 Angus Wu PROGRAMMING METHDOLODGY AND SOFTWARE ENGINEERING Local Variable initializing local variables don’t count on local variables automatically being initialized to zero long sum = 0; /* running total */

Copyright©1998 Angus Wu PROGRAMMING METHDOLODGY AND SOFTWARE ENGINEERING Local Variable variables declared within a block avg is declared when it is needed. #include int main() { int next, n; /* next input, number of inputs */ long sum = 0; /* running total */ for (n = 0; scanf("%i", &next) == 1; n++){ sum += next; { /* compute and print input average */ double avg = (n == 0) ? 0.0 : (double) sum / n; printf("Average of %i values is %f.\n", n, avg); } return 0; }

Copyright©1998 Angus Wu PROGRAMMING METHDOLODGY AND SOFTWARE ENGINEERING Local Variable block/compound statements group of statements surrounded by braces { statement;. statement; } or statement, statement;

Copyright©1998 Angus Wu PROGRAMMING METHDOLOGY AND SOFTWARE ENGINEERING int main() { int x; x= 25; x= sq (x); printf(“%d\n”, x); return 0; } int sq ( int x) { x=x*x; return x; } Scope of Variable

Copyright©1998 Angus Wu PROGRAMMING METHDOLOGY AND SOFTWARE ENGINEERING Scope of Variable #include int sq(int x); int main() {int x; x= 25; printf(" The address of x in main is %d\n", &x); x= sq(x); printf("%d\n", x); return 0; } int sq(int a) { printf(" The address of a in sq is %d\n", &a); printf(" what is x %d\n", x); a=a*a; return a; }

Copyright©1998 Angus Wu PROGRAMMING METHDOLODGY AND SOFTWARE ENGINEERING Local Variable Lifetime they exist only from block entry to block exit they exist/are accessible only within the function where they are declared when enter a block/function, space is reserved for its local variables when exit the block/function, the reserved space is free

Copyright©1998 Angus Wu PROGRAMMING METHDOLODGY AND SOFTWARE ENGINEERING Global Variable exist throughout the life of the program known to all program AVOID GLOBAL VARIABLES WHENEVER POSSIBLE (for information hidden)

Copyright©1998 Angus Wu PROGRAMMING METHDOLODGY AND SOFTWARE ENGINEERING unsigned long charcnts[UCHAR_MAX + 1]; /* 0..UCHAR_MAX */ int main() { void print_counters(void); int c; while(c = getchar(), c != EOF) charcnts[c]++; print_counters(); return 0; } void print_counters(void) { int i; for (i = 0; i < UCHAR_MAX; i++) if (charcnts[i]) /* write count only when nonzero */ { printf("\\%03o ", i); isprint(i) ? printf("(%c)", i) : printf(" "); printf(": %lu\n", charcnts[i]); }

Copyright©1998 Angus Wu PROGRAMMING METHDOLODGY AND SOFTWARE ENGINEERING Storage Classes A variable’s storage class provides information about its visibility, lifetime, and location. auto register static extern

Copyright©1998 Angus Wu PROGRAMMING METHDOLODGY AND SOFTWARE ENGINEERING Storage Class - Auto it is the default storage class it derives from automatic creation and removal on block entry and exit it is used to make local variable explicit it is stored in memory{ auto int x, y; int x, y;.. } }

Copyright©1998 Angus Wu PROGRAMMING METHDOLODGY AND SOFTWARE ENGINEERING Storage Class it is the default storage class it derives from automatic creation and removal on block entry and exit it is used to make local variable explicit it is stored in memory{ auto int x, y; int x, y;.. } }

Copyright©1998 Angus Wu PROGRAMMING METHDOLODGY AND SOFTWARE ENGINEERING Storage Class - Register variables are stored in the machine’s high speed registers making frequently accessed variables register leads to faster and smaller programs restrictions only local variables and function parameters not global variables register variables is not kept in memory so can’t take it address with &

Copyright©1998 Angus Wu PROGRAMMING METHDOLODGY AND SOFTWARE ENGINEERING Storage Class - register restrictions can’t use scanf/similar functions to read a value directly into a register variable Example /* Faster version of array searching function. */ int table_search(int a[], register int n, register int t) { register int i; for (i = 0; i < n && a[i] != t; i++) ; /* search for matching value */ return (i != n) ? i : -1; }

Copyright©1998 Angus Wu PROGRAMMING METHDOLODGY AND SOFTWARE ENGINEERING Storage Class - static as local variables live only within the block in which they reside, it will be erased when exits the block/function keep the variable alive after leaving the block alternative to global variable

Copyright©1998 Angus Wu PROGRAMMING METHDOLODGY AND SOFTWARE ENGINEERING Storage Class - static Example /* Keep a count of times function is called (buggy version). */ #include int main() { void testfunc(void); testfunc(); testfunc(); testfunc(); return 0; } void testfunc(void) { int cnt = 0; printf("testfunc call #%i\n", ++cnt); }

Copyright©1998 Angus Wu PROGRAMMING METHDOLODGY AND SOFTWARE ENGINEERING Storage Class - static Example /* Keep a count of times function is called (working version). */ #include int main() { void testfunc(void); testfunc(); testfunc(); testfunc(); return 0; } void testfunc(void) { static int cnt = 0; printf("testfunc call #%i\n", ++cnt); }

Copyright©1998 Angus Wu PROGRAMMING METHDOLODGY AND SOFTWARE ENGINEERING Storage Class - extern use with global variables to refer to global variable its declaration will not lead to any memory allocation usage define global variable once, and use external declaration everywhere else

Copyright©1998 Angus Wu PROGRAMMING METHDOLODGY AND SOFTWARE ENGINEERING Storage Class - extern Example /* A program to count the different characters in its input. Ituses global variables to hold the counts. */ #include unsigned long charcnts[UCHAR_MAX + 1]; /* 0..UCHAR_MAX */ int chars = UCHAR_MAX + 1; int main() { void print_counters(void); int c; while(c = getchar(), c != EOF) charcnts[c]++; print_counters(); return 0; }

Copyright©1998 Angus Wu PROGRAMMING METHDOLODGY AND SOFTWARE ENGINEERING Storage Class - extern Example /** Function to print the character counts. */ #include void print_counters(void) {extern unsigned long charcnts[];/* table of counts */ extern int chars; /* entries in table */ int i; for (i = 0; i < chars; i++) if (charcnts[i]) /* write count only when nonzero */ { printf("\\%03o ", i); isprint(i) ? printf("(%c)", i) : printf(" "); printf(": %lu\n", charcnts[i]); }

Copyright©1998 Angus Wu PROGRAMMING METHDOLODGY AND SOFTWARE ENGINEERING Storage Class - extern void function(void) { extern variable... } an extern within a function provides type information to just that function

Copyright©1998 Angus Wu PROGRAMMING METHDOLODGY AND SOFTWARE ENGINEERING Storage Class - extern Example /* A program to count the different characters in its input. Ituses global variables to hold the counts. */ #include unsigned long charcnts[UCHAR_MAX + 1]; /* 0..UCHAR_MAX */ int chars = UCHAR_MAX + 1; void print_counters(void); int main() {int c; while(c = getchar(), c != EOF) charcnts[c]++; print_counters(); return 0; }

Copyright©1998 Angus Wu PROGRAMMING METHDOLODGY AND SOFTWARE ENGINEERING Storage Class - extern Example /* Function to print the character counts. */ #include extern unsigned long charcnts[];/* table of counts */ extern int chars; /* entries in table */ void print_counters(void) {int i; for (i = 0; i < chars; i++) if (charcnts[i]) /* write count only when nonzero */ { printf("\\%03o ", i); isprint(i) ? printf("(%c)", i) : printf(" "); printf(": %lu\n", charcnts[i]); }

Copyright©1998 Angus Wu PROGRAMMING METHDOLODGY AND SOFTWARE ENGINEERING Storage Class - extern extern variable.. ; void function(void) {. } an extern declared outside provides type information to all functions within a file by placing external declarations before any of them

Copyright©1998 Angus Wu PROGRAMMING METHDOLODGY AND SOFTWARE ENGINEERING Type Qualifier Storage Classes provide information about a variable’s lifetime and visibility Type Qualifiers provide additional information about how the variable is going to be used const int PAGELEN =60; declares PAGELEN as an int and its value should remain constant throughout its lifetime

Copyright©1998 Angus Wu PROGRAMMING METHDOLODGY AND SOFTWARE ENGINEERING Type Qualifier #include int main() { void print_counters(const unsigned long charcnts[]); static unsigned long charcnts[UCHAR_MAX + 1]; /* 0..UCHAR_MAX */ int c; while(c = getchar(), c != EOF) charcnts[c]++ print_counters(charcnts); return 0; }

Copyright©1998 Angus Wu PROGRAMMING METHDOLODGY AND SOFTWARE ENGINEERING Type Qualifier void print_counters(const unsigned long charcnts[]) { int i; for (i = 0; i < UCHAR_MAX; i++) if (charcnts[i]) /* write count only when nonzero */ { printf("\\%03o ", i); isprint(i) ? printf("(%c)", i) : printf(" "); printf(": %lu\n", charcnts[i]); }

Copyright©1998 Angus Wu PROGRAMMING METHDOLODGY AND SOFTWARE ENGINEERING Type Qualifier why not using #define instead of const const allows the compiler to flag as an error any attempt to assign a value to that variable #define is can’t be replaced with const totally Example #define MAXVALS 100 const int MAXVALS = 100 unsigned long buckets[MAXVALS];

Copyright©1998 Angus Wu PROGRAMMING METHDOLODGY AND SOFTWARE ENGINEERING Header File to avoid defining external declarations for constantly used variables and definition /*Main program using extern yes or no. */ #include int main() { int yesorno(void); extern const int YES, NO; printf("Enter a YES or NO answer: "); (yesorno() == YES)?printf("YES!\n"):printf("NO!\n"); return 0; }

Copyright©1998 Angus Wu PROGRAMMING METHDOLODGY AND SOFTWARE ENGINEERING Header File / * Prototypes and constants in "yesorno.h".*/ extern const int YES; extern const int NO; int yesorno(void); /*Main program using extern yes or no. */ #include #include “yesorno.h” int main() { printf("Enter a YES or NO answer: "); (yesorno() == YES)?printf("YES!\n"):printf("NO!\n"); return 0; }

Copyright©1998 Angus Wu PROGRAMMING METHDOLODGY AND SOFTWARE ENGINEERING Pointer What is it? It is simply a data type that can hold address int data; the compiler reserves a memory location to data lets it be location is data’s address or it is a pointer to data 10000

Copyright©1998 Angus Wu PROGRAMMING METHDOLODGY AND SOFTWARE ENGINEERING Pointer In C, a data’s value can be accessed directly by providing its name or indirectly through a pointer its called indirect pointer access or call- by-reference for parameter passing in function call

Copyright©1998 Angus Wu PROGRAMMING METHDOLODGY AND SOFTWARE ENGINEERING Pointer int *iptr ; /* pointer to integer */ declaration allocates space for the named pointer variable, but not make it point to anything to use it, use the address operator & to return the address of its operand iptr = &data ; pointer iptr points to data, assuming data is stored in memory location 10000, then iptr contains 10000

Copyright©1998 Angus Wu PROGRAMMING METHDOLODGY AND SOFTWARE ENGINEERING Pointer Accessing the pointed to value uses the indirection * operator int data=0; int value; int *iptr; iptr = &data; value = *iptr; what is value? 0

Copyright©1998 Angus Wu PROGRAMMING METHDOLODGY AND SOFTWARE ENGINEERING Pointer

Copyright©1998 Angus Wu PROGRAMMING METHDOLODGY AND SOFTWARE ENGINEERING Pointer

Copyright©1998 Angus Wu PROGRAMMING METHDOLODGY AND SOFTWARE ENGINEERING Pointer int *iptr=NULL; int i =0; int n=17; int j=23; Addresses: &i=8eac8 &n=8eac4 &j=8eac0 Initial values: iptr=0 i=0 n=17 j=23 iptr = &i; n = *iptr; Later values: iptr=8eac8 i=0 n=0 j=23 *iptr = j; *iptr = *iptr + 10; Final values: iptr=8eac8 i=33 n=0 j=23

Copyright©1998 Angus Wu PROGRAMMING METHDOLODGY AND SOFTWARE ENGINEERING Pointer Possible error Dereference a pointer variable before it is assigned with an address Without initialization of pointer variable as NULL

Copyright©1998 Angus Wu PROGRAMMING METHDOLODGY AND SOFTWARE ENGINEERING BASIC DATA OPERATION C passes data/parameters by value. Calling a function, the following will be processed: allocates space for its parameters copies the values passed as the function’s arguments When the function returns, this space is de- allocated. That is, a function cannot change values of its arguments.

Copyright©1998 Angus Wu PROGRAMMING METHDOLODGY AND SOFTWARE ENGINEERING BASIC DATA OPERATION int main( ) { int x,y; scanf(“%d”, &x); y= square(x); } int square(data) int data; { return(data*data); } A memory location is allocated for data when the square function is called. It is also for the storage of the intermediate result data*data. After that, the locations for data and data*data will be de-allocated.

Copyright©1998 Angus Wu PROGRAMMING METHDOLODGY AND SOFTWARE ENGINEERING PASS-BY-VALUE When calling a function, the value of the argument is passed. The function will operate on the value passed from the calling statement, but not on the argument itself. int main( ){.. functionx(arg); …. void functionx(arg) int arg; {…… value

Copyright©1998 Angus Wu PROGRAMMING METHDOLODGY AND SOFTWARE ENGINEERING PASS-BY-VALUE int main( ) { int x; scanf(“%d”, &x); x = square(x); } void square(data) int data; { return(data*data); } int main( ) { int x; scanf(“%d”, &x); square(x); } void square(data) int data; { return(data*data); } * bad function call

Copyright©1998 Angus Wu PROGRAMMING METHDOLODGY AND SOFTWARE ENGINEERING PASS-BY-REFERENCE #include int main( ) { int x; scanf("%d", &x); square(&x); printf("%d \n", x); } int square(int *data) { *data=(*data)*(*data); }

Copyright©1998 Angus Wu PROGRAMMING METHDOLODGY AND SOFTWARE ENGINEERING PASS-BY-REFERENCE use & to pass a pointer to the variable the function then dereferences the pointer with * to access or modify the variable’s value

Copyright©1998 Angus Wu PROGRAMMING METHDOLODGY AND SOFTWARE ENGINEERING PASS-BY-REFERENCE /* A program that doesn't exchange two values.*/ #include int main() { void swap(int x, int y); int s, t; s = 10; t = 20; printf("Before swap, s=%i, t=%i\n", s, t); swap(s, t); printf("After swap, s=%i, t=%i\n", s, t); return 0; } /* Incorrectly exchanges only values of its parameters*/ void swap(int x, int y) { int temp; temp = x; x = y; y = temp; }

Copyright©1998 Angus Wu PROGRAMMING METHDOLODGY AND SOFTWARE ENGINEERING PASS-BY-REFERENCE /*A program that does exchange two values.*/ #include int main() { void swap(int *xptr, int *yptr); int s, t; s = 10; t = 20; printf("Before swap, s=%i, t=%i\n", s, t); swap(&s, &t); printf("After swap, s=%i, t=%i\n", s, t); return 0; } /* Correctly exchanges a pair of values in caller */ void swap(int *xptr, int *yptr) { int temp; temp = *xptr; *xptr = *yptr; *yptr = temp; }

Copyright©1998 Angus Wu PROGRAMMING METHDOLODGY AND SOFTWARE ENGINEERING PASS-BY-REFERENCE function (&var). address of variable. function (*ptr) pointer {..dereference using *operator Statement operates on *ptr;. }