Computer Programming Fall 2012 תרגול 6 פונקציות

Slides:



Advertisements
Similar presentations
פונקציות תכנות בשפת סי תרגול 6.
Advertisements

Programming Arrays. Question Write a program that reads 3 numbers from the user and print them in ascending order. How many variables do we need to store.
Programming Arrays. Example 1 Write a program that reads 3 numbers from the user and print them in reverse order. How many variables do we need to store.
C Programming Tutorial – Part I CS Introduction to Operating Systems.
Tutorial ICS431 – Introduction to C.
Do-while loop Syntax do statement while (loop repetition condition)
Chapter 6: Control Structures Computer Programming Skills Second Term Department of Computer Science Foundation Year Program Umm Alqura.
C Programming Lecture 7 : Control Structures. Control Structures Conditional statement : if, switch Determine a block of statements to execute depending.
UniMAP SemI-09/10EKT120: Computer Programming1 Week 5 – Functions (1)
Functions: Part 2 of /11/10: Lecture 16 CMSC 104, Section 0101 John Y. Park 1.
Introduction to Computer Organization & Systems Topics: C arrays C pointers COMP Spring 2014 C Part IV.
Structured Programming Approach Module VIII - Additional C Data Types Arrays Prof: Muhammed Salman Shamsi.
CCSA 221 Programming in C CHAPTER 7 WORKING WITH ARRAYS 1.
Strings program. C Program to Check if a given String is Palindrome #include void main() { char string[25], reverse_string[25] = {'\0'}; int i, length.
Strings program. C Program to Check if a given String is Palindrome #include void main() { char string[25], reverse_string[25] = {'\0'}; int i, length.
UNIT 10 Multidimensional Arrays.
UNIT-4 1. Arrays: Definition and declaration, Initialization, Accessing elements of arrays, Storing values in arrays, Inter-function Communication: Passing.
WEEK 8 Class Activities Lecturer’s slides.
Computer Programming for Engineers
Functions Dr. Sajib Datta Functions A function is a self-contained unit of program code designed to accomplish a particular task. Some functions.
Arrays Name, Index, Address. Arrays – Declaration and Initialization int x; y[0] y[1] y[2]
Week 3.  TO PRINT NUMBERS FROM 1 TO 20  TO PRINT EVEN NUMBERS FROM 1 TO 20 2.
Arrays in C. What is Array? The variables we have used so far can store a single value. Array is a new type of variable capable of storing many values.
EKT120: Computer Programming
IS12 - Introduction to Programming Lecture 19: Functions and Arrays
EKT120 COMPUTER PROGRAMMING
2008/11/19: Lecture 18 CMSC 104, Section 0101 John Y. Park
Lecture 7 Arrays 1. Concept of arrays Array and pointers
C Programming Tutorial – Part I
Strings (מחרוזות).
CSE1320 Loop Dr. Sajib Datta
CS1010 Programming Methodology
Functions Dr. Sajib Datta
Week 4 – Repetition Structures / Loops
Array 9/8/2018.
Functions Dr. Sajib Datta
מצביעים והקצאה דינאמית
Dynamic memory allocation and Intraprogram Communication
2008/11/10: Lecture 16 CMSC 104, Section 0101 John Y. Park
מבוא כללי למדעי המחשב תרגול 2
Dynamic memory allocation and Intraprogram Communication
Computer Programming תרגול 6 פונקציות
Engineering Programming A
Arrays, Part 1 of 2 Topics Definition of a Data Structure
Introduction to Programming in C
Introduction to Programming and the C Language
תרגול Introduction to C - Fall Amir Menczel.
Arrays & pointers C How to Program, 8/e.
Computer Programming Summer 2017
Software John Sum Institute of Technology Management
CNG 140 C Programming (Lecture set 8)
Lecture 10 Arrays.
Loops in C.
Functions, Part 2 of 3 Topics Functions That Return a Value
Computer Programming תרגול 6 פונקציות
A function with one argument
Arrays, Part 1 of 2 Topics Definition of a Data Structure
Arrays, Part 1 of 2 Topics Definition of a Data Structure
CS150 Introduction to Computer Science 1
Week 6 CPS125.
Arrays.
Programming Strings.
2008/11/19: Lecture 18 CMSC 104, Section 0101 John Y. Park
ARRAYS ..
Functions, Part 2 of 3 Topics Functions That Return a Value
Functions, Part 2 of 3 Topics Functions That Return a Value
Visit for more Learning Resources
Presentation transcript:

Computer Programming Fall 2012 תרגול 6 פונקציות Introduction to C - Fall 2010 - Amir Menczel

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

