CS50 – Week 1 – C

Lecture 1

C

syntax

#include <stdio.h>

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

f stands for"format"

  • Variables int counter = 0;
  • Incramenting "change [counter] by (1)" is counter = counter + 1 syntactic sugarcounter +=1 counter++
  • Conditionals
if (x < y)
{
    printf("x is not less than y\n");
}
else
{
    printf("x is not less than y\n");
}
if (x < y)
{
    printf("x is less than y\n");
}
else if (x > y)
{
    printf("x is greater than y\n");
}
else if (x == y) // `if (x == y)` is logically unnecessary
{
    printf("x is equal to y\n");
}
  • While Loops
while (true) // repeat it forever
{
    printf("hello, world\n");
}
  • For Loops
for (int i = 0; i < 50; i++) \\ i++ == i = i+1
{
    printf("hello, world\n");
}
  • User Input
string answer = get_string("What's your name?\n");
printf("hello, %s\n", answer); // %s: placeholder

hello.c

#include <stdio.h>

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

Compilation

source code -> compiler -> machine code

Command-Line Arguments

terminal

clang -o hello hello.c
./hello

make

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

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

make hello