[C 프로그래밍] 1. 기초 개념
C언어 영상 보고 내용 정리: https://www.youtube.com/watch/2NWeucMKrLI
printf 입력
- 쌍따옴표 안에 넣어줘야 하고 마지막에 ; 넣어줘야 함
int main()
{
    printf("");
    return 0;
}
새로운 줄 출력 \n & 탭 \t & alert \a
int main()
{
    printf("I miss 우\n");
    printf("우 miss 윤 too\n");
    return 0;
}
Comments 주석
/* 안녕 나는 c언어는 처음이야 */Conversion Characters 변환 문자
(1) string (\s)
int main()
{
    printf("%s is the best food\n","망고");
    return 0;
}
(2) numbers (\d) - decimal
int main()
{
    printf("%d is the best number\n",614);
    return 0;
}
(3) float (\f)
int main()
{
    printf("%f is the best number\n",614.000);
    return 0;
}
- float에서 소수점 자리도 지정해줄 수 있음
 printf("%.2f is the best number\n",614.000);
Variables 변수
- 변수명 처음은 알파벳으로만 & 공백 없이
int main()
{
    int age; /* age라는 변수가 있는데 정수로 받아줄 것임*/
    age=22;
    printf("I am %d years old", age);
    return 0;
}
int main()
{
    int age; /* age라는 변수가 있는데 정수로 받아줄 것임*/
    age=2020-2000;
    printf("I am %d years old", age);
    return 0;
}
String Terminator
- array사용할거면 어떤 데이터타입 사용할건지 지정
- char~
int main()
{ /* array사용할거면 어떤 데이터타입 사용할건지 지정*/
    char name[14]="Bucky Roberts";
    printf("my name is %s", name);
    return 0;
}Arrays
- array, list에서 특정부분만 바꾸기 가능
int main()
{ /* array사용할거면 어떤 데이터타입 사용할건지 지정*/
    char name[14]="Bucky Roberts";
    printf("my name is %s \n", name);
    name[2]="zzz";
    printf("my name is %s", name);
    return 0;
}- 굳이 리스트 안에 숫자 안 넣어줘도 알아서 세준다
char food[]="tuna";
    printf("my favorite food is %s \n", food);- strpy(변경할 리스트, 변경할 값[새로 저장할 값])
char food[]="tuna";
    printf("my favorite food is %s \n", food);
    strcpy(food,"bacon");
    printf("my favorite food is %s \n", food);
    return 0;Creating Header File
