Jul 18, 2024
Today we delve into C programming, a traditional and older programming language. Although C might look cryptic initially, it builds on concepts from week zero, such as functions, loops, and conditionals. The focus is on learning problem-solving strategies, using C capabilities.
hello.c
).make filename
converts source code to an executable../filename
executes the compiled machine code.#include <stdio.h>
int main(void) {
printf("Hello, world!\n");
return 0;
}
#include <stdio.h>
: Includes standard input-output library.int main(void) { ... }
: Main function that returns an integer.printf(...)
: Function to print formatted output.\n
: Newline character.#include <cs50.h>
#include <stdio.h>
int main(void) {
string name = get_string("What's your name? ");
printf("Hello, %s\n", name);
return 0;
}
get_string
to get user input.int
, float
, char
, string
(CS50 specific)int x = 5;
float y = 5.5;
char z = 'A';
string s = "hello";
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");
}
if
, else if
, else
to handle multiple conditions, double equals ==
for comparison.int i = 0;
while (i < 3) {
printf("meow\n");
i++;
}
for (int i = 0; i < 3; i++) {
printf("meow\n");
}
void meow(void) {
printf("meow\n");
}
int main(void) {
for (int i = 0; i < 3; i++) {
meow();
}
return 0;
}
int add(int a, int b) {
return a + b;
}
int main(void) {
int sum = add(2, 3);
printf("%d\n", sum); // Outputs 5
return 0;
}
ls
: List files in directorycd
: Change directorycp
: Copy filesmv
: Move (rename) filesrm
: Remove filesls // Show directory contents
cd foldername // Change to directory
cp source destination // Copy a file
mv oldname newname // Rename a file
rm filename // Delete a file
float x = 1.0 / 10.0;
printf("%.10f\n", x); // Might not perfectly print 0.1000000000
double
can mitigate this but not eliminate it entirely.Next steps include diving into problem sets that necessitate the application of these concepts, gradually building proficiency in solving complex problems programmatically.