Overview of Previous Lesson(s) Over View  C++  KeywordsReserved words  IdentifiersProgrammers defined variables  Variables A named storage location.

Slides:



Advertisements
Similar presentations
C++ Basics Variables, Identifiers, Assignments, Input/Output.
Advertisements

True or false A variable of type char can hold the value 301. ( F )
Computer Science 1620 Loops.
Computer Science 1620 Other Data Types. Quick Review: checklist for performing user input: 1) Be sure variable is declared 2) Prompt the user for input.
1 The first step in understanding pointers is visualizing what they represent at the machine level. In most modern computers, main memory is divided into.
Data Types, Expressions and Functions (part I)
Basic Elements of C++ Chapter 2.
© Janice Regan, CMPT 128, Jan CMPT 128: Introduction to Computing Science for Engineering Students Data representation and Data Types Variables.
 2003 Prentice Hall, Inc. All rights reserved. 1 Functions and Recursion Outline Function Templates Recursion Example Using Recursion: The Fibonacci Series.
Chapter 8 Friends and Overloaded Operators. Copyright © 2005 Pearson Addison-Wesley. All rights reserved. Slide 2 Overview Friend Function (8.1) Overloading.
Object Oriented Programming Spring COMSATS Institute of Information Technology Functions OOP in C++ by Robert Lafore - Chapter#5 Kaleem Ullah
1 Chapter 3 Numeric Types, Expressions, and Output Dale/Weems/Headington.
COMPUTER PROGRAMMING. Functions What is a function? A function is a group of statements that is executed when it is called from some point of the program.
CSC 270 – Survey of Programming Languages C++ Lecture 1 : C++ As A Better C.
Week 1 Algorithmization and Programming Languages.
C++ Programming: Basic Elements of C++.
Constants Numeric Constants Integer Constants Floating Point Constants Character Constants Expressions Arithmetic Operators Assignment Operators Relational.
Fundamental Programming: Fundamental Programming Introduction to C++
Chapter 7 Additional Control Structures. Chapter 7 Topics l Switch Statement for Multi-Way Branching l Do-While Statement for Looping l For Statement.
1 Lecture 04 Structural Programming in C++ You will learn: i) Operators: relational and logical ii) Conditional statements iii) Repetitive statements.
Introduction to C++ Version 1.1. Topics C++ Structure Primitive Data Types I/O Casting Strings Control Flow.
Chapter 4: Subprograms Functions for Problem Solving Mr. Dave Clausen La Cañada High School.
Chapters 1-5 Review C++ Class. Chapter 1 – the big picture Objects Class Inheritance Reusability Polymorphism and Overloading.
1 Chapter 2 C++ Syntax and Semantics, and the Program Development Process.
Structure Programming Lecture 8 Chapter 5&6 - Function – part I 12 December 2015.
Chapter 3 – Variables and Arithmetic Operations. Variable Rules u Must declare all variable names –List name and type u Keep length to 31 characters –Older.
Introducing C++ Programming Lecture 3 Dr. Hebbat Allah A. Elwishy Computer & IS Assistant Professor
GE 211 Dr. Ahmed Telba. // compound assignment operators #include using namespace std; int main () { a =5 int a, b=3; a = b; a+=2; // equivalent to a=a+2.
Manish K Parmar PGT (CS) K V VVNagar Thursday, December 24, 2015 Lesson on USER DEFINED FUNCTION IN C++ Presented by Manish K Parmar PGT Computer Science.
Chapter 3 Functions. 2 Overview u 3.2 Using C++ functions  Passing arguments  Header files & libraries u Writing C++ functions  Prototype  Definition.
CS1201: PROGRAMMING LANGUAGE 2 FUNCTIONS. OVERVIEW What is a Function? Function Prototype Vs Decleration Highlight Some Errors in Function Code Parameters.
C++ Programming Lecture 13 Functions – Part V The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
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.
Recap……Last Time [Variables, Data Types and Constants]
Programming Fundamentals. Topics to be covered Today Recursion Inline Functions Scope and Storage Class A simple class Constructor Destructor.
Lecture 5: Expressions and Interactivity Professor: Dr. Miguel Alonso Jr. Fall 2008 CGS2423/COP1220.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 3 - Functions Outline 3.15Functions with Empty Parameter Lists 3.16Inline Functions 3.17References.
Array in C++ / review. An array contains multiple objects of identical types stored sequentially in memory. The individual objects in an array, referred.
Functions BICSE-6A Mr. Naeem Khalid Lecturer, Dept. of Computing.
Pointers & References. Pointers Pointer arithmetic Pointers and arrays Pointer-related typedef’s Pointers and const References.
Reference Parameters There are two ways to pass arguments to functions: pass- by-value and pass-by-reference. pass-by-value –A copy of the arguments’svalue.
 Static  Example for Static Field  Example for Static Method  Math class methods  Casting  Scope of Declaration  Method Overloading  Constructor.
