1 / 24

פונקציות תכנות בשפת סי תרגול 6

פונקציות תכנות בשפת סי תרגול 6. פונקציות - חזרה. פונקציות ועיצוב תוכנה : ● פונקציות מאפשרות שימוש בקטעי קוד כקופסה שחורה ללא צורך לדעת את פרטי המימוש. ● מספיק לדעת מה נעשה ולא איך. ● פירוק תוכנית ליחידות לוגיות משפר את הקריאות, מונע חזרה על אותם קטעי קוד, ומקל על ביצוע שינויים בתוכנית.

burgessl
Download Presentation

פונקציות תכנות בשפת סי תרגול 6

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


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

  2. פונקציות - חזרה • פונקציות ועיצוב תוכנה: • ● פונקציות מאפשרות שימוש בקטעי קוד כקופסה שחורה ללא צורך לדעת את פרטי המימוש. • ●מספיק לדעת מה נעשה ולא איך. • ●פירוק תוכנית ליחידות לוגיות משפר את הקריאות, מונע חזרה על אותם קטעי קוד, ומקל על ביצוע שינויים בתוכנית. • ●ניתן להגדיר פונקציות באותו קובץ או בקבצים שונים אשר יקושרו במהלך ה-linking. • ניתן להשתמש בפונקציות שנכתבו על-י די מתכנתים אחרים. • פונקציות- לשם מה? • ●חיסכון בכתיבה - כאשר יש צורך לבצע את אותה תת משימה מספר פעמים נגדיר אותה פעם אחת כפונקציה ונשתמש בה בכל • מקום נדרש. כך נעשה שימוש חוזר בפונקציה במקום לכתוב מחדש את אותו קטע קוד. • ●כתיבה מבנית- מאפשרת פיתוח מודולים שאינם קשורים זה לזה, ובשלב מאוחר יותר לשלב לקטע קוד בהתאם לצורך של • המתכנת. • ●כתיבת פונקציות מאפשרת חלוקה ברורה לתת משימות לשם פיתרון בעיה כוללת. • בצורה כזו האלגוריתם קריא יותר אל מול האפשרות של פיתוח פונקציה ראשית ארוכה המבצעת הרבה תת משימות. • ●תהליך תיקון השגיאות (debugging) קל יותר בקוד הבנוי מפונקציות מכיוון שלכל פונקציה תפקיד משלה, ומשתנים השייכים • רק לה.

  3. פונקציות - חזרה הכרזה והגדרה של הפונקציה: ●הכרזה (אבטיפוס של הפונקציה = function prototype): ;(return-type function-name(arguments declaration ●הגדרה: return-type function-name(arguments) {function body} Formal parameters לפני השימוש בפונקציה חייבים להכריז או להגדיר את הפונקציה! ערך מוחזר: void/non-void type העברת ארגומנטים: הערכים של הפרמטרים האקטואלים actual parameters)) מועתקים לפרמטרים הפורמאלים (formal parameters )ובכך הפונקציה מקבלת את הארגומנטים שלה. זכרו שאין השפעה על הפרמטרים האקטואלים!!!

  4. פונקציות - דוגמה • כתוב פונקציה המחשבת ומחזירה את המספר הגדול ביותר בין שלושת המספרים השלמים • המועברים לפונקציה כפרמטרים: • #include<stdio.h> • int max3(int,int,int); //function prototype • void main() • { • inta,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(intx,inty,int z) //functiondefinition • { • int max; //help variable • max=x; • if(y>max) • max=y; • if(z>max) • max=z; • return max; • }

  5. פונקציות - דוגמה כתוב תוכנית הקולטת עשרה שלשות של מספרים שלמים, מחשבת ומדפיסה את המספר הגדול ביותר בין כל המספרים הנקלטים. נשתמש בפונקציה max3. • #include<stdio.h> • #define N 10 • int max3(int,int,int); //function prototype • void main() • { • inta,b,c; //input variables • int max10; //the biggest value • inti; //loop variable • for(i=0;i<N;i++) { • printf ("enter 3 integers : "); • scanf("%d%d%d",&a,&b,&c); • if(i==0) • max10=max3(a,b,c); • else • if(max3(a,b,c)>max10) • max10=max3(a,b,c);} • printf ("max10= %d\n",max10); • } • /*Here we will place the function definition of max3*/

  6. דוגמאות למימוש הפונקציות לטיפול במחרוזות: #include<stdio.h> • /****************************************************************** • intstrlen (char s[]); • Finds length of string • Parameters: s - array of chars • Returns: length of string that s holds • *******************************************************************/ • intstrlen(char s[]) • { • inti = 0; • while (s[i]) i++; • returni; • } • /******************************************************************* • intstrcmp (char s[], char t[]); •  Compares two strings lexicographically • Parameters: s, t - string to be compared • Returns: lexicographical difference between s and t • *******************************************************************/ • intstrcmp(char s[], char t[]) • { • inti; • for (i = 0; s[i] == t[i]; i++) • if (s[i] == '\0') return 0; • return s[i] - t[i]; • }

  7. דוגמה לשימוש בפונקציות בשימוש במחרוזות (המשך) • /******************************************************************* • char *strcpy (char dest[], const char src[]); • Copies the string pointed to by src (including the terminating ‘\0' • character) to the string pointed to by dest. The strings may not • overlap, and the destination string dest must be large enough to • receive the copy. • Returns: the destination string • *******************************************************************/ • char *strcpy(chardest[], constcharsrc[]) • { • inti; • for (i = 0; dest[i] = src[i]; i++); • returndest; • }

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

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

  10. תרגיל 2 כתוב תכנית הקולטת משפט (המילים במשפט מופרדות ברווח אחד בלבד) ומחשבת ומדפיסה את מספר המילים במשפט. . numWordsעליך להיעזר בפונקציה • #include<stdio.h> • #include<string.h> • 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; //loop variable • int num=0; //number of words • do{ • if (b[i]==' ') • num++; • }while(b[i]); • return ++num; • } פתרון:

  11. תרגיל 3 כתוב תוכנית הממיינת מספרים שלמים במערך נתון לפי סדר עולה. עליך להתשמש בשיטת מיון selection sort. בשפת סי מעבירים מערך לפונקציה לפי שיטה call by reference (העברה לפי כתובת ), כלומר את כל השינויים שהפונקציה מבצעת על האלמנטים של המערך היא מבצעת על האלמנטים המקוריים של המערך בזיכרון המחשב בגלל ששם המערך שמעובר כפרמטר הוא הכתובת של האיבר הראשון של המערך. הרעיון הבסיסי הוא למצוא בכל שלב את האיבר הגדול ביותר ולהשים אותו בסוף. פתרון: #include<stdio.h> #define ARR_DEF {7,2,8,1,5,6,4} /*FUNCTION PROTOTYPES:*/ /*(1) sort elements of the array arr of size size in an increasing order. */ void selectionSort(int arr[], int size); /*(2) swap elements of arr with index x,y*/ void swap(int arr[], int x, int y); /*(3) find the index of the largest element of arr between positions 0..size-1*/ int indexOfLargest(int arr[], int size); /*(4) print the array arr */ void printArray(int arr[], int size);

  12. /*IMPLEMENTATION:*/ int main() { int arr[] = ARR_DEF ; selectionSort(arr,7); printArray(arr, 7); } void selectionSort(int arr[], int size) { int i; printArray(arr, size); /*Print the array before the sort:*/ for (i = size - 1; i >= 0; i--) swap(arr, indexOfLargest(arr, i + 1), i); printArray(arr, size); /*Print the array after the sort:*/ } void printArray(int arr[], int size) { int i; for(i = 0; i < size; i++) printf("%d ",arr[i]); putchar('\n'); } void swap(int arr[], int idx1, int idx2) { int tmp; tmp = arr[idx1]; arr[idx1] = arr[idx2]; arr[idx2] = tmp; } int indexOfLargest(int arr[], int size) { int i; int idxLargest = 0; for (i = 1; i < size; i++) if (arr[idxLargest] < arr[i]) idxLargest = i; return idxLargest; }

  13. תרגיל 4 כתוב תוכנית הקולטת לשני מערכים מספרים שלמים. התוכנית מבצעת מיזוג של שני מערכים לתוך מערך שלישי (בהנחה שהוא מספיק גדול). התוכנית שומרת על הסדר המקורי שהיה בין כל שני איברים שמקורם באותו מערך. התוכנית דואגת לכך שאם שני המערכים המקוריים היו ממויינים, גם המערך שמכיל את המיזוג שלהם יהיה ממוין. #include<stdio.h> #define MAX 100 /*This function merges two arrays without changing the order between elements in that come from the same array.*/ void merge(int arr1[], int n1, int arr2[], int n2, int res[]) { int i, j, k; for (i=j=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 may be true (or neither)*/ while(i < n1) res[k++] = arr1[i++]; while(j < n2) res[k++] = arr2[j++]; }

  14. תרגיל 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) { printf("Value %d: ", i+1); scanf("%d", &a2[i]); } merge(a1, n1, a2, n2, a3); for (i = 0; i < n1 + n2; ++i) printf("%4d", a3[i]); printf("\n"); }

  15. תרגיל 5 גרסת bubble sort למערך של מחרוזות: כתוב תוכנית הקולטת מספר מחרוזות וממיינת אותם לפי סדר לקסיקוגרפי. נממש בשיטת מיוןbubble sort (מיון בועות) – האלגוריתם הזה מסדר תווים במחרוזת לפי סדר עולה. עליך להשתמש בתרגיל זה בפונקציות ספריה string.h הבאות: strcmp() ו- strcpy() . #include<stdio.h> #include<string.h> #define MAX 100 #define STRLEN 32 void bubble(char vals[][STRLEN], int n) { int i, j; char temp[STRLEN]; for (i = 0; i < n-1; ++i) for (j = 0; j < n-1-i; ++j) if (strcmp(vals[j],vals[j+1]) > 0) { strcpy(temp,vals[j]); strcpy(vals[j],vals[j+1]); strcpy(vals[j+1],temp); } } פתרון:

  16. תרגיל 5 (המשך) void main() { int n, i; char vals[MAX][STRLEN]; printf("Enter the desired number of strings (maximum %d strings): ",MAX); scanf("%d", &n); getchar();/*Get the '\n' character.*/ printf("Now enter the %d strings (each one should be no longer than %d characters): \n",n,STRLEN-1); for (i = 0; i < n; ++i) { printf("String %d= ", i+1); gets(vals[i]); } bubble(vals, n); for (i = 0; i < n; ++i) printf("%s\n", vals[i]); }

  17. תרגיל 5 (המשך) int main() { int temp; char str1[10]="mice"; char str2[10]="nice"; char str3[10]; printf("the length of \"%s\" is %d\n", str1,strlen(str1)); strcpy(str3,str2); printf("str3 is now equal to \"%s\"\n", str3); temp=strcmp(str1,str3); if (temp<0) printf("\"%s\" comes before \"%s\" in a dictionary\n", str1, str3); else printf("\"%s\" does not come before \"%s\" in a dictionary\n", str1, str3); }

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

  19. תרגיל 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] = {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;

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

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

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

  23. תרגיל 7 - פתרון #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"); }

  24. תרגיל 7 – פתרון (המשך) /********************* 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 return FALSE; }

More Related