Note 1
C Programming Language
I always wanted to learn C. I mean C really is the fundamental language that inspired so many others like PHP, Java, C++, and so much more. Also there is that coolness in C. Is it only me? Or do you also feel that sensation when you see 90+% gray dot in GitHub repository for Linux Kernel? Writing in C and going low level has its own coolness. In this note, we will discuss some fundamental features in C for us to actually use it for writing goodies. Many of the contents here are based on the video “C Programming Tutorial for Beginners” from freeCodeCamp by Mike Dane and many other online tutorials [Dan18].
1.1 Foundations
The previous note contains much more detailed explanations on data structures, algorithms, and solving problems. So in this section, instead of discussing everything from scratch again, let’s focus on the syntax for C and some distinct features that C shines with.
For our first program, let’s output “Hello, world!” and see how to compile C programs.
For our header, we have standard input/output and we use printf to print output “Hello, world!”. Now there are two popular ways of compiling it and we can use either GCC or Clang. They are nearly identical (please don’t get mad at me!), and I will be using Clang since I am on macOS.
With this, let’s discuss about input/output and basic data types.
1.1.1 Input/Output and Basic Data Types
Now this printf function can be very powerful. Like Java, we can pass values into placeholders like %d, %f, %s, %c, namely double, float, string, and character. Here is an example.
Code 1.1.2: 26clcwy-02
1#include <stdio.h> 2 3int main() { 4 int age = 123; 5 double gpa = 3.14; 6 char name[] = "Enoch"; 7 8 printf("%s is %d years old.\n", name, age); 9 printf("He has a GPA of %f and a letter grade of %c\n", gpa, ’A’); 10 printf("%s also loves math. For example...\n", name); 11 printf("%f / %d = %f\n", 1.0, 5, 1.0 / 5); 12 13 return 0; 14}
As you can see, we can define integer, double, float, and character as usual. We can also pass our values into the place holder. You may have noticed that we wrote char name[] = "Enoch"; instead of string name = "Enoch";. This is because unlike other languages, C doesn’t have data type string in its usual sense. We will discuss more about this as we discuss arrays and pointers. Finally, notice that we wrote \(1.0\) instead of \(1\) for our first %f in the last line. This is because \(1\) by itself is an integer and we will get an error. Compiling and running, we get the following output.
Output 1.1.3
As you can see, we get \(3.140000\) instead of \(3.14\). When displaying, C likes to give a more accurate value. Continuing, we have same commenting style as C++.
Similar to other languages, we can define a constant with const and arrays with arr[] as well. Here is an example of using constants and arrays.
Code 1.1.6: 26clcwy-04
1#include <stdio.h> 2 3int main() { 4 const int FIXED_VALUE = 5; 5 int arr[5] = { 1, 2, 3, 4, 5 }; 6 double tensor[2][3] = {{0.0, 0.1, 0.2}, 7 {1.0, 1.1, 1.2}}; 8 char string[10] = "string"; 9 10 printf("Fixed value: %d\n", FIXED_VALUE); 11 printf("Second element of the array: %d\n", arr[1]); 12 printf("Second row, third column: %f\n", tensor[1][2]); 13 printf("Third charater in the string: %c\n", string[2]); 14 15 return 0; 16}
Output 1.1.7
Now as mentioned previously, strings are quite different in C. They are not totally different data types, but just an array of characters. This simple nature of C is one of the factors that makes C special, but also slightly annoying.
Now before moving onto inputs and outputs, here is one more data type. This one called struct is quite interesting because it is user-defined and also a composite data type. It can look like a class without functions, but they are different. Struct defines data type that we can use to organize information. Here is an example usage.
Code 1.1.8: 26clcwy-05
1#include <stdio.h> 2 3typedef struct { 4 float a; 5 float b; 6 float c; 7} array ; 8 9struct vector { 10 float x; 11 float y; 12}; 13 14int main() { 15 // Using vec 16 struct vector vec; 17 vec.x = 0.1; 18 vec.y = 0.2; 19 printf("v = <%f, %f>\n", vec.x, vec.y); 20 21 // Using arr 22 array arr = { .a = 0.1, .b = 0.2, .c = 0.3, }; 23 printf("arr = [%f, %f, %f]\n", arr.a, arr.b, arr.c); 24 25 return 0; 26}
Struct is nice because we can use it like a template and reuse it multiple times. Also we will discuss more on typedef later but we can use it as shown above to avoid writing more characters. Let’s now turn our attention to inputs and outputs in C. We already discussed outputs, so let’s see how we can take values in from the user in C.
Code 1.1.10: 26clcwy-06
1#include <stdio.h> 2 3int main() { 4 char name[10], fullName[30], alp; 5 int age; 6 double date; 7 8 printf("Full Name: "); 9 fgets(fullName, 30, stdin); 10 printf("First Name: "); 11 scanf("%s", name); // No ampersand here 12 printf("Age: "); 13 scanf("%d", &age); // You need this ampersand! 14 printf("Date: "); 15 scanf("%lf", &date); // %lf not %f 16 printf("Alphabet: "); 17 scanf(" %c", &alp); // You need the space in front of %c! 18 19 printf("Hi %s, today is %f\n", name, date); 20 printf("Your full name is %s", fullName); 21 printf("You are %d years old and you chose %c!\n", age, alp); 22 23 return 0; 24}
Output 1.1.11
The ampersand that you see is there because we pass a pointer to scanf, but we will get there in a second. Also when passing a character, float, and a string with spaces in it, we need to consider few factors. This is the place where I said its kinda annoying and awkward at first, but they are what makes C, the C!
Also, C is designed to give us low level access, so as you can see with getting string inputs, we can manually allocate memory necessary. Now continuing with input/output and simple data types, let’s move on to conditionals and loops.
1.1.2 Conditionals and Loops
The syntax for conditionals for C is identical to the ones for C++. Here is an example of using if-else statements.
Similarly, we could also use switch statements.
Code 1.1.14: 26clcwy-08
1#include <stdio.h> 2 3int main() { 4 int choice; 5 printf("Your choice (1-3): "); 6 scanf("%d", &choice); 7 8 switch (choice) { 9 case 1: 10 printf("Your choice is 1\n"); 11 break; 12 case 2: 13 printf("Your choice is 2\n"); 14 break; 15 case 3: 16 printf("Your choice is 3\n"); 17 break; 18 default: 19 printf("Invalid Option\n"); 20 break; 21 } 22 23 return 0; 24}
Output 1.1.15
Continuing, we also have the same syntax for for, while, and do-while loops.
Code 1.1.16: 26clcwy-09
1#include <stdio.h> 2 3int main() { 4 for (int i = 0; i < 5; i++) { 5 printf("%d ", i); 6 } 7 printf("\n"); 8 9 int ctr = 0; 10 while (ctr < 5) { 11 printf("%d ", ctr); 12 ctr++; 13 } 14 printf("\n"); 15 16 do { 17 printf("%d ", ctr); 18 ctr++; 19 } while (ctr < 0); 20 printf("\n"); 21 22 return 0; 23}
Now before wrapping up this section, let’s discuss about functions.
1.1.3 Functions
Functions in C works like many other languages. Here is an example of a hello user function.
When we want our main function to be on the very top, then we need something called prototype. Function prototypes and declaration are used interchangeably with slight difference in nuance. As shown below, we need to basically tell the compiler that the function that we will be using in the main function exists, so that it doesn’t complain about it.
This is it for this section! In the next section, we will discuss more about pointers and we mentioned briefly here.