Introduction to Functions

Slides:



Advertisements
Similar presentations
True or false A variable of type char can hold the value 301. ( F )
Advertisements

Computer Science 1620 Loops.
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 5 Looping.
A loop is a repetition control structure. it causes a single statement or block to be executed repeatedly What is a loop?
Chapter 6 - Repetition. Introduction u Many applications require certain operations to be carried out more than once. Such situations require repetition.
Chapter 5: Loops and Files.
Functions Modules in C++ are called functions and classes
ASP.NET Programming with C# and SQL Server First Edition Chapter 3 Using Functions, Methods, and Control Structures.
COMPUTER PROGRAMMING. Control Structures A program is usually not limited to a linear sequence of instructions. During its process it may repeat code.
Project 1 Due Date: September 25 th Quiz 4 is due September 28 th Quiz 5 is due October2th 1.
Functions Introduction to Programming By Engr. Bilal Ahmad 1ITP by Engr. Bilal Ahmad.
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.
Functions in C Programming Dr. Ahmed Telba. If else // if #include using namespace std; int main() { unsigned short dnum ; cout
Copyright © Nancy Acemian 2004 For Loops-Break-Continue COMP For loop is a counter controlled loop. For loop is a pretest loop. Used when number.
Additional Control Structures. Chapter 9 Topics Switch Statement for Multi-way Branching Do-While Statement for Looping For Statement for Looping Using.
Functions Modules in C++ are called functions and classes Functions are block of code separated from main() which do a certain task every C++ program must.
1 Additional Control Structures. 2 Chapter 9 Topics  Switch Statement for Multi-way Branching  Do-While Statement for Looping  For Statement for Looping.
Chapter 7 Additional Control Structures. 2 2 void GetYesOrNo (/* out */ char& response) // Inputs a character from the user // Postcondition: response.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 7 Clicker Questions September 22, 2009.
Chapter 8 Repetition Statements. Introduction Iteration - process of looping or the repetition of one or more statements Loop body - the statement, or.
COMPUTER PROGRAMMING. Iteration structures (loops) There may be a situation when you need to execute a block of code several number of times. In general,
Program Flow Control - Looping Addis Ababa Institute of Technology Yared Semu April 2012.
COMPUTER PROGRAMMING. Functions’ review What is a function? A function is a group of statements that is executed when it is called from some point of.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 5 Looping.
Structure Programming Lecture 8 Chapter 5&6 - Function – part I 12 December 2015.
Introduction to Loops Iteration Repetition Counting Loops Also known as.
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.
Loops and Files. 5.1 The Increment and Decrement Operators.
1 Standard Version of Starting Out with C++, 4th Brief Edition Chapter 5 Looping.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5: Looping.
Modular Programming – User Defined Functions. CSCE 1062 Outline  Modular programming – user defined functions  Value returning functions  return statement.
1 For Loops l From Chapter 9 l A shorthand way of coding count loops.
Copyright © 2012 Pearson Education, Inc. Chapter 5: Loops.
Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 5 Looping.
1 Programming in C++ Dale/Weems/Headington Chapter 9 Additional Control Structures (Switch, Do..While, For statements)
Chapter 6 - Repetition. while Loop u Simplest loop u Two parts: test expression and loop body u Pre-tested loop –Execute loop body if test true –Bypass.
Repetition Statements (Loops). 2 Introduction to Loops We all know that much of the work a computer does is repeated many times. When a program repeats.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
Variables  A piece of memory set aside to store data  When declared, the memory is given a name  by using the name, we can access the data that sits.
LECTURE # 8 : REPETITION STATEMENTS By Mr. Ali Edan.
Copyright 2006 Addison-Wesley Brief Version of Starting Out with C++ Chapter 5 Looping.
CSIS 113A Lecture 5 Functions. Introduction to Functions  Building Blocks of Programs  Other terminology in other languages:  Procedures, subprograms,
Functions Skill Area 314 Part B. Lecture Overview Functions Function Prototypes Function Definitions Local Variables Global Variables Default Parameters.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
Lecture 7 – Repetition (Loop) FTMK, UTeM – Sem /2014.
Introduction to Loop. Introduction to Loops: The while Loop Loop: part of program that may execute > 1 time (i.e., it repeats) while loop format: while.
Review 1.
REPETITION CONTROL STRUCTURE
CHAPTER 4 REPETITION CONTROL STRUCTURE / LOOPING
Lecture 6 Repetition Richard Gesick.
School of EECS, Peking University
Chapter 5: Looping Starting Out with C++ Early Objects Seventh Edition
Control Statements Kingdom of Saudi Arabia
Repetition Structures (Loops)
Chapter 5: Looping Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley.
Lecture 4B More Repetition Richard Gesick
Chapter 8 Repetition Statements
Lecture 4A Repetition Richard Gesick.
Alternate Version of STARTING OUT WITH C++ 4th Edition
Additional Control Structures
6 Chapter Functions.
Computing Fundamentals
Control Structures Part 2
Control Structures Part 1
Chapter 6: User-Defined Functions I
2.6 The if/else Selection Structure
Based on slides created by Bjarne Stroustrup & Tony Gaddis
Based on slides created by Bjarne Stroustrup & Tony Gaddis
LOOPS The loop is the control structure we use to specify that a statement or group of statements is to be repeatedly executed. Java provides three kinds.
Instructor: Hidayah Elias Course: COMPUTER PROGRAMMING (BFC 2042)
Presentation transcript:

