이번에는 Pset 2 풀기전에 section을 먼저 듣고 가겠습니당

저번에 section 안 듣고 pset 먼저 하다가 진짜 머릿속에 ???가 한가득이었기에...

 

이번에도 중복되는 것 제외하고 중요하다고 생각되는 것들만 정리해볼게용!

 

 

 

 

1. Array

 

Q. How do we create an array?

 

A.

ⓐ Name 

ⓑ Size

ⓒ Type (a single type of data)

 

Ex) int nights [5] = {7, 8, 6, 7, 8};

        ⓒ    ⓐ      ⓑ

 

 

Q. Can you change the size of an array?

A. You can't change the size of an array in C. 

 

 

Q. Can an array exist on multiple planes, like a 3D array for instance?

A. There can be an array that actually contains arrays inside of itself.

 

 

Q. Let's say we have an array of five elements. Could we add only three and later on add the other two?

A. Yes, you could. 

 

 

<Practice> - Doubling Up

Creating an array of integers in which each integer is 2 times the value of the previous integer.

 

 

 

 

☆ A phrase is an array of characters !

<Practice> - Alphabetical

 

 

 

 

 

2. Command-line Arguments

 

→ When we run mario, we didn't give any input - just ./mario

     int main (void) : this function takes no arguments.

 

→ We can change our C code to take some input now. (int argc, string argv[])

     If we type ./mario 8 in the terminal : argc = 2(inputs),

                                                                    argv[0] = ./mario,

                                                                    argv[1] = 8

 

 

☆ argc = the number of inputs to our program at the command line

☆ argv[] = the array of strings, the array of inputs to our program at the command line

 

'CS50' 카테고리의 다른 글

[CS50] Week 3 Review  (1) 2024.10.01
[CS50] Pset 2 : Scrabble, Readability, Caesar  (1) 2024.09.29
[CS50] Week 2 Review  (2) 2024.09.23
[CS50] Week 1 Section + Pset 1 : Mario-more  (0) 2024.09.15
[CS50] Pset 1 : Credit  (1) 2024.09.13

 


Week 2

:  Deeper look about C


 

 

Lecture Contents

 

 

 

 

 

1. Compiling 

 

-Encryption : the act of hiding plain text from prying eyes (암호화)

-Decrypting : the act of taking an encrypted piece of text and returning it to a human-readable form (해독)

 

We learned about a compiler last week:

source code -> compiler -> machine code

- VS Code utilizes a compiler called clang or c language

Ex) If you were to type make hello, it runs a command that executes clang

 

#include <cs50.h>
#include <stdio.h>

