פונקציות לעיתים קרובות לא נוח להגדיר את כל התוכנה בתוך גוף אחד.

Slides:



Advertisements
Similar presentations
1 Programming in C++ Lecture Notes 9 Functions (Returning Values) Andreas Savva.
Advertisements

Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 5. Functions.
Writing and Testing Programs Drivers and Stubs Supplement to text.
Local, Global Variables, and Scope. COMP104 Slide 2 Functions are ‘global’, variables are ‘local’ int main() { int x,y,z; … } int one(int x, …) { double.
#include using namespace std; void main() { cout
Functions Parameters & Variable Scope Chapter 6. 2 Overview  Using Function Arguments and Parameters  Differences between Value Parameters and Reference.
CS1201: Programming Language 2 Recursion By: Nouf Almunyif.
C++ function call by value The call by value method of passing arguments to a function copies the actual value of an argument into the formal parameter.
Functions Pass by Reference Alina Solovyova-Vincent Department of Computer Science & Engineering University of Nevada, Reno Fall 2005.
Current Assignments Homework 3 is due tonight. Iteration and basic functions. Exam 1 on Monday.
CHAPTER 8 CONTROL STRUCTURES Prepared by: Lec. Ghader R. Kurdi.
CSC1201: Programming Language 2 Lecture 1 Level 2 Course Nouf Aljaffan (C) CSC 1201 Course at KSU1.
Lecture 7: Making Decisions Professor: Dr. Miguel Alonso Jr. Fall 2008 CGS2423/COP1220.
Lecture 4 Function example. Example1 int max (int a, int b) { int c; if (a > b) c = a; else c = b; return (c); } void main ( ) {int x, y; cin>>x>>y; cout.
CHAPTER 10 ARRAYS AND FUNCTIONS Prepared by: Lec. Ghader Kurdi.
Function User defined function is a code segment (block) that perform an specific action. Function Definition: Function Definition: Return_DT F_name (
Introduction to Functions.  A complex problem is often easier to solve by dividing it into several smaller parts, each of which can be solved by itself.
1 Programming Principles II Lecture Notes 4 Functions (Returning Values) Andreas Savva.
April 11, 2005 More about Functions. 1.Is the following a function call or a function header? calcTotal(); 2.Is the following a function call or a function.
Lecture 7 Computer Programming -1-. Conditional Statements 1- if Statement. 2- if ….. else Statement. 3- switch.
משפטי תנאי ( לוגיקה ) קרן כליף. 2 © Keren Kalif ביחידה זו נלמד :  משפטי תנאי  משפט switch  משפט if מקוצר.
1 C++ Classes and Data Structures Course link…..
LESSON 2 Basic of C++.
#define #include<iostream> using namespace std; #define GO
Command Line Arguments
Chapter 5 Function Basics
Functions and an Introduction to Recursion
School of EECS, Peking University
Programming fundamentals 2 Chapter 1:Array
לולאות קרן כליף.
Quiz Next Monday.
Reserved Words.
Programming fundamentals 2 Chapter 2:Function
Dynamic Memory Allocation Reference Variables
Function User defined function is a code segment (block) that perform an specific action and may return a value. Function Definition: Return_DT F_name.
CSC1201: Programming Language 2
Chapter 5 Function Basics
Function User defined function is a code segment (block) that perform an specific action. Function Definition: Return_DT F_name ( list of formal parameters)
אבני היסוד של תוכנית ב- C++
אבני היסוד של תוכנית ב- C++
Programming -2 برمجة -2 المحاضرة-7 Lecture-7.
Data type List Definition:
מחרוזות-String בשפת C++ ישנו תפקיד מיוחד למערך מסוג char רצף של תווים הנמצאים במערך מסוג char המסתיימת בתו אפס (הכוונה לאפס ממש '0\' , ולא לתו '0')
CS150 Introduction to Computer Science 1
Chapter 5 Function Basics
הרצאה 03 אבני היסוד של תוכנית ב- C
Starting Out with C++: From Control Structures through Objects
Pointers & Functions.
اصول کامپیوتر ۱ مبانی کامپیوتر و برنامه‌سازی
The Run-Time Stack and Reference Parameters
Pass by Reference.
CS150 Introduction to Computer Science 1
Summary Two basic concepts: variables and assignments Basic types:
If Statements.
CS1201: Programming Language 2
Local, Global Variables, and Scope
Functions and an Introduction to Recursion
CS150 Introduction to Computer Science 1
Fundamental Programming
CSC1201: Programming Language 2
Introduction to Algorithms and Programming
Using string type variables
Pointers & Functions.
(Dreaded) Quiz 2 Next Monday.
CS1201: Programming Language 2
TOPIC: FUNCTION OVERLOADING
Introduction to Functions
Programming Strings.
Introduction to Algorithms and Programming COMP151
Methods and Data Passing
Presentation transcript:

פונקציות לעיתים קרובות לא נוח להגדיר את כל התוכנה בתוך גוף אחד. עדיף לחלק תוכנה לבלוקים / תהליכים נפרדים (תכנית משנה – קטע קוד) שנוכל לבצע בכל עת ולתכנת כל בלוק / תהליך בנפרד.   זאת גם אחד מהתנאים לכתיבת תוכנה טובה. רעיון: לחלק תוכנה לתת-תוכנות קטנות יחסית . ואם יש שגיאה אז קל יותר למצוא לתקן אותה. קטע קוד כזה נקרא פונקציה. נגדיר את מושג הפונקציה.

תזכורת מעניינת: כל תוכנית שכתבנו עד היום כוללה פונקציה המוכרת לנו מימים ימימה: int main() { …… return 0; } ממנה מתחיל ביצוע התכנית. בכל תכנית שלנו תמיד תהיה פונקציה main() והמעבד מתחיל את הרצת התכנית מפונקציה זאת. הפונקציות אחרות נוספות תכללנה בתכנית על-פי שיקול דעתנו.  

Type Function_Name(Type Parmeter_1,…,Type Parameter_n) { ……. } הגדרה פורמאלית:   Type Function_Name(Type Parmeter_1,…,Type Parameter_n) { ……. } )רשימת-פרמטרים שהפונקציה מקבלת מה-(mainשם-פונקציה ערך-מוחזר לידי הפונקציה ל-main בתוך סוגריים () נכתוב את הנתונים שהפונקציה מקבלת מה- main ננקוב בסוגו של כל משתנה ובשם המשתנה לפיו תתייחס הפונקציה אל הנתון. הפונקציה חייבת לקבל נתונים מאותו סוג שצוין ,באותו סדר שצוין, ובאותה כמות שצוינה. פונקציה מסוג int, char, float, double יכולה להחזיר ערך אחד בלבד פקודת החזרת ערך:   return (parameter)

//-------------------------------- cout<< "\nThank You\n"; }

בדוגמה זו בהגדרת הפונקציה, לפני שמה, מופיעה המילה השמורה void משמעה- "כלום" . הפונקציה לא מקבלת שום פרמטרים מה- main()ולא מחזירה כלום (void) ל- main().

הסבר: יש לשים לב לאופן הרישום:   גוף של פונקציה הגדרנו אחרי main() אבל שם של הפונקציה כולל סוגה ופרמטרים צריך להגדיר לפני main(). שיטה זו מאפשרת לנו לכתוב מספר רב של פונקציות, גם כאלה אשר קוראות זו לזו, מבלי שנצטרך ליחס כל חשיבות לסדרן. #include <stdio.h> void myfunc(); (prototype) – הפרוטוטיפ של הפונקציה //--------------------------------------------- void main() { cout<<"Ma nishma\n"; myfunc() ; //קריאה לפונקציה cout<<"ok\n"; //-------------------------------- cout<< "\nThank You\n"; } void myfunc() cout<< "Beseder\n" ;

דוגמא : פונקציה שכן מקבלת ערכים אך מחזירה void #include <iostream> #include <string> using namespace std;  void min(int num1, int num2) { if (num1<num2) cout<<"num1="<<num1<<endl<<"num2="<<num2<<endl<<"num1<num2"<<endl;  else cout<<num1<<endl<<num2<<endl<<"num1>num2"<<endl; } int main () int num1,num2;   cout<<"num1=? num2=?"<<endl; cin>>num1>>num2; min(num1,num2); return 0;

דוגמא : פונקציה שכן מקבלת ערכים אך מחזירה void+ הפונקציה שלא מקבלת פרמטרים מה- main() ולא מחזירה פרמטר ל-main()   #include<iostream> using namespace std; //--------------------------------------- void myname() { cout<<"func name is:"<<endl; } void mymekabelet(double a, double b) double mykefel=a*b; cout<<"kefel =a*b="<<mykefel<<endl; int main() double a,b; cout<<"Enter your numbers:"<<endl; cin>>a>>b; cout<<"Your numbers:"<<"a="<<a<<" "<<"b="<<b<<endl<<endl; myname();   mymekabelet(a,b);

#include<iostream> using namespace std; //------------------------------------- double mysym(double a, double b) { double mysyma=a+b; return mysyma; } //--------------------------------------- double myhisur(double a, double b) double myhisura=a-b; return myhisura; void myname() cout<<"my name is....."<<endl;

void mymekabelet(double a, double b) { double mykefel=a*b; cout<<"kefel =a*b="<<mykefel<<endl; } //--------------------------------------- int main() double a,b,hibur,hisur; cout<<"Enter your numbers:"<<endl; cin>>a>>b; cout<<"Your numbers:"<<"a="<<a<<""<<"b="<<b<<endl<<endl; hibur=mysym(a,b); hisur=myhisur(a,b); myname(); mymekabelet(a,b); cout<<"a+b="<<hibur<<endl; cout<<"a-b="<<hisur<<endl;

דוגמה: #include <iostream> using namespace std; int max(int x, int y) { if (x>y) return x; else return y; }   int main() int x = 5, y = 7; int m = max(x,y); cout<<"max = "<<m<<endl; cout<<"max = "<<max(9,-8)<<endl; return 0; הפונקציה max מוגדרת כך שהיא מקבלת שני פרמטרים מסוג int ומחזירה ערך גם מסוג int . תפקידה של הפונקציה הוא למצוא את המספר הגדול מבין שני המספרים שהיא מקבלת. הפונקציה main קוראת לפונקציה max עם הפרמטרים 5 ו- 7 ומבצעת השמה של ערך המוחזר על-ידי הפונקציה ל- m , לאחר מכן התוצאה נשלחת למסך. בסוף התוכנית שוב ישנה קריאה לפונקציה max אך הפעם עם ערכים 9 ו- 8-.

המשמעות של פונקציה המחזירה void היא שהפונקציה אינה מחזירה ערך כלל. דוגמה 1 #include<iostream> using namespace std; void triangleStars(int n) } for (int i = 1; i <= n; i++) { for (int j = n; j >= i; j--) cout << "* "; cout << endl; int main() int num; cout << "enter number of strings "; cin >> num; triangleStars(num); return 0; פונקציה triangleStars הוגדרה כפונקציה המחזירה ערך void , כוון שהיא לא מחזירה ערך כלל, רק מדפיסה משולש ישר זווית של n כוכביות על המסך.  

דוגמה 2 פונקציה isEven מקבלת מספר שלם x ומחזירה אמת אם המספר הוא זוגי, אחרת היא מחזירה שקר bool isEven(int x) { bool ans = true; if (x%2 != 0) ans = false; } return ans;

#include<iostream> סוגים של משתנים נתבונן בדוגמא פשוטה:  ב-C++ נכתוב:  #include<iostream> using namespace std;  int stam();  int main() { int z=8; int w=stam(); cout<<"from main="<<5*z<< " " <<"from stam()="<< w <<endl; return 0; }   int stam() int z=6; return(5*z); } 

כאן הגדרנו משתנה z פעמיים: פעם אחד בתוך פונקציה main() ופעם בפונקציה stam() אבל משתנה z שהוגדר בתוך פונקציה stam() אינו משפיע על משתנה z החיצוני (של ה-MAIN). כל משתנה המוגדר בתוך פונקציה נקרא משתנה לוקאלי (משתנה מקומי) אפשר לגשת למשתנה הזה רק בתוך הפונקציה. הוא לא קיים מחוץ לפונקציה.  

נתבונן בדוגמא אחרת(f4): ב-C נכתוב: #include<iostream> using namespace std;  int z=2; int stam();  int main()   { cout<<"from stam()"<<stam()<<endl; return 0; } int stam() return(5*z);

כאן לא הגדרנו בתוך פונקציה שום משתנה ולא העבנו שום פרמטר, אבל לא נקבל טעות.   למשתנה שהגדרנו לפני main() ניתן לגשת מכל חלק של תוכנה. המשתנה כזה נקרא משתנה גלובאלי הערה: עדיף לצמצם בשימוש של משתנים גלובאליים ולהגדיר משתנים לוקליים בתוך הפונקציה.