Variables in C Topics  Naming Variables  Declaring Variables  Using Variables  The Assignment Statement Reading  Sections
CMSC 104, Version 8/061L09VariablesInC.ppt Variables in C Topics Naming Variables Declaring Variables Using Variables The Assignment Statement Reading.
CSIS 113A Lecture 5 Functions. Introduction to Functions  Building Blocks of Programs  Other terminology in other languages:  Procedures, subprograms,
Programming Languages -2 C++ Lecture 3 Method Passing Function Recursion Function Overloading Global and Local variables.
Programming Fundamentals Enumerations and Functions.
CHAPTER 4 FUNCTIONS Dr. Shady Yehia Elmashad. Outline 1.Introduction 2.Program Components in C++ 3.Math Library Functions 4.Functions 5.Function Definitions.
Functions Modules in C++ are called functions and classes. Main reason to use functions is : – get aid in conceptual organization.
Functions  Simple Functions  Passing Arguments to Functions  Returning Values from Functions  Reference Arguments  Overloaded Functions  Recursion.
A Sample Program #include using namespace std; int main(void) { cout
 2000 Prentice Hall, Inc. All rights reserved Program Components in C++ Function definitions –Only written once –These statements are hidden from.
C++ Programming Lecture 13 Functions – Part V By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department.
Overview of Previous Lesson(s) Over View  I nteractive development environment is a software application that provides comprehensive facilities to computer.
C++ Lesson 1.
Chapter 1.2 Introduction to C++ Programming
LESSON 06.
Chapter Topics The Basics of a C++ Program Data Types
Chapter 1.2 Introduction to C++ Programming
Chapter 1.2 Introduction to C++ Programming
Chapter 1.2 Introduction to C++ Programming
Programming Fundamentals
Basic Elements of C++.
School of EECS, Peking University
Pointers and Pointer-Based Strings
Basic Elements of C++ Chapter 2.
FUNCTIONS& FUNCTIONS OVERLOADING
Chapter 7 Additional Control Structures
Pointers and Pointer-Based Strings
Functions Chapter No. 5.
Presentation transcript:

Overview of Previous Lesson(s)

Over View  C++  KeywordsReserved words  IdentifiersProgrammers defined variables  Variables A named storage location in the computer’s memory for holding a piece of data.  Data Types  Looping structuresDecision structures  For loopIf  WhileIf / else  Do WhileSwitch 3

Over View..  Operator Precedence  Operator precedence orders the operators in a priority sequence.  In an expression with more than one operator, evaluate in this order: - (unary negation), in order, left to right * / %, in order, left to right + -, in order, left to right Example expression * 2 – 2 4 evaluate first evaluate second evaluate third

Over View…  Type Conversion and Casting  Implicit type conversion:  When an expression involving variables of different types then for each operation to be performed, the compiler has to arrange to convert the type of one of the operands to match that of the other.  Explicit Type Conversion:  A forced conversion from one type to another is referred as explicit type conversion.  Auto keyword is used as the type of a variable in a definition statement and have its type deduced from the initial value. auto n = 16; // Type is int auto pi = ; // Type is double 5