int main(void)
{
   string name = get_string("What's your name?: ");
   printf("hello, $s\n, name);
}

 

In the terminal window, type : 

clang -o hello hello.c -lcs50

=> Enables the compiler to access cs50 library.

 

 

Major steps of compiling :

 

preprocessing 

: where the header files (#) in your code are effectively copied and pasted into your file. 

The code from cs50.h is copied into your program. This step can be visualized as follows:

string get_string(string prompt);
int printf(string format, ...);

int main(void)
{
   string name = get_string("What's your name?" );
   printf("hello, %s\n, name);
}

 

 

compiling

: where your program is converted into assembly code. This step can be visualized as follows:

 

 

assembling

: where the compiler converts your assembly code into machine code. This step can be visualized as follows:

 

linking

: where code from your included libraries are concerted also into machine code and combined with your code.

This step can be visualized as follows:

 

 

 

 

 

2. Debugging

 

: to address the bugs

 

Let's purposely insert a bug within your code:

#include <stdio.h>

int main(void)
{
   for(int i =0; i <= 3; i++)
   {
      printf("#\n");
   }
}

=> 4 bricks appear instead of the intended 3. 

#

#

#

#

 

 

ⓐ printf : a very useful way of debugging your code.

#include <stdio.h>

int main(void)
{
   for(int i = 0; i <=3; i++)
   {
      printf("i is %i\n, i);
      printf("#\n");
   }
}

=> i is 0, i is 1, i is 2, i is 3

You might realize that your code needs to be corrected as follows: (<= is replaced with <)

for(int i = 0; i < 3; i++)

 

 

This code can be further improved as follows:

#include <cs50.h>
#include <stdio.h>

void print_column(int height);

int main(void)
{ 
   int h = get_int("Height: ");
   print_column(h);
}

void print_column(int height)
{
   for (int i = 0; i <= height; i++)
   {
      printf("#\n");
   }
}

=> This sill results in a bug. (n+1 bricks instead of the intended n)

 

 

debugger : a software tool created by programmers to help track down bugs in code.

  ▷ First, set a breakpoint by clicking to the left of a line of your code, just to the left of the line number.

      When clicked, you will see a red dot appearing.

  ▷ Second, run debug50 ./buggy(the name of your file).  It will seem like this:

=> Click the step over button and notice how the value of h increases.

It will show how your code is running step by step. 

 

 

Rubber duck debugging 

 

 

 

 

 

3. Arrays

 

Each data type requires a certain amount of system resources:

◎ bool : 1 byte

◎ int : 4 bytes

◎ long : 8 bytes

◎ float : 4 bytes

◎ double : 8 bytes

◎ char : 1 byte

◎ string : ? bytes

 

#include <stdio.h>

int main(void)
{
   int score1 = 72;
   int score2 = 73;
   int score3 = 33;
   
   printf("Average: %f\n", (score1+score2+score3) / 3.0);
}

=> Notice of using %f and 3.0 so that the cauculation is rendered as a floating point value in the end.

 

These variables are stored in memory like:

* 1 block = 1 digit

 

 

Using Arrays

int scores[3] : a way of telling the compiler to provide you 3 back-to-back places in memory of size int to store 3 scores. 

#include <cs50.h>
#include <stdio.h>

int main(void)
{
   //Get scores
   int scores[3];
   scores[0] = get_int("Score: ");
   scores[1] = get_int("Score: ");
   scores[2] = get_int("Score: ");
   
   //Print average
   printf("Average: %f\n", (scores[0] + scores[1] + scores[2]) / 3.0);
}

-> We can still improve this code as follows:

#include <cs50.h>
#include <stdio.h>

int main(void)
{
   int scores[3];
   for (int i = 0; i < 3; i++)
   {
      scores[i] = get_int("Score: ");
   }
   
   printf("Average: %f\n", (scores[0] + scores[1] + scores[2]) / 3.0);
}

-> We can simplify or abstract away the calculation of the average as follows:

 

#include <cs50.h>
#include <stdio.h>

const int N =3;

float average(int length, int array[]);

int main(void)
{
   //Get scores
   int scores[N];
   for (int i = 0; i < N; i++)
   {
      scores[i] = get_int("Score: ");
   }
   printf("Average: %f\n", average(N, scores));
   
float average(int length, int array[])
{
   //Calculate average
   int sum = 0;
   for (int i = 0; i < length; i++)
   {
      sum += array[i];
   }
   return sum / (float) length;

- A new function called 'average' is declared. 

- Const (constant value) of N is declared. 

- 'Average' function takes int array[] : the compiler passes an array to this function.

 

 

 

 

 

4. Strings

 

A string is an array or characters (char).

-Begins with the first character and ends with a special character called a NUL character:

In decimal :

 

 

▶ Hi!

#include <stdio.h>

int main(void)
{
   char c1 = 'H';
   char c2 = 'I';
   char c3 = '!';
   
   printf("%c%c%c\n", c1, c2, c3);
}

-> When we replace %c with %i :

printf("%i%i%i\n", c1, c2, c3);

=> 72  73  33

 

 

Using arrays

#include <cs50.h>
#include <stdio.h>

int main(void)
{
   string s = "HI!";
   printf("%i %i %i %i\n", s[0], s[1], s[2], s[3]);
}

=> 72  73  33  0(NUL)

 

 

▶ Hi! BYE!

#include <cs50.h>
#include <stdio.h>

int main (void)
{
   string s = "HI!";
   string t = "BYE!";
   
   printf("%s\n", s);
   printf("%s\n", t);
}

=> We can improve this code as follows using array:

#include <cs50.h>
#include <stdio.h>

int main(void)
{
   string words[2];
   
   words[0] = "HI!";
   words[1] = "BYE!";
   
   printf("%s\n", words[0]);
   printf("%s\n", words[1]);
}

 

 

 

 

 

5. String Length

 

 

: How do we discover the length of an array?

#include <cs50.h>
#include <stdio.h>

int main(void)
{
   //Prompt for user's name
   string name = get_string("Name: ");
   
   //Count number of characters up until '\0' (aka NUL)
   int n = 0;
   while (name[n] != '\0')
   {
      n++;
   }
   printf("%i\n", n);
}

=> This can be improved as follows:

 

#include <cs50.h>
#include <stdio.h>

int string_length(string s);

int main(void)
{
   //Prompt for user's name
   string name = get_string("Name: ");
   int length = string_length(name);
   printf("%i\n", length);
}

int string_length(string s)
{
   //Count number of characters up until '\0'
   int n = 0;
   while (s[n] != '\0')
   {
      n++;
   }
   return n;
}

 

 

Other programmers have created code in the string.h library to find the length of a string.

#include <cs50.h>
#include <stdio.h>
#include <string.h>

int main(void)
{
   string name = get_string("Name: ");
   int length = strlen(name);
   printf("%i\n", length);
}

→ Notice that it uses a function strlen.

 

 

 

: How do we convert all lowercase characters to uppercase ones?

#include <stdio.h>
#include <cs50.h>
#include <string.h>

int main(void)
{
    string s = get_string("Before: ");
    printf("After: ");
    for(int i = 0, n = strlen(s); i < n; i++)
    {
        if(s[i] >= 'a' && s[i] <= 'z')
        {
            printf("%c", s[i] - 32);
        }
        else
        {
            printf("%c" , s[i]);
        }
    }
    printf("\n");
}

→ If the character is lowercase, it subtracts the value 32 from it to convert it to uppercase, according to this:

ASCII values chart

 

Now, we can use ctype.h library :

#include <stdio.h>
#include <cs50.h>
#include <string.h>
#include <ctype.h>

int main(void)
{
     string s = get_string("Before: ");
     printf("After: ");
     for (int i = 0, n = strlen(s); i < n; i++)
     {
          if(islower(s[i]))
          {
               printf("%c", toupper(s[i]));
          }
          else
          {
               printf("%c", s[i]);
          }
     }
     printf("\n");
}

toupper function is used to convert each character to uppercase.

 

Because the toupper function automatically knows to uppercase only lowercase characters, your code can be simplified as follows:

#include <stdio.h>
#include <cs50.h>
#include <string.h>
#include <ctype.h>

int main(void)
{
     string s = get_string("Before: ");
     printf("After: ");
     for (int i = 0, n = strlen(s); i < n; i++)
     {
          printf("%c", toupper(s[i]));
     }
     printf("\n");
}

 

 

 

 

 

6. Command-Line Arguments

 

 

-Command-line arguments are those arguments that are passed to your program at the command line.

Ex) All those statements you typed after clang = command-line arguments

 

greet.c

#include <stdio.h>
#include <cs50.h>

int main(void)
{
    string answer = get_string("What's your name?: ");
    printf("hello, %s\n", answer);
}

→ It says 'hello' to the user. However, it would be nice to be able to take arguments before the program even runs.

 

#include <stdio.h>
#include <cs50.h>

int main(int argc, string argv[])
{
     if (argc == 2)
     {
        printf("hello, %s\n", argv[1]);
     }
     else 
     {
        printf("hello, world\n");
     }
}

 

☆ Notice that this program knows 

1) argc    : the number of command line arguments

2) argv[] : the array of the characters passed as arguments at the command line

 

☆ argc == 2 / argv[1]

: './greet Jeeyoon \0'

         0          1         2

   argv[0]  argv[1]  argv[2]

 

 

 

 

 

7. Exit Status

 

 

When a program ends, a special exit code is provided to the computer.

When exits without error: a status code of 0

When an error occurs: a status code of 1

 

status.c

#include <stdio.h>
#include <cs50.h>

int main(int argc, string argv[])
{
     if (argc != 2)
     {
          printf("Missing command-line argument\n");
          return 1;
     }
     printf("hello, %s\n", argv[1]);
     return 0;
}

 

 

 

 

 

8. Cryptography (암호화)

 

 

 

-Cryptography : the art of ciphering and deciphering a message

*key : a special argument passed to the cipher along with the plaintext

 

 

 

점점 밀리고 있는 스케쥴... 정신 차리고 다시 스케쥴 맞춰 따라가기!!! 아자아자뵹

이렇게 2주차 강의도 끄읕! 😁

'CS50' 카테고리의 다른 글

[CS50] Pset 2 : Scrabble, Readability, Caesar  (1) 2024.09.29
[CS50] Week 2 Section  (0) 2024.09.24
[CS50] Week 1 Section + Pset 1 : Mario-more  (0) 2024.09.15
[CS50] Pset 1 : Credit  (1) 2024.09.13
[CS50] Week 1 Review  (1) 2024.09.10

 

Section은 Lecture과 Pset 사이의 간극을 줄여주는 추가 강의 세션입니당

Pset 풀기 전에 이걸 듣고 했다면 더 쉬웠을까요.. 

아무튼 중요하다고 생각되는 부분들만 메모해놓겠음!!

 

 

 

1. Variable : name for some value that can change

int calls = 3;

int : (data) type  /  calls : name  /  3 : value  /  = : assignment operator

 

 

 

2. Data Types

-Why do we need to decide which data types to use?

: It would determine what we can make the variable do!

 

<Truncation>

int calls = 4;
calls += 1; 
calls -= 2;
calls *= 3;
calls /= 2;

-In this case, int calls = 4;

because we're storing it in integer!

(float calls = 4.5;)

 

 

 

3. Placeholder

int main(void)
{
   string first_name = get_string("What is your first name?");
   string last_name = get_string("What is your last name?");
   printf("Hello, %s %s\n", first_name, last_name);
}

 

=> There can be multiple placeholders if you need!

Ex) 5th line : %s  %s

 

 

 

4. While Loops

int j = 0;
while (j < 4)
{
   printf("#");
   j++;
}
printf("\n");

=> ####\n

 

 

 

5. For Loops

for (int j = 0; j < 4; j++);
{
   printf("#");
}
printf("\n");

=> ####\n

 

 

 

6. Loop in Loop (Don't be afraid to put loop in loop!)

for (int i = 0; i < 4; i++)
{
   for (int j = 0; j < 4; j++)
    {
      printf("#");
    }
    printf("\n");
}

=> ####\n

      ####\n

      ####\n

      ####\n

 

 

 

7. Mario (Pset 1)

#include <stdio.h>
#include <cs50.h>

//List Function Prototype at the top (because C reads from top to bottom)
void print_row(int length);

int main(void)
{
   int height = get_int ("Height: ");
   for (int i =0; i < height; i++)
   {
      print_row(i + 1); //get the input of height from the user and use my own function
   }
   
//Creating my own function called print_row
void print_row(int length)
{
   for (int i = 0; i < length; i++)
   {
      printf("#");
   }
   printf("\n");
}

 

★ You can create your own function (Here, for example, print_row())

    -> But remember to list that function prototype at the top so that C can read it from top to bottom

★ print_row (i + 1) : enables you to print something like this:

#

##

###

...

 

★ How  do we change it from left-lined to right-lined? Like this:

#                                    #

##              ->             ##

###                          ###

 

=> Let's look at the relationship between 4 variables (height, row, column, and space)

height row space column
Ex) 4 0 3 1
1 2 2
2 1 3
3 0 4

 

Space = height - row - 1

 

 

 

The result being like:

#include <stdio.h>
#include <cs50.h>

int main(void)
{
int height, row, column, space;
do
{
height = get_int ("Height: ");
}
while (height < 1);

for (row = 0; row < height; row++)
{
for (space = 0; space < height - row - 1; space++)
{
printf(" ");
}
for (column = 0; column < height - space; column++)
{
printf("#");
}
printf(" ");
for (column = 0; column < height - space; column++)
{
printf("#");
}
printf("\n");
}
}


'CS50' 카테고리의 다른 글

[CS50] Week 2 Section  (0) 2024.09.24
[CS50] Week 2 Review  (2) 2024.09.23
[CS50] Pset 1 : Credit  (1) 2024.09.13
[CS50] Week 1 Review  (1) 2024.09.10
[CS50] Week 0 Review  (2) 2024.08.28

 

 

진짜 머리 터지는 줄 알았던 credit 과제..

아직 내가 정말 이해했는지 확신도 없지만 기록 & 복습 용으로 남겨놓으려 해용 

 

 

<What to do>

  1. Prompt credit card number (has to be > 0, using get_long())
  2. Calculate Checksum (digits * 2 & digit not multiplied by 2 - seperately)
  3. Check for card length & starting digits (identify if it's VISA, AMEX, or MASTER)
  4. Printf which card it is & if it's valid or invalid

 


 

 

 

1. Prompt credit card number

 

int main(void)
{
   do
   {
      long card = get_long("Card No:  ");
   }
   while (card < 0);

 

☆ do~while 을 사용해서 card number가 0보다 크도록 설정해주기

☆ 숫자가 크기 때문에 get_long function 사용해주기

 

 

 

 

2. Calculate Checksum

 

카드 각 digit의 숫자를 판별하고, Luhn's Algorithm 을 사용해서 2로 곱하거나 곱하지 않고 더해야 함

EX) Card No: 4003600000000014

       4 0 0 3 6 0 0 0 0 0 0 0 0 0 1 4

=> 밑줄 친 부분은 2를 곱해서 각 digit을 더하고, 밑줄 치지 않은 부분은 그냥 각 digit을 더해서 두 가지의 합의 last digit == 0 이면 됨

 


ⓐ  각 digit에 이름 붙이기

card8   card16  card7  card15  card6   card14  card5  card13  card4   card12   card3  card11  card2  card10  card1  card9

 

 

ⓑ  각 digit 숫자 판별법

last digit card를 10으로 나눈 나머지 card % 10
second-to-last digit card를 100으로 나눈 나머지 / 10으로 나눈 몫 (card %100) / 10
third-to-last digit card를 1000으로 나눈 나머지/ 100으로 나눈 몫 (card %1000) / 100
fourth-to-last digit card를 10000으로 나눈 나머지/ 1000으로 나눈 몫 (card %10000) / 1000

...

first digit까지 구할 수 있음

 

 

ⓒ-1)  2로 곱해야 하는 밑줄 친 숫자들 판별 *2

card1 (card %100) / 10 *2
card2 (card %10000) / 1000 *2
card3 (card %1000000) / 100000 *2
card4 (card %100000000) / 10000000 *2
card5 (card %10000000000) / 1000000000 *2
card6 (card %1000000000000) / 100000000000 *2
card7 (card %100000000000000) / 10000000000000 *2
card8 (card %10000000000000000) / 1000000000000000 *2

 

 

ⓒ-2) 각 자릿수의 digit을 더해야 하므로 각 digit을 구하면

card1 (card1 % 100) / 10 + (card1 % 10)
card2 (card2 % 10000) / 1000 + (card2 % 1000)
card3 (card3 % 1000000) / 100000 + (card3 % 100000)
card4 (card4 % 100000000) / 10000000 + (card4 % 10000000)
card5 (card5 % 10000000000) / 1000000000 + (card5 % 1000000000)
card6 (card6 % 1000000000000) / 100000000000 + (card6 % 100000000000)
card7 (card7 % 100000000000000) / 10000000000000 + (card7% 10000000000000)
card8 (card8 % 10000000000000000) / 1000000000000000 + (card8 % 1000000000000000)

 

 

ⓓ 2로 곱하지 않는, 밑줄 치지 않은 숫자들 판별

card9 card % 10 
card10 (card %1000) / 100
card11 (card %100000) / 10000
card12 (card %10000000) / 1000000
card13 (card %1000000000) / 100000000
card14 (card %100000000000) / 10000000000
card15 (card %10000000000000) / 1000000000000
card16 (card %1000000000000000) / 100000000000000

 

 

ⓔ sum 구하기 & sum의 조건

 

sum1 = card1 + card2+ card3 + card4 + card5 + card6 + card7 + card8

sum2 = card9 + card10 + card11+ card12 + card13 + card14 + card15 + card16

sum3 = sum1 + sum2

 

=> sum3의 last digit == 0이어야 함

=> if (sum3 % 10) != 0, then the card is invalid

 

☆ != : 같지 않으면

 

 

 

3. Check for card length & starting digit

 

Card No. of digits Starts with
VISA 13 or 16 4
AMEX 15 34, 37
MASTERCARD 16 51,52,53,54,55

 

ⓐ VISA

first digit = keep divide by 10 until remainder < 10 (while loop)

while (visa >= 10)
{
   visa /= 10;
}

 

ⓑ AMEX

first 2 digits = divide by 10000000000000 (13 zeros)

while (amex >= 10000000000000)
{
   amex /= 10000000000000)
}

 

ⓒ MASTER

first 2 digits = divide by 100000000000000 (14 zeroes)

while (master >= 100000000000000)
{
   master /= 100000000000000)
}

 

 

 

 

