C Coding
C is a general-purpose programming language. It is closely associated with the UNIX system where it was developed, since the system and most of the programs that run on it are written in C. The language is not explicitly tied to one operating system or machine, and is useful for writing a variety of programs ranging from operating systems and compilers to major programs in many different domains.
All of the features of C are contained in some form within C++ so when working with C++ it can be more efficent to work with C constructs instead of their newer equivilent. One example of this includes the ?: operator which can be used as a far more efficent version of a if statment Which unfortunately looks god awful in code

Basic Examples

Hello World

1
#include <stdio.h> // Inclusion for standard Input/Output library
2
3
main()
4
{
5
printf("Hello Hackers\n"); //print 'Hello Hackers' with a new line (\n).
6
return 0; // Linux returns 0 typically for a successful run, Windows likes the opposite
7
}
Copied!

For Loops (with a bit of int concatenation)

1
#include <stdio.h> // Standard input output
2
3
int main() {
4
int beers; // Initialisation of int for beers
5
6
printf("A fitting example for hackers.\n\n");
7
8
for (beers = 99; beers > 0; beers-- ) // This will loop until beers = 0
9
{
10
printf("Bottles of beer on the wall, %d Bottles of beer\n", beers);
11
printf("Take one down and pass it around, %d bottles of beer on the wall.\n\n", beers);
12
}
13
14
printf("No more bottles of beer on the wall, no more bottles of beer.\n");
15
printf("Go to the store and buy some more, 99 bottles of beer on the wall.\n");
16
printf("\nAnd conditional loops are just that easy");
17
18
return 0;
19
}
Copied!

While Loops (with the rand function)

1
#include <stdio.h> // Standard input output
2
#include <time.h> // Using time to seed the random function
3
#include <stdlib.h> // Standard Library
4
5
int main() {
6
7
printf("Lets spin to win\nLooking for Tails\n\n");
8
srand(time(NULL));
9
10
while (rand() % 2 == 0) // Heads
11
{
12
printf("Not yet, it was heads\n");
13
}
14
15
printf("Tails");
16
}
Copied!

File Creation

1
#include <stdio.h> // Standard input output (which includes file input output)
2
3
main() {
4
FILE *filepath;
5
char buff[255]; // Liable for buffer overflows if mishandled
6
7
filepath = fopen("./test.txt", "w+"); // Opens a text file for both reading and writing
8
fprintf(filepath, "Lorem ipsum dolor sit amet,\n");
9
fputs("consectetur adipiscing elit,\n", filepath);
10
fclose(filepath);
11
12
filepath = fopen("./test.txt", "r");
13
fscanf(filepath, "%s", buff); // fscanf will read until it encounters a space
14
fgets(buff, 255, filepath); // fgets will read from current pointer position until it encounters a end of line
15
fgets(buff, 255, filepath); // fgets in this instance will read the entire second line
16
}
Copied!