강좌 : 부스트캠프 모두를 위한 컴퓨터과학(cs50 2019)
// 주어진 배열에서 숫자를 찾을때
#include<cs50.h>
#include<stdio.h>
int main(void)
{
int numbers[] = {4,7,9,34,54,40}; // 배열 정의 및 값 입력
for (int i=0;i<sizeof(numbers);i++) // 배열의 크기만큼 반복
{
if(numbers[i]==50)
{
printf("Found\n");
return 0;
}
}
printf("Not found\n");
return 1;
}
// 주어진 배열에서 문자열을 찾을때
#include<cs50.h>
#include<stdio.h>
#include<string.h>
int main(void)
{
string names[]={"홍길동", "김철수","김영희","임꺽정"};
string numbers[]={"123-456","123-457","123-458","123-459"};
for (int i=0;i<sizeof(numbers);i++)
{
if(strcmp(names[i],"홍길동")==0) // strcmp : 두 문자열이 같다면 0을 반환
{
printf("Found %s\n",numbers[i]);
return 0;
}
}
printf("Not found\n");
return 1;
}
typedef
: 새로운 타입을 정의한다의 의미
struct
: C에 미리 정의된 키워드로 마치 그릇처럼 여러가지 자료형을 담을 수 있다
#include<cs50.h>
#include<stdio.h>
#include<string.h>
typedef struct
{
string name;
string number;
}
person; // person 이라는 이름의 구조체를 자료형으로 정의
int main(void)
{
string n = get_string("name: "); // 사용자에게 이름값을 받는다
person people[4];
people[0].name ="홍길동";
people[0].number ="123-456";
people[1].name ="김철수";
people[1].number ="123-457";
people[2].name ="김영희";
people[2].number ="123-458";
people[3].name ="임꺽정";
people[3].number ="123-459";
for (int i=0;i<sizeof(people);i++)
{
if(strcmp(people[i].name,n)==0) // 두 문자열이 같은지 확인
{
printf("Found %s\n",people[i].number);
return 0;
}
}
printf("Not found\n");
return 1;
}