4. Printf which card it is & if it's valid or invalid

 

ⓐ VISA

if (visa == 4 && (length == 13 || length == 16))
{
   printf("%s\n", "VISA");
   return 0;
}

 

 

ⓑ AMEX

if ((amex == 34 || amex == 37) && length == 15)
{
   printf("%s\n", "AMEX");
   return 0;
}

 

 

ⓒ MASTER

if ((master == 51 || master == 52 || master == 53 || master == 54 || master == 55) && length == 16)
{
   printf("%s\n", "MASTERCARD");
   return 0;
}

 

 

ⓓ If invalid

else
{
   printf("%s\n", "INVALID");
   return 0;
}

 

 


 

이제 위의 코드들을 종합해서 VS Codespace에 적어보면 아래와 같습니다!

#include <stdio.h>
#include <cs50.h>

int main(void)
{
long card;
// Prompt card number which is over 0
do
{
card = get_long("Card No: ");
}
while (card < 0);

int card1, card2, card3, card4, card5, card6, card7, card8, card9, card10, card11, card12, card13, card14, card15, card16;

// Identify digits multiplied by 2
card1 = ((card % 100) / 10) * 2;
card2 = ((card % 10000) / 1000) * 2;
card3 = ((card % 1000000) / 100000) * 2;
card4 = ((card % 100000000) / 10000000) * 2;
card5 = ((card % 10000000000) / 1000000000) * 2;
card6 = ((card % 1000000000000) / 100000000000) * 2;
card7 = ((card % 100000000000000) / 10000000000000) * 2;
card8 = ((card % 10000000000000000) / 1000000000000000) * 2;

// Identify each digit of card1~8
card1 = (card1 % 100 / 10) + (card1 % 10);
card2 = (card2 % 100 / 10) + (card2 % 10);
card3 = (card3 % 100 / 10) + (card3 % 10);
card4 = (card4 % 100 / 10) + (card4 % 10);
card5 = (card5 % 100 / 10) + (card5 % 10);
card6 = (card6 % 100 / 10) + (card6 % 10);
card7 = (card7 % 100 / 10) + (card7 % 10);
card8 = (card8 % 100 / 10) + (card8 % 10);

//Identify digits that are not multiplied by 2
card9 = (card % 10);
card10 = (card % 1000) / 100;
card11 = (card % 100000) / 10000;
card12 = (card % 10000000) / 1000000;
card13 = (card % 1000000000) / 100000000;
card14 = (card % 100000000000) / 10000000000;
card15 = (card % 10000000000000) / 1000000000000;
card16 = (card % 1000000000000000) / 100000000000000;

//Identify each digit of card9~16
card9 = (card9 % 100 / 10) + (card9 % 10);
card10 = (card10 % 100 / 10) + (card10 % 10);
card11 = (card11 % 100 / 10) + (card11 % 10);
card12 = (card12 % 100 / 10) + (card12 % 10);
card13 = (card13 % 100 / 10) + (card13 % 10);
card14 = (card14 % 100 / 10) + (card14 % 10);
card15 = (card15 % 100 / 10) + (card15 % 10);
card16 = (card16 % 100 / 10) + (card16 % 10);

//Sumup
int sum1, sum2, sum3;
sum1 = card1 + card2 + card3 + card4 + card5 + card6 + card7 + card8;
sum2 = card9 + card10 + card11 + card12 + card13 + card14 + card15 + card16;
sum3 = sum1 + sum2;

//Check if the last digit of sum3 == 0
int length = 0;
if ((sum3 % 10) != 0)
{
printf("%s\n", "INVALID");
return 0;
}

//Length ++
long visa = card;
long amex = card;
long master = card;


while (card > 0)
{
card = card / 10;
length++;
}

//Check for the starting digit(s) of VISA and print if it's valid
while (visa >= 10)
{
visa /= 10;
}
if (visa == 4 && (length == 13 || length == 16))
{
printf("%s\n", "VISA");
return 0;
}

//Check for the starting digit(s) of AMEX and print if it's valid
while (amex >= 10000000000000)
{
amex /= 10000000000000;
}
if ((amex == 34 || amex ==37) && length == 15)
{
printf("%s\n", "AMEX");
return 0;
}

//Check for the starting digit(s) of MASTER and print if it's valid
while (master >= 100000000000000)
{
master /= 100000000000000;
}
if ((master == 51 || master == 52 || master == 53 || master == 54 || master == 55) && length == 16)
{
printf("%s\n", "MASTERCARD");
return 0;
}
else
{
printf("%s\n", "INVALID");
return 0;
}
}

 

 

  체크해보니 에러가 없다고 드디어 뜨네요... 이래봬도 수정 한 500번 함..

 

 

 

 

