C
Table of Contents
The Logo of The C Programming Language [1] |
---|
Introduction
C is a general-purpose, procedural computer programming language first designed and created by Dennis Ritchie and Bell Labs in 1972. It was designed to be compiled and to provide the developer the option to directly access memory. As of April 2021, C was ranked first in The Importance of Being Earnest (TIOBE) index, an index measuring the most popular programming languages. The C programming language has inspired many future programming languages' basic features, control structures, or just general syntax. This includes C++, C#, Java, Javascript, Objective-C, and many more [2].
This wiki page serves as a very basic introduction to the C language but should not be the sole resource for learning this comparatively difficult and complex programming language. It will go over general syntax and a few features but will not go in depth and will certainly not go over all the features. Readers are strongly recommended to pickup a dedicated book, such as The C Programming Language by Brian Kernighan and Dennis Ritchie or C Programming: A Modern Approach by K. N. King for more comprehensive information. It is also highly suggested that the reader set up their own development environment, such as through an Integrated Development Environment (IDE), to develop their own C code.
Setting Up The Development Environment
For beginners, it is recommended to use an IDE to compile and debug code. For a comprehensive setup tutorial for using the Eclipse IDE to program in C, please refer here.
Otherwise, you can also choose to use a text editor like VSCode and install a compiler such as MinGW-w64 to compile the code from the command line. There are several options available, in terms of code editors and compilers. Plenty of resources explaining these resources and how to install them are available online.
Basic Program
It is essentially tradition to begin learning a new programming language by writing a program that will print "Hello World!". The code for printing "Hello World!" in C goes like this:
#include <stdio.h> int main(void) { printf("Hello World!\n"); return 0; }
On the first line, the library stdio.h is imported. The #include is a preprocessor directive that instructs the compiler to include code and functions from the header stdio.h [3]. The stdio.h library includes the standard functions such as printf or scanf but other standard header libraries can be included. If you are importing your own local headers, you can declare it like
#include "header_name_goes_here.h"
The C language has things known as functions, which are routines, or blocks of code, which take arguments and return a single value. In this example, we define a function called "main" which is of type "int", or integer, and takes in "void" paramters. "main" is a special function name as it is the entry point for all C code. The "int" indicates that the function returns an integer value. What goes inside the parentheses defines the parameters of the function. Currently, it is stated as "void" which means it takes in nothing [4].
The printf function is used in C to display output to the screen. The quotation marks indicates that whatever contained inside should be printed as-is [3]. \n is known as an escape sequence - a full list of these are available in a later section. Just know for now that it is a newline character and pushes the cursor to the next line. This would be useful if you wished to print sentences on multiple lines. The function is returned at the end with the "return 0" statement. In the main function, the return 0 statement is important as it essentially indicates to the operating system that the program succeeded [3].
You'll also notice that statements such as printf and return 0 are suffixed with semicolons. All statements in C must be followed by a semicolon. As you write more code, this will become more natural.
Variables and Data Types
C is a statically typed langauge so any variable you declare has a type assigned to it [4]. These are some example variable declarations:
int age; // Declares a variable "age" with type int float height; // Declares a variable "height" with type float double weight; // Declares a variable "weight" with type double
Note that comments in C start with a "//". Multiline comments start with a "/*" and end with a "*/". Variable names can contain uppercase/lowercase characters, digits, and the underscore character, but cannot start with a digit [4]. You can also initialize these variables with a value like so:
int age = 20; // Declares a variable "age" with type int and initializes it with 20 float height = 175.5f; // Declares a variable "height" with type float and initializes it with 175.5 double weight = 75; // Declares a variable "weight" with type double and initializes it with 75
Note that float types need to append an "f" at the end of the value because the compiler normally interprets floats as doubles. Once a variable is declared, you can change or access its value at any time using the = operator [4]:
age = 50; // age is now 50 height = 156.7f; // height is now 156.7 weight = 60.4; // weight is now 60.4
char types store a character although it refers it through its ASCII value. int types store integers while floating-point numbers (float, double, long double) store real numbers. Most programming languages have a dedicated boolean type (true or false) but not C, unless you include the header file <stdbool.h>. C considers zero as false and anything nonzero as true.
Here is a full list of the basic data types [5]:
Data Type | Typical Memory Size in Bytes1 | Typical Range (or what it stores)2 |
---|---|---|
char | 1 | -128 to 127 |
signed char | 1 | -128 to 127 |
unsigned char | 1 | 0 to 255 |
unsigned short int | 2 | -32,768 to 32,767 |
unsigned int | 4 | 0 to 4,294,967,295 |
int | 4 | -2,147,483,648 to 2,147,483,647 |
long int | 4 | -2,147,483,648 to 2,147,483,647 |
unsigned long int | 4 | 0 to 4,294,967,295 |
long long int | 8 | -(2^63) to (2^63)-1 |
unsigned long long int | 8 | 0 to 18,446,744,073,709,551,615 |
float | 4 | 24 bits of precision [4] |
double | 8 | 53 bits of precision [4] |
long double | 16 | 64 bits of precision [4] |
12Note that the amount of memory required, and ultimately how many digits each data type can store, is entirely dependent on the architecture/environment you're running the code on. The table above provides the standard values. The only guarantee is that a short is not longer than an int, a long is not shorter than an int, etc [4].
With the <stdint.h> header, the programmer can specify the number of bytes for a particular data type.
Basic Operators
Arithmetic Operators [4]
c = a + b // Adds a and b and returns the result, storing it in c c = a - b // Subtracts b from a and returns the result, storing it in c c = a * b // Multiplies a and b and returns the result, storing it in c c = a / b // Divides a by b and returns the result, storing it in c c = a % b // Returns the remainder from dividing a by b and stores it in c
Unary Operators [4]
a = +b // a is equal to positive b a = -b // a is equal to negative b a++ // Increments a by 1 after using a ++a // Decrements a by 1 before using a a++ // Decrements a by 1 after using a ++a // Increments a by 1 before using a
Compound Assignment Operators [4]
a += b // Adds b to a a -= b // Subtracts b from a a *= b // Multiplies a by b a /= b // Divides a by b a %= b // a is equal to remainder of a / b
Comparison Operators [4]
Note C does not have a built-in boolean type (true or false) but it regards zero as false and anything non-zero as true.
a == b // Checks if a is equal to b and returns 0 or 1 a != b // Checks if a is not equal to b and returns 0 or 1 a > b // Checks if a is greater than b and returns 0 or 1 a < b // Checks if a is less than b and returns 0 or 1 a >= b // Checks if a is greater than or equal to b and returns 0 or 1 a <= b // Checks if a is less than or equal to b and returns 0 or 1
Logical Operators [4]
!a // NOT; if a is true, returns false and vice versa a && b // AND; if both a and b are true, returns true, else false a || b // OR; returns true unless both a and b are false
Conditionals
if (condition) { // run the code encapsulated within these braces if the condition is true } if (washedDishes) { // Notice that this will run if washedDishes is any number besides 0 } else { // This part will be executed if washedDishes == 0 } // We can combine the two concepts above to create the below if... else if... structure: if (completedHomework > 5) { // do something if the number of completed homeworks assignments is greater than 5 } else if (completedHomework > 2) { // do something if the number of completed homeworks assignments is greater than 2 but less than 5 (as the first block was not executed meaning completedHomework was not greater than 5) } else { // do something if the number of completed homeworks assignments is not greater than 2 }
Printing and Reading
Basics of Printing
As mentioned previously, the printf function allows us to print something to the console, like so:
printf("Hi! This is printed to the console.\n");
The \n is an example of an escape sequence. Escape sequences start with a "\" and do not represent exactly what should be printed. Here is a list of some escape sequences [6]:
Escape Sequence | Character Represented |
---|---|
\a | Alert (Beep, Bell) |
\b | Backspace |
\n | Newline |
\t | Horizontal Tab |
\\ | Backslash (\) |
\" | Double quotation mark |
A comprehensive list can be found here.
Format Specifiers
An important concept for both printing and reading is the format specifier. If the programmer wishes to print the value of a variable, they must use a format specifier like so:
#include <stdio.h> int main(void) { int myAge = 18; printf("I am %d years old.", myAge); // Prints: I am 18 years old. return 0; }
%d acts as a placeholder for the myAge variable, which is of type int. You specify what variable will go in that placeholder by stating the variable name after the string and a comma. %d is used specifically for int types while %f is used for floating-point numbers. The order of the variable names after the string matters. Here is an example:
#include <stdio.h> int main(void) { int myAge = 18; float myHeight = 175.5; printf("I am %d years old and %f centimeters tall.", myAge, myHeight); // Prints: I am 18 years old and 175.5 centimeters tall. return 0; }
For more information on the various format specifiers and how to format certain output, please refer here.
Reading Input
scanf allows us to read input. Here is an example to read user input:
#include <stdio.h> int main(void) { int usersAge; printf("Please enter your age: "); scanf("%d", &usersAge); printf("You are %d years old.", usersAge); return 0; }
The above program asks for the user's age, stores it in usersAge, then prints a statement with the user inputted age. scanf ends once the newline (Enter key) is detected. Note the use of an ampersand. This is required for entering a user-inputted value into a variable. The ampersand actually returns the memory address of the variable and is widely used for pointers but we don't go over pointers in this wiki page. Furthemore, scanf is more complicated than what's explained here and is not the best function for user input. If you wish to learn more about any of these concepts, many resources are available for you to read.
Loops
Loops are ways to automate repetitive processes. There are three main types of loops in C:
While Loop
while (condition) { // do something }
An example application of a while loop may be like:
// Prints the numbers 1 through 100 int i = 1; while (i <= 100) { printf("%d\n", i); i++; }
i is initially 1, which satisifies the condition that i should be less than or equal to 100, so the code within the while loop is executed, which is printing the value of i and then incrementing i. This continues until i is equal to 101, which fails to meet the condition.
Do... While Loop
do { // do something } while (condition);
The Do... While loop is essentially a variant of the original While loop but instead where the code block is guaranteed to run at least once. The following is an example of how it could be used:
int n = 0; do { printf("Would you like to proceed? Enter 1 if yes. "); scanf("%d", &n); } while (n != 1);
The above program prompts at least once if the user would like to proceed and continues to prompt until n == 1.
For Loop [3]
A for loop can be thought of as a specific variant of a While loop.
for ( variable initialization goes here; condition goes here; variable update goes here ) { // code goes here }
The above concept is best understood through an example. We can take the While loop example and simplify it through a For loop:
// Prints the numbers 1 through 100 for (int i = 1; i <= 100; i++) { printf("%d\n", i); }
Any variables the programmer wishes to use goes in the first of three spots within the parentheses. You can declare and initialize multiple variables by separating them with a comma. The comma is known as the comma operator. After the first semicolon, you put the condition there. This condition is tested after every iteration of the loop but before executing the variable update, which is what comes after the second semicolon - in this case it's incrementing i. It does not have to necessarily be an incrementation but can also be all types of operations.
Arrays
An array is a variable that can store multiple values of the same type [3]. We can define an array of int values like so:
int ages[6];
The ages array consists of 6 ints. Within C, you must always specify the size of the array [3]. Initializing this array can be done like this:
int ages[6] = {34, 20, 76, 40};
Notice that we only initialized the first four entries of the array. Missing values will automatically be initialized as 0 for an int array. Therefore, the above array can be visualized like so:
int ages[6] | ||||||
---|---|---|---|---|---|---|
Index | 0 | 1 | 2 | 3 | 4 | 5 |
Value | 34 | 20 | 76 | 40 | 0 | 0 |
It is important to note that the first index of arrays is referenced by 0, not 1. Therefore, the last index is 5, not 6. The above array values can be accessed or redefined like so:
ages[0]; // Returns 34 ages[1]; // Returns 20 printf("%d", ages[2]); // Prints: 76 ages[3] = 20; // Assigns 20 to the fourth element of the ages array ages[4] = 50; // Assigns 50 to the fifth element of the ages array printf("%d", ages[5]+10);// Prints: 10
Test Your Knowledge
So far, all the concepts learnt have been extremely basic. Just as a quick knowledge check, try to code a program in C where you initialize an array of 100 entries all with 0 and then using a loop, reassign values to the array so that the first element of the array is 5 and then each subsequent element of the array is 5 more than the previous. Then, print the array in a 10*10 table like so (You will need the "\t"):
5 10 15 20 25 30 35 40 45 50 55 60 65 70 75 80 85 90 95 100 105 110 115 120 125 130 135 140 145 150 155 160 165 170 175 180 185 190 195 200 205 210 215 220 225 230 235 240 245 250 255 260 265 270 275 280 285 290 295 300 305 310 315 320 325 330 335 340 345 350 355 360 365 370 375 380 385 390 395 400 405 410 415 420 425 430 435 440 445 450 455 460 465 470 475 480 485 490 495 500
Where From Here
From here, you still need to learn about 2D arrays, functions, enums, structs, pointers, memory allocation, algorithms, linked lists and so much more, but that is left as an exercise to the reader. As mentioned at the beginning, you can read books such as The C Programming Language by Brian Kernighan and Dennis Ritchie or C Programming: A Modern Approach by K. N. King for more comprehensive information or just follow an online course like from edX or Learn-C.
References
[1] Rezonansowy, The logo of The C Programming Language, used in the cover of the book, The C Programming Language, by Brian W. Kernighan and Dennis M. Ritchie, published in 1978. Wikimedia Commons, 2013.
[2] “C (programming language),” Wikipedia, 05-Apr-2021. [Online]. Available: https://en.wikipedia.org/wiki/C_(programming_language). [Accessed: 06-Apr-2021].
[3] “Introduction to C,” Introduction to C - Cprogramming.com. [Online]. Available: https://www.cprogramming.com/tutorial/c/lesson1.html. [Accessed: 07-Apr-2021].
[4] F. Copes, “The C Beginner's Handbook: Learn C Programming Language basics in just a few hours,” freeCodeCamp.org, 10-Mar-2020. [Online]. Available: https://www.freecodecamp.org/news/the-c-beginners-handbook/. [Accessed: 07-Apr-2021].
[5] “Data Types in C,” GeeksforGeeks, 03-Nov-2020. [Online]. Available: https://www.geeksforgeeks.org/data-types-in-c/. [Accessed: 09-Apr-2021].
Contributors:
User | Last Update |
---|---|
Mayurakhi Khan | 1114 days ago |
Former user (Deleted) | |
Former user (Deleted) | |
Former user (Deleted) |