Over View… 6 ScopeScope

 Namespaces provide a way to separate the names used in one part of a program from those used in another.  namespace keyword is used to declare a namespace namespace myStuff { // Code that I want to have in the namespace myStuff... }  This defines a namespace with the name myStuff. 7

Over View…  Structures  A structure is a collection of simple variables.  The data items in a structure are called the members of the structure. 8

Over View… 9  Enumeration:  To cope the need for variables that have a limited set of possible values.  An enum declaration defines the set of all names that will be permissible values of the type, are called enumerators.  Ex, It can be usefully referred to by labels the days of the week or months of the year. enum Week{Mon, Tues, Wed, Thurs, Fri, Sat, Sun} thisWeek;

Over View… 10  A function groups a number of program statements into a unit and gives it a name.  This unit can then be invoked from other parts of the program.  The function’s code is stored in only one place in memory, even though the function is executed many times in the course of the program.

Over View… 11 Function Components

Over View… 12  Function with no arguments // starline() // function definition void starline() //function declarator { for(int j=0; j<45; j++) //function body cout << ‘*’; cout << endl; }

13

Contents  Passing Arguments to Functions  Returning Values from Functions  Reference Arguments  Const Function Arguments  Function Overloading  Recursion  Inline Functions  Default Arguments 14

Passing Arguments to Function  An argument is a piece of data passed from a program to the function.  Arguments allow a function to operate with different values, or even to do different things, depending on the requirements of the program calling it.  Passing Constants:  Lets discuss the starline function. 15

Passing Constant // tablearguments.cpp // demonstrates function arguments #include using namespace std; void repchar(char, int); //function declaration 16

Passing Constant.. int main() { repchar(‘-’, 43); //call to function cout << “Students Result” << endl; repchar(‘=’, 23); //call to function cout << “Student A got 85 Marks” << endl; cout << “Student B got 73 Marks” << endl; cout << “Student C got 68 Marks” << endl; repchar(‘-’, 43);//call to function return 0; } 17

Passing Constant… // repchar() // function definition void repchar(char ch, int n) //function declarator { for(int j=0; j<n; j++) //function body cout << ch; cout << endl; } 18

Program Output Students Result =================== Student A got 85 Marks Student A got 73 Marks Student A got 69 Marks

Passing Variables // variablearguments.cpp // demonstrates variable arguments #include using namespace std; void repchar(char, int);// function declaration 20

Passing Variables.. int main() { char char_in; int number_in; cout << “Enter a character: “; cin >> char_in; cout << “Enter number of times to repeat it: “; cin >> number_in; repchar(char_in, number_in); return 0; } 21

Passing Variables… // repchar() // function definition void repchar(char ch, int n) //function declarator { for(int j=0; j<n; j++) //function body cout << ch; cout << endl; } 22

Passing Variables…  Here’s some sample interaction with VARARG: Enter a character: + Enter number of times to repeat it:  The data types of variables used as arguments must match those specified in the function declaration and definition, just as they must for constants.  That is, char_in must be a char, and number_in must be an int. 23

Passing by Value  In previous example the particular values possessed by char_in and number_in will be passed to the function after function call is executed in main function body.  When these constants were passed to it, the function creates new variables to hold the values of these variable arguments.  The function gives these new variables the names and data types of the parameters specified in the declarator: ch of type char and n of type int.  It initializes these parameters to the values passed.  They are then accessed like other variables by statements in the function body. 24

Passing by Value..  Passing arguments in a way, where the function creates copies of the arguments passed to it, is called passing by value. 25

Structure as Argument  Entire structures can be passed as arguments to functions.  We’ll try to understand the passing of a structure as an argument to a function with the help of a example.  A structure called circle represents a circular shape.  Circles are positioned at a certain place on the console screen, and have a certain radius.  They also have a color and a fill pattern.  In this example the Console Graphics Lite functions library is also used. 26

Circle Structure // circstrc.cpp // circles as graphics objects #include “msoftcon.h” // for graphics functions struct circle //graphical circle { int xCo, yCo; //coordinates of center int radius; color fillcolor; //color fstyle fillstyle; //fill pattern }; void circ_draw(circle c) { set_color(c.fillcolor); //set color set_fill_style(c.fillstyle); //set fill pattern draw_circle(c.xCo, c.yCo, c.radius); //draw solid circle } 27

Circle Program int main() { init_graphics(); //initialize graphics system //create circles circle c1 = { 15, 7, 5, cBLUE, X_FILL }; circle c2 = { 41, 12, 7, cRED, O_FILL }; circle c3 = { 65, 18, 4, cGREEN, MEDIUM_FILL }; circ_draw(c1); //draw circles circ_draw(c2); circ_draw(c3); set_cursor_pos(1, 25); //cursor to lower left corner return 0; } 28

Output 29

Returning Values from Function  A function can return a single value to the calling program after its execution.  Usually this return value consists of an answer to the problem the function has solved.  Lets see a function whose job is to convert the pounds into kilograms and return the weight in kg. // convert.cpp // demonstrates return values, converts pounds to kg #include using namespace std; float lbstokg(float); //declaration 30

Main Body & Function int main() {float lbs, kgs; cout << “\nEnter your weight in pounds: “; cin >> lbs; kgs = lbstokg(lbs); cout << “Your weight in kilograms is “ << kgs << endl; return 0;} // lbstokg() // converts pounds to kilograms float lbstokg(float pounds) {float kilograms = * pounds; return kilograms; } 31

Returning Values..  Here’s some interaction with this program: Enter your weight in pounds: 182 Your weight in kilograms is  When a function returns a value, the data type of this value must be specified by the function.  In this function declaration does this by placing the data type, float before the function name in the declaration and the definition.  If we want more than one values in return ????? * Structures 32

Reference Arguments  A reference provides an alias a different name for a variable.  Passing arguments by reference uses a mechanism that Instead of a value being passed to the function, a reference to the original variable, in the calling program, is passed. // ref.cpp // demonstrates passing by reference #include using namespace std; 33

Reference Arguments.. int main() { void intfrac(float, float&, float&); //declaration float number, intpart, fracpart; //float variables do { cout << “\nEnter a real number: “; //number from user cin >> number; Intfrac(number, intpart, fracpart); //find int and frac cout << “Integer part is “ << intpart //print them << “, fraction part is “ << fracpart << endl; } while( number != 0.0 ); //exit loop on 0.0 return 0; } 34

Reference Arguments.. // intfrac() finds integer and fractional parts of real number void intfrac(float n, float& intp, float& fracp) { long temp = static_cast (n); //convert to long, intp = static_cast (temp); //back to float fracp = n - intp;//subtract integer part }  Reference arguments are indicated by the ampersand (&) following the data typefloat& intp  The & indicates that intp is an alias, another name, for whatever variable is passed as an argument. 35

Reference Arguments… 36

Const Function Arguments  Arguments passing by reference can be used to allow a function to modify a variable in the calling program.  Main reason why passing by reference used is efficiency, but you don’t want the function to modify it.  Here const modifier is used with the variable in the function declaration, to guarantee such thing. void aFunc(int& a, const int& b); //declaration { a = 107; // its OK b = 111; //error: can’t modify constant argument } 37

Function Overloading  Function overloading allows to use the same function name for defining several functions as long as they each have different parameter lists.  When the function is called, the compiler chooses the correct version for the job based on the list of arguments you supply.  The compiler must always be able to decide unequivocally which function should be selected in any particular instance of a function call, so the parameter list for each function in a set of overloaded functions must be unique. 38

Function Overloading.. // overload.cpp demonstrates function overloading #include using namespace std; void repchar(); //declarations void repchar(char); void repchar(char, int); int main() { repchar();// Call with no arguments repchar(‘=’);// Call with a single argument repchar(‘+’, 30);// Call with 2 Arguments return 0; } 39

Function Overloading… // repchar()// displays 45 asterisks void repchar() {for(int j=0; j<45; j++) // always loops 45 times cout << ‘*’; // always prints asterisk cout << endl; } // displays 45 copies of specified character void repchar(char ch) {for(int j=0; j<45; j++) // always loops 45 times cout << ch; // prints specified character cout << endl ; } 40

Function Overloading… // displays specified number of copies of specified character void repchar(char ch, int n) } for(int j=0; j<n; j++) // loops n times cout << ch;// prints specified character cout << endl; }  This program prints out three lines of characters. Here’s the output: ********************************************* =============================================  The first two lines are 45 characters long, and the third is

Function Overloading… 42

Recursion  Recursion involves a function calling itself.  This phenomena is much easier to understand with an example without going into the verbose..  Now we will calculate a Factorial using recursion. #include using namespace std; unsigned long factfunc(unsigned long); //declaration 43

Recursion.. int main() { int n; //number entered by user unsigned long fact; //factorial cout << “Enter an integer: “; cin >> n; fact = factfunc(n); cout << “Factorial of “ << n << “ is “ << fact << endl; return 0; } 44

Recursion... // factfunc()calls itself to calculate factorials unsigned long factfunc(unsigned long n) { if(n > 1) return n * factfunc(n-1); //self call else return 1; } 45

Inline Functions 46

Inline Functions.. 47  Functions that are very short, say one or two statements, are candidates to be inlined. #include using namespace std; // lbstokg() converts pounds to kilograms inline float lbstokg(float pounds) { return * pounds; } int main() { float lbs; cout << “\nEnter your weight in pounds: “; cin >> lbs; cout << “Your weight in kilograms is “ << lbstokg(lbs) ; return 0; }

Default Arguments  Surprisingly, a function can be called without specifying all its arguments.  This won’t work on just any function, The function declaration must provide default values for those arguments that are not specified. #include using namespace std; void repchar(char=’*’, int=45); //declaration with default arguments int main() { repchar(); //prints 45 asterisks repchar(‘=’); //prints 45 equal signs repchar(‘+’, 30); //prints 30 plus signs return 0; } 48

Default Arguments.. // repchar() // displays line of characters void repchar(char ch, int n) //defaults supplied if necessary { for(int j=0; j<n; j++) //loops n times cout << ch; //prints ch cout << endl; } 49

Thank You 50