Chapter 2
Your First Programs

Once you’ve got your IDE and your compiler installed, it’s time to start working on your first program. We’re going to follow a tradition that dates back to the prehistoric days of computing (1967!), and make your first program print out the simple text message “Hello, World!”

In the screenshots for this chapter, I’ll be using emacs on a Linux machine, but since C is so portable, you can follow along with whatever environment you happen to be using.

Hello, World!

Your first program in C is short, simple, and to the point. Fire up your development environment and save a new file as hello.c. Enter the following:

#include <stdio.h>
void main()
{
    printf("Hello, world!
");
    
}

Save the file, and then compile it. If you’re using an IDE, this can be done from the menu—there’s most likely a Save and Compile button or menu item. If you’re just using a text editor, then go to your terminal and enter

gcc hello.c -o hello

Assuming everything is done correctly, you should now have a new file in your directory, hello. When you don’t specify a name for your compiled program, gcc uses the default name of a.out. The -o flag in your gcc command gives your compiled executable the name hello.

Now run your program. In a terminal, enter

./hello

and you should be greeted with Hello, world! in your terminal (Figure 2-1).

Pretty simple, right? Let’s take a look at the program, line by line.

c02f001.tif

Figure 2-1: Output of hello.c

The first line tells the compiler to include a common header file, stdio.h, when it compiles. The filename stands for standard input output. It provides you with all the code you need for getting input and printing output to the terminal or other physical devices supported by your system.

The void main() block of code, surrounded by opening and closing brackets, is the main function in your program. The word void means that the function is not expected to return anything, and the empty parentheses after main show that the function takes no arguments.

Inside the main function block, the printf function prints Hello, world! to the screen, followed by a carriage return (the ).

This is a pretty simple program; I’d expect it to compile without errors. If you do have errors, it will probably be from a missing semicolon at the end of a line or from a missing closing bracket. In that case, gcc should alert you during the compilation process. In the case of a missing semicolon, you should get a message along the lines of

error: expected ',' or ';' before 'char'

Data Types

With your first program up and running, let’s take a moment to talk about C’s data types.

C has data types similar to other programming languages; these types include int, char, short, long, double, float, and various combinations of those (e.g., long double). Table 2-1 shows the most common data types and the range of values each can have. You can have multiple variables of the same type, but each variable must have a unique name. C is case-sensitive, so number is different from Number and NUMBER.

Table 2-1: Common data types

WildcardValue rangeUnsigned range
int%d−32,767 to +32,7670 to 65535
char%c–127 to 127 0 to 255
short%i−32,767 to +32,7670 to 65535
long%l−2,147,483,647 to +2,147,483,6470 to 4,294,967,295
float%f1.17549435e-38 to 3.40282347e+38n/a
double%g2.2250738585072014e-308 to 1.7976931348623157e+308n/a

One important thing to remember is that, unlike languages like Python, C requires you to declare your variable types, and to do so ahead of time. In other words, Python’s dynamic typing (for example) allows you to enter

x = 15
y = "Your mother is a hamster!"

and Python understands that x is an integer and y is a string. In C, you must explicitly state that:

int x = 15;
char y[26] = "Your mother is a hamster!"; 

(Note that y is an array of characters, not a string.) With older versions of gcc, declaring variables was even more inconvenient—you had to declare the variable first, and then set it. In other words, you had to type

int x;
x = 15; 

on separate lines, rather than combining them into one statement. Luckily, C standards progressed and C now allows declaring and setting in one statement.

So assuming your program compiled and ran, let’s make it a bit more interesting by adding some input from the user.

Hello, You Entered…

Open hello.c again in your editor. Modify the main() function to reflect the following:

int main()
{
    int number;
    printf("Please enter a number: ");
    scanf("%d", &number);
    printf("Hello, you entered %d
", number);
    return number;
}

Save the file and then compile it, again with

gcc hello.c -o hello

and run it with

./hello

Your terminal prompt should now ask you for a number and then repeat that number back to you. Again, it’s pretty simple. Let’s take a look at the additions to the program.

After declaring number to be an integer (see the previous section “Data Types”), the program asks for a number and then reads the input from the user by using the scanf function. The %d tells the program to expect an integer, which is then placed into the memory location called number that we initialized earlier. Then the program prints the entered number, again using %d to specify an integer.

Finally, we changed the function type from void, which returns nothing, to int, which returns an integer. Specifically, it returns the integer you entered. Here, the program does nothing with the information, but you can use this type of function to get input from any source and return it to the main program.

Now that you’ve gotten a quick introduction with some working programs, let’s dig a little deeper into C’s syntax.

if/then/else Conditions

As in many other programming languages, C allows you to make decisions regarding the flow of code with if/then/else and switch statements.

The syntax of the if/then/else statement is simple:

if (x == 4)
{
    printf("Yup, it's four!
");
}
else if (x ==5)
{
    printf("Nope, it's five!
");
}
else
{
    printf("It's something else entirely.
");
}

The logic here is as follows: The program checks to see if x is equal to 4. If it is, it prints the first printf statement and then skips the rest of the conditional checks and moves on. If x doesn’t equal 4, the program checks to see if x equals 5. If it does, the program prints that printf statement and jumps out of the conditional loop. Finally, if x is neither 4 nor 5, the last else covers all other bases. The program prints the last line, and then continues.

Obviously, if you have to compare x against 15 different integers and perform a different task in each case, the standard if/then statement can get a bit unwieldy. In that case, C has the switch statement, which is more elegant.

switch (x)
{
    case 1:
        printf("It's one!
");
        break;
    case 2:
        printf("It's two!
");
        break;
    case 3:
        printf("It's three!
");
        break;
    default:
        printf("It's something else entirely!
");
}

The logic here should be pretty self-explanatory; the program checks x against each case and executes the appropriate printf statement. The break statement is necessary to break the code out of the conditional loop. Without it, the program will execute each line after the successful case. The default statement is optional and covers “everything else.” It comes at the end of the switch statement and is executed only if none of the previous cases applied.

Loops

The ability to have a program repeat one task over and over again is just as important in C as in any other language. C has three types of loops: for, while, and do/while. Let’s look at them.

for

int i; 
for (i=0; i<4; i++)
{
    printf("This is loop number %d
", i);
}

The first line of a for loop is actually a declaration, comparison, and assignment statement all in one. This code first sets i equal to 0. Then it sees if i is less than 4. If it is, it executes the contained (bracketed) code and then adds 1 to i and repeats the process. If you compile and execute this code, you should see

This is loop number 0
This is loop number 1
This is loop number 2
This is loop number 3

An important thing to note here is that if i is equal to 4, the code doesn’t execute. In this case, it still executes four times, since i starts at 0 (like many loops in programming), but if you set your loop with different starting and ending points, keep in mind that the less-than (<) symbol might end your loop earlier than you thought.

while

int x = 0;
while (x < 10)
{
    printf("x equals %d
", x);
    x++;
}

while is similar to the for loop. In fact, it’s so similar that you might be inclined to wonder why you would use this particular loop at all. The while loop is most useful if you are constantly checking a condition that might be updated by another part of your code. Here, obviously, we set and update x ourselves, but if we were monitoring a sensor, we could continue to loop until the sensor return reached a particular value.

do/while

do/while is almost exactly like the while loop:

int x = 4;
do 
{
    printf("Still happening!
");
}
while (x == 4);

The difference is that here, the condition (is x equal to 4?) is checked only after the printf line is executed, so it always executes at least once. A while loop says “Loop while this is true, and do this,” whereas a do/while loop says “Do this, and then keep doing it while this is true.” A small difference, but an important one.

A Few Notes about Syntax

C is pretty easy to understand, syntax-wise. All statements must end in a semicolon. If you see a line that doesn’t, it’s because that statement is continued on another line. A for loop, for example, is just one long statement.

Comments, which you should use often, start with //. Anything that comes after a double forward slash is ignored by the compiler. To comment out a block of code, use a matching pair of /* and */:

/*
Anything within this block can be ignored.
*/

Whitespace doesn’t matter. Neither do carriage returns. In fact, most of the “pretty” code you see looks that way only for the programmer. Functionally,

for (i=0; i<5; i++)
{
    printf("This is another loop!
");
    x = y * (i + 5);
}

is exactly the same as

for(i=0;i<5;i++){printf("This is another loop!
");x=y*(i+5);}

and will be understood by most compilers just fine. That being said, however, please don’t write your code like that. It’s impossible to read and—perhaps more important—to debug. Use comments and whitespace generously. It’s just good programming practice.

So that is your introduction to C. Let’s jump into a simple programming project with the Raspberry Pi Zero!

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.149.249.252