그럼 안뇽... 

Week 1 이 이렇게 어려우면 다음주부터는 어떻게 될까~ 하하하

'CS50' 카테고리의 다른 글

[CS50] Week 2 Review  (2) 2024.09.23
[CS50] Week 1 Section + Pset 1 : Mario-more  (0) 2024.09.15
[CS50] Week 1 Review  (1) 2024.09.10
[CS50] Week 0 Review  (2) 2024.08.28
[CS50] 코딩 공부 시작  (0) 2024.08.18

Week 1 

: learning about how to write good code in the programming language C


 

Lecture Contents
 

 
 
 
 
1. Machine Code
 
-Source Code : human readable
-Machine Code : machine readable, ones and zeros
 
We should convert source code to machine code using a compiler. A compiler is a very special piece of software. 

Source Code ->Compiler-> Machine Code

 
 
 
 
2. Hello World
 
*VS Code*
We will be using three commands to write, compile, and run our first program.

code hello.c
make hello
./hello

1) code hello.c : creates a file and allows us to type instructions for this program.
2) make hello   : compiles the file from our instructions in C and creates an executable file called hello.
3) ./hello           : runs the program called hello.
 
then, write code as follows :

#include <stdio.h>

int main (void)
{
   printf ("hello, world\n");
}

1) printf : a function that can output a line of text. 
2) \n      : creates a new line after the words hello, world.
3) #include <stdio.h> : tells the compile that you want to use the capabilities of a library called stdio.h, a header file. This allows you, among many other things, to utilize the printf function.
 
 
 
 
 