- 다른 헤더(~.h라고 저장해야 함) 파일에서 정의한 것을 불러다가 (상단에 #include "~.h") 쓸 수 있다
#include <stdio.h>
#include <stdlib.h>
#define MYNAME "Tuna Butter" /*MYNAME이란 변수를 찾으면서 찾으면 튜나버터로 바꿔주기*/
int main()
{
    printf("name : %s",MYNAME);
    return 0;
}Getting input with scanf
- scanf("받을 것의 속성(%d,%s..)", 저장받을 array)
- 그런데 이 scanf는 입력받을 때 띄어쓰기(스페이스) 만나면 입력의 끝이라고 인식함
 따라서 woo woo 라고 쓰면 안되고 woowoo 라고 입력해야 함
#include <stdio.h>
#include <stdlib.h>
int main()
{
    char firstname[20];
    char crush[20];
    int numberofBabies;
    printf("What is your name? \n");
    scanf("%s",firstname);
    printf("Who are you going to marry? \n");
    scanf("%s",crush);
    printf("How many kids do you want to have? \n");
    scanf("%d",&numberofBabies);
        printf("%s and %s will marry and have %d babies", firstname, crush, numberofBabies);
    return 0;
}
- before every single variables에 연산자 &을 꼭 써줘야 한다, except for arrays
Math Operators
- plus
 
int main()
{
    int weight = 595;
    printf("if i eat mango, I will weigh %d \n", weight+12);
    return 0;
}
- % remainder
int main()
{
    int weight = 595;
    printf("if i eat mango, I will weigh %d \n", weight %  12);
    return 0;
}
- 정수로 출력하기, 실수로 출력하기
int main()
{
    int a=80;
    int b =90;
    printf("%d \n", a/b);
    int c=80.0;
    int d =90.0;
    printf("%f \n", c/d);
    return 0;
}
Order Operations
- () 괄호 먼저 계산
Calculating the Average Age
int main()
{
    int a;
    int b;
    int c;
    a = b = c = 100;
    printf("%d %d %d", a, b, c);
    
    return 0;
}
 
int main()
{
    float age1, age2, age3, average;
    age1=age2=4.0;
    printf("enter your age\n");
    scanf("%f", &age3);
    average=(age1+age1+age3) / 3;
    printf("\n average %f", average);
    return 0;
}
Calculate Interest
int main()
{
    int pageview =0;
    pageview=pageview+1;
    printf("page views : %d \n", pageview);
    pageview=pageview+1;
    printf("page views : %d \n", pageview);
    float balance = 1000.00;
    balance*=1.1;
    printf("balance : %f \n", balance);
    balance*=1.1;
    printf("balance : %f \n", balance);
    balance*=1.1;
    printf("balance : %f \n", balance);
    return 0;
}Typecasting
- 계산 할 때 int와 float을 더하면 정확하지 않은 결과 나올 때도 있음
- 따라서 type을 변경해줘야 한다, 동일하게
int main()
{
float avgProfit;
    int priceofpumpkin = 10;
    int sales = 50;
    int dayworked = 7;
    avgProfit=((float)priceofpumpkin * (float)sales) / (float)dayworked;
    printf("profit: %f", avgProfit);
    return 0;
}if
(1) 형식
- if(조건) {
 조건이 참이면 돌려질 코드
 }
int main()
{
    if(4<10) {
        print("yes");
    }
    return 0;
}
(2) 적용
int main()
{
    int age;
    printf("How old are you?\n");
    scanf("%d", &age);
    if(age>=18) {
        printf("You may enter this website");
    }
    if (age<19) {
        printf("Nothing to see here!");
    }
    return 0;
Nesting if statements
: if 안에 if문을 놔주기
int main()
{
    char gender;
    int age;
    printf("How old are you?\n");
    scanf("%d", &age);
    printf("What is your gender? (m/f) \n");
    scanf("%s", &gender);
    if(age>=18) {
        printf("You may enter this website ");
        if (gender=='m'){
            printf("dude");
        }
        if (gender=='f') {
            printf("lady");
        }
    }
    if (age<18) {
        printf("Nothing to see here!");
    }
    return 0;if ~ else
int main()
{
    char gender;
    int age;
    printf("How old are you?\n");
    scanf("%d", &age);
    printf("What is your gender? (m/f) \n");
    scanf("%s", &gender);
    if(age>=18) {
        printf("You may enter this website ");
        if (gender=='m'){
            printf("dude");
        }
        else {
            printf("my lady");
        }
    }
    else{
        printf("Noting to see here!");
    }
    return 0;
}
More than two choices : else if
int main()
{
    float grade1;
    float grade2;
    float grade3;
    printf("Enter your three test grade: \n");
    scanf(" %f", &grade1);
    scanf(" %f", &grade2);
    scanf(" %f", &grade3);
    float avg = (grade1+grade2+grade3)/3;
    printf("Average: %.2f \n", avg);
    if (avg>=90){
        printf("A");
    } else if(avg>=80){
        printf("B");
    } else if(avg>=70){
        printf("C");
    }else if(avg>=60){
        printf("D");
    }
    else{
        printf("F");
    }
    return 0;
}
반성사항 : 스캔 받은 것을 담아둘 때, array 아닌데 저장할거면 무조건 &연산자 써야한다
int main()
{
    float grade1;
    float grade2;
    float grade3;
    printf("Enter your three test grade: \n");
    scanf(" %f", grade1); #작동되지 않음 이렇게 앞에 &안 붙이고 실행하면
    scanf(" %f", grade2);
    scanf(" %f", grade3);
    float avg = (grade1+grade2+grade3)/3;
    printf("Average: %.2f \n", avg);
    return 0;
}
(1) More than one condition - &&
: use && signs
int main()
{
    int HoursStudied=60; /*10 or more hours*/
    int KidsBeatUp=0;
    
    if((test1)&&(test2)){ /*&&연산자로 묶어주면 됨*/
        printf("code");
    }
    
    return 0;
}
(2) More than one condition - OR (||)
int main()
{
    char answer;
    printf("Do you like bagles(y/n) \n");
    scanf(" %c", &answer);
    if((answer=='y')||(answer=='n')){
        printf("Good Job");
    }else{
        printf("Wrong spelling dude");
    }
    return 0;
}
Shorthand if else
(1) 형식 : (test) ? trueCode : falseCode; => 참이면 truecode 출력, 아니라면 falsecode 출력
int main()
{
    (test) ? trueCode : falseCode;
    return 0;
}
(2) 적용
int main()
{
    char lastName[20];
    printf("Last name : \n");
    scanf("%s", lastName);
    (lastName[0] < 'M') ? printf("Blue Team") : printf("Red Team");
    return 0;
}(3) 적용 : 친구가 한명일 때만 friend로 출력되게 하고 나머지 경우에는 s 붙이기
int main()
{
    int friends=9;
    printf("I have %d friend%s", friends, (friends!=1)? "s" : "");
    return 0;
}Increment Operator(++) / Decrement Operator(--)
int main()
{
    int tuna = 20;
    printf("%d\n", tuna);
    tuna++;
    ++tuna;				
    printf("%d\n", tuna);
    tuna--;
    printf("%d\n", tuna);
    return 0;
}
(2) ++를 앞에 붙이냐(왼), 뒤에 붙이느냐(오) 따라서 결과가 달라짐
왼 : change a before doing anything else
오 : change a after the equation 
int main()
{
    int a=5, b=10, answer=0;
    /* =>++left : change a before doing anything else*/
    answer = ++a * b;
    printf("Answer : %d \n",answer);/*60 이 출력됨*/
    
    a=5, b=10, answer=0;
    answer = a++ * b;
    /* => right++ : change a after the equation */
    printf("Answer : %d \n", answer);/*50이 출력됨*/
}
while loop
int main()
{
    int tuna=1;
    while(tuna< 5){
        printf("Tuna is now %d \n",tuna);
        tuna++;
    }
    return 0;
}
(2)
int main()
{
    int day=1;
    float amount= .01;
    while(day <=31){
        printf("Day:%d \t Amount: $ %.2f \n", day, amount);
        amount*=2;
        day++;
    }
    return 0;
}
do While Loops
(1) 형태
int main()
{
	float grade = 0 ;
    do{
        this code;
    }while(this test is true);
    return 0;
}
(2) 적용
int main()
{
    float grade = 0 ;
    float scoreEntered = 0;
    float numberOfTests = 0;
    float average = 0;
    printf("Press 0 when complete, \n\n");
    do{
        printf("Tests :%.0f     Average:%.2f",numberOfTests, average);
        printf("\nEnter test scores ");
        scanf("%f", &scoreEntered);
        grade +=scoreEntered;
        numberOfTests++;
        average=grade/numberOfTests;
    }while(scoreEntered != 0);
    return 0;
}
=>
for Loop
: for(bacon=1; bacon<=10; bacon++) => 베이컨이 1부터 10까지 있고, 한번 돌때마다 베이컨을 하나씩 늘려주어라
(1) 베이컨을 하나씩만 늘리는 경우
int main()
{
    int bacon;
    for(bacon=1; bacon<=10; bacon++){
        printf("Bacon is %d \n", bacon);
    }
    return 0;
}
=>
(2) 베이컨을 8개씩 늘리고 싶을 때
int main()
{
    int bacon;
    for(bacon=1; bacon<=100; bacon+=8){
        printf("Bacon is %d \n", bacon);
    }
    return 0;
}
=>
(3) 이중 for
int main()
{
    int columns;
    int rows;
    for(rows=1; rows<=6; rows++){
        for(columns=1;columns<=4;columns++){
            printf("%d ", columns);
            }
        printf("\n");
    }
    return 0;
}
break
int main()
{
    int a;
    int howMany;
    int maxAmount=10;
    printf("How many times do you want this loop to loop? (up to ten)\n");
    scanf("%d", &howMany);
    for(a=1;a<=maxAmount;a++){
        printf("%d \n", a);
        if (a==howMany){
            break;
        }
    }
    return 0;
}
Continue
- 밑에 있는 것 무시하고 다시 반복문 처음으로 돌아가라
 =>아래를 출력하면 6이랑 8일 때는 출력이 되지 않음
int main()
{
    int num=1;
    do{
            if(num==6 || num==8){
                num++;
                continue;
            }
        printf("%d is available \n",num);
        num++;
    }while(num<=10);
    return 0;
}
Switch
int main()
{
    char grade='A';
    switch(grade){
        case 'A': printf("sweet! \n");
            break;
        case 'B': printf("Try harder! \n");
            break;
        case 'C': printf("I C you didn't study \n");
            break;
        case 'D': printf("Embarrassing \n");
            break;
        case 'F': printf("HAHAHA \n");
            break;
        default : printf("NON SENSE!"); /* 어떤 케이스에도 속하지 않을때 디펄트값 출력*/
    }
    return 0;
}
Few Character Functions
- #include <ctype.h> =>/provides a bunch of built-in characters/
(1) int랑 character 이랑 interchange 되는 부분
- isalpha : 알파벳이면 참, 아니면 거짓
- isdigit : 숫자면 참, 아니면 거짓
int main()
{
    int tuna='88';
    if(isalpha(tuna)) {
        printf("%c is a letter",tuna);
    }else{
        if(isdigit(tuna)){
            printf("%c is a number",tuna);
        }else{
        printf("OMGGGGGG");
    }
    }
    return 0;
}
toupper
:직접적으로 소문자인 것을 대문자로 바꾸는 것, 만약 소문자 아니고 대문자나 다른 문자면 그냥 그대로 출력해준다
int main()
{
    char a='a';
    char b='F';
    char c='7';
    printf("%c \n",toupper(a));
    printf("%c \n",toupper(b));
    return 0;
}
strcat
- ham이라는 글자에 strcat 해서 글자 append하기 가능,
 다만[] 안에 있는 숫자 수만 안 넘게
int main()
{
    char ham[100]="hey";
    strcat(ham," Bucky");
    printf("%s",ham);
    return 0;
}
strcpy
:replaces one string with another string
int main()
{
    char ham[100]="hey";
    strcat(ham,"Bucky SMELLS");
    strcpy(ham, "Bucky is Awesome");
    printf("%s",ham);
}
=>SMELLS 문장이 아닌 AWESOME 문장이 출력된다
Puts & Gets
- scanf는 hello darling 이라고 입력하면, hello 다음의 스페이스를 끝나는 것으로 인식한다는 문제점이 있음
개념 및 예시 출처 : 링크텍스트
- get
헤더파일 : <stdio.h>, 
함수원형 : char~ gets(char~ str);
=> gets 함수가 "문자열"이라고 감지하는 기준은 개행(\n)입니다.
gets 함수는 들어온 문자열에 대해 '\0'울 붙여줍니다.
정리하면, 표준입력으로 들어온 문자열을 개행한 부분 앞까지 짤라서 char* 타입의 문자열로 저장해주고, 자동으로 문자열 맨 끝에 '\0'을 넣어서 문자열을 완성해 줍니다.
- puts
헤더파일 : <stdio.h>,
함수원형 : int puts(const char* str)
=>매개변수로 들어온 char* 타입의 문자열의 주소값으로 가서 문자열의 끝 '\0'이 나올때까지의 문자들을 표준출력(output)에 쭉 출력해주다가 다 출력한 후에는 친절하게 개행('\0') 까지 넣어주는 함수
(1) 예시1
int main()
{
    char catname[30];
    char catfood[20];
    char sentence[75]=" ";
    puts("What is your cat name? : ");
    gets(catname);
    puts("What does he loves to eat? : ");
    gets(catfood);
    strcat(sentence, catname);
    strcat(sentence, " loves to eat ");
    strcat(sentence, catfood);
    printf(sentence);
}
(2) 예시2
//[C언어/C++] puts example.
//BlockDMask.
#include<stdio.h>
 
int main(void)
{
    char str[100];
    for (int i = 0; i < 3; ++i)
    {
        printf("input : ");
        gets_s(str);
 
        printf("output : ");
        puts(str);
    }
    return 0;
}
Rounding Numbers (floor / ceil)
int main()
{
    float bacon1=9.44;
    float bacon2=3.3;
    printf("bacon 1 is %.2f\n",floor(bacon1));
    printf("bacon 1 is %.2f\n",floor(bacon2));
    printf("bacon 1 is %.2f\n",ceil(bacon1));
    printf("bacon 1 is %.2f\n",ceil(bacon2));
}
Absolute value : abs
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <math.h>
int main()
{
    int year1;
    int year2;
    int age;
    printf("Enter a year \n");
    scanf(" %d", &year1);
    printf("Enter another year \n");
    scanf(" %d", &year2);
    age=year1-year2;/*절대화 안돼서 나와서 마이너스 나올수도 있음*/
    printf("%d \n", age);
    
    age=abs(age); /*절대화 되어서 나옴*/
    printf("%d \n", age);
    return 0;
}
pow
- pow(5,3) => 5^3
int main()
{
    printf("%f \n", pow(5,3) );
    return 0;
}
sqrt
- 제곱근
int main()
{
    printf("%.0f \n", sqrt(16) );
    return 0;
}
Random number Generator with ran
(1)
=> rand() 하면 무작위의 number이 나온다
int main()
{
    int i;
    int diceRoll;
    for(i=0; i<20; i++){
        printf("%d \n",rand());
    }
}(2) 범위 지정해놓고 그 안에서만 랜덤 넘버 출력되게 하기(주사위처럼)
int main()
{
    int i;
    int diceRoll;
    for(i=0; i<20; i++){
        diceRoll=(rand() %6) +1 ;
        printf("%d \n",diceRoll);
    }
}
int and float arrays
(1)=> not useful
int main()
{
    int i;
    int meatballs[4] = {7,9,43,21}; /* initializing array*/
    for(i=0;i<4;i++){
        printf("element %d: %d \n",i,meatballs[i]);
    }
}(2)
                      
int main()
{
    int i;
    int meatballs[5]; /* initializing array*/
    int totalballs=0;
    for(i=0; i<5;i++){
        printf("How many meatballs did you eat on day %d? \n",i+1);
        scanf("%d",&meatballs[i]); /* 여기다가 &연산자 꼭 붙여줘야 함 */
    }
    for(i=0; i<5;i++){
            totalballs+=meatballs[i];
    }
    int avg = totalballs /5;
    printf("You ate %d meatballs total, that's an average of %d per day! \n", totalballs, avg);
}
                      pararell arrays (최댓값 갱신)
                       
int main()
{
    int i;
    int player[5]={58,66,68,71,87};
    int goals[5]={26,39,25,29,31};
    int gamesplayed[5] = {30,30,28,30,26};
    float ppg[5];
    float bestPPG=0.0;
    int bestplater;
    for (i=0;i<5;i++){
        ppg[i]=(float)goals[i]/gamesplayed[i];
        printf(" %d \t %d \t %d \t %.2f \n",player[i],goals[i],gamesplayed[i],ppg[i]);
        if (ppg[i]>bestPPG){
            bestPPG=ppg[i];
            bestplater=player[i];
        }
    }
    printf("\n The best player is %d \n", bestplater);
    return 0;
}
                       Sorting arrays (while true & swwapping & temp)
                       
int main()
{
    int i, temp, swapped;
    int howmany=10;
    int goals[howmany];
    for(i=0;i<howmany;i++){
        goals[i]=(rand()%25)+1;
    }
    printf("Original list \n");
    for(i=0;i<howmany;i++){
        printf("%d \n",goals[i]);
    }
    while(i){
        swapped=0;/* sorted됐으면 0, 아니면 1 */
        for(i=0;i<howmany-1;i++){
            if(goals[i]>goals[i+1]){
                int temp=goals[i];
                goals[i]=goals[i+1];
                goals[i+1]=temp;
                swapped=1;
                }
        }
        if (swapped==0){
            break;
        }
    }
    printf("Sorted list \n");
    for(i=0;i<howmany;i++){
        printf("%d \n", goals[i]);
    }
    return 0;
}
                       Pointers
그림 출처 링크텍스트
                            
- 컴퓨터 데이터가 어떤 위치에 저장되는지 보여줌
 
int main()
{
    int mango=22;
    printf("%p", &mango);
    return 0;
}                       =>
  
(2) 좀 더 시각적이게
int main()
{
    int mango=22;
    printf("Address \t\t name \t Value \n");
    printf("%p \t %s \t %d \n", &mango,"mango",mango);
    return 0;
}                       =>   이때  %p는 int나 str에서나 담지 못함(캐릭터도 있고 숫자도 있어서)
따라서 포인터에 저장하는 것 (store addresses)
  
(3) 저장하는 것
int main()
{
    int mango=22;
    printf("Address \t\t name \t\t Value \n");
    printf("%p \t %s \t\t %d \n", &mango,"mango",mango);
    int * pMango=&mango; /*we're going to hold a memory address called a pointer now*/
    printf("Address \t\t name \t\t Value \n");
    printf("%p \t %s \t\t %d \n", pMango,"mango",mango); /* 포인터에 저장한 애로 위치 불러오기기*/
    printf("Address \t\t name \t\t Value \n");
    printf("%p \t %s \t %d \n", &pMango,"pMango",pMango); /*피망고가 저장되어있는 위치- - 피망고가 저장하고 있는 값은 망고의 위치*/
    return 0;
}                       Dereference Pointer
: go to the variable and get the value of it !!
                       
int main()
{
    int mango=22;
    int * pMango=&mango; /*we're going to hold a memory address called a pointer now*/
    printf("Address \t\t name \t\t Value \n");
    printf("%p \t %s \t\t %d \n", pMango,"mango",mango); /* 포인터에 저장한 애로 위치 불러오기기*/
    printf("%p \t %s \t %d \n", &pMango,"pMango",pMango); /*피망고가 저장되어있는 위치- - 피망고가 저장하고 있는 값은 망고의 위치*/
    
    printf("\n&pMango :%d \n",*pMango)
    /* 포인터 앞에 *붙이면(dereference) 자신이 저장하고 있는 위치값 내놓는 게 아니라 
    내가 포인팅 하고 있는 애한테로 가서 그 애의 value값을 가져온다 */
    
    return 0;
}
                       (+) 더 나아가서 "*pMango" 는 mango랑 exactly same, 따라서 *pMango의 값을 변경하면 mango의 값도 변경이 된다
==>      
int main()
{
    int mango=22;
    int * pMango=&mango; /*we're going to hold a memory address called a pointer now*/
    printf("Address \t\t name \t\t Value \n");
    printf("%p \t %s \t\t %d \n", pMango,"mango",mango); /* 포인터에 저장한 애로 위치 불러오기기*/
    printf("%p \t %s \t %d \n", &pMango,"pMango",pMango); /*피망고가 저장되어있는 위치- - 피망고가 저장하고 있는 값은 망고의 위치*/
    printf("\n*pMango :%d \n",*pMango);
    /* 포인터 앞에 *붙이면(dereference) 자신이 저장하고 있는 위치값 내놓는 게 아니라
    내가 포인팅 하고 있는 애한테로 가서 그 애의 value값을 가져온다 */
    *pMango=71;
    printf("\n*pMango :%d \n",*pMango);
    printf("\n*mango :%d \n",mango);
    return 0;
}                      Arrays and Pointer
                       
int main()
{
    int i;
    int meatballs[5]={7,9,43,21,3};
    printf("Element \t Address \t\t Value \n");
    for (i=0;i<5;i++){
        printf("meatballs[%d] \t %p \t %d \n",i, &meatballs[i],meatballs[i]);
    }
    printf("\nmeatballs \t\t %p \n", meatballs); /*원래는 %p 값에 할당할 때 앞에 &연산자 붙여줘야 하는데, 저렇게 아무것도 안 붙이고 써주면 array 에 있는 첫번째 element를 가리키게 된다*/
    return 0;
}
                       => array names are just pointers to the first element
  
Strings and Pointers
=> whenever we make simple arrays of characters, it's hard to chamge because the name of the array it is constant,
however when we mae a pointer to a string, pointer here is a variable.
Since all that doing is its storing the address of sth sothat we can treat it like a string, saying start this address, start movie 2 and start printing until you get to 0
                       
int main()
{
    char movie[]="Sungwoo Love"; //it is a constant, cannot change it//
    char *movie2[]="I love Sungwoo"
    
    puts(movie2); //puts means print out the things that movie 2 is saving its location until it arrives to the final(0)//
    
    movie2="DONGSUNGMARRY";
    
    puts(movie2); //we can change this cuz it's a variable//
    
 
    return 0;
}
                       Problems with String Lengths
- 만약 영화 제목으로 20글자까지만 입력받게 만들었는데 (char movie[20];)
 20글자를 초과하게 된다면 =>
 fgets(pMovie,20,stdin)
 이렇게 해주면 20글자 넘어가면 잘라버리낟
 
                       
int main()
{
    char movie[20];
    char *pMovie=movie; //whenever you set a pointer equal to an array, don't use the &, cuz the name of your array is already a memory address//
    fgets(pMovie, 20, stdin);//,maximum length-so if the number gets over it, it cuts it off. stdin=input from keyboard//
    puts(pMovie);
    return 0;
}
                       =>
  
The Heap
- heap : 컴퓨터에는 extra memory들이 존재하고 있음, heap은 이러한 leftover memory, which we can borrow whenever we need and give it back whenever our programs ends
- malloc : allocate memory or get memory from the heap, so the only parameter this function takes if how much memory do you need
 => first thing to save memory == malloc
 (how you get the extra memory)
 
- free  : to give it back
 =>
 
                       
int main()
{
    int *points;
    points=(int *) malloc(5 & sizof(int));
  
  /*sizeof(int) saves us from finding out how many bytes each system store in its variable*/
  
    /* (int*)=>int typecast pointer whenever you're storing*/
    
    free(points0) 
    
    return 0;
                       Creating an Expandable program using the heap
- 사용자가 입력한 값에 따라서 array의 길이가 달라지게 해주기
                       
int main()
{
   int i, howmany;
   int total=0;
   float average=0.0;
   int * pointArray;
   printf("How many numbers do you want to average? \n");
   scanf(" %d", &howmany);
   pointArray=(int *) malloc(howmany * sizeof(int));
   printf("Enter them hoss! \n");
;
   for(i=0;i<howmany;i++){
    scanf("%d",&pointArray[i]);
    total+=pointArray[i];
   }
   average=(float)total/(float)howmany;
   printf("Average is %f", average);
   free(pointArray);
   return 0;
}
                       Structures
- '.' used for accessing individual elements or items inside your structure
                       
int main()
{
   struct user dongyun;
   struct user sungwoo;
   dongyun.userID=1;
   sungwoo.userID=2;
   puts("Enter the first name of user1");
   gets(dongyun.firstname);
   puts("Enter the first name of user2");
   gets(sungwoo.firstname);
   printf("User 1 id is %d \n", dongyun.userID);
   printf("User 2 first name is %s \n", sungwoo.firstname);
   return 0;
}
                       Writing files in C
(1) sequential access file
- r :read
- a: add to end of the file (append)
- fprint : file에 써라
 
int main()
{
    FILE *Fpointer;
    Fpointer= fopen("bacon.txt","w");
return 0;
}                       =>bacon이라는 파일이 없어도 컴퓨터가 알아서 생성해 줄 것
int main()
{
    FILE *Fpointer;
    Fpointer= fopen("bacon.txt","w");
    fprintf(Fpointer, "I love cheese \n");
    fclose(Fpointer); /*done with this and back your data to your computer*/
return 0;
}                => 베이컨이라는 txt파일이9 생기고 아이러브치즈가 파일안에 작성이 된다
how to Read Files
- feof loop : 라인이 있는 동안 계속 진행해라
int main()
{
    FILE *Fpointer;
    Fpointer= fopen("bacon.txt","r");
    char singleline[150];
    while(!feof(Fpointer)){
        fgets(singleline, 150, Fpointer);
        puts(singleline);
    }
    fclose(Fpointer);
return 0;
}                       => 문장들 사이에 빈칸들이 있는데 한 문장의 끝이 \n 이 있는 것으로 인식하기 때문이다
Append to file
                       
int main()
{
    FILE *Fpointer;
    Fpointer= fopen("bacon.txt","a");
    fprintf(Fpointer, "\nI really want to be a developer.");
    fprintf(Fpointer, "\nActually it is the only way for me.");
return 0;
}                       =>
  
Random File Access
- w+ : 처음엔 writing mode로 열었다가 나중엔 r모드로 바꿔라!
- wseek : 문서에 작성된 곳 인덱스에 접근하는 것
- SEEKSET : 처음부터 찾아보아라 seek to the beginning(커서가 맨앞)
- SEEKEND : seek to the end
fseek(Fpointer, -6, SEEK_END); 왼쪽 방향으로 가는 것
fseek(Fpointer, 7, SEEK_SET);  오른쪽 방향으로 가는 것, 위에 것과 도달점 same
int main()
{
    FILE *Fpointer;
    Fpointer= fopen("bacon.txt","w+");
    fputs("pumpkkin",Fpointer);
    fclose(Fpointer);
return 0;
}                       =>
  
Functions
- return : we are done with the program, go back to sth else
- 프로그램은 위에서부터 함수를 읽는다
- 따라서 함수를 main 밑에 만들어놓고 이 함수명을 main위에 설정해주고(이런 함수가 존재한다~라고 말할 수 있게), 그러면 main 이 함수 읽으면서 결과 출력
                       
void printSth();
int main(){
    printSth();
    return 0;
}
void printSth(){
    printf("I'm a function");
    return;
}                     Global , Local
(1) 이렇게 하면 int가 다 적용되어서 두번 잘 출력
                       
void printSth();
int warts=23;
int main(){
    printf("I have %d warts \n", warts);
    printSth();
    
    return 0;
}
void printSth(){
    printf("I have %d warts \n", warts);
    return;
}
                       =>
  
(2) int를 main안에서만 정의해주면 printSth 함수에선 이를 인식하지 못해서 오류가 난다
                       
void printSth();
int main(){
    int warts=23;
    printf("I have %d warts \n", warts);
    printSth();
    return 0;
}
void printSth(){
    printf("I have %d warts \n", warts);
    return;
}
                       =>
  
Passing arguments to Functions
                       
void convert2dollars(float euro);
int main(){
    float europrice1 = 1.00;
    float europrice2 = 5.50;
    convert2dollars(europrice1);
    return 0;
}
void convert2dollars(float euro){
    float usd = euro * 1.37;
    printf("%.2f Euros - %.2f USD\n", euro, usd);
    return;
}
                       =>
  
Return Values
-리턴은 리턴한 값을 함수에 저장해주는 것
int calculateBonus(int yearsworked);
int main(){
    int yunibonus = calculateBonus(14);
    int woobonus = calculateBonus(2);
    printf("%d $ \n",yunibonus);
    printf("%d $ \n",woobonus);
    return 0;
}
int calculateBonus(int yearsworked){
    int bonus=yearsworked * 250;
    if (yearsworked > 10 ){
        bonus+=1000;
    }
    return bonus;
}     Pass by Reference vs Pass by Value
- 그냥 값으로 받으면 달라지지 않음, main 에서 지정된 인풋 값 그대로가 value 반영되기 때문 => 따라서 99로 튜나가 안 변하고 입력받은 값인 20 그대로 내보낸다
- 그러나 reference 해서 받으면 영향 안받기 때문에
 함수에서 지정한 64로 그대로 나온다
 
void passbyvalue(int i);
void passbyaddress(int *i);
int main(){
    int tuna=20;
    passbyvalue(tuna);
    printf("Passing by value, tuna is now %d \n", tuna);
    passbyaddress(&tuna);
    printf("Passing by address, tuna is now %d \n", tuna);
    return 0;
}
void passbyvalue(int i){
    i=99;
    return;
}
void passbyaddress(int *i){
    *i = 64;
    return;
}                   =>
  
Author And Source
이 문제에 관하여([C 프로그래밍] 1. 기초 개념), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://velog.io/@myway00/C저자 귀속: 원작자 정보가 원작자 URL에 포함되어 있으며 저작권은 원작자 소유입니다.
                                
                                
                                
                                
                                
                                우수한 개발자 콘텐츠 발견에 전념
                                (Collection and Share based on the CC Protocol.)