You are on page 1of 12

C

Table of Contents

1. IN CODE WRITING WINDOW........................................................................................................................... 2


2. IN TERMINAL WINDOW.................................................................................................................................... 2
3. COMMAND LINE................................................................................................................................................. 2
- ls:...............................................................................................................................................................................2
- cd................................................................................................................................................................................2
- cp................................................................................................................................................................................2
- rm...............................................................................................................................................................................2
- mv...............................................................................................................................................................................3
4. PRINTF................................................................................................................................................................. 3
5. DATA TYPE.......................................................................................................................................................... 3
A. STRING............................................................................................................................................................................3
B. INT............................................................................................................................................................................... 3
C. LONG............................................................................................................................................................................3
D. FLOAT.......................................................................................................................................................................... 3
E. DOUBLE........................................................................................................................................................................4
F. PARITY......................................................................................................................................................................... 4
G. CHAR............................................................................................................................................................................4
H. BOOL............................................................................................................................................................................ 4
6. VOID...................................................................................................................................................................... 4
7. CONDITIONAL STATEMENTS.......................................................................................................................... 6
8. ARITHMETIC OPERATORS............................................................................................................................... 7
9. LOOP..................................................................................................................................................................... 7
10. VARIABLES AND SCOPE............................................................................................................................... 8
11. ARRAYS........................................................................................................................................................... 9
12. COMMAND – LINE ARGUMENTS............................................................................................................... 10
13. STRUCT.......................................................................................................................................................... 10
- IF WE WANTED TO IMPLEMENT A PROGRAM THAT SEARCHES A PHONE BOOK, WE MIGHT
WANT A DATA TYPE FOR A “PERSON”, WITH THEIR NAME AND PHONE NUMBER...................................10
- IT TURNS OUT IN C THAT WE CAN DEFINE OUR OWN DATA TYPE, OR DATA STRUCTURE, WITH
A STRUCT, WHICH COULD CONTAIN OTHER DATA TYPES INSIDE IT, IN THE FOLLOWING SYNTAX:..10
14. SEARCH AND SORT..................................................................................................................................... 11
1. In code writing window

- To start: include <stdio.h> (stdio.h: file name)


- //: note to self

2. In terminal window
- Compile code before running it, through a command:

 clang (ex: clang hello.c)

 clang -o hello hello.c: tell clang to use hello as the output filename and use hello.c
as the source code.
 If use CS50’s library, via #include <cs50.h>, for the get_string function, add a
flag -l: clang -o hello hello.c -lcs50

 make (ex: make hello)

- To run our program, type in another command, which is ./ + (folder name) (ex: ./hello)

3. Command line
- ls: short for “list”, this command will give you a readout of all the files and folders in current
directory
- cd <directory>

 short for “change directory”, this command changes your current directory to
<directory>, which you specify, in your workspace or on your operating system
 the shorthand name for the current directory is “.” and for the parent directory of the
current directory is “. .”
 If ever curious about the name of the current directory, though the terminal prompt will
often tell you, you can type pwd (present working directory)
 mkdir <directory>: make directory, create a new subdirectory called <directory> located
in the current directory

- cp <source> <destination>

 short for “copy”, this command will allow you to create a duplicate of the file you specify
as <source>, which it will save in <destination>
 cp -r: copy entire directories

- rm <file>

 short for “remove”, this command will delete <file> after it asks you to confirm (y/n) you
want to delete it
 rm -f: skip the confirmation
 rm -r: delete entire directories
 can also combine -r and -f flags into -rf
 there is no undo

- mv <source> <destination>: short for “move”, this command will allow you to effectively
rename a file, moving it from <source> to <destination>

4. Printf
- printf (“hello, world\n”); \n: to get a new line

5. Data type
a. String

- Data type
- Store a series of characters – words, sentences, paragraphs and the like
- #include <cs50.h>

string answer = get_string(“What’s your name?\n”);


printf(“Hello, %s\n”, answer); (%: variable)(s: string)

b. Int

- Data type
- Used for variables that will store integers
- Always take up 4 bytes of memory (32 bits)
- Unsigned int is a qualifier that can be applied to certain types (including int), which effectively
doubles the positive range of variables of that type, at the cost of disallowing any negative values

c. Long

- Integers with more bits, so they can count higher than an int

