שפת C/מערכים/תרגילים: הבדלים בין גרסאות בדף

תוכן שנמחק תוכן שנוסף
שחזור מהשחתה
←‏3: הוספת תרגיל נחמד
שורה 87:
printf("The sum of the diagonal is: %d\n",sum);
return 0;
}
</pre>
</div>
}}
 
 
 
== 4 ==
כתבו תוכנית שנתון לה מערך בגודל מסוים (HEIGHT על WIDTH), ועליכם להדפיס אותו בצורה מעגלית. לדוגמה, אם נתון המערך הבא:
<pre style="text-align:left; direction:ltr;">
#define WIDTH 3
#define HEIGHT 4
char arr[HEIGHT][WIDTH]=
{ {'1','2','3'} , {'4','5','6'} , {'7','8','9'} , {'a','b','c'}};
</pre>
שנראה כך:
{| class="wikitable" dir="ltr"
|-
| 1 || 2 || 3
|-
| 4 || 5 || 6
|-
| 7 || 8 || 9
|-
| a || b || c
|}
היא תדפיס:
<pre style="text-align:left; direction:ltr;">
1 2 3 6 9 c b a 7 4 5 8
</pre>
 
{{מוסתר|פתרון|2=
<div style="text-align:left; direction:ltr;">
<pre>
#include <stdio.h>
 
#define WIDTH 3
#define HEIGHT 4
 
#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[HEIGHT][WIDTH]=
{ {'1','2','3'} , {'4','5','6'} , {'7','8','9'} , {'a','b','c'}};
 
//filling_this_array(arr,HEIGHT,WIDTH);
 
 
//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=WIDTH-1;
d=HEIGHT-1;
l=0;
 
for(count=0;count<WIDTH*HEIGHT;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;
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;
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;
}
</pre>