 Building blocks of a C++ program  Each function has a name, which is used to call the function; functions call each other  You will write your own.

Slides:



Advertisements
Similar presentations
Introduction to C Programming
Advertisements

C++ Programming: Program Design Including Data Structures, Third Edition Chapter 7: User-Defined Functions II.
Chapter 7: User-Defined Functions II
Engineering Problem Solving With C++ An Object Based Approach Chapter 9 Pointers and Creating Data Structures.
Chapter 10.
Command-line arguments CS 201 Fundamental Structures of Computer Science.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 5 - Functions Outline 5.1Introduction 5.2Program.
Functions Definition: Instruction block called by name Good design: Each function should perform one task and do it well Functions are the basic building.
Tuesday, January 09, 2007 Memory is necessary for all operations of reason. - Blaise Pascal.
Handout on Functions Passing Values to Functions #include int mult(int, int); int main() { int a = 10, b = 20; cout
1 Functions and Structured Programming. 2 Structured Programming Structured programming is a problem-solving strategy and a programming methodology. –The.
 2003 Prentice Hall, Inc. All rights reserved. 1 Functions Modules: functions and classes Programs use new and “prepackaged” modules –New: programmer-defined.
Lesson 6 Functions Also called Methods CS 1 Lesson 6 -- John Cole1.
Overview scope - determines when an identifier can be referenced in a program storage class - determines the period of time during which that identifier.
1 Functions Modules: functions and classes Programs use new and “prepackaged” modules –New: programmer-defined functions, classes –Prepackaged: from the.
CS 192 Lecture 3 Winter 2003 December 5, 2003 Dr. Shafay Shamail.
1 CS 192 Lecture 5 Winter 2003 December 10-11, 2003 Dr. Shafay Shamail.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. C How To Program - 4th edition Deitels Class 05 University.
Copyright © 2012 Pearson Education, Inc. Chapter 6: Functions.
Chapter 6: Functions Starting Out with C++ Early Objects
C++ Programming: From Problem Analysis to Program Design, Fifth Edition, Fifth Edition Chapter 7: User-Defined Functions II.
Project 1 Due Date: September 25 th Quiz 4 is due September 28 th Quiz 5 is due October2th 1.
224 3/30/98 CSE 143 Recursion [Sections 6.1, ]
Introduction to Computer Algorithmics and Programming Ceng 113 Functions and Recursive Functions.
CPS120: Introduction to Computer Science Decision Making in Programs.
1 FUNCTIONS - I Chapter 5. 2 What are functions ? Large programs can be modularized into sub programs which are smaller, accomplish a specific task and.
USER-DEFINED FUNCTIONS. STANDARD (PREDEFINED) FUNCTIONS  In college algebra a function is defined as a rule or correspondence between values called the.
Chapter 8: Arrays and Functions Department of Computer Science Foundation Year Program Umm Alqura University, Makkah Computer Programming Skills
Built-In and user-Defined functions Software Design Concepts Lecture IV Dr. Sothy Vignarajah.
 2003 Prentice Hall, Inc. All rights reserved. 1 Arrays Outline Introduction Arrays Declaring Arrays Examples Using Arrays.
