C - astromechanic/cheat_sheets GitHub Wiki
File extension .c
Cloud IDE from CS50 https://ide.cs50.io/ У меня в облаке на CS50 лежит пара программ на С.
Source code .c To run a program, you need to compile the source code into binary. Only the binary file is executable
Hello World
#include<stdio.h>
int main(void)
{
printf("Hello, world");
}
// this is a comment
Compile and run some simple stuff
gcc -o hello hello.c
./hello
gcc is a compiler collection. We can also use another one, called clang. It looks like this:
clang -o hello hello.c
When using a header is not enough to tell the computer how to execute/understand where the functions from the library come from (= it's not enough to include the header), then use -l + name of the library:
clang -o hello hello.c -lcs50
Get two numbers from the user and add them
#include<cs50.h>
#include<stdio.h>
int main(void)
{
int x = get_int("x: ");
int y = get_int("y: ");
printf("%i\n", x + y);
}
Divide two numbers
#include<cs50.h>
#include<stdio.h>
int main(void)
{
int x = get_int("x: ");
int y = get_int("y: ");
float z = (float) x / (float) y; // casting = convert int x into float
printf("%f\n", z);
}
if (x > y)
{
// do something
}
else if (x < y)
{
// do something else
}
else
{
// do something else
}
Functions
void meow(void); // prototype - in order that compile knows that there is a function meow()
int main(void)
{
meow(3);
}
void meow(int n)
{
for (int i = 0; i < n; i++)
{
printf("meow");
}
}
Arrays
int scores[3]; // declaring an array you need to specify type and length
scores[0] = 72;
scores[1] = 43;
scores[2] = 34;
double balance[5] = {1000.0, 2.0, 3.4, 7.0, 50.0}; // init an array
Use single '' for separate chars: char c = 'H'; Use double "" for everything else: string s = "Hi";
#include<string.h>
strlen(string) // get length of string