[CS50x] Lecture 1.

2021. 5. 14. 00:03Data science

반응형

Lecture 0 was about basic concepts of computational language and using scratch to understand the basic logic of it.

I have created some scratch projects and submitted one of them(which is not completed 100%) 

I am going to update it sometime soon. 

 

Lecture 1 has 2 labs and 2 assignments. (I have done 3 of them and 1 more to be submitted) 

It's so good to have such labs and assignments so that I can understand the theories along with the actual practices. (Actually, for me, the one who didn't study CS before, it's not easy at all.)

 

what to consider for the quality 

Correctness 

Design: more efficient, well-written, w/o unnecessary repetition

Style: aesthetic, consistent indentation, affect how readable it is visually

 

CS50 IDE(Integrated Development Environment) - ide.cs50.io

Command Line Interface(CLI): prompt at which we need to enter text commands

- Scratch is a graphical user interface(GUI)

 

Compiling

the compiler takes source code(we write) as input and produces machine code as output 

- use "make" to access a compiler in CS50 IDE 

the compiler is the interpreter between computer and human 

the computer speaks with the patterns of 0 and 1 (binary)

 

functions, arguments, parameters

*Functions: small actions or verbs, programmed version of an algorithm

- can have side effects: visual side effect-> different form (printed to the screen)

- return values, variables 

*Arguments: the input to functions

*Library: a bunch of code already written 

- string is word, text, letter etc. 

string answer = get_string("What's your name?"); 

- right values to input left variable 

- datatype should be declared as well -> string 

printf("hello, %s" answer);
//printf: print also format code %s-> plug in some actual value (string type)

- use the return value(stored one) by using %s (format code) 

- put the following value into %s 

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