הכרזה והגדרה של פונקציות הכרזה (אבטיפוס של הפונקציה = function prototype): ; (return-type function-name(arguments declaration הגדרה: return-type function-name(arguments) { function body… }       לפני השימוש בפונקציה חייבים להכריז או להגדיר את הפונקציה! ערך מוחזר: יכול להיות כל טיפוס שקיים ב-C (int, float, וכו'). או void (פונקציה המוגדרת עם טיפוס החזרה void לא מחזירה ערך).

פונקציות - דוגמה כתוב פונקציה המחשבת ומחזירה את המספר הגדול ביותר בין שלושת המספרים השלמים המועברים לפונקציה כפרמטרים: #include<stdio.h> int max3(int,int,int); //function prototype void main() { int a,b,c; //input variables printf("enter 3 integers : "); scanf("%d%d%d",&a,&b,&c); printf("maximum integer is : %d\n",max3(a,b,c)); } int max3(int x,int y,int z) //function definition int max; //help variable max=x; if(y>max) max=y; if(z>max) max=z; return max;

פונקציות - דוגמה #include<stdio.h> כתוב תוכנית הקולטת 30 מספרים שלמים, מחשבת ומדפיסה את המספר הגדול ביותר בין כל המספרים הנקלטים. נשתמש בפונקציה max3 . #include<stdio.h> int max3(int,int,int); //function prototype void main() { int a, b, c, i, max; scanf("%d%d%d",&a,&b,&c); max= max3(a,b,c); for (i=1;i<10;i++) { if (max3(a,b,c)>max) } printf ("max= %d\n",max); /*Here we will place the implementation of max3*/

העברת ארגומנטים הערכים המועברים אל הפונקציה כפרמטרים מועתקים. לכן, כל שינוי שהפונקציה תבצע בארגומנטים לא ישתקף מחוץ לפונקציה עצמה. פלט: a=1 b=2

העברת ארגומנטים (המשך) לעומת זאת, אם מעבירים לפונקציה מערך, כל שינוי בתוך המערך עצמו יישמר גם לאחר סיום ריצת הפונקציה. פלט: a[0]=2 a[1]=1

דוגמאות למימוש הפונקציות לטיפול במחרוזות: /****************************************************************** Parameters: s - array of chars, must contain ‘\0’. Returns: length of string that s holds *******************************************************************/ unsigned int strlen(char s[]) { unsigned int len = 0; while (s[len] != ’\0’) len++; return len; } /******************************************************************* Compares two strings lexicographically Parameters: s, t - string to be compared Returns: lexicographical difference between s and t int strcmp(char s[], char t[]) int i; for (i = 0; s[i] == t[i]; i++) if (s[i] == '\0') return 0; e return s[i] - t[i];

תרגיל 1 כתוב תוכנית הקולטת ציונים שקיבלו 100 סטודנטים בקורס תכנות בשפת סי. התוכנית ומדפיסה את המספר הסידורי של הסטודנטים שקיבלו ציון גבוה מהציון הממוצע. #include<stdio.h> #define NUM_STUD 100 /******** Function prototypes *********/ void inputGrades(int [],int); float avg(int [], int); void bestStud(int [],float,int); void main() { int grades[NUM_STUD];//data array float av_mark;//average mark inputGrades(grades,NUM_STUD); av_mark=avg(grades,NUM_STUD); bestStud(grades,av_mark,NUM_STUD); }

תרגיל 1 (המשך פתרון) /******* Function definitions *********/ תרגיל 1 (המשך פתרון) /******* Function definitions *********/ void inputGrade(int arr[],int size) { int i; //loop variable for(i=0;i<size;i++) printf("Enter %d student mark -> ", i+1); scanf("%d", &arr[i]); } float avg(int arr[], int size) int sum=0; // sum of grades int i;//loop variable for (i=0;i<size;i++) sum=sum+arr[i]; return sum/(float)size; void bestStud(int arr[],float av, int size) for(i=0; i<size; i++) if (arr[i]>av) printf("The best student number is %d\n",i+1);

תרגיל 2 כתוב תכנית הקולטת משפט (המילים במשפט מופרדות ברווח אחד בלבד) ומחשבת ומדפיסה את מספר המילים במשפט. . numWordsעליך להיעזר בפונקציה int numWords(char []);//function prototype void main() { char sent[256];//input sentence puts("Enter the sentence :"); gets(sent); printf("Number of words is %d\n“ , numWords(sent)); } int numWords(char b[] ){ //function definition int i=0, num=0; do{ if (b[i++]==' ') num++; } while(b[i]); return ++num;

תרגיל 3 - סודוקו כתבו תכנית אשר קולטת לוח סודוקו מלא בגודל 9x9 , ובודקת האם הלוח הינו לוח סודוקו חוקי. ניתן להניח שהמשתמש מזין ערכים חוקיים. כלומר מספרים שלמים בין 1 ל-9. לאיזה תתי משימות (פונקציות) נחלק את התכנית?

תרגיל 3 - פיתרון

תרגיל 3 - פיתרון

תרגיל 3 - פיתרון

תרגיל 4 #include <stdio.h> #define MAX 100 כתוב תוכנית הקולטת מספרים שלמים לתוך שני מערכים. אפשר להניח שהמשתמש מכניס מספרים כך שכל מערך ממוין. התוכנית מבצעת מיזוג של שני מערכים לתוך מערך שלישי, כך שהוא יכיל את איברי שני המערכים וגם יהיה ממוין. #include <stdio.h> #define MAX 100 /*This function merges two sorted arrays into a third array.*/ void merge(int arr1[], int n1, int arr2[], int n2, int res[]) { int i, j, k; for (i=0,j=0,k=0; i < n1 && j < n2; k++) if (arr1[i] < arr2[j]) res[k] = arr1[i]; i++; } else res[k] = arr2[j]; j++; /* only one of the two is true */ while(i < n1) res[k++] = arr1[i++]; while(j < n2) res[k++] = arr2[j++]; } //void merge

תרגיל 4 (המשך) void main() { int n1, n2, i; תרגיל 4 (המשך) void main() { int n1, n2, i; int a1[MAX], a2[MAX], a3[MAX * 2]; printf("Number of values for 1st array: "); scanf("%d", &n1); for (i = 0; i < n1; ++i) printf("Value %d: ", i+1); scanf("%d", &a1[i]); } printf("Number of values for 2nd array: "); scanf("%d", &n2); for (i = 0; i < n2; ++i) scanf("%d", &a2[i]); merge(a1, n1, a2, n2, a3); for (i = 0; i < n1 + n2; ++i) printf("%d ", a3[i]); printf("\n");

תרגיל 5 מערך דו מימדי כפרמטר תרגיל 5 מערך דו מימדי כפרמטר 3 2 1 4 8 11 -2 9 7 נגדיר "פרח" המערך דו מימדי כך: 3X3- האיברים מתוך תת מערך בגודל - האיבר המרכזי במערך הוא "לב הפרח". - ארבעת האיברים הצמודים לו בפינותיו הם "עלי הפרח". - הערך של "לב הפרח" שווה לסכום ערכי "עלי הפרח". מספרים שלמים15X18כתוב תוכנית הקולטת למערך בגודל המערך נקרא "פרחוני", אם יש בו לפחות 5 "פרחים". התוכנית תבדוק אם המערך הוא "פרחוני", ותציג כפלט הודעה מתאימה.

תרגיל 5 - פתרון #include<stdio.h> #define TRUE 1 #define FALSE 0 #define ROW 15 #define COL 18 /*********************** Function prototypes **********************/ void in_arr(int [][COL],int,int); int is_flower(int[][COL],int,int); /***************************************************************/ void main() { int arr[ROW][COL];//input array int count=0;//number of flowers int i,j;//loop counters in_arr(arr,ROW,COL); for(i=0;i<ROW;i++) for(j=0;j<COL;j++) count=count+is_flower(arr,i,j); if(count>=5) printf("Yes\n"); else printf("No\n"); }

תרגיל 5 – פתרון (המשך) /********************* Function definitions **************************/ void in_arr(int a[][COL],int n,int m) { int i,j;//loop counters for(i=0;i<n;i++) for(j=0;j<m;j++) printf("Enter %d row %d col element -> ",i+1,j+1); scanf("%d",&a[i][j]); } int is_flower(int b[][COL],int k,int l) int sum;//sum of flower's elements if(k==0||k==ROW-1||l==0|l==COL-1) return FALSE; sum=b[k-1][l-1]+b[k-1][l+1]+b[k+1][l-1]+b[k+1][l+1]; if(b[k][l]==sum) return TRUE; else

תרגיל 6 פיתוח הבינום של ניוטון מוגדר באופן הבא: n משולש פסקל הוא סידור של מקדמי הבינום, המסומנים ב- , בצורה של משולש שווה שוקיים, כאשר הוא למעשה מספר השורה של המקדם במשולש ו-kהוא מיקומו בשורה זו (מספור השורות והמיקומים בכל שורה מתחיל מ-0). הקודקוד העליון של משולש זה מכיל

תרגיל 6 (המשך) פתרון: #include <stdio.h> #define ARR_SIZE 20 /*Pascal Triangle -prints a pascal triangle Parameters: nLines - bottom line level */ void pascalTri(int nLines) { int arr[ARR_SIZE+1] = {0}; int i, level; /*Check if level is in array bounds:*/ if (nLines >= ARR_SIZE) return; for (level = 0; level <= nLines; level++) /*Set the last number in level to 1:*/ arr[level] = 1;

תרגיל 6 (המשך)

תרגיל 6 (המשך)