So far in our programming series, we’ve learned about some basic concepts like variables, functions, and operators with examples given in the C language. Now it’s time to apply everything we’ve learned to a more meaningful, problem-solving example.
In order to solve that problem, however, we’re going to have to discuss some things that we haven’t mentioned before. These are not complicated, but slightly more abstract ideas than the ones we’ve covered already. Now that you’re familiar with some basic C programming, you’re ready for these new concepts.
The first thing we’re going to discuss are standard libraries. The C standard library provides macros, type definitions, and functions for tasks like string handling, mathematical computations, input/output processing, memory allocation and several other operating system services. Basically, the libraries are a collection of code modules written by other people, which you can use without actually knowing how they were implemented. One example of using a library is the printf function we used before. However, in order to use these libraries, you have to emphasize which one you are going to use, simply by writing:
in the beginning of your program.
Let’s continue. The next thing needed for our example is a concept called structs. Structs allow programmers to group variables in a meaningful way, to describe or catalog something. This way, you can “make new data types,” since the language enables you to perform operations on your struct just like on some other data type.
For instance, if you want to work with points, which we are going to do in the video example, you can define a struct called Point. The two variables we need to describe a point are the coordinates: x and y. So, here’s the syntax for defining a struct Point in C:
Now, you can use Point as any other data type, and access its members by writing some_point.x or some_point.y.
Finally, the last term you need to familiarize yourself with is loops. Loops are programming constructs that enable you to easily do something multiple times. You can specify how many times you want an operation to be performed, and the condition when the repetition stops.
Here’s the syntax for defining a so-called for loop in C:
for(i=0; i<n; ++i)
This will repeat an action n times; the variable i (in this context called an iterator) will be initialized with the value 0. Then, a check will be made to see if i < n. If it is, some operation will be repeated, and i will be increased by 1. If not, we exit the loop.
To see how you can actually use these concepts when writing a program, please see the video below. In the video, we’ll solve a more complex and interesting problem using what we’ve learned so far. Please note, we will not yet be covering input checking and user interfaces but will in future articles so stay tuned.