34
1 Introduction to Programming in C ללללל4 14.08.2011

Introduction to Programming in C

  • Upload
    zev

  • View
    47

  • Download
    6

Embed Size (px)

DESCRIPTION

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; - PowerPoint PPT Presentation

Citation preview

Page 1: Introduction to  Programming in C

11

Introduction to Programming in C

4תרגול

14.08.2011

Page 2: Introduction to  Programming in C

מטרת התרגול

מערכים•מחרוזות•

2 Introduction to Programming in C - Fall 2010 – Erez Sharvit, Amir Menczel

Page 3: Introduction to  Programming in C

מערכים

עם שלושה תאים: הגדרת מערך•

int nums[3];פנייה לתא במערך ע"י האינדקס של התא:•

nums[0]=1;nums[1]=3;nums[2]=nums[1]+nums[0];

C Programming Intoduction - Fall 2011 - Erez Sharvit, Amir Menczel

3

Page 4: Introduction to  Programming in C

דוגמא: מערך של מספרים

מספרים 20התוכנית הבאה )עמוד הבא( קולטת סדרה של •שלמים לתוך מערך ומחשבת את הממוצע שלהם

4 Introduction to Programming in C - Fall 2010 – Erez Sharvit, Amir Menczel

Page 5: Introduction to  Programming in C

C Programming Intoduction - Fall 2011 - 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(;}

Page 6: Introduction to  Programming in C

: אורך מחרוזת2דוגמא התוכנית הבאה קולטת מחרוזת ומדפיסה את אורכה•

6 Introduction to Programming in C - Fall 2010 – Erez Sharvit, Amir Menczel

#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(;}

Page 7: Introduction to  Programming in C

: השוואת מחרוזות1תרגיל כתבו תוכנית אשר קולטת שתי מחרוזות ובודקת אם הן שוות•

7 Introduction to Programming in C - Fall 2010 – Erez Sharvit, Amir Menczel

Page 8: Introduction to  Programming in C

C Programming Intoduction - Fall 2011 - 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”(;}

Page 9: Introduction to  Programming in C

: הפיכת מחרוזת2תרגיל כתבו תוכנית אשר קולטת מחרוזת והופכת אותה•

9 Introduction to Programming in C - Fall 2010 – Erez Sharvit, Amir Menczel

Page 10: Introduction to  Programming in C

C Programming Intoduction - Fall 2011 - 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 stringfor )right--; left < right; left++, right--({ char temp;

// Swap current left & right elementstemp = s[left];s[left] = s[right];s[right] = temp;

}

Page 11: Introduction to  Programming in C

מיון בועות מספרים LENכתבו תוכנית אשר קולטת מערך של עד •

. באופן הבא:מיון בועותוממיינת אותו בעזרת

–Nums קלוט LENמספרים –i LEN - 1, בצע:i > 1 כל עוד–

)1j 0 , בצע:j < iכל עוד 2(

אז: Nums[J] > Nums[J+1]אם 1( Num[j] Num[j+1]החלף

–j j + 1

)3i i - 1

11

Page 12: Introduction to  Programming in C

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 sortfor )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 arrayfor )i = 0; i < len; i++(

printf)“%d, “, a[i](;

Page 13: Introduction to  Programming in C

צריך לממש את התוכנית הבאה:•(, ומילה charsקלט: מערך דו-ממדי המכיל תווים )–

המורכבת מתווים אשר אורכה קצר משני ממדי המערך.

, אין צורך לקלוט אותו ממשתמש.(Hardcoded)הקלט נתון •פלט: הדפסת כל המופעים של המילה במערך –

הדו-ממדי, כאשר המילה יכולה להופיע בשורה (horizontally) או בעמודה (vertically)

חלוקת עבודה לשלבים:•נבין כיצד למצוא את כל המופעים בשורות.–נבין כיצד למצוא את כל המופעים בעמודות.–

האם יש דמיון למציאה עבור שורות.•

- מערכים 1תרגיל דו-ממדיים

Page 14: Introduction to  Programming in C

#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;

1 פתרון תרגיל

Page 15: Introduction to  Programming in C

// 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(;

}