int main(void)
{
	string answer = get_string("What is your name?);
    printf("hello, %s", answer); 
}
#need to be re-compile

- Why do we have to re-compile it every single time? It's because C is an old language. 

- \n:  move the cursor to the next line by using \n. (escape sequence)

- do the right-hand side functions and save them to the left-hand-side variable. 

 

main, header files

int main(void)
{

}

- main: This is the same as  "when flag clicked"

- header file ends with .h : some other set of code like a library

 i.e. #include <stdio.h> : standard input output dot h. (famous c file)

 

Tools

- help50, styke50, check50 

- type this on the terminal: help50 make hello, syte50 hello.c, check50 cs50/problems/hello ->github username and pwd

- comment(//blah blah ~):  the purpose of the code to be presented

 

Command 

- ls: list of the contents 

- rm: remove 

- mv: move (rename the file: mv hello.c goodbye.c) 

- mkdir: make a directory

- mv hello.c lecture/ : move to the lecture directory(folder)

- cd lecture/: go inside of lecture directory 

- mv helloc.c ..: move the file to the folder up above(parent folder) 

- cd ..: go up to the parent folder 

- rmdir: remove directory 

- ..(double dot) parent directory , .(single dot) current directory

- source code: hello.c, machine code: hello(contains only 0 and 1) -> hello*(shown in the terminal when you check the ls) when you compile this file will be created automatically

 

+From the short Clip 

: can be used within the IDE or any UNIX-based system

: ls - list (read out all the files and folders from the current directory)

: cd- change directory ( cd directory or dot(.) or double dot(..) - go to the parent directory)

: pwd - present working directory ( ~/: tilde is home directory )

: cd enter -> go to tilde(~) 

: mkddir - make a directory 

: cp - copy ( cp <source><destination> : copy a file -> cp hello.txt hi.txt ) 

: copy whole directory -> cp -r pset0 pset3 

: rm - remove the file ( rm -f <file> : no undo(force to remove wo question) / rm -r <directory> : get rid of the directory including whole contents in it / rm -rf <directory> : get rid of the directory completely wo question and no undo

: mv - move location ( mv greddy.c greedy.c : rename the file / 

 

more to discover ... 

chmod 

Ln

touch

rmdir

man

diff

sudo

clear 

telnet  

 

DataType & variable 

Int 

- from "- 2 to the 31st power" to "2 to the 31st power -1" (because of zero)

***unsigned int( %u ): instead of storing negative values, storing only positive values : "0 to 2 to the 32nd power-1 "(0 to 4 billion)

 

 

 

 

 

 

 

 

Char: 0 to 127 characters 

Floating: 4 bytes memory, decimal parts, have a precision problem(we cannot so precise with limited digits(32 btis))

Double: 8 bytes memory, same as float but it can have 64 bits 

 

Void: this is not a data type, it's a type. The function can have a void return type(no output-i.e.printf) main doesn't take any arguments(it's also void) 

 

  • For printf, too, there are different placeholders for each type:
    • %c for chars
    • %f for floats, doubles
    • %i for ints
    • %li for longs
    • %s for strings

 

*cs50.h to be included 

bool: Boolean data type, True or False(In C, this is not a standard default)

String: word, collections of characters, long or short series of characters  

 

*Creating variable : declare datatype and variable name -> int number; , char letter; you can also declare multiple variable(if they are same data type -> int height, weight; )

*declaration->assignment. / initialization(declare and assignment at the same time)  

: int number; -> number = 17; / int number = 17;

 

Operator 

Methematical operations

+ for addition

- for subtraction

* for multiplication

/ for division

% for remainder

Boolean operators 

- 0 is false, non-zero is true 

*Logical operators

- And(&&): true only when both are true. 

- OR( || ): False only when both are false 

- NOT( ! ) : opposite 

*Relational operators 

- less than , less than or equal to , greater than, greater than or equal to 

- Equality (==), inequality (!=) ; double equal for this case ! 

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

int main(void)
{
    int x = get_int("x: ");

    int y = get_int("y: ");

    printf("%i\n", x + y);
    //put number in i(i dont know what this is)
}

- if you input not an integer, it's going to be ignored until you input the integer value.

- If you input 4 billion or 3 billion, it's going to be ignored again. (int only use 32 bits total - roughly as high as 4 billion including negative and zero; 2 billion to the negative and positive directions) 

- what if we use "long(64 bits)" instead of int. ↓

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

int main(void)
{
    long x = get_long("x: ");

    long y = get_long("y: ");

    printf("%li\n", x + y);
	//%li for long
}

- it works with 4 billion 

 

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

int main(void)
{
    // Get numbers from user
    int x = get_int("x: ");
    int y = get_int("y: ");

    // Divide x by y
    float z = x / y;
    printf("%f\n", z);
}

- logically correct. But the result is given back the integer divide by integer-> lose all of the decimal point values 

- The math is already done from the right-hand side, so even though z is float, the result is already int 

- you can change the whole code, but you can also do casting.

- cast: the data type to another 

float z = (float) x / (float) y;

-after casting x and y, you will find the result is also float type. Indeed working. 

 

Conditional statements

if, ifelse, else - use boolean expression to make a decision 

 

switch: depends on what user types 

- use "break" or you will fall through each case

 

 

 

 

 

 

 

 

 

? : - ternary operator (simulate if - else) 

- if expr is true, first value , if its not later value. 

  int x = (expr) ? 5 : 6; 

 

 

 

 

 

 

 

 

 

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

int main(void)
{
    // Prompt user for x
    int x = get_int("x: ");

    // Prompt user for y
    int y = get_int("y: ");

    // Compare x and 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");
    }
}

- condition 

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

int main(void)
{
    char c = get_char("Do you agree? ");

    // Check whether agreed **Y and N to be quoted
    if (c == 'Y' || c == 'y')
    {
        printf("Agreed.\n");
    }
    else if (c == 'N' || c == 'n')
    {
        printf("Not agreed.\n");
    }
}

 

Loops( forever in the scratch ) - 3 majors

while(true): over and over and forever. (infinite loop) true is always true. until we find a break or kill the programming run 

while(boolean expression): until the boolean expression becomes false code inside of curly brace will last. 

do { } while(boolean expression): boolean expression is true, go back to do. at least do 1 time no matter it's true or not

for loop: for(int i=0; i<10; i++) {body}

-> for( 1 variable declare ; 2 boolean expression ; 4 finally counter variable is incremented ;) : { 3 body executed} 

-> 1 2 3 4 2 3 4 2 3 4 ... eventually i =10 then, stop the loop 

** Use a while loop when we want a loop to repeat an unknown number of times(might not run at all): keep updating or moving things no matter how long the user plays the game 

** do-while loop when you don't know how many times to repeat, but run at least one; prompting the user for input 

** for a loop when you know a discrete number of times, though you might not know the number 

while(true)    //to make infinite loop input True 
{
	printf("hello, world\n");
}
int i = 0; 
while(i<50)                     //counting up to number 50
{
	printf("hello, world\n");   //keep printing this 
	i++;                        //i = i +1; , i += 1; 
}
int i = 1;                       //count through 50
while (i <= 50)
{
    printf("hello, world\n");
    i++;
}

//this is not conventional 

- There are various ways to solve the problems. But it's highly recommended you use the conventional ways. 

for (int i = 0; i < 50; i++)
{
    printf("hello, world\n");
}
//inside of the parenthesis in for clause, you can put more then boolean and also more than 1 line)

- The most convenient ways to conduct. 

 

Abstraction: problem-solving principle 

- better design: flexibility to reuse the function in multiple places 

#include <stdio.h>

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

- this is not a good design

#include <stdio.h>

int main(void)
{
    for (int i = 0; i < 3; i++)  //initialize the values, check the condition , add the number
    {
        printf("meow\n");
    }
}
#include <stdio.h>

void meow(void) {                 //create own custom functions "meow" 
  printf("meow\n");
}

int main(void)
{
    for (int i = 0; i < 3; i++)
    {
        meow();					 //call this function
    }
}
#include <stdio.h>

void meow(void);             //meow function is declared at the end it's because it's customed functions

int main(void)
{
    for (int i = 0; i < 3; i++)
    {
        meow();            //but if you don't declare this function before this command, it will cause an error
    } 
}

//Ususally put the custom functions at the bottom of code 
//Because main function rathen being at the top

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

- give the hint on the top, it's called prototype,(not declare it yet), to make sure that code is compiled successfully. 

#include <stdio.h>

void meow(int n);  //prototype

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

void meow(int n)
{
    for (int i = 0; i < n; i++)
    {
        printf("meow\n");
    }
}
#include <cs50.h>
#include <stdio.h>

int get_positive_int(void);   //prototype : will be declared later 

int main(void)                //main function
{
    int i = get_positive_int();   //user will input the data 
    printf("%i\n", i);
}

// Prompt user for positive integer
int get_positive_int(void)       //customed function, no input: void 
{
    int n;
    do
    {
        n = get_int("Positive Integer: ");    //scope of variable: inside of the curly brace (check below comment
    }
    while (n < 1);            // not negative integer, until it returns positive value, repeatedly do "do" 
    return n;
}

- if you declared the variable type inside of the curly brace, you cannot use it outside of the curly brace. so assign it earlier

 

Mario

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

int main(void)
{
    for (int i = 0; i < 3; i++)
    {
        for (int j = 0; j < 3; j++)
        {
            printf("#");
        }
        printf("\n");   //every single time after printing J
    }
}

 

Memory, imprecision, and overflow

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

int main(void)
{
    float x = get_float("x: ");
    float y = get_float("y: ");

    printf("%.50f\n", x / y);    
    //to print more than significant digit->%.50f: 
    //the number of decimal places displayed
}

-> floating-point imprecision: not enough bits to store all possible values, computer store the closest values it can

- Integer overflow: 2 billion int + 2 billion ints? (over 32 bits) , date data: 19 Jan 2038 already reaches 4 billion 

 

 

 

 

 

 

 

 

 

command line 

: can be used within the IDE or any UNIX-based system 

: ls - list (read out all the files and folders from the current directory)

: cd- change directory ( cd directory or dot(.) or double dot(..) - go to the parent directory)

: pwd - present working directory ( ~/: tilde is home directory )

: cd enter -> go to tilde(~) 

: mkddir - make a directory 

: cp - copy ( cp <source><destination> : copy a file -> cp hello.txt hi.txt ) 

: copy whole directory -> cp -r pset0 pset3 

: rm - remove the file ( rm -f <file> : no undo(force to remove wo question) / rm -r <directory> : get rid of the directory including whole contents in it / rm -rf <directory> : get rid of the directory completely wo question and no undo

: mv - move location ( mv greddy.c greedy.c : rename the file / 

 

more to discover ... 

chmod 

Ln

touch

rmdir

man

diff

sudo

clear 

telnet  

반응형