3. Functions
 
<In Scratch>
: Used say block to display any text on the screen
<In C>
: function printf
 

printf ("hello, world\n");

 
 
 
 
 
4. Variables
 
<In Scratch>
: we had the ability to ask the user “What’s your name?” and say “hello” with that name appended to it.
<In C>

#include <stdio.h>

int main(void)
{
   string answer = get_string("What's your name? ");
   printf("hello, %s\n", answer);
}

 
1) get_string (function) : to get a string from the user
2) %s                               : a placeholder called a format code that tells the printf function to prepare to receive a string.
3) answer (variable)       : is of type string and can hold any string within it. 
**There are many data types such as int, bool, char, etc.
 
-> Notice that numerous errors appear when running make hello because string and get_string are not recognized by the compiler. 
 

#include <cs50.h>
#include <stdio.h>

int main(void)
{
   string answer = get_string("What's your name? ");
   printf("hello, %s\n", answer);
}

Notice that #include <cs50.h> has been added to the top of your code.
-> Now works!
 
 
There are many format codes :

%c
%f
%i
%li
%s

%s  is used for string variables. %i is used for int or integer variables.
 
 
 
 
 
5. Conditionals
 
*In C, you can assign a value to an int or integer as follows:

int counter = 0;

 
*You can add one to counter as follows:

