תרגול בנושא

‫תרגול ‪ – 4‬מערכים‪ ,‬מערכים דו מימדיים‪ ,‬ומחרוזות‬
‫מערכים חד‪-‬מימדיים‪:‬‬
‫הסבר קצר על מערכים‪:‬‬
‫‪ ‬חזרה ‪ -‬מהו משתנה ?‬
‫‪ ‬מערך – קבוצה של משתנים אשר הגישה אל כל משתנה בה מתבצעת באמצעות‬
‫שם הקבוצה ומיקום המשתנה בקבוצה‪.‬‬
‫‪ ‬מוטיבציה‪ :‬פעולות חוזרות על מספר רב של משתנים בעלי תפקיד דומה‪.‬‬
‫‪ ‬הגדרת מערך ‪:‬‬
‫;]‪int ids[7‬‬
‫;]‪char name[12‬‬
‫;}‪int arr[] = {1,2,45,6‬‬
‫‪ ‬הכנסת ערך למשתנה במערך(כתיבה)‪:‬‬
‫;'‪name[3] = 'm‬‬
‫‪ ‬קריאת ערך ‪:‬‬
‫;]‪x = arr[3] + arr[5‬‬
‫;)]‪printf("%c %d",name[2],ids[0‬‬
‫(בקיצור כמו משתנים רגילים)‬
‫תרגילים על מערכים חד‪-‬מימדיים‪:‬‬
‫‪ .1‬כתוב תוכנית אשר קולטת ‪ 5‬מספרים שלמים מהמשתמש‪ ,‬ומדפיסה את האיבר‬
‫המינימאלי‪ ,‬המקסימאלי ואת סכום האיברים של המערך‪ .‬ניתן לבצע זאת ב‪ online-‬אך‬
‫נרצה לממש בעזרת מערך‪ .‬בצעו כל חלק בנפרד (קליטה‪ ,‬מינ'‪,‬מקס'‪,‬סכום) ולפני שאתם‬
‫פותרים כל חלק‪ ,‬קחו קצת זמן לחשוב על האלגוריתם עבורו (הסגרו על האלגוריתם ורק‬
‫א"כ תכתבו את הקוד)‪.‬‬
‫‪1‬‬
:‫תשובה‬
#include <stdio.h>
#define NUMBER_OF_ELEMENTS 5
void main()
{
int arr[NUMBER_OF_ELEMENTS];
int i,min,max,sum;
/* Read the input numbers */
printf("Insert %d numbers\n",NUMBER_OF_ELEMENTS);
for(i=0; i<NUMBER_OF_ELEMENTS; i++)
{
printf("%d : ", i+1);
scanf("%d",&arr[i]);
}
/* Calculate the min, max and sum of the numbers: */
for(i=sum=0,min=max=arr[0];i<NUMBER_OF_ELEMENTS;i++)
{
if(min > arr[i])
min=arr[i];
if(max < arr[i])
max=arr[i];
sum+=arr[i];
}
printf("Minimum= %d , Maximum= %d , Sum= %d\n",min,max,sum);
}
‫ נתונות שתי רשימות של מספרי זהות של סטודנטים עבור‬:‫ מציאת מספרים משותפים‬.2
‫ כתבו‬.‫ רוצים למצוא אם קיים סטודנט תחמן הרשום בשתי המחלקות‬.‫שתי מחלקות‬
‫ של‬.‫ז‬.‫תוכנית המאתחלת שני מערכים עם תוכן הרשימות ואשר כותבת למסך את מס' ת‬
.‫כל הסטודנטים התחמנים‬
).‫ ואח"כ כתבו את הקוד‬, ‫(שוב – קחו זמן לחשוב על אלגוריתם‬
:‫תשובה‬
void main()
{
int arr1[]={12,15,5,88,234,567};
int arr2[]={66,4,567,5,88,2563,33,55};
int i,j,len1,len2;
len1 = sizeof(arr1)/sizeof(int);
len2 = sizeof(arr2)/sizeof(int);
for(i=0;i<len1;i++)
for(j=0;j<len2;j++)
if(arr1[i]==arr2[j])
printf("Common ID Found: %d\n",arr1[i]);
}
2
:‫מימדיים‬-‫מערכים דו‬
:‫דוגמה‬
‫ (ללא‬matr ‫ממדי של תווים‬-‫ במערך הדו‬word ‫חפשו את כל המופעים של המילה הנתונה‬
!‫ המילה יכולה ליהיות מאוזנת או מאנכת‬.)‫שימוש בפונקציות ספריה‬
:‫פתרון‬
#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;
// 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.
{
for(k=j, l=0; l<WORDSIZE && matr[i][k]==word[l]; k++, l++);//Scan the word
// if it is there.
if(l==WORDSIZE) //Check if the whole word was
//encountered.
printf("The word was found horizontally!!! Its coordinates are: x1=%d,
y1=%d, x2=%d, y2=%d\n", i, k-WORDSIZE,i,k-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);
}
}
/******************
OUTPUT:
***************************************
The word was found horizontally!!! Its coordinates are: x1=3, y1=0, x2=3, y2=2
The word was found vertically!!! Its coordinates are: x1=0, y1=0, x2=2, y2=0
************************************************************************/
3
:‫מחרוזות‬
:‫הסבר קצר על מחרוזות‬
. '\0' – ‫ים אשר מסתיימת בתו המיוחד‬-char ‫ היא למעשה מערך של‬C-‫ מחרוזת ב‬
.‫ המחרוזת לא חייבת לתפוס את כל המערך‬
‫ על מנת שלא נהיה צריכים לשלוח לפונקציה את אורך‬,‫\' הוא למעשה מוסכמה‬0' 
‫ היתה צריכה לקבל בנוסף את‬,'\0' -‫ לולא ה‬,strcpy() ‫המחרוזת (למשל הפונקציה‬
.)‫אורך המחרוזת‬
‫זהו מערך של תווים‬
‫עדיין‬
‫עדיין‬
‫עדיין‬
:‫עכשיו אפשר גם להגיד שזה מערך של תווים וגם להגיד שזו מחרוזת‬
char word[10];
word[0] = ‘A’;
word[1] = ‘b’;
word[2] = ‘a’;
word[3] = ‘\0’;
A
b
a
\0
D
F
s
z
a
E
‫ אפשר לעשות אותה פעולה ע"י‬
char word[10] = “Aba”;
. ‫\' בסוף‬0'-‫המהדר מסיק שמדובר במחרוזת ומוסיף אוטומטית את ה‬
:)<string.h>( strlen ,strcmp ,strcpy ‫מעבר קצר על‬

1) strcmp():
int strcmp(const char *s1, const char *s2);
The function compares successive elements from two strings, s1 and s2,
until it finds elements that are not equal.



If all elements are equal, the function returns zero.
If the differing element from s1 is greater than the element from s2
(both taken as unsigned char), the function returns a positive number.
Otherwise, the function returns a negative number.
2) strlen():
size_t strlen(const char *s);
The function returns the number of characters in the string s, not including
its terminating null character.
3) strcpy():
char *strcpy(char *s1, const char *s2);
The function copies the string s2, including its terminating null character, to
successive elements of the array of char whose first element has the
address s1. It returns s1.
4
:‫תרגילים על מחרוזות‬
‫ מצוא אותיות שמופיעות במילה‬,‫ שבהנתן מילה אשר נקלטה מהמשתמש‬,‫לפניכם אלגוריתם‬
:‫ ומדפיס אותן למסך‬,‫יותר מפעם אחת‬
‫ בתחום‬i ‫עבור על כל אינדקס‬
‫ בתחום‬j ‫עבור על כל אידקס‬
W[i] ‫ הדפס את‬W[i] = = W[j] ‫אם‬
? “abc” ‫ מה יודפס בהתקבל המילה‬:‫שאלה‬
. i!=j -‫ האלגוריתם מוטעה וע"מ לתקנו יש להוסיף לתנאי ש‬. “abc” :‫תשובה‬
.'‫תקנו את האלג‬
? “koshka” ‫ מה יודפס בהתקבל המילה‬:‫שאלה‬
. “kk” :‫תשובה‬
‫ בסוף התוכנית יש‬,‫ אם לא נמצאו אותיות חוזרות‬.C-‫ממשו את האלג' כתוכנית ב‬
.‫להדפיס למסך הודעה מתאימה‬
:‫תשובה‬
#include <stdio.h>
#define MAX_WORD_LEN 256
void main()
{
char inWord[MAX_WORD_LEN];
char alphabet[26]={0};//From 97 for 'a' character to 122 for 'z' character!
int i,j,found=0;
printf("Insert your word in lowercase letters(%d chars
max):",MAX_WORD_LEN);
gets(inWord) ;// The gets function reads a line from the standard input stream
//stdin and stores it in inWord. The line consists of all
//characters up to and including the first newline character
//('\n'). gets then replaces the newline character with a null
//character ('\0') before returning the line.
for(i=0;inWord[i]!='\0';i++)//Run over all the letters of the word:
alphabet[inWord[i]-'a']++; //inWord[i] contains the ascii value of the
//current letter in the word. Subtracting 'a' (which is the ascii value of
//the letter a) from this value will give the position of the current letter
//in the array alphabet[]. We incremet the element of alphabet[] at this
//position so that eventually, alphabet[] will store the number of
//occurences of each letter in the word.
5
for(i=0;i<26;i++)//Run over all the elements in alphabet[]:
for(j=0;alphabet[i]>1&&j<alphabet[i];j++)//Print every letter that
//occurred more than once (i.e., every letter for which the
//corresponding element in alphabet[] contains a number larger than 1),
//as many times as it reoccured:
{
printf("%c",i+'a'); //Print the reoccuring letter as a character (not its
//ascii value!!!) using "%c".
found++;//Update the flag that says we found reoccurring letters.
}
if(!found)
printf("Didn't find any double letters!\n");
}
‫ כתוב תוכנית אשר קולטת מן המשתמש מילה ומדפיסה על המסך הודעה אם המילה‬.1
‫ פלינדרום היא מילה שניתן לקרא אותה באופן זהה מימין לשמאל ומשמאל‬.‫פלינדרום או לא‬
. aba, c, abbaabba :‫ המילים הבאות הן פלינדרומים‬,‫ למשל‬.‫לימין‬
:‫תשובה‬
#include <stdio.h>
#include <string.h>
void main()
{
int i,len;
char w1[256];
printf("Please enter a word no longer than 256 characters:\n");
gets(w1);
len=strlen(w1);//Get the length of the input string.
for (i=0 ; i < len/2 && w1[i] == w1[len-i-1] ; i ++);
if (i==len/2)
printf("The word is a palindrome! \n");
else
printf("The word isn't a palindrome! \n");
}
****!!!‫ יתר השאלות לתרגול בבית‬- ‫ אם לא נשאר מספיק זמן‬:‫*****הערה‬
6
(Magic square) ‫קסם‬-‫ בניית ריבוע‬:‫מימדיים‬-‫דוגמה נוספת לשימוש במערכים דו‬
‫ לפי ההגדרה‬,‫ כריבוע קסם‬5x5 ‫מימדי בגודל‬-‫כתבו תוכנית הממלאת ומדפיסה מערך דו‬
:‫והאלג' הבאים‬
A “Magic square” is a double array of numbers consisting
of the distinct positive integers 1, 2, ...,n arranged such that
the sum of the numbers in any horizontal, vertical, or main
diagonal line is always the same number known as the
magic constant M2(n):
Here is a method to fill a “Magic square” of odd dimensions
n x n:
For odd n, a very straightforward technique known as
the Siamese method can be used, as illustrated on the left.
It begins by placing a 1 in any location (in the center
square of the top row in the above example), then
incrementally placing subsequent numbers in the square
one unit above and to the right. The counting is wrapped
around, so that falling off the top returns on the bottom
and falling off the right returns on the left. When a
square is encountered that is already filled, the next
number is instead placed below the previous one and the
method continues as before.
:‫פתרון‬
#include <stdio.h>
#define N 5
void main()
{
int magic[N][N]={0}, i, j, count;
for(count=1,i=0,j=N/2;count<=N*N; count++)
{
if(i<0) i+=N; //Falling off the top returns us to the bottom.
if(j==N) j-=N; //Falling off the right returns us to the left.
while(magic[i][j]) //When encountering a square that is already filled:
{
i++;
j--;
if(i==N) i-=N; //Falling off the bottom returns us to the top.
if(j<0) j+=N; //Falling off the left returns us to the right.
i++;
if(i==N) i-=N;
}/* while */
magic[i--][j++]=count;
}/* for */
7
for(i=0; i<N; i++)//Print the magic square onto the screen:
{
for(j=0;j<N;j++)
printf("%4d",magic[i][j]);
putchar('\n');
}
}
:‫דוגמאות נוספות לעבודה עם מחרוזות‬
‫ התוכנית אומרת לו איזו מבין שתיהן גדולה יותר‬,‫ המשתמש כותב שתי מילים‬.1
!‫ צריך להסביר מהו יחס לקסיקוגרפי‬.)strcmp-‫לקסיקוגרפית (ללא שימוש ב‬
‫ עוצרים‬,‫\' במחרוזת הראשונה‬0' ‫ עוברים אות אות וברגע שיש חוסר שוויון או‬:'‫אלג‬
.‫ובודקים עבור המקום שהגענו אליו באיזה מהמחרוזות יש תו גדול יותר‬
:‫תשובה‬
#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:");
gets(w1);
printf("Please enter second word:");
gets(w2);
for (i=0 ; w2[i] && w1[i] == w2[i] ; i++);
if (!w1[i] && !w2[i])
printf("equal\n");
else if (w1[i] > w2[i])
printf("first bigger\n");
else
printf("last bigger\n");
}
8
‫ המשתמש מכניס משפט ואנו עוברים ומשנים כל אות ראשונה בכל מילה לאות גדולה‬.2
.)‫ לא נוגעים בה‬-‫(אם היא כבר גדולה‬
:‫תשובה‬
#include <stdio.h>
void main()
{
int i,len;
char w1[256];
printf("Please enter a sentence:\n");
gets(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);
}
‫ התוכנית מדפיסה על המסך את המילה הארוכה‬,‫ מילים‬5 ‫ המשתמש כותב משפט בן‬.3
.strlen ,strcmp ,strcpy ‫ אין להשתמש בפונקציות‬.‫ביותר במשפט‬
:‫תשובה‬
#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");
gets(w1);
do{
if (w1[i] == ' ' || w1[i] =='\0')//If we are at the end
//of the last word or at the end of the sentence:
{
if (curWordLen>maxWordLen)
{
maxWordLen = curWordLen;
maxWordLoc = i;
}
curWordLen = 0;
}else
curWordLen++;
}while(w1[i++]);
while (maxWordLoc && w1[maxWordLoc-1] !=' ')
maxWordLoc--;
while (w1[maxWordLoc] && w1[maxWordLoc]!=' ')
putchar(w1[maxWordLoc++]);
}
9
strlen ,strcmp
‫ אלא שכעת מותר להשתמש בפונקציות‬,‫ כמו השאלה הקודמת‬.4
.‫ תווים‬256 ‫ ידוע כי המילים מוגבלות בגודלן ע"י‬. ,strcpy
:‫תשובה‬
#include <stdio.h>
void main()
{
int i=0,len,maxWordLoc;
int maxWordLen=0;
int curWordLen=0;
char longest[256]="",w1[256];
printf("Please enter a sentence consisting of 5 words:\n");
for (i=0 ; i<5 ; i++)
{
scanf("%s",w1);
if (strlen(w1) > strlen(longest))
strcpy(longest,w1);
}
printf("%s\n",longest);
}
!!!‫בהצלחה‬
10