Viren Bhagat

My Notes: C (CS50)

3/20/2020

Lecture 1 of CS50 is dives more into using a programming language (instead of Scratch) and opts to teach and learn with C. Per Wikipedia, "C, as in the letter c) is a general-purpose, procedural computer programming language supporting structured programming, lexical variable scope, and recursion, while a static type system prevents unintended operations. By design, C provides constructs that map efficiently to typical machine instructions and has found lasting use in applications previously coded in assembly language. Such applications include operating systems and various application software for computers, from supercomputers to embedded systems."

I believe it is a good language to start with but is a little old and maybe wouldn't be used in a modern day job (as a web/FE/software engineer).

Scratch provided a more visual and easier to grasp GUI type of environment for programming as where while using C, you are using a text editor and a terminal.

Scratch vs Code Editor

CS50 provides a code sandbox to write and execute your code. It is found here. Here is a little overview of what it looks like, also some rules and syntax of C and the sandbox.

cs50sandbox

#include <stdio.h>

Line 1: Importing C Standard Input/Output Library - need to include library to access in-built functions (like printf), etc. (if anyone reads this and has worked with JS, I think of importing packages from npm) (Helpful Quora link explaining more about stdio.h) --

int main(void) { }

Line 3: int main(void) { } -- this is a function defintion

  • main is the name of the first function in your program when you run it
  • int is a data type which would be returned (will talk about data types). for main function, it should always return int
  • void is the the input or parameters expected into the function
  • curly braces are where you put what the function will run (print statement, loops, etc.)

--

printf("Hello\n"); 

Line 4: print statement displays the input in the parentheses next to it into the terminal. the f in printf is for formatted. "Hello" is a string (another data type) and double quotes must be used. The \n is to provide a line break. Semicolons must be used, think of it as a period to end a sentence in English language.

Once you write out some valid program, you need to run it in the terminal. There is no 'run' button like in a GUI or in Scratch. CS50 Sandbox uses Clang to compile your program into readable code for the computer. It outputs a new file which the computer can read and execute.

  1. create file, hello.c (.c for C language)
  2. write code
  3. save and enter 'make hello' into terminal
  4. compiler outputs machine code in file 'hello'
  5. in terminal, execute ./hello
  6. Output in terminal, "Hello"

hello.c --> make hello (command in terminal) --> hello

Source Code (C, Python, etc.) --> Compiler --> Machine Code (binary, 0s and 1s)

--

The Command Line (Terminal) Again, not being in Scratch, the user interface is a little different. You can type commands in the terminal to look up files and directories among another thing. It is a very power thing within programming. Here is a list of a few important commands. ls (list of files & folders in direct), pwd (print working directory - shows where you are), mkdir (make directory), and so on.

--

User Input

So far, we've just shown you how to print a string ("Hello"). Part of programming is input. Taking that input, doing something with it, and producing the output. Within a library in C, which we can include in our code, there are pre-built functions in order to obtain input from the user.

get_string("Whats your name?\n");

This function prompts a user, via command line, asking for the user's name. Again, we see the word string. A string is a text based data type, made up of multiple chars (characters). If you put getstring into your int main(void) function, the terminal will prompt you, and you can enter your input, but nothing happens after that. See below code on something else we can do with getstring, more useful I'd argue.

get_string variable example

It is using get_string() again, but we are introducing a variable here now. A variable is essentially a way to store data in memory. So once a user enters a name, that string value will be saved within a variable. One other thing is the type is in front of the variable. You must declare the type of data that is being saved in the variable (again, JS peeps, this is different. I think this is what TS(?) does). In line 7, we see something different as well, %s. This is a placeholder for the variable, it is an s for data type string. We also had to to include one more library on line 2 for this program.


Numbers & Incrementing Values in C

Another data type in C is integer (int). Integers are just number values. It can be initialized like below -

int counter = 0;

Two things to note, we are beginning the variable declaration with the type in front (int). Also we are setting counter to 0. In real life, = represents equality. In programming, = represents assignment.

The variable counter can be incremented or decremented in a few ways. Once intialized like above,

  • counter = counter + 1;
  • counter += 1;
  • counter++;
  • counter = counter - 1;
  • counter -= 1;
  • counter--;

Conditionals in C

Conditionals are a way to control the logic in programming. If this number is bigger than that number, print out the bigger number. Or vice versa. It is easier to see a visual representation but you can do a lot with if/else statements when writing your code.

if (x < y)
{
    printf("x is less than y\n");
}
else if (x > y)
{
    print("x is greater than y\n");
}
else 
{
    printf("x is equal to y\n");
}

This code block would run top down, going through the first conditional. if it is true, it will print that statement and end running. If the first conditional is false, it will run the else if, checking for truthiness. If not, it will print the else statement.


Loops

A loop statement is intended to run the same code more than one. It is tied in with conditionals. If statement is true, repeat the code. Check the statement again and run if its true. There are a few different loops. For loops, while loops, and do...while loops.

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

int main (void)
{
  int counter = 5;
  while (counter > 0) 
   {
      printf("Counter is at %i\n", counter);
      counter--;
   }
}

This is an example of a while loop. We create a integer variable, set it to 5. While the variable is greater than 0, we print the counter. Each loop, we also subtract 1 from the counter variable. If we did not include this statement, it would turn into an infinite loop and probably crash the program.

A for loop is structured a little different, example below -

for (int i = 0; i < 5; i++) 
{
    printf("We're at step %i\n", i);
}

The intialized integer, conditional, and increment is all done in one line.


Data Types in C

There are many data types in C, but we mainly deal with

-bool (Boolean, true or false value) -char (Single character) -float (Floating point, number w/ decimal) -int (integer, a number) -long (very large number, like in the billions) -string (multiple chars together, words, sentences, etc.)


Operations in C

Most operators are straight forward. + for addition, - for subtraction,

  • for multiplication, / for division. The % symbol is used for a remainder.

    9 % 5 == 4 8 % 4 == 0 10 % 3 == 3

If you see, ||, that equates to OR. If you see &&, that equates to AND.


Customs Functions in C

So far, we've seen a few built in functions (get_string(), and the general main()) one, but we're allowed to make our own functions in C (you would hope so right?!).

#include <stdio.h>

void hello(void);

int main(void)
{
  hello();
  hello();
  hello();
}

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

So in the above code, we made our own custom function, hello(). It doesn't take in any input or any output besides a print statement. We have to reference it before the main function because it is not defined otherwise. C is read top to bottom, left to right. If the computer is going down the lines of code, hello is referenced in main but would not yet have been defined.

Void means it takes or returns no value. We can re-write the code a little more efficiently.

#include <stdio.h>

void hello(int n);

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

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

Here again, we are referencing hello above main so we will not get undefined errors. We now use a loop in hello function, and it takes in an argument of an integer (n), so it is more dynamic of a program now.


Resources, Sources, & Useful Links

Lecture 1 on YouTube

CS50 on edX

computer science, cs50, notes, #LearnInPublic