counter = counter + 1;

 
also as:

counter = counter ++;

 
 
Let's use this new knowledge to write some conditionals!
For example, you might want to do one thing if x is greater than y / something else if that condition is not met.
 
<In Scratch>
If ~ then, If ~ else ~
<In C>

#include <cs50.h>
#include <stdio.h>

int main(void)
{
   int x = get_int("What's x? ");
   int y = get_int("What's y? ");
   
   if (x < y)
   {
      printf("x is less than y\n");
   }
}

 
Flow charts are a way by which you can examine how a computer program functions. Such charts can be used to examine the efficiency of our code :

#include <cs50.h>
#include <stdio.h>

int main(void)
{
   int x = get_int("What's x? ");
   int y = get_int("What's y? ");
   
   if (x < y)
   { 
      printf("x is less than y\n");
   }
   else if (x > y)
   {
      printf("x is greater than y\n");
   }
   else 
   {
      printf("x is equal to y\n");
   }
}

-> You can see the efficiency of our code design decisions.
 
 
**string vs char
string : a series of characters
char   : a single character
 
Using char in conditionals : 

#include <cs50.h>
#include <stdio.h>

int main(void)
{
   // Prompt user to agree
   char c = get_char("Do you agree? ");
   
   // Check whether agreed
   if (c == 'Y' || c == 'y');
   {
      printf("Agreed.\n");
   }
   else if (c == 'N' || c == 'n');
   {
      printf("Not agreed.\n");
   }
}

 
1) == : something is equal to something else
2) ||   : or
 
 
 
 
 
6. Loops
 

  • How to make computer say 'meow' three times?

 
1) simply copy + paste

#include <stdio.h>

int main(void)
{
     printf("meow\n");
     printf("meow\n");
     printf("meow\n");
}

=> But we have an opportunity for better design!
 
 
 
2) while loop

#include <stdio.h>

int main(void)
{
     int i = 0;
     while (i < 3)
     {
          printf("meow\n");
          i++;
     }
}

 
we can even loop forever using the following code:

#include <stdio.h>
#include <cs50.h>

int main(void)
{
     while (true)
     {
          printf("meow\n");
     }
}

 
 
 
3) for loop + create my own function

void main(void)
{
     printf("meow\n");
}

=> void main (void)
 void   : the function does not return any values.
(void) : no values are being provided to the function. 
 

#include <stdio.h>

void meow(void);

int main(void)
{
      for(int i = 0; i < 3; i++)
      {
           meow();
      }
 }
 
 void meow(void)
 {
     printf("meow\n");
 }

=> Notice that meow function is defined at the bottom of the code & the prototype of the function is provided at the top of the code as void meow(void);
 

#include <stdio.h>

void meow(int n);

int main(void)
{
     meow(3);
}

// Meow some number of times
void meow(int n)
{
     for (int i = 0, i < n; i++)
     {
          printf("meow\n");
     }
}

=> This is a better design because if you want to change the number of times saying 'meow', you can just change the number of 'n'.
 
 
 
 
7. Operators and Abstraction

  • How to implement a calculator in C.

1) simple way 

#include <stdio.h>
#include <cs50.h>

int main(void)
{
     // Prompt user for x
     int x = get_int("x : ");
     
     // Prompt user for y
     int y = get_int("y : ");
     
     // Perform addition
     printf("%i\n", x + y);
}

%i  : be ready to print the value of x + y, which is int
 
Mathematical operators included in C :
+  (addition)
-   (subtraction)
*   (multiplication)
/    (division)
%  (for remainder)
 
 
2) add function

#include <stdio.h>
#include <cs50.h>

int add(int a, int b);

int main(void)
{
   int x = get_int("x: ");
   
   int y = get_int("y: ");
   
   int z = add(x, y);
   printf("%i\n", z);
}

int add(int a, int b)
{
     int c = a + b;
     return c;
}

=> However, do we actually need variable z & c?
 
It can be further improved as follows:

#include <stdio.h>
#include <cs50.h>

int add(int a, int b);

int main(void)
{
   int x = get_int("x: ");
   
   int y = get_int("y: ");
   
   printf("%i\n", add(x,y));
}

int add(int a, int b)
{
   return a + b;
}

=> We can put add function in printf function.
 
 
 
3) truncation : truncates a double value after the decimal point and gives the integer part as the result.

#include <stdio.h>
#include <cs50.h>

int main(void)
{
   long x = get_long("x: ");
   
   long y = get_long("y: ");
   
   printf("%li\n", x + y);
}

 
 
 
 
 
8. Linux and the Command Line
 
- Linux : an operating system that is accesible via the command line in the terminal window in VS Code.

  • cd : for changing our current directory
  • cp : for copying files and directories
  • ls   : for listing files in a directory
  • mkdir : for making a directory
  • mv : for moving (renaming) files and directories
  • rm : for removing (deleting) files
  • rmdir : for removing (deleting) directories

 
 
 
 
9. Mario
 

1) How to represent these four horizontal blocks?

#include <stdio.h>

int main(void)
{
   for (int i = 0; i < 4; i++)
   {
        printf("?");
   }
   printf("\n");
}

 
 

 
2) How to represent these three vertical blocks?

#include <stdio.h>

int main(void)
{
   for (int i = 0, i < 3; i++)
   {
      printf("#\n");
   }
}

 
 
 

 
3) How to make a three-by-three group of blocks?
 

#include <stdio.h>

int main(void)
{
   for (int i = 0; i < 3; i++)
   {
      for (int j = 0; j < 3; j++)
      {
         printf("#");
      }
      printf("\n");
   }
}

=> ###
     ###
     ###
Notice that one loop is inside another.
 
 
4) What if we want to ensure the number of bloks to be constant = unchangeable?

