-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)
{
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:
#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.
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");
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)
: 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 chartsare 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 putadd functioninprintf 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
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!
꽤나 많은 시간을 들여야 하는데, 나는 1주일에 15시간을 잡았더니 3hrs x 5days, 평일 하루에 3시간씩 투자를 해야한다.
이렇게 했을 때 2024년 12월 말까지 완료하는 것으로 목표를 잡을 수 있었다!
2. 코딩을 배우는 이유
갑자기 코딩을 왜 배우냐?
첫 번째 이유는 컴퓨터 지식의 필요성을 느꼈기 때문이다.
대학교 휴학 직전 학기 졸업 요건 충족차 C언어 과목을 수강했다. 나는 컴퓨터 프로그래밍과는 거리가 멀다고 생각했는데, 내가 생각한대로 웹사이트를 만들거나 의도한대로 식의 답을 도출해낼 수 있는 컴퓨터 언어를 배우기 시작했을 때, 멀게 느껴졌던 것은 그저 경험의 부재에서 비롯된 것이란 걸 깨달았다. 경험하고 보니 파고들수록 재밌는 학문이었다. 최근 사무직 알바 지원 과정에서 워드나 엑셀 등 컴퓨터 지식의 필요성을 느끼며 컴퓨터를 조금 더 잘 알고싶은 욕구가 생기게 되었다. 컴퓨터 언어는 그 중 하나이고, 재미를 느꼈던 과목이니 C언어를 포함해 조금 더 다양한 언어들을 공부해보고자 강의를 찾게 되었다. 요즘은 컴퓨터를 잘 다룰 수 있는 능력이 꽤나 중요해졌기도 하고, 코딩은 엑셀이나 워드보다는 취준 때 나의 경쟁력을 조금 더 높여주지 않을까 하는 현실적인 이유도 있다.
두 번째 이유는 솔직히 말해서 그냥 재미있을 것 같았기 때문이다. ㅎ
원래도 인풋이 있을 때 아웃풋이 답으로 정확히 나오는 수학같은 학문을 좋아하는 편이다. 내가 설계한 대로 컴퓨터가 계산을 하고 게임화면을 만들고 웹사이트를 디자인한다니! 참 매력적인 것 같다. 물론 그만큼의 노력이 수반되어야 하겠지만 ...^^
세 번째 이유는 무엇이든 배우고 싶었기 때문이다!
학구열이 높은 편은 아니었는데 요즘은 새로운 걸 배우는 것이 즐겁다. 예를 들면 요즘 요가나 러닝 같은 내 몸과 친해지는 활동에 푹 빠졌는데, 내 머리도 너무 쉰 게 아닐까.. 그래서 머리를 쓰고 싶었다. 이러다 뇌가 평평해지는 게 아닐까 하는 ㅎㅎ 걱정도 들고
이왕 공부할 거 정말 새로운 것을 배워보고 싶었고, 내가 못하는 것을 배워보고 싶었다. 사실 나는 약간 특이한(?) 성향이 있는데 내가 못하는 것이나 부족한 것들을 다방면에서 채워나가는 과정이 참 좋다. 그래서 육각형을 꽉 채우고 싶어하는 .. 완벽주의자? 음