7-1. swap함수!!

2013. 4. 8. 11:08프로그래밍/C언어 연습문제 및 풀이




#include <stdio.h>

void swap(unsigned char *Px,unsigned char *Py);

int main()

{

unsigned char arr[]="Rotation";

unsigned char *arrP = arr;

int iCnt;

int jCnt;

int isize;

int y;

isize = sizeof(arr)/sizeof(arr[0]);

y = isize;

for(iCnt=0; iCnt < isize-1; ++iCnt)

{

printf("%d\n",iCnt);

if(y==isize)

{

swap(arrP,arrP+y-1);

for( jCnt = 1; jCnt < isize; ++jCnt)

{

printf("%c",*(arr+jCnt));

}

y=y-1;

putchar('\n');

continue;

}

else

{

swap(arrP+y-1,arrP+y);

for(jCnt = 1; jCnt < isize; ++jCnt)

{

printf("%c",*(arr+jCnt));

}

y=y-1;

putchar('\n');

}

}

return 0;

}


void swap(unsigned char *Px,unsigned char *Py)

{

int temp = *Px;

*Px = *Py;

*Py = temp;

}




<소스 최적화> - swap함수를 쓰지 않고

#include <stdio.h>

int main()
{
  int i;  
  int  j;     
  char str[9="Rotation";  // 배열 초기화
  char ch;               // 배열 0번 저장 변수


  for(i = 0; i<9; i++)
  {
    printf("%s\n",str);    // 출력
    ch = str[0];      // 배열 0번 R, ch에 저장

    for(j = 0; j< 8; j++)  // 배열 인덱스 0~ 7까지 한칸씩 초기화
    {
      str[j] = str[j+1];
    }
    str[7= ch;      // 8번째 배열 자리가 빈다. 그러므로 그 자리에 
            //처음에 ch에 저장해 둔 str[0]값을 넣는다.
            // 그러면 otationR이 관성되고, 다름 for문이 실행.
  }

  return 0;
}