#include <stdio.h>

int main(void)
{
   const int n = 3;
   for (int i = 0; i < n; i++)
   {
      for (int j = 0; j < n; j++)
      {
         printf("#");
      }
      printf("\n");
   }
}

=> now n is a constant, which means it can never be changed. 
 
 
5) How to prompt the user for the size of the grid?

#include <stdio.h>
#include <cs50.h>

int main(void)
{
   int n = get_int("Size: ");
   
   for (int i = 0; i < n; i++)
   {
      for (int j = 0; j < n; j++)
      {
         printf("#");
      }
      printf("\n");
   }
}

=> get_int
 
 
★ We can protect our program form bad behavior by checking to make sure the user's input satisfies our needs.

#include <stdio.h>
#include <cs50.h>

int main(void)
{
   int n;
   do
   {
      n = get_int("Size: ");
   }
   while (n < 1);
   
   for (int i = 0; i < n; i++)
   {
      for (int j = 0; j < n; j++)
      {
         printf("#");
      }
      printf("\n");
   }
}

=> Now the user will be continuously prompted for the size until the user's input is 1 or greater.
 
 
 
 
10. Comments
 
-where you leave explanatory remarks to yourself and others.
-each comment is a few words or more, providing the reader an opportunity to understand what is happening in a specific block of code.
-form : // comment

#include <cs50.h>
#include <stdio.h>

int main(void)
{
   //Prompt user for positive integer
   int n;
   do
   {
      n = get_int("Size: ");
   }
   while (n < 1);
   
   // Print a n-by-n grid of bricks
   for (int i = 0; i < n; i++)
   {
      for (int j = 0; j < n; j++)
      {
         printf("#");
      }
      printf("\n");
   }
}

 
 
 
 
 
11. Types
 
 
-Types refer to the possible data that can be stored within a variable. 
Ex) char : a single character like 'a' or '2'.
 
-Types are very important because each type has specific limits.
Ex) the highest value of int : 4294967295
 

  • bool : a Boolean expression of either true or false
  • char : a single character like 'a' or '2'
  • double : a floating-point value with more digits than a float
  • float : a floating-point value, or real number with a decimal value
  • int : integers up to a certain size, or number of bits
  • long : integers with more vits, so they can count higher than an int
  • string : a string of characters

'CS50' 카테고리의 다른 글

[CS50] Week 2 Review  (2) 2024.09.23
[CS50] Week 1 Section + Pset 1 : Mario-more  (0) 2024.09.15
[CS50] Pset 1 : Credit  (1) 2024.09.13
[CS50] Week 0 Review  (2) 2024.08.28
[CS50] 코딩 공부 시작  (0) 2024.08.18

 Week 0 


 Lecture Contents

 

 

  1. What is Computer Science?

Computer Programming is taking some input and creating some output : solving a problem.


input ->

black box -> output

* the black box is the focus

 

 

 

  2. Unary vs Binary - how to present NUMBERS

 

- Unary : one finger at a time (one, two, three, four...)

- Binary : a number system based only on the numerals 0 and 1 

ex) 0 = 00000000                 5 = 00000101

      1  = 00000001                  6 = 00000110

      2  = 00000010                  7 = 00000111

      3  = 00000011                  8 needs more bits(meaning binary digits) = 00001000

      4  = 00000100

 

=> Computers use 'base-2' form to count.

      ... 2^3    2^2    2^1    2^0

      ... 8        4         2        1

 

-Computers usually use 8 digits to count numbers. 

ex) 11111111= 255

 

 

 

   3. ASCII - how to present LETTERS

 

We use ASCII because of an overlap of the zeros and ones that represent numbers and letters. 

The map of ASCII values was created to map specific letters to specific numbers.

ex) to say HI! 

->  H    I     !

     72  73  33

= 01001000   01001001   00100001

 

 

 

4. Unicode - how to present EMOJI

 

Unicode expanded the number of bits that can be transmitted and understood by computers.

-Unicode for thumbs up 👍🏻 :

U+1F44D

 

-Unicode for the same thumbs up, but with a different skin tone 👍🏼 :

U+1F44D  U+1F3FD

 

 

 

5. RGB Representation - how to present COLORS

 

RGB (red, green, and blue) is a combination of three numbers.


red
72


green
73
blue
33

the result

-> 72/73/33 was HI! in letters, but it represents this color in RGB representation.

 

 

 

6. How to present IMAGES, VIDEOS, and MUSIC

 

-images : collections of RGB values

-videos : sequences of many images

-music : can be represented through MIDI data

 

 

 

7. Algorithms 

 

Problem solving is central to computer programming.

 

Q. How to locate a single name in a phonebook?

a. simply read from page one to the next to the next until reaching the last page

b. search two pages at a time

c. go to the middle of the phone book and ask, “Is the name I am looking for to the left or to the right?” Then, repeat

    this process, cutting the problem in half and half and half.  

-> each of these is algorithm

( red : a / yellow : b / green : c )

 

 

 

8. Pseudocode

 

Pseudocode is a human-readable version of your code. It is important for 2 reasons. 

1. It allows you to think through the logic of your problem in advance.

2. You can later provide this information to others that are seeking to understand your coding decisions and how your

    code works.

 

Composition of Pseudocode : 

  • functions 
  • conditionals
  • boolean expressions (true/ false)
  • loops 

 

 

9. Artificial Intelligence

 

What if there are thousands of possible interactions? Do we need to write tons of pseudocodes?

-> NO! 

 

-LLM (Large Language Model) : a type of AI program that can recognize and generate text, among other texts. 

 

 

 

10. Scratch

 

Scratch is a coding language with a simple visual interface.

 

It looks like this :

 

 

 

 

 


 

What I learned

 

I've never seriously learned about computer science or computer programming except one C# class I took in Korea.