- שורות1 פתרון תרגיל

Page 16: Introduction to  Programming in C

//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(; } }

- עמודות1 פתרון תרגיל

Page 17: Introduction to  Programming in C

- פלט1 פתרון תרגיל

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

•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

Page 18: Introduction to  Programming in C

2תרגיל

הדפסת ערכי מטריצה )מערך דו-מימדי( בצורה מעגלית(, ועליה 3 על 4כתבו תוכנית שנתונה לה מטריצה בגודל מסוים )

להדפיס אותה בצורה מעגלית. לדוגמה, אם נתון המערך הבא: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

1 2 3

4 5 6

7 8 9

‘a’ ‘b’ ‘c’

Page 19: Introduction to  Programming in C

2פתרון תרגיל #include <stdio.h> #define UP 0 #define RIGHT 1 #define DOWN 2 #define LEFT 3 int main)( {

int dir; //direction int x,y; //posiotion int u,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;

19

Page 20: Introduction to  Programming in C

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;

Page 21: Introduction to  Programming in C

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;

21

Page 22: Introduction to  Programming in C

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;}

22

Page 23: Introduction to  Programming in C

. ascii-ים הוא ע"י תווי charהייצוג של תווים כ- •.a’ == 97( ‘int), ועל כן 97 הוא ’a‘ של asciiלדוגמא, ייצוג –

.asciiכל האותיות באנגלית מופיעות באופן עוקב ב- • וכן הלאה.99 הוא ’c‘, ערך 98 הוא ’b‘ערך –

נוכל לנצל תכונה זו על מנת לבצע השוואות ואריתמטיקה של •תווים.

דוגמא:•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(;

ASCII codes

Page 24: Introduction to  Programming in C

ASCII Table

Page 25: Introduction to  Programming in C

פלינדרום הוא מילה שנקראת באופן זהה כאשר •קוראים אותה מן הסוף להתחלה.

דוגמאות לפלינדרומים:•–“a” –“aba”–“a man, a plan, a canal – panama” בהתעלם מסימני(

פיסוק ורווחים(

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

- פולינדרום4תרגיל

Page 26: Introduction to  Programming in C

#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"(; else printf)"The word isn't a palindrome! \n"(;}

4פתרון תרגיל

Page 27: Introduction to  Programming in C

השוואה לקסיקוגרפית )מילונית( היא כזו •שמשווה מילים לפי סדר הופעתם במילון.

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

לקסיקוגרפית.

– השוואה לקסיקוגרפית5תרגיל

Page 28: Introduction to  Programming in C

#include <stdio.h>#define MAX_WORD_LEN 256void 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"(; else if )w1[i] > w2[i]( printf)"first bigger\n"(; else printf)"last bigger\n"(;}

5פתרון תרגיל

Page 29: Introduction to  Programming in C

צריך לממש את התוכנית הבאה:•קלט: מחרוזת שמייצגת משפט.–אותה מחרוזת, כאשר כל מילה מתחילה באות פלט:–

גדולה.

זכרו- ניתן לנצל את התכונות האריתמטיות של •התווים. ההפרש בין כל אות גדולה ואות קטנה

הוא קבוע.asciiבקוד

6תרגיל

Page 30: Introduction to  Programming in C

#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(;}

6פתרון תרגיל

Page 31: Introduction to  Programming in C

צריך לממש את התוכנית הבאה:• מילים.5 מחרוזת שמייצגת משפט המכיל קלט:–פלט: המילה הארוכה ביותר במשפט.–

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

פעולה כזו גם על מחרוזות.

7תרגיל

Page 32: Introduction to  Programming in C

#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++](;

7פתרון תרגיל

Page 33: Introduction to  Programming in C

while )maxWordLoc && w1[maxWordLoc-1] !=' '( maxWordLoc--;

while )w1[maxWordLoc] && w1[maxWordLoc]!=' '( putchar)w1[maxWordLoc++](;

}

7פתרון תרגיל

Page 34: Introduction to  Programming in C

: מעקב8תרגיל #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(;}