1. What is C and who made it?
C is a general-purpose high-level language. Dennis Ritchie made C at Bell Labs for the UNIX operating system. C first worked in 1972.
Full lesson: C intro
45 questions about C with short answers and code. Each answer links to a full lesson on this site. Free, with no signup and no ads.
C is a general-purpose high-level language. Dennis Ritchie made C at Bell Labs for the UNIX operating system. C first worked in 1972.
Full lesson: C intro
A token is the smallest unit the compiler can read. The compiler breaks source code into tokens. Keywords, names, and numbers are tokens.
Full lesson: C basic syntax
You write a type and then a name. You can give the variable a value at the same time. You must declare a variable before you use it.
int count = 10;
float price = 2.5;
Full lesson: C variables
C has basic types such as int, float, double, and char. Each type has a size and a range. The size can change on different systems.
int n = 5;
char c = 'A';
double d = 1.5;
Full lesson: C data types
The if statement tests a condition. If the condition is true, the code block runs. C treats zero as false and any non-zero value as true.
int a = 10;
if (a > 5) {
printf("big\n");
}
Full lesson: C if
The if block runs when the condition is true. The else block runs when the condition is false. Only one block runs.
if (a > 5) {
printf("big\n");
} else {
printf("small\n");
}
Full lesson: C if else
A for loop has three parts: start, condition, and step. The loop runs while the condition is true. The step runs after each pass.
int i;
for (i = 0; i < 3; i++) {
printf("%d\n", i);
}
Full lesson: C for loop
A while loop tests a condition before each pass. The body runs while the condition is true. If the condition is false at the start, the body never runs.
int i = 0;
while (i < 3) {
printf("%d\n", i);
i++;
}
Full lesson: C while loop
You write a type, a name, and a size in brackets. The first element has index 0. The elements sit in contiguous memory.
int nums[3] = {1, 2, 3};
printf("%d\n", nums[0]);
Full lesson: C arrays
C stores a string as a char array with a null character at the end. The null character marks the end of the string. The array needs one extra space for it.
char site[7] = {'R', 'U', 'N', 'O', 'O', 'B', '\0'};
printf("%s\n", site);
Full lesson: C strings
A function has a return type, a name, and parameters. You call it by its name and pass the arguments. The function returns a value to the caller.
int add(int a, int b) {
return a + b;
}
int sum = add(2, 3);
Full lesson: C functions
The typedef keyword gives a new name to a type. The new name works as a short form of the old type. People often use capital letters for the new name.
typedef unsigned char BYTE;
BYTE b1, b2;
Full lesson: C typedef
The fopen function opens a file or creates a new file. It returns a FILE pointer for the stream. It returns NULL if the open fails.
FILE *fp = fopen("file.txt", "r");
if (fp == NULL) {
printf("open failed\n");
}
Full lesson: C file io
A common mistake is a condition that never becomes false. Then the loop runs forever. Check that the step moves the value toward the end.
int i;
for (i = 0; i < 3; i--) { /* wrong: i goes down */
printf("%d\n", i);
}
Full lesson: C loops
A common mistake is a char array with no space for the null character. Then the string has no end mark. Make the array one element larger than the text.
char s[3] = "abc"; /* wrong: no room for '\0' */
char t[4] = "abc"; /* correct */
Full lesson: C strings
You put one if statement inside another if block. The inner if runs only when the outer condition is true.
if (a == 100) {
if (b == 200) {
printf("Both true\n");
}
}
Full lesson: C nested if
A nested loop has one loop inside another loop. The inner loop runs completely for each iteration of the outer loop.
for (i = 1; i <= 3; i++) {
for (j = 1; j <= 2; j++) {
printf("%d %d\n", i, j);
}
}
Full lesson: C nested loops
The abs() function returns the absolute value of an integer. It is in the <stdlib.h> header. Use fabs() for floating-point numbers.
int x = -5;
printf("%d\n", abs(x)); // prints 5
Full lesson: C function abs
The div() function divides two integers and returns a structure. The structure has two members: quot for the quotient and rem for the remainder.
div_t d = div(27, 4);
printf("quot = %d, rem = %d\n", d.quot, d.rem);
Full lesson: C function div
The cos() function returns the cosine of an angle in radians. It is in the <math.h> header. You must link the math library when you compile.
#include <math.h>
double result = cos(0.0); // returns 1.0
Full lesson: C function cos
The ferror() function checks a file stream for an error. It returns a non-zero value if an error occurred. Use it after a file operation.
FILE *fp = fopen("test.txt", "r");
if (ferror(fp)) {
printf("File error\n");
}
Full lesson: C function ferror
The perror() function prints a message to stderr. The message describes the last error. You give a prefix string as the argument.
FILE *fp = fopen("nofile.txt", "r");
if (fp == NULL) {
perror("Error opening file");
}
Full lesson: C function perror
The strerror() function returns a pointer to a string. The string describes the error code you pass. It is in the <string.h> header.
#include <string.h>
printf("%s\n", strerror(2)); // prints "No such file or directory"
Full lesson: C function strerror
The tmpfile() function creates a temporary binary file. The file is removed automatically when you close it or when the program ends. It returns a FILE pointer or NULL on error.
FILE *tmp = tmpfile();
if (tmp != NULL) {
fputs("data", tmp);
fclose(tmp);
}
Full lesson: C function tmpfile
The difftime() function returns the difference in seconds between two time_t values. The result is a double. It is in the <time.h> header.
time_t start = time(NULL);
// ... some work ...
time_t end = time(NULL);
double diff = difftime(end, start);
Full lesson: C function difftime
A common mistake is to forget to change the condition inside the loop. The loop then runs forever. Always update the loop variable.
int i = 0;
while (i < 5) {
printf("%d\n", i);
i++; // without this, infinite loop
}
Full lesson: C while loop
A common mistake is to forget braces for the inner if. The else then binds to the wrong if. Always use braces to make the logic clear.
if (a > 0) {
if (b > 0) {
printf("both positive\n");
}
}
Full lesson: C nested if
A common mistake is to use abs() on a float or double. The abs() function works only on integers. Use fabs() from <math.h> for floating-point values.
double x = -3.5;
// wrong: abs(x) truncates to int
printf("%f\n", fabs(x)); // correct
Full lesson: C function abs
A common mistake is to use the file pointer without checking for NULL. If fopen() fails, it returns NULL. Always check before you read or write.
FILE *fp = fopen("data.txt", "r");
if (fp == NULL) {
perror("fopen");
return 1;
}
Full lesson: C file io
A common mistake is to use div() with a zero denominator. This causes undefined behavior. Always check the denominator before you call div().
int denom = 0;
if (denom != 0) {
div_t d = div(10, denom);
}
Full lesson: C function div
A C program has a main function. The main function is the entry point. It contains statements inside braces.
#include <stdio.h>
int main() {
printf("Hello");
return 0;
}
Full lesson: C basic syntax
Use the #include directive. It copies the header contents into your file. Use angle brackets for standard headers.
#include <stdio.h>
Full lesson: C header files
The if statement runs a block when the condition is true. A non-zero value is true. A zero value is false.
if (x > 0) {
printf("positive");
}
Full lesson: C if
The while loop runs a block while the condition is true. It checks the condition before each run. The loop can run zero times.
while (i < 5) {
i++;
}
Full lesson: C while loop
Use the array name and an index in brackets. The first element has index 0. The last element has index size minus 1.
int a[3] = {1, 2, 3};
printf("%d", a[0]);
Full lesson: C arrays
Use the %s format specifier. The array must have enough space. The input stops at a space.
char name[20];
scanf("%s", name);
Full lesson: C strings
Call fopen with mode "r". It returns a FILE pointer. Check the pointer for NULL.
FILE *fp = fopen("data.txt", "r");
if (fp == NULL) { /* handle error */ }
Full lesson: C file io
Include the math.h header. Call pow with the base and the exponent. It returns a double result.
#include <math.h>
double r = pow(2.0, 3.0);
Full lesson: C function pow
Include the math.h header. Pass the angle in radians. The function returns the sine value.
#include <math.h>
double s = sin(1.0);
Full lesson: C function sin
Include the math.h header. Pass the exponent as a double. The function returns e raised to that power.
#include <math.h>
double v = exp(1.0);
Full lesson: C function exp
The log function needs a positive input. A zero or negative input gives an error or NaN. Check the input before the call.
if (x > 0) {
double r = log(x);
}
Full lesson: C function log
The loop condition stays true if the body does not change it. Update the control variable inside the loop. A missing update causes an infinite loop.
int i = 0;
while (i < 5) {
i++;
}
Full lesson: C while loop
C does not check array bounds. An index outside the array causes undefined behavior. Keep the index from 0 to size minus 1.
int a[3];
a[3] = 5; /* wrong: out of bounds */
Full lesson: C arrays
The %s format has no width limit. A long input can overflow the array. Use a width limit in the format.
char name[20];
scanf("%19s", name);
Full lesson: C strings
The sin function expects radians. A degree value gives a wrong result. Convert degrees to radians first.
double rad = deg * 3.14159 / 180.0;
double s = sin(rad);
Full lesson: C function sin