When I was in that class, I thought computer programming is all about difficult pseudocodes, signs, numbers, ... etc because that's all I had learned from it. However, I realized that what I learned is just the tip of the iceberg. What really matters is that computer programming actually helps me think and figure out more deeply to solve problems when we face them. I've learned it while solving Problem Set 0 -which is your assignment for week 0- using Scratch, but I'll talk about it more in detail in the next post about my Problem Set 0. The professor is a lot more passionate about what they study and teach, what they say is easy to hear and understand. Also there is an AI dog professor as well. (He's so cute. I don't remember his name but I'm super impressed by the intelligence he has and how well he was made.) I'm really looking forward to the next week's lecture! 

'CS50' 카테고리의 다른 글

[CS50] Week 2 Review  (2) 2024.09.23
[CS50] Week 1 Section + Pset 1 : Mario-more  (0) 2024.09.15
[CS50] Pset 1 : Credit  (1) 2024.09.13
[CS50] Week 1 Review  (1) 2024.09.10
[CS50] 코딩 공부 시작  (0) 2024.08.18

1. CS50 소개

CS50: Introduction to Computer Science

미국 하버드 대학교에서 무료로 제공하는 컴퓨터 언어 (C, Python, SQL, and JavaScript plus CSS and HTML) 강의!

온라인 영어 강의이고, 하버드 대학교 computer science 교수님들이 강의를 해주신다.

무료이지만 $219를 내면 수강을 완료했다는 Verified Certificate도 발행해준다. $153.30으로 할인 중이네요

공식 홈페이지에는 한 주에 10-20시간씩 총 11주가 걸린다고 나와 있다.

꽤나 많은 시간을 들여야 하는데, 나는 1주일에 15시간을 잡았더니 3hrs x 5days, 평일 하루에 3시간씩 투자를 해야한다.

이렇게 했을 때 2024년 12월 말까지 완료하는 것으로 목표를 잡을 수 있었다!

 

 

 

 

 

2. 코딩을 배우는 이유

갑자기 코딩을 왜 배우냐?

첫 번째 이유는 컴퓨터 지식의 필요성을 느꼈기 때문이다.

대학교 휴학 직전 학기 졸업 요건 충족차 C언어 과목을 수강했다. 나는 컴퓨터 프로그래밍과는 거리가 멀다고 생각했는데, 내가 생각한대로 웹사이트를 만들거나 의도한대로 식의 답을 도출해낼 수 있는 컴퓨터 언어를 배우기 시작했을 때, 멀게 느껴졌던 것은 그저 경험의 부재에서 비롯된 것이란 걸 깨달았다. 경험하고 보니 파고들수록 재밌는 학문이었다. 최근 사무직 알바 지원 과정에서 워드나 엑셀 등 컴퓨터 지식의 필요성을 느끼며 컴퓨터를 조금 더 잘 알고싶은 욕구가 생기게 되었다. 컴퓨터 언어는 그 중 하나이고, 재미를 느꼈던 과목이니 C언어를 포함해 조금 더 다양한 언어들을 공부해보고자 강의를 찾게 되었다. 요즘은 컴퓨터를 잘 다룰 수 있는 능력이 꽤나 중요해졌기도 하고, 코딩은 엑셀이나 워드보다는 취준 때 나의 경쟁력을 조금 더 높여주지 않을까 하는 현실적인 이유도 있다.

두 번째 이유는 솔직히 말해서 그냥 재미있을 것 같았기 때문이다. ㅎ

원래도 인풋이 있을 때 아웃풋이 답으로 정확히 나오는 수학같은 학문을 좋아하는 편이다. 내가 설계한 대로 컴퓨터가 계산을 하고 게임화면을 만들고 웹사이트를 디자인한다니! 참 매력적인 것 같다. 물론 그만큼의 노력이 수반되어야 하겠지만 ...^^

세 번째 이유는 무엇이든 배우고 싶었기 때문이다!

학구열이 높은 편은 아니었는데 요즘은 새로운 걸 배우는 것이 즐겁다. 예를 들면 요즘 요가나 러닝 같은 내 몸과 친해지는 활동에 푹 빠졌는데, 내 머리도 너무 쉰 게 아닐까.. 그래서 머리를 쓰고 싶었다. 이러다 뇌가 평평해지는 게 아닐까 하는 ㅎㅎ 걱정도 들고

이왕 공부할 거 정말 새로운 것을 배워보고 싶었고, 내가 못하는 것을 배워보고 싶었다. 사실 나는 약간 특이한(?) 성향이 있는데 내가 못하는 것이나 부족한 것들을 다방면에서 채워나가는 과정이 참 좋다. 그래서 육각형을 꽉 채우고 싶어하는 .. 완벽주의자? 음

그래서 내가 못하는 분야를 환영한다! 못하면 새롭게 배우면 되는 거니까~

 

 


 

 

올해 안에 내가 정말 이 프로그램 수강을 완료하면 참 뿌듯할 것 같다.

항상 나에게 부족한 끈기를 이 수업이 내게 선물해주면 좋겠다.

맨 아래에 강의 홈페이지 링크를 첨부하니 누구든 나랑 가치 하장 ㅎㅎ!

2024.08.15 ~

 

 

 

https://pll.harvard.edu/course/cs50-introduction-computer-science

 

CS50: Introduction to Computer Science | Harvard University

An introduction to the intellectual enterprises of computer science and the art of programming.

pll.harvard.edu

 

'CS50' 카테고리의 다른 글

[CS50] Week 2 Review  (2) 2024.09.23
[CS50] Week 1 Section + Pset 1 : Mario-more  (0) 2024.09.15
[CS50] Pset 1 : Credit  (1) 2024.09.13
[CS50] Week 1 Review  (1) 2024.09.10
[CS50] Week 0 Review  (2) 2024.08.28

+ Recent posts