d. Float

- Data type
- To store floating-point values – real numbers
- Always take up 4 bytes of memory (32 bits)

float price = get_float(“What’s the price?\n”)


printf(“Your total is %.2f.\n”, price * 1.0625); (2f: 2 decimal point)
e. Double

- Data type
- To store floating- point values – real numbers
- Always take up 8 bytes of memory (64 bits)
- Double precision compared to float

f. Parity

- Saying a value is even or odd

g. Char

- Data type
- To store single character
- Always take up 1 byte of memory (8 bits)

h. Bool

- Data type
- Store a Boolean value – true/ false to compare values
- #include <cs50.h>
- In C, every nonzero value is equal to true, and zero is false
- Two main types of Boolean expressions

 Logical operators:

 Logical AND (&&) is true if and only if both operands are true, otherwise false
(ex: x && y is true if and only if x is true and y is true)
 Logical OR (||) is true if and only if at least one operand is true, otherwise false
 Logical NOT (!) inverts the value of its operand (ex: x is true so !x is false)

 Relation operators

 Less than (x < y)


 Less than or equal to (x <= y)
 Greater than (x > y)
 Greater than or equal to (x >= y)
 Equality (x == y)
 Inequality (x != y)

6. Void
- Type
- Function can have a void return type, which just means they don’t return a value
- The parameter list of a function can also be void. It simply means the function takes no
parameters

For 3 times cough (fixed numbers)

void cough (void) (custom function will be written below, just need first line here)

int main (void) (main part should put first)

{
for (int i = 0, i < 3, i++)
{
cough ();
}
}

void cough (void) (custom function)

{
printf (“cough\n”);
}

For n times cough (n: variable)

void cough (int n)

int main (void)

cough (3);

void cough (int n)

for (int i = 0, i < n, i++)


{
printf(“cough\n”);
}

}
7. Conditional statements
- If

 If (Boolean – expression)  If (Boolean – expression)

{ {
} }
Else
{
}

- Switch statement: specify distinct case, instead of relying on Boolean expressions. It’s important
to “break ;” between each case, or you will fall through each case (unless that is desired
behaviour)

In code writing part


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

int main (void)


{
int x = get_int(“x\n”);
switch (x)
{

case 1: case 4:
printf (“One!\n”); printf (“Four, ”);
break;
case 3:
case 2: printf (“Three, ”);
printf (“Two!\n”);
break; case 2:
printf (“Two, ”);
case 3:
printf (“Three!\n”); case 1:
break; printf (“One, ”);

default: default:
printf (“Sorry!\n”); printf (“Blast off!\n”);
}
}

$ make int $ make int


$ ./int part
In terminal $ ./int

 x  x
3 3
 Three!  Three, two, one, blast off!

- Ternary operator (?:): used to replace very simple if-else

