Friday, 2 June 2017

A little bit of C

C is a general purpose programming language that is available for many platforms and is built in to most, if not all, versions of Linux. Raspian is no exception.

In this blog I've been looking at the languages available for the Raspberry Pi and writing simple programs to give you a feel of the language (e.g. see A Little Bit of Julia on this blog).


As I said there is no need to set up C in Raspian - it's just there!

Here is a simple program that shows how to use simple input and output, decisions, loops and functions.

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

// define a function to get a guess
int guess(){
    printf("Enter a guess (1 to 10): ");
    int a;
    return a;
// Start here
int main(int argc, char **argv)
    time_t t;
    srand((unsigned) time(&t));
    int x = rand()%10+1;
    for(int i = 0; i < 5; i++){
        int answer = guess();
        if (answer == x){
    printf("The answer was %d\n",x);
    return 0;

If you've looked at my Python or Julia blogs, you will be familiar with this program.

C is a compiled language, which means that it is converted into machine code by a program called a compiler before it can be run. This is different to a language like Python which is interpreted, that is, the program text is read and executed directly. A compiled program tends to run faster than an interpreted one.

To get this program working use your favourite editor to create the program and save it. Now open a terminal window and cd to the appropriate directory. Let's say you called the program guess.c (and you should use a .c extension), then type the command

gcc guess.c -o guess.exe

This invokes the compiler and produces and executable file called guess.exe.

To run it do this


That's it.

The program is reasonably straightforward. If you are familiar with Python, or any other language you should be able to work out what is going on here although the specific functions may be unfamiliar.

One thing that might look a bit peculiar the the method of generating a random number. We have to seed the number generator with an unknown number (this is the reason we use the time) otherwise we will get the same set of numbers each time the program is run. The rand() function, itself, produces a pseudo random integer between 0 and 32767 (at least). We use the remainder operator and add one, to get to the range 1 to 10.

One difference with Python is that blocks of code inside a function, if statement or loop are enclosed with curly braces. Indentation is not strict, as in Python, but it is, of course, conventional to indent properly.

This is the C version of the program in my tutorials Just Enough Python (see below).


Just Enough Python
An brief introduction that will get you programming quickly

No comments:

Post a Comment