Exercise 00: ft_putchar
• Write a function that displays the character passed as a parameter.
특정 character 변수를 출력하는 함수
저수준 입출력 write함수만 허용됨
unistd 헤더를 포함시킴
#include <unistd.h>
void ft_putchar(char c)
{
write(1, &c, 1);
}
Exercise 01: ft_print_alphabet
• Create a function that displays the alphabet in lowercase, on a single line, by ascending order, starting from the letter ’a’
알파벳을 a부터 z까지 출력하는 함수
#include <unistd.h>
void ft_print_alphabet(void)
{
char c;
c = 'a';
while (c <= 'z')
{
write(1, &c, 1);
c++;
}
}
Exercise 02: ft_print_reverse_alphabet
• Create a function that displays the alphabet in lowercase, on a single line, by descending order, starting from the letter ’z’
01번과 마찬가지, 하지만 역순으로 입력
#include <unistd.h>
void ft_print_reverse_alphabet(void)
{
char c;
c = 'z';
while (c >= 'a')
{
write(1, &c, 1);
c--;
}
}
Exercise 03: ft_print_reverse_alphabet
• Create a function that displays all digits, on a single line, by ascending order.
01, 02번과 마찬가지, 이번에는 숫자 0~9
void ft_print_numbers(void)
{
char c;
c = '0';
while (c <= '9')
{
write(1, &c, 1);
c++;
}
}
Exercise 04: ft_is_negative
• Create a function that displays ’N’ or ’P’ depending on the integer’s sign entered as a parameter. If n is negative, display ’N’. If n is positive or null, display ’P’.
입력받은 숫자가 0보다 작으면 N을 출력하고 그 외(0포함)에는 P를 출력하는 함수
#include <unistd.h>
void ft_is_negative(int n)
{
char neg;
char pos;
neg = 'N';
pos = 'P';
if (n < 0)
write(1, &neg, 1);
else
write(1, &pos, 1);
}
neg와 pos라는 변수를 할당해서 작성했는데, write함수에 대해 제대로 알고 난 뒤에 이렇게 할 필요가 없다는 것을 알게됨. write의 두번째 변수는 &를 붙인 것처럼 변수의 결과값이 아닌 주소값을 넣어야 함.
write(1, 'N', 1) 라고 작성했었는데 당연히 오류...
wirte(1, "N', 1) 라고 작성하면 정상적으로 출력
" "쌍따옴표로 묶인 것은 string
string은 char * 즉 character 배열 첫번째의 주솟값임
포인터 공부 후에 깨닫게 됨.
Exercise 05: ft_print_comb
• Create a function that displays all different combinations of three different digits in ascending order, listed by ascending order - yes, repetition is voluntary.
0~9까지 숫자의 3가지 조합을 출력하는 프로그램 3가지 숫자의 조합도 오름차순, 그리고 그 조합 모두 또한 오름차순
ex) 012, 013, 014, 015, 016, 017, 018, 019, 023, ..., 789
#include <unistd.h>
void ft_print_comb(void)
{
char num[3];
char sep[2];
num[0] = '0';
sep[0] = ',';
sep[1] = ' ';
while (num[0] <= '7')
{
num[1] = num[0] + 1;
while (num[1] <= '8')
{
num[2] = num[1] + 1;
while (num[2] <= '9')
{
write(1, &num, 3);
if (num[0] != '7')
write(1, &sep, 2);
num[2]++;
}
num[1]++;
}
num[0]++;
}
}
단순히 반복문 3번 돌림
num : 숫자 세개가 들어갈 배열
sep : 출력 시 결과값을 구분해줄 쉼표와 띄어쓰기가 들어간 배열
마지막에는 sep가 출력되면 안되는데 678, 679, 689, 789 로 끝나기 때문에 첫번째 숫자가 7만 아니면 구분자 출력.
Exercise 06: ft_print_comb2
• Create a function that displays all different combination of two two digits numbers (XX XX) between 00 and 99, listed by ascending order.
05번과 비슷하지만 두자리 숫자 두개의 조합을 오름차순으로 출력
ex) 00 01, 00 02, 00 03, 00 04, 00 05, ..., 00 99, 01 02, ..., 97 99, 98 99
#include <unistd.h>
void ft_print_comb2(void)
{
int num1;
int num2;
char print[5];
char sep[2];
num1 = 0;
print[2] = ' ';
sep[0] = ',';
sep[1] = ' ';
while (num1 <= 98)
{
num2 = num1 + 1;
while (num2 <= 99)
{
print[0] = '0' + num1 / 10;
print[1] = '0' + num1 % 10;
print[3] = '0' + num2 / 10;
print[4] = '0' + num2 % 10;
write(1, &print, 5);
if (num1 != 98)
write(1, &sep, 2);
num2++;
}
num1++;
}
}
두자리 숫자 두개라서 character로 대소 비교하기보다는 그냥 int로 비교하기로 함. 그 후에 그 int를 10으로 나눈 몫, 나머지로 하나씩 출력
print : 앞 숫자 두개, 띄어쓰기, 뒷 숫자 두개
총 길이 5의 배열 선언
Exercise 07: ft_putnbr
• Create a function that displays the number entered as a parameter. The function has to be able to display all possible values within an int type variable.
숫자를 입력하면 그 숫자 그대로 출력. 06번의 10으로 나눈 몫, 나머지를 이용했음. 근데 음수 나머지에 대한 의문?
수학에서 n을 p로 나눈 몫 q와 나머지 r을 정의할때 나머지 r은 0보다 크고 p보다 작은 숫자, 즉 양수이다. 즉 -357을 10으로 나누면 몫은 -36 나머지는 3이다.
하지만 C에서는 몫-35와 나머지-7로 나온다. 오히려 좋아...
void ft_putnbr(int nb)
{
char arr[10];
int len;
int num;
len = 0;
if (nb < 0)
write(1, "-", 1);
if (nb == 0)
write(1, "0", 1);
while (nb != 0)
{
num = nb % 10;
if (num < 0)
num *= (-1);
arr[len++] = '0' + num;
nb /= 10;
}
while (len > 0)
{
write(1, &arr[--len], 1);
}
}
주어진 숫자가 음수인 경우 먼저 -기호를 먼저 출력하고 시작
그 후 나머지를 계속 배열 arr에 저장 (음수인 경우 양수로 바꿔서) 주어진 숫자가 0이 될 때 까지 반복. 그런데 이렇게 할 경우 주어진 숫자가 0일 경우 출력이 안되기 때문에 먼저 0인 경우 0을 출력.
Exercise 08: ft_print_combn
• Create a function that displays all different combinations of n numbers by ascending order.
앞서 푼 05번의 일반화 유형. 05번에서는 3개의 숫자 조합이기 때문에 단순히 반복문을 3번 돌렸지만, 주어진 n에 대해서 조합을 출력해야하기 때문에 재귀를 이용해야 함.
#include <unistd.h>
void recurse(int n, int depth, char *result)
{
char sep[2];
int num;
sep[0] = ',';
sep[1] = ' ';
num = result[depth - 1] + 1;
if (depth == n)
{
write(1, result, n);
if (result[0] != 10 - n + '0')
write(1, &sep, 2);
}
else
{
while (num <= '9')
{
result[depth] = num;
recurse(n, depth + 1, result);
num++;
}
}
}
void ft_print_combn(int n)
{
char arr[10];
int i;
i = 0;
while (i <= 10 - n)
{
arr[0] = '0' + i;
recurse(n, 1, arr);
i++;
}
}
재귀함수 recurse함수 선언
각 매개변수의 의미
먼저 현재 depth에 이 전 depth에 들어간 숫자보다 하나 큰 숫자를 선언(num 변수). depth가 n과 같다면 숫자가 다 채워졌으니 출력. 그렇지 않으면 num이 9가 될 때 까지 result에 채워넣고 depth를 1 증가시켜서 recurse함수 다시 호출(재귀)
-> numdmf 9까지 돌리지 않고, 10 - depth로 했으면 효율성을 더 높일 수 있었겠음...
좋은 글 감사합니다. 자주 올게요 :)