int x;
if (expr)
{

x = 5;

int x = (expr) ? 5 : 6; }
else
{

x = 6;

8. Arithmetic operators
- Can add (+), subtract (-), multiply (*), and divide (/)
- Modulus operator (%) – số dư

Ex: int m = 13 % 4; // m is now 1

- Shortcut

Ex: x = x*5 is the same as x*=5

x = x + 1 is the same as x + = 1 or x++

x = x – 1 is the same as x - = 1 or x - -
9. Loop
- While: repeat an unknown number of times, and possibly not at all

 Infinite loop

while (true)

 If the Boolean-expr evaluates to true, all lines of code between the curly braces will
execute repeatedly, in order from top to bottom, until Boolean-expr evaluates to false.

while (boolean-expr)

- Do-while: repeat an unknown number of times, but at least once.

do

while (boolean-expr)

- For: repeat a discrete number of times, though you may not know the number at the moment the
program is compiled.

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

10. Variables and scope


- Scope is a characteristic of a variable that defines from which functions that variable may be
accessed.

 Local variables: can only be accessed within the functions in which they are created
 Global variables: can be accessed by any function in the program
- For the most part, local variables in C are passed by value in function calls
- When a variable is passed by value, the callee receives a copy of the passed variable, not the
variable itself.
- That means that the variable in the caller is unchanged unless overwritten.
- Things can get particularly insidious if the same variable names appear in multiple functions,
which is perfectly okay as long as the variables exist in different scopes

11. Arrays
- Arrays are a fundamental data structure
- We use arrays to hold values of the same type at contiguous memory locations.
- In C, the elements of an array are indexed starting from 0
- Array declarations: type name [size];

 Type: what kind of variable each element of the array will be


 Name: what you want to call the array
 Size: how many elements in the array

- When declaring and initializing an array simultaneously, there is a special syntax that may be
used to fill up the array with its starting values

// instantiation syntax // individual element syntax

bool truthtable [] = { false, true, true } bool truthtable [3];

truthtable [0] = false;

truthtable [1] = true

truthtable [2] = true

- Arrays can consist of more than a single dimension (ex: bool battleship [10][10]).
- While we can treat individual elements of arrays as variables, we cannot treat entire arrays
themselves as variables.
- We cannot, for instance, assign one array to another using the assignment operator. Instead, we
must use a loop to copy over elements one at a time.

int foo [5] = {1; 2; 3; 4; 5};


int bar [5];

for (int j = 0; j < 5; j++)


{
bar [j] = foo [j];
}

- Arrays are passed by reference. The callee receives the actual array

12. Command – Line Arguments


- To collect command-line arguments from the user, declare main as:

int main (int argc, string argv [])


{
}

- argc (argument count): this integer-type variable will store number of command-line arguments
the user typed when the program was executed
- argv (argument vector): this array of strings stores, one string per element, the actual text the user
typed at the command-line when the program was executed. The first element of argv is always
found at argv[0]. And the last element is [argc – 1]

13. Struct
- If we wanted to implement a program that searches a phone book, we might want a data type for
a “person”, with their name and phone number.
- It turns out in C that we can define our own data type, or data structure, with a struct, which
could contain other data types inside it, in the following syntax:

Typedef struct
{
String name;
String number; (string if include symbols and formatting, like + or -)
}
Person;

- Without struct

 Make sure that the first name in names matches the first number in numbers, and so on.
 If the name at a certain index i in the names array matches, return the phone number in
the numbers array at the same index.

- With struct

 Create an array of the person struct type, and name it “people”. Set the values for each
field, or variable, inside each person struct, using the dot operator, ..
 In loop, more certain that the number corresponds to the name since they are from the
same person struct.
 Improve the design of program with a constant (Const int NUMBER = 10;), and store
values not in code but in a separate file or even a database.

Without struct With struct

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


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

int main(void) typedef struct


{ {
string names[] = {"Brian", "David"}; string name;
string numbers[] = {"+1-6-4", "+1-9-4"}; string number;
}
for (int i = 0; i < 2; i++) person;
{
if (strcmp(names[i], "David") == 0) int main(void)
{ {
printf("Found %s\n", numbers[i]); person people[2];
return 0;
} people[0].name = "Brian";
} people[0].number = "+1-6-4";
printf("Not found\n");
return 1; people[1].name = "David";
} people[1].number = "+1-9-4";

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


{
if (strcmp(people[i].name, "David") == 0)
{
printf("Found %s\n", people[i].number);
return 0;
}
}
printf("Not found\n");
return 1;
}

14. Search and sort


Worst case scenario Best case scenario
Linear Iterate across the array Look through the entire array The target element is the
search from left to right, search of n elements. first element of the array.
for a specified element. O (n) Ω (1)
Binary Divide and conquer, Divide a list of n elements in The target element is at the
search reducing the search area by half repeatedly to find the midpoint of the full array.
half each time, trying to target element. Ω (1)
find a target number. Array O (log n)
must first be sorted.
Bubble Move higher valued The array is in reverse order. The array is already
sort elements generally towards Hence, “bubble” each of the n perfectly sorted and make
the right and lower value elements all the way across the no swaps on the first pass.
elements generally towards array in n times. Ω (n)
the left. O (n2 )
Selection Find the smallest unsorted Iterate over each of the n Iterate over each of the n
sort element and swap it with elements of the array and elements of the array and
the first element of the repeat n times. repeat n times.
unsorted part. O (n2 ) Ω (n2 )
Merge Sort smaller arrays and Split n elements up and then The array is already
sort then combine those arrays recombine them, effectively perfectly sorted. But still
together in sorted order. doubling the sorted subarrays have to split and recombine
as we build them up. it back together.
O (n log n) Ω (n log n)

You might also like