C01

김원호·2023년 7월 23일

42seoul

목록 보기
4/10

Exercise 00 : ft_ft
• Create a function that takes a pointer to int as a parameter, and sets the value "42" to that int.

포인터의 첫 등장.
포인터를 입력 받으면 그 포인터가 가리키는 값에 42를 넣는 문제.

void	ft_ft(int *nbr)
{
	int	num;

	num = 42;
	*nbr = num;
}

Exercise 01 : ft_ultimate_ft
• • Create a function that takes a pointer to pointer to pointer to pointer to pointer to pointer to pointer to pointer to pointer to int as a parameter and sets the value "42" to that int.

00번에 이어서 다중포인터로 할당하는 문제.
어이없게 오래걸렸는데 그냥 한번에 포인터를 할당하면 됐음...
그래도 오히려 그래서 더 포인터 공부 많이 할 수 있었음.

void	ft_ultimate_ft(int *********nbr)
{
	int	num;

	num = 42;
	*********nbr = 42;
}

Exercise 02 : ft_swap
• Create a function that swaps the value of two integers whose addresses are enteredas parameters.

두 포인터가 주어지면 해당 포인터가 가리키는 두 숫자를 바꿈.

void	ft_swap(int *a, int*b)
{
	int	temp;

	temp = *a;
	*a = *b;
	*b = temp;
}

Exercise 03 : ft_div_mod

두 숫자가 주어지면 div와 mod에 각각 몫과 나머지를 할당하는 문제.

void	ft_div_mod(int a, int b, int *div, int *mod)
{
	int	p;
	int	q;

	p = a / b;
	q = a % b;
	*div = p;
	*mod = q;
}

Exercise 04 : ft_ultimate_div_mod

04번과 동일한데 그 결과를 각각 a와 b에 직접 할당.

void	ft_ultimate_div_mod(int *a, int *b)
{
	int	p;
	int	q;
	int	div;
	int	mod;

	p = *a;
	q = *b;
	div = p / q;
	mod = p % q;
	*a = div;
	*b = mod;
}

Exercise 05 : ft_putstr
• Create a function that displays a string of characters on the standard output.

문자열이 주어지면 그 문자열을 출력하는 함수.

#include <unistd.h>

void	ft_putstr(char *str)
{
	int	i;

	i = 0;
	while (str[i] != '\0')
	{
		write(1, &str[i], 1);
		i++;
	}
}

문자열의 끝을 의믜하는 null(\0)이 나올때 까지 출력.

Exercise 06 : ft_strlen
• Create a function that counts and returns the number of characters in a string.

문자열이 주어지면 해당 문자열의 길이를 리턴하는 함수.

int	ft_strlen(char *str)
{
	int	count;

	count = 0;
	while (*str != '\0')
	{
		count++;
		str++;
	}
	return (count);
}

05번과 마찬가지로 문자열의 끝이 나올때 까지 count 증가.

Exercise 07 : ft_rev_int_tab
• Create a function which reverses a given array of integer (first goes last, etc).

배열과 그 크기가 주어지면 그 배열을 거꾸로 뒤집는 함수.

void	ft_rev_int_tab(int *tab, int size)
{
	int	temp;
	int	i;

	i = 0;
	while (i < size / 2)
	{
		temp = tab[i];
		tab[i] = tab[size - 1 - i];
		tab[size - 1 - i] = temp;
		i++;
	}
}

배열의 길이의 절반까지 loop를 돌면서 앞 뒤를 바꿔줌

Exercise 08 : ft_sort_int_tab
• Create a function which sorts an array of integers by ascending order.

배열이 주어지면 그 배열을 정렬하여주는 함수.

void	bubble_sort(int *arr, int len)
{
	int	i;
	int	j;
	int	temp;

	i = 0;
	while (i < len - 1)
	{
		j = 0;
		while (j < len - i - 1)
		{
			if (arr[j] > arr[j + 1])
			{
				temp = arr[j + 1];
				arr[j + 1] = arr[j];
				arr[j] = temp;
			}
			j++;
		}
		i++;
	}
}

void	ft_sort_int_tab(int *tab, int size)
{
	bubble_sort(tab, size);
}

가장 구현하기 간단한 bubble sort이용.

0개의 댓글