Lecture 22: Reviews for Exam 2. Functions Arrays Pointers Strings C Files.
1 Command-Line Processing In many operating systems, command-line options are allowed to input parameters to the program SomeProgram Param1 Param2 Param3.
1 Announcements Note from admins: Edit.cshrc.solaris instead of.tcshrc Note from admins: Do not use delta.ece.
A first program 1. #include 2. using namespace std; 3. int main() { 4. cout
Strings Programming Applications. Strings in C C stores a string in a block of memory. The string is terminated by the \0 character:
CHAPTER 10 ARRAYS AND FUNCTIONS Prepared by: Lec. Ghader Kurdi.
Chapter Functions 6. Modular Programming 6.1 Modular Programming Modular programming: breaking a program up into smaller, manageable functions or modules.
Copyright © 2002 W. A. Tucker1 Chapter 9 Lecture Notes Bill Tucker Austin Community College COSC 1315.
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
Function User defined function is a code segment (block) that perform an specific action. Function Definition: Function Definition: Return_DT F_name (
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 6: User-Defined Functions I.
1 MORE ON MODULAR DESIGN: MODULE COMMUNICATIONS. 2 WHEN A FUNCTION IS INVOKED, MEMORY IS ALLOCATED LOCALLY FOR THE FORMAL PARAMETERS AND THE VALUE OF.
General Computer Science for Engineers CISC 106 Lecture 12 James Atlas Computer and Information Sciences 08/03/2009.
DCT1063 Programming 2 CHAPTER 1 POINTERS Mohd Nazri Bin Ibrahim Faculty of Computer, Media & Technology TATi University College
Lecture 2 Functions. Functions in C++ long factorial(int n) The return type is long. That means the function will return a long integer to the calling.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 6: Functions.
C++ Programming Lecture 14 Arrays – Part I The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
Lecture 4 – Function (Part 1) FTMK, UTeM – Sem /2014.
CSIS 113A Lecture 5 Functions. Introduction to Functions  Building Blocks of Programs  Other terminology in other languages:  Procedures, subprograms,
CPS120 Introduction to Computer Science Exam Review Lecture 18.
Array and Pointers An Introduction Unit Unit Introduction This unit covers the usage of pointers and arrays in C++
Building Programs from Existing Information Solutions for programs often can be developed from previously solved problems. Data requirements and solution.
Lecture 9 – Array (Part 2) FTMK, UTeM – Sem /2014.
FUNCTIONS (C) KHAERONI, M.SI. OBJECTIVE After this topic, students will be able to understand basic concept of user defined function in C++ to declare.
1 This week Basics of functions Stack frames Stack vs. Heap (brief intro) Calling conventions Storage classes vs. scope Library functions Overloading.
BIL 104E Introduction to Scientific and Engineering Computing Lecture 4.
Functions and Structured Programming
C-language Lecture By B.S.S.Tejesh, S.Neeraja Asst.Prof.
Programmazione I a.a. 2017/2018.
User-Defined Functions
Chapter 5 - Functions Outline 5.1 Introduction
Function User defined function is a code segment (block) that perform an specific action. Function Definition: Return_DT F_name ( list of formal parameters)
Functions A function is a “pre-packaged” block of code written to perform a well-defined task Why? Code sharing and reusability Reduces errors Write and.
6 Chapter Functions.
The Function Prototype
Based on slides created by Bjarne Stroustrup & Tony Gaddis
Functions Imran Rashid CTO at ManiWeber Technologies.
Presentation transcript:

 Building blocks of a C++ program  Each function has a name, which is used to call the function; functions call each other  You will write your own functions, e.g. main(), and also use pre-written functions from standard library

/* This program contains two functions: main() and myfunc(). */ #include void myfunc(); // myfunc's Protoype int main() { cout << "In main()"; myfunc(); // call myfunc() cout << "Back in main()"; return 0; } void myfunc() // myfunc’s Definition { cout << " Inside myfunc() "; }

void myfunc(); // myfunc's Protoype  Like variable declaration; tells the compiler about the return type of the function and the number and type of parameters it needs from the calling function: return_type functionName ( parameter list );  So, place prototypes before main()  main() is predefined in C++ and does not need a prototype  Can’t the compiler look ahead and get definitions?  Prototype can be omitted if whole function placed before it is called; is that a good practice?

// Returning a value. #include int mul(int x, int y); // mul()'s prototype int main() { int answer; answer = mul(10, 11); // assign return value cout << "The answer is " << answer; return 0; } // This function returns a value. int mul(int x, int y) { return x * y; // return product of x and y }

 Pre-written functions in libraries that you can use  Just include the proper header file  Compiler gets prototype from the header file and searches appropriate libraries itself to get function definition  e.g. math library has mathematical functions in it #include #include //or int main() { cout << sqrt(9.0); return 0; }

 Scope rules tell that a variable is visible to which parts of your program; also define variable’s lifetime  3 types of variables: local, global, formal parameters

 A variable can be declared inside any block and is then local to that block  Block: {} int main() { {int x = 4;} cout << x; return 0; }  error C2065: 'x' : undeclared identifier  Memory storage for a local variable created when entering its block and destroyed when its block exited

 Most common block is a function #include void func(); int main() { int x; // local to main() x = 10; func(); cout << x; // displays ? return 0; } void func() { int x; // local to func() x = -199; cout << x; // displays ? }  Each variable x has a separate location in memory  Identically-named variables in inner block ‘hide’ or override those in the outer block; Avoid this practice

#include int main() { int i, j; i = 10; j = 100; if(j > 0) {// start of block int i; // this i is separate from outer i i = j / 2; // outer j is known here cout << “first inner i: " << i << '\n'; } if(i < 50) { i += 10; cout << “2 nd inner i: “ << i << endl; } cout << "outer i: " << i << '\n'; return 0; }  Declaring within a conditional block also saves memory; see next slide

int main() { int choice; cout << "(1) add numbers or "; cout << "(2) concatenate strings?: "; cin >> choice; if(choice == 1) { int a, b; /* activate two integer vars */ cout << "Enter two numbers: "; cin >> a >> b; cout << "Sum is " << a+b << '\n'; } else { char s1[80], s2[80]; /* activate two strings */ cout << "Enter two strings: "; cin >> s1; cin >> s2; strcat(s1, s2); cout << "Concatenation is " << s1 << '\n'; } a = 10; // *** Error *** -- a not known here! return 0; }

 Variables declared in for loops are local according to current spec for C++ for(int i = 0; i<10; i++) cout << i << " "; i = 100; // *** Error *** -- i not known here!  Does not work on Visual C (i.e. no error)  Can declare a variable within any conditional expression if(int x = 20) { cout << "This is x: "; cout << x; } x = 2; //*** Error *** -- x not known here!  Not a good practice

 Formal parameters: variables that receive values passed to a function  Scope local to the function #include int mult(int, int); int main() { int a = 10, b = 20; cout << mult(a, b); //cout << x << y; // *** Error *** --unknown identifiers x, y return 0; } int mult(int x, int y)// can have different names here { return x*y; }

 Usually declared outside any function; have life as long as the program runs  Can be used by all following functions  Usually placed at the beginning of program  Initialized only at the start of the program; uninitialized default to zero  An identically named local variable masks global one

#include void func(); int i = 2;// global int main() { cout << i << endl; func(); cout << i << endl; int i = 5;// local. What if i=5; cout << i << endl; func(); return 0; } void func() { cout << i << endl; int i = 3; // local cout << i << endl; }   if i = 5 at the indicated place

#include void drill(); int count; //count and num_right are global int num_right; int main() { cout << "How many practice problems: "; cin >> count; num_right = 0; do { drill(); count--; } while(count); cout << "You got " << num_right << “ right.\n"; return 0; } void drill() { int count; /* This count is local. */ int a, b, ans; // Generate two numbers between 0 and 99. a = rand() % 100; b = rand() % 100; // The user gets three tries to get it right. for(count=0; count<3; count++) { cout << "What is " << a << " + " << b << "? "; cin >> ans; if(ans==a+b) { cout << "Right\n"; num_right++; return; } cout << "You've used up all your tries.\n"; cout << "The answer is " << a+b << '\n'; }

 No big deal. Just declare parameter as type _______ ? #include void f(int *j);//or void f(int *); int main() { int i; int *p; p = &i; // p now points to i f(p); cout << i; // i is now 100 return 0; } void f(int *j) { *j = 100; // var pointed to by j is assigned 100 } i 26 p j 100

 The pointer variable not necessary. Can generate and pass the address of i as such to f() #include void f(int *j); int main() { int i; f(&i); cout << i; return 0; } void f(int *j) { *j = 100; // var pointed to by j is assigned 100 } i 26 j 100

#include int sqr_it(int x); int main() { int t=10; cout << sqr_it(t) << ' ' << t; //output? } int sqr_it(int x) { x = x*x; return x;}  IMPORTANT: What’s the difference between the above function, and the ones on previous two slides?  Here, a copy of the value of t is passed. t remains unaltered. x is a local variable, which could have been named t  Called “Call by Value”  Previous called “Call by Reference” where the original variable (not a copy) is accessed by the called function (copy) t x

 What is an array name without index?  Address of first element passed to function. So actual array accessed, not a copy. Saves memory  3 ways to pass this address I. Declare parameter as an array of same type and size #include void display(int num[10]); //or display(int [10]); int main() { int t[10],i; for(i=0; i<10; ++i) t[i]=i; display(t); // pass array t to a function cout <<endl; for(i=0; i<10; i++) cout << t[i] << ' '; //output? } // Print some numbers. void display(int num[10]) { int i; for(i=0; i<10; i++) cout << num[i] << ' '; //output? for(i=0; i<10; i++) (num[i] = num[i] + 1); }

II. Can also declare as display(int num[]) i.e. unsized. Same thing  Internally, compiler converts int num[10] or int num[] to int * III. So, why not declare parameter as a pointer to int void display(int *num) { int i; for(i=0; i<10; i++) cout << num[i] << ' '; //or *(num+i) }  How is a single element passed? As an ordinary variable #include void display(int num); //each element is of type int int main() { int t[10],i; for(i=0; i<10; ++i) t[i]=i; for(i=0; i<10; i++) display(t[i]); //only one element passed } void display(int num) { cout << num << ' ';}

#include void cube(int *n, int num); int main() { int i, nums[10]; for(i=0; i<10; i++) nums[i] = i+1; cout << "Original contents: "; for(i=0; i<10; i++) cout << nums[i] << ' '; cout << '\n'; cube(nums, 10); // compute cubes cout << "Altered contents: "; for(i=0; i<10; i++) cout << nums[i] << ' '; return 0; } void cube(int *n, int num) { while(num) { *n = *n * *n * *n; num--; n++; }  Original contents:  Altered contents:

 What is a string stored as? So what should we pass? #include void stringupper(char *str); int main() { char str[80]; strcpy(str, "this is a test"); stringupper(str); cout << str; // display uppercase string return 0; } void stringupper(char *str) { while(*str) { *str = toupper(*str); // uppercase one char str++; // move on to next char }  Can also declare as an array of char stringupper(char[])

 return statement can be used without a value for void functions. Must return a value for non- void functions  Control passed back to calling function when return encountered or closing curly brace of function #include void power(int base, int exp); int main() { power(2, 10); return 0; } void power(int base, int exp) { int i; if(exp<0) return; i = 1; for( ; exp; exp--) i = base * i; cout << "The answer is: " << i << endl; }

 Can have multiple return statements. Function returns as soon as the first one encountered void f() { //... switch(c) { case 'a': return; case 'b': //... case 'c': return; } if(count<100) return; //... }

 non-void functions return values to the calling function. Therefore, can call a non-void function and use that call as an operand in an expression (as it has a value) in the calling function  x = power(y);  if(max(x, y)) > 100) cout << "greater";  switch(abs(x)) {...  Don’t necessarily have to store the returned value in a variable #include int main() { int i; i = abs(-10); // stored cout << abs(-23); // just used abs(100); // returned value discarded return 0; }

#include int find_substr(char *sub, char *str); int main() { int index; index = find_substr("three", "one two three"); cout << "Index of three is " << index; // index is 8 return 0; } int find_substr(char *sub, char *str) { int t; char *p, *p2; for(t=0; str[t]; t++) { p = &str[t]; // reset pointers p2 = sub; while(*p2 && *p2==*p) { // check for substring p++; p2++; } /* If at end of p2 (i.e., substring), then a match has been found. */ if(!*p2) return t; // return index //of match } return -1; // no match found }

#include char *get_substr(char *sub, char *str); int main() { char *substr; substr = get_substr("three", "one two three four"); cout << "substring found: " << substr; return 0; } char *get_substr(char *sub, char *str) { int t; char *p, *p2, *start; for(t=0; str[t]; t++) { p = &str[t]; // reset pointers start = p; p2 = sub; while(*p2 && *p2==*p) { //check for substring p++; p2++; } /* If at end of p2 (i.e., substring), then a match has been found. */ if(!*p2) return start; /* return pointer to beginning of substring */ } return 0; // no match found }

 To pass info to main() from the command line  e.g. cl hellouser  Here, cl and hellouser are command line arguments  main() receives infor about these arguments in two parameters: int main( int argc, char *argv[])  argc (argument count) parameter is an integer that holds the number of arguments on the command line. Always at least 1, as program name also counted  argv (argument variable) parameter is a null-terminated array of pointers to strings  argv[0] points to program name on command line, argv[1] points to the first argument, and so on. argv[argc]==0

#include int main(int argc, char *argv[]) { if(argc!=2) { cout << "You forgot to type your name.\n"; return 1; } cout << "Hello " << argv[1] << '\n'; return 0; }  If we name this program as greeting, then after making an exe file we can type greeting Shamail at the command prompt and the program will execute and output: Hello Shamail  Spaces and tabs usually separate strings; for a longer string, use quotes e.g. greeting “Shafay Shamail” outputs Hello Shafay Shamail

 Can access individual characters in the command line strings by using a double subscript. See the program echo below #include int main(int argc, char *argv[]) { int t, i; for(t=0; t<argc; ++t) {// t denotes the t th string i = 0; while(argv[t][i]) {// t[i] accesses the i th character of t cout << argv[t][i]; ++i; cout << ' '; } cout << ' '; } return 0; }  e.g. echo hi there results in e c h o h i t h e r e

 Want to pass numbers to main( ), but it takes strings  Use atof(), atoi(), atol() #include int main(int argc, char *argv[]) { double a, b; a = atof(argv[1]); b = atof(argv[2]); cout << a + b; return 0; }  atoi(“2”) gives 2 ; atof(“-11.11”) gives

#include int main(int argc, char *argv[]) { double a, b; a = atof(argv[1]); b = atof(argv[2]); cout << a + b; return 0; } #include int main(int argc, char *argv[]) { while(--argc > 0) cout << *++argv << endl; return 0; } #include int main(int argc, char *argv[]) { for(int j=0; j<argc; j++) cout << argv[j] << endl; return 0; } #include int main(int argc, char *argv[]) { char **argvector = argv; double a, b; a = atof(*++argvector); b = atof(*++argvector); cout << a + b; return 0; }