Introduction to Functions Addis Ababa Institute of Technology Yared Semu May 2012

Recap Program Flow Control while loop do…while loop for Loop break continue

Revision #include <iostream> using namespace std; int main () { int n; cout << "Enter the starting number :> "; cin >> n; while (n>0) cout << n << ", "; n--; } cout << "FIRE!\n"; return 0; Enter the starting number > 8 8, 7, 6, 5, 4, 3, 2, 1, FIRE!

The for Loop Statement The for loop is ideal for working with counters because it provides built-in expressions that initialize and update variables. It’s a pretest loop.

Contd… How it Works: 1) INITIALIZATION is executed. Generally it is an initial value setting for a counter variable. This is executed only once. 2) CONDITION is checked. If it is true the loop continues, otherwise the loop ends and statement is skipped (not executed). 3) STATEMENT(S) is executed. As usual, it can be either a single statement or a block enclosed in braces { }. 4) Finally, whatever is specified in the UPDATE field is executed and the loop gets back to step 2.

Omitted Expressions This for loop produces the result: The initialization and update fields are optional. They can remain empty, but in all cases the semicolon signs between them must be written. int i=0; for ( ; i < 10; ) { cout << i << " "; i++; } This for loop produces the result: 0 1 2 3 4 5 6 7 8 9

Contd… Although you do not see it very often, it is worth noting that the following example produces an infinite loop: for (;;) statement(s) When condition is not specified it defaults to true .

Null statements It is also possible to omit the statement part of a for loop. This is called a null statement, and it is declared by using a single semicolon. for(int i = 0; i< 10; i++) ; This loop increments i using the ++ operator 10 times. When the statement is executed, the null statement evaluates to nothing, and consequently, doesn't do anything.

Multiple Declarations Optionally, using the comma operator (,) we can specify more than one expression in any of the fields included in a for loop, like in initialization, for example. for (int i=0, j=9; i < 10; i++, j--) cout << i << " " << j << endl;

Multiple Declarations The previous program produces the result

The break statement It can be used to end an infinite loop, or to force it to end before its natural end. For example, we can stop the count down to launching a space shuttle before its natural end (maybe because of an engine check failure?):

Example 10, 9, 8, 7, 6, 5, 4, 3, countdown aborted! // break loop example   #include <iostream> using namespace std; int main () { int n; for (n=10; n>0; n--) cout << n << ", "; if (n==3) cout << "countdown aborted!"; break; } return 0; 10, 9, 8, 7, 6, 5, 4, 3, countdown aborted!

The continue statement The continue statement causes the program to skip the rest of the loop in the current iteration as if the end of the statement block had been reached, causing it to jump to the start of the following iteration.

Contd… In a while loop, this means the program jumps to the test expression at the top of the loop. 2) In a do-while loop, the program jumps to the test expression at the bottom of the loop, which determines if the next iteration will begin. 3) In a for loop, continue causes the update expression to be executed, and then the test expression to be evaluated.

Example // continue loop example #include <iostream> using namespace std;   int main () { for (int n=10; n>0; n--) if (n==5) continue; cout << n << ", "; } cout << "FIRE!\n"; return 0; 10, 9, 8, 7, 6, 4, 3, 2, 1, FIRE!

Introduction to Functions

Modular Programming A function is a collection of statements that performs a specific task. (also called a module) and is executed when it is called from some point of the program. A function performs some computation and usually yields a result. Modular Programming: breaking down a program into a set of manageable functions, or modules.

Function Definition type name ( parameter1, parameter2, ...) { statements } Where: TYPE : is the data type specifier of the data or value returned by the function. NAME : is the identifier by which it will be possible to call the function. Naming rules are the same as those for variables PARAMETER LIST : (as many as needed): a list of variables that hold values being passed into the function. The different parameters are separated by commas. STATEMENT(S) : is the function's body. It is a block of statements surrounded by braces { }.

The main Function Line 1 is known as the function header Name Parameter List goes here Return Type Body Line 1 is known as the function header Every statement within the curly braces is regarded as the function body. The last statement within the function is usually a special statement (return statement) that returns the value computed by the function

Example float cube(float num) { float r = num*num*num; return r; } Identify the parts of this function.

Function Call Statements The main function starts executing automatically when the program starts. All other functions have to be called explicitly to start executing. This is done by using function call statements.

Program Flow With Functions At the point at which the function is called from within main, the control is lost by main and passed to function (addition). When the called function finishes execution, it returns the control back to the function that called it in the first place (in this case, main).

Program Flow with Function(2) void printString() { cout<<“In Function Call…”<<endl; cout<<“Hello World!”<<endl; }   int main () cout<<“Before function call…”<<endl; printString(); cout<<“After function call…”<<endl; return 0; Predict the output!

Example The result is 8 #include <iostream> using namespace std; // function example #include <iostream> using namespace std;   int addition (int a, int b) { int r; r=a+b; return (r); } int main () int z; z = addition (5,3); cout << "The result is " << z; return 0; The result is 8

Contd… We can see the similarity between the structure of the call to the function and the declaration of the function itself some code lines above: The parameters and arguments have a clear correspondence. Values that are passed into a function are called arguments and the variables that accept these values are called parameters.

Contd… The following line of code return (r); finalizes function addition, and returns the control back to the function that called it in the first place (in this case, main).

Another example int subtraction (int a, int b) { int r = a-b; return (r); }   int main () int x=5, y=3, z; z = subtraction (7,2); cout << "The first result is " << z << '\n'; cout << "The second result is " << subtraction (7,2) <<'\n'; cout << "The third result is " << subtraction (x,y) << '\n'; z= 4 + subtraction (x,y); cout << "The fourth result is " << z << '\n'; return 0; Note: we have made several calls to function subtraction. The first result is 5 The second result is 5 The third result is 2 The fourth result is 6

Functions with no type. The use of void. If you remember the syntax of a function declaration: type name ( argument1, argument2 ...) statement you will see that the declaration begins with a type (i.e., the type of the datum that will be returned by the function with the return statement). But what if we want to return no value? Imagine that we want to make a function just to show a message on the screen. We do not need it to return any value. In this case we should use the void type specifier for the function. This is a special specifier that indicates absence of type.

Example I'm a function //void function example #include <iostream> using namespace std;   void printmessage () { cout << "I'm a function!"; } int main () printmessage (); return 0; I'm a function

Points to Remember You must define the function before calling it. When writing a parameter list, each variable must have a data type associated with it. You can't leave out the data type of a variable even if it has the same type as the variable declared before it. A function call, when used as an expression, evaluates to the value returned by the function.

Quiz (5pts) Write a menu driven program that does addition, subtraction, multiplication, and division of two numbers. Define each operation in its own function. The program should end only when the user asks it to.

Course Project Group yourselves into groups of 4. Write the names of each group member and submit it to me tomorrow.