1 / 34

Introduction to Programming in C

Introduction to Programming in C. תרגול 4. 14.08.2011. 1. מטרת התרגול. מערכים מחרוזות. Introduction to Programming in C - Fall 2010 – Erez Sharvit, Amir Menczel. מערכים. הגדרת מערך עם שלושה תאים: int nums[ 3 ]; פנייה לתא במערך ע"י האינדקס של התא: nums[0]=1; nums[1]=3;

zev
Download Presentation

Introduction to Programming in C

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. Introduction to Programming in C תרגול 4 14.08.2011 1

  2. מטרת התרגול • מערכים • מחרוזות Introduction to Programming in C - Fall 2010 – Erez Sharvit, Amir Menczel

  3. מערכים • הגדרת מערך עם שלושה תאים: int nums[3]; • פנייה לתא במערך ע"י האינדקס של התא: nums[0]=1; nums[1]=3; nums[2]=nums[1]+nums[0]; C Programming Intoduction - Fall 2011 - Erez Sharvit, Amir Menczel

  4. דוגמא: מערך של מספרים • התוכנית הבאה (עמוד הבא) קולטת סדרה של 20 מספרים שלמים לתוך מערך ומחשבת את הממוצע שלהם Introduction to Programming in C - Fall 2010 – Erez Sharvit, Amir Menczel

  5. #define MAX_LEN 20 • void main() • { • int i, sum =0; • int nums[MAX_LEN]; • // Get numbers • printf(“Enter %d numbers: “, MAX_LEN); • for (i = 0; i < MAX_LEN; i++) • scanf(“%d”, &nums[i]); • // Calc average • for (i = 0; i < MAX_LEN; i++) • sum += nums[i]; • printf(“Sum = %.2f”, (float)sum / MAX_LEN); • } C Programming Intoduction - Fall 2011 - Erez Sharvit, Amir Menczel

  6. דוגמא 2: אורך מחרוזת • התוכנית הבאה קולטת מחרוזת ומדפיסה את אורכה • #define BUFF_SIZE 256 • void main() • { • int len = -1; • char s[BUFF_SIZE]; • printf(“Enter String: ”); • scanf(“%s”, s); • // Calc length • while (s[++len] != ‘\0’); • printf(“Length = %d”, len); • } Introduction to Programming in C - Fall 2010 – Erez Sharvit, Amir Menczel

  7. תרגיל 1: השוואת מחרוזות • כתבו תוכנית אשר קולטת שתי מחרוזות ובודקת אם הן שוות Introduction to Programming in C - Fall 2010 – Erez Sharvit, Amir Menczel

  8. #define BUFF_SIZE 256 • void main() • { • int i; • char s1[BUFF_SIZE], s2[BUFF_SIZE]; • printf/scanf • // Run as long strings match or (at least) one string ends • for (i = 0; s1[i] == s2[i] && s1[i] != ‘\0’; i++); • // Current value indicate whether strings equal • if (s1[i] != s2[i]) • printf(“Not equal”); • else • printf(“Equal”); • } C Programming Intoduction - Fall 2011 - Erez Sharvit, Amir Menczel

  9. תרגיל 2: הפיכת מחרוזת • כתבו תוכנית אשר קולטת מחרוזת והופכת אותה Introduction to Programming in C - Fall 2010 – Erez Sharvit, Amir Menczel

  10. int left, right; • char s[BUFF_SIZE]; • printf/scanf • // Get initial left & right positions • left = 0; • right = -1; • while (s[++right] != ‘\0’) ; • // Reverse string • for (right--; left < right; left++, right--) • { • char temp; • // Swap current left & right elements • temp = s[left]; • s[left] = s[right]; • s[right] = temp; • } C Programming Intoduction - Fall 2011 - Erez Sharvit, Amir Menczel

  11. מיון בועות • כתבו תוכנית אשר קולטת מערך של עד LEN מספרים וממיינת אותו בעזרת מיון בועות. באופן הבא: • Nums קלוט LEN מספרים • i  LEN - 1 • כל עודi > 1, בצע: • j  0 • כל עוד j < i , בצע: • אם Nums[J] > Nums[J+1] אז: החלף Num[j]  Num[j+1] • jj + 1 • ii - 1

  12. int i, j, len = 0, a[LEN], isLastValue = 0; // Get number until -1 is entered printf(“Enter numbers (-1 to finish): “); while ( (len < LEN) && (!isLastValue) ) { scanf(“%d”, &a[len]); if (a[len] == -1) isLastValue = 1; len++; } // Sort array using bubble sort for (i = len - 1; i > 1; i--) for (j = 0; j < i; j++) if (a[j] > a[j + 1]) { int temp = a[j]; a[j] = a[j + 1]; a[j + 1] = temp; } // Print sorted array for (i = 0; i < len; i++) printf(“%d, “, a[i]);

  13. תרגיל 1- מערכים דו-ממדיים • צריך לממש את התוכנית הבאה: • קלט: מערך דו-ממדי המכיל תווים (chars), ומילה המורכבת מתווים אשר אורכה קצר משני ממדי המערך. • הקלט נתון (Hardcoded), אין צורך לקלוט אותו ממשתמש. • פלט: הדפסת כל המופעים של המילה במערך הדו-ממדי, כאשר המילה יכולה להופיע בשורה (horizontally) או בעמודה (vertically) • חלוקת עבודה לשלבים: • נבין כיצד למצוא את כל המופעים בשורות. • נבין כיצד למצוא את כל המופעים בעמודות. • האם יש דמיון למציאה עבור שורות.

  14. פתרון תרגיל 1 #include<stdio.h> #define ROW 5 #define COL 5 #define WORDSIZE 3 void main() { char matr[ROW][COL]= {{'r','v','o','q','w'}, {'a','h','s','x','l'}, {'n','k','s','d','m'}, {'r','a','n','j','r'}, {'d','k','u','c','a'}}; char word[WORDSIZE+1]="ran"; //Leave room for the ‘\0’ character. int i,j,k,l;

  15. פתרון תרגיל 1 - שורות // Search for horizontal words (along the rows): for(i=0; i<ROW; i++) //Scan the rows. for(j=0; j<=COL-WORDSIZE; j++) //Scan the columns. { //Scan the word if it is there. for(k=j, l=0; l<WORDSIZE && matr[i][k]==word[l]; k++, l++);if(l==WORDSIZE) printf("The word was found horizontally!!! Its coordinates are: x1=%d, y1=%d, x2=%d, y2=%d\n", i, k-WORDSIZE,i,k-1); }

  16. פתרון תרגיל 1 - עמודות //Search for vertical words (along the columns): for(i=0; i<COL; i++) //Scan the columns: for(j=0; j<=ROW-WORDSIZE; j++) //Scan the rows: { for(k=j, l=0;l<WORDSIZE && matr[k][i]==word[l]; k++, l++); if(l==WORDSIZE) printf("The word was found vertically!!! Its coordinates are: x1=%d, y1=%d, x2=%d, y2=%d\n", k-WORDSIZE,i,k-1,i); } }

  17. פתרון תרגיל 1 - פלט • The word was found horizontally!!! Its coordinates are: x1=0, y1=0, x2=0, y2=2“ • The word was found vertically!!! Its coordinates are: x1=3, y1=0, x2=3, y2=2

  18. תרגיל 2 הדפסת ערכי מטריצה (מערך דו-מימדי) בצורה מעגלית כתבו תוכנית שנתונה לה מטריצה בגודל מסוים (4 על 3), ועליה להדפיס אותה בצורה מעגלית. לדוגמה, אם נתון המערך הבא: char matrix[4][3]= { {'1','2','3'} , {'4','5','6'} , {'7','8','9'} , {'a','b','c'}}; היא תדפיס: 1 2 3 6 9 c b a 7 4 5 8

  19. פתרון תרגיל 2 #include <stdio.h> #define UP 0 #define RIGHT 1 #define DOWN 2 #define LEFT 3 int main() { int dir; //direction intx,y; //posiotion intu,r,d,l; //limits: up, right, down, left int count; //just counts the cells that printed char arr[4][3]= { {'1','2','3'} , {'4','5','6'} , {'7','8','9'} , {'a','b','c'}}; //at first, direction set to be right dir=RIGHT; //we start at this corner x=0; y=0; //at first, limits are edges of array u=1; r=3-1; d=4-1; l=0;

  20. פתרון תרגיל 2 for(count=0;count<3*4;count++) { printf("%c ", arr[x][y]); switch(dir){ case UP: //move to direction x--; //if we are on the limit: move limit one step to center & change direction if(x==u) { u++; dir=(dir+1)%4; } break;

  21. פתרון תרגיל 2 case RIGHT: //move to direction y++; //if we are on the limit: move limit one step to center & change direction if(y==r) { r--; dir=(dir+1)%4; } break; case DOWN: //move to direction x++; //if we are on the limit: move limit one step to center & change direction if(x==d) { d--; dir=(dir+1)%4; } break;

  22. פתרון תרגיל 2 case LEFT: //move to direction y--; //if we are on the limit: move limit one step to center & change direction if(y==l) { l++; dir=(dir+1)%4; } break; } } return 0; }

  23. ASCII codes • הייצוג של תווים כ- char-ים הוא ע"י תווי ascii. • לדוגמא, ייצוג ascii של ‘a’ הוא 97, ועל כן (int) ‘a’ == 97. • כל האותיות באנגלית מופיעות באופן עוקב ב- ascii. • ערך ‘b’ הוא 98, ערך ‘c’ הוא 99 וכן הלאה. • נוכל לנצל תכונה זו על מנת לבצע השוואות ואריתמטיקה של תווים. • דוגמא: if (c >= ‘a’ && c <= ‘z’) printf(“%c is an alphabetic character\n”, c); • דוגמא שקולה: If (c – ‘a’ >= 0 && c – ‘z’ <= 0) printf(“%c is an alphabetic character\n”, c);

  24. ASCII Table

  25. תרגיל 4 - פולינדרום • פלינדרום הוא מילה שנקראת באופן זהה כאשר קוראים אותה מן הסוף להתחלה. • דוגמאות לפלינדרומים: • “a” • “aba” • “a man, a plan, a canal – panama” (בהתעלם מסימני פיסוק ורווחים) • צריך לממש את התוכנית הבאה: • קלט: מחרוזת מן המשתמש. • פלט: הודעה האם המחרוזת היא פלינדרום או לא.

  26. פתרון תרגיל 4 #include<stdio.h> #include<string.h> void main(){ int i,len=-1; char w1[256]; printf(“Enter String: ”); scanf(“%s”, w1); // Calc length while (w1[++len] != ‘\0’); for (i=0 ; i < len/2 && w1[i] == w1[len-i-1] ; i ++); if (i==len/2)printf("The word is a palindrome! \n"); elseprintf("The word isn't a palindrome! \n"); }

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

  28. פתרון תרגיל 5 #include<stdio.h> #define MAX_WORD_LEN 256 void main(){ int i; char w1[MAX_WORD_LEN], w2[MAX_WORD_LEN]; printf("Please enter first word:"); scanf(“%s”, w1); printf("Please enter second word:"); scanf(“%s”, w2); for (i=0 ; w2[i] && w1[i] == w2[i] ; i++); if (!w1[i] && !w2[i])printf("equal\n"); elseif (w1[i] > w2[i])printf("first bigger\n"); elseprintf("last bigger\n"); }

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

  30. פתרון תרגיל 6 #include<stdio.h> void main(){ int i,len; char w1[256]; printf("Please enter a sentence:\n"); scanf(“%s”, w1); for (i=0; w1[i] ; i++) if (!i || w1[i-1]==' ') if (w1[i] >='a' && w1[i]<='z') w1[i] += 'A' - 'a';//This is actually subtracting 32 from w1[i]. printf("%s\n",w1); }

  31. תרגיל 7 • צריך לממש את התוכנית הבאה: • קלט: מחרוזת שמייצגת משפט המכיל 5 מילים. • פלט: המילה הארוכה ביותר במשפט. • זכרו:גם מחרוזת היא מערך. כמו שיכולנו לעבוד על מערך באמצעות לולאות מקוננות, ניתן לבצע פעולה כזו גם על מחרוזות.

  32. פתרון תרגיל 7 #include<stdio.h> void main(){ int i=0,len,maxWordLoc, maxWordLen=0, curWordLen=0; char w1[256]; printf("Please enter a sentence consisting of 5 words:\n"); scanf(“%s”, w1); do{ if (w1[i] == ' ' || w1[i] =='\0'){ if (curWordLen>maxWordLen){ maxWordLen = curWordLen; maxWordLoc = i; } curWordLen = 0; }else curWordLen++; }while(w1[i++]);

  33. פתרון תרגיל 7 while (maxWordLoc && w1[maxWordLoc-1] !=' ') maxWordLoc--; while (w1[maxWordLoc] && w1[maxWordLoc]!=' ') putchar(w1[maxWordLoc++]); }

  34. #define BUFF_SIZE 256 • void main() • { • int i = -1, x = 0; • char s[BUFF_SIZE]; • printf(“Enter a string: ”); • gets(s); • while (s[++i] != '\0') • if (s[i] >= '0' && s[i] <= '9') • { • x *= 10; • x += s[i] - '0'; • } • i = -1; • while (s[++i] != '\0') • if (s[i] >= '0' && s[i] <= '9') • { • s[i] = x % 10 + '0'; • x /= 10; • } • puts(s); • } תרגיל 8: מעקב

More Related