Basic C C

Basic C. Before we begin, let me just say that C is not a good language to start programming in. If you don't know any programming languages, don't start with C. Learn BASIC or Pascal first, to get down some essential programming theory before you enter an advanced-level language like C. BASIC is excellent for your first language, and Pascal will teach you many useful things.

That said, if you already know BASIC or Pascal (or better yet, both), here is a basic introduction to the essentials of C.

The printf command: (equivalent to BASIC's PRINT command)

What does the "f" stand for? The "f" in "printf" stands for "formatted". Although it can be (and often is) used to output simple text strings, printf can also be used to insert variables (as we'll see below shortly), as well as to specify the field width (typically used to specify the number of decimal places for a number). printf seems deceptively simple at first, but it has a few formatting options which give it some sophistication that goes beyond simple "Hello, world!" functionality.

printf's syntax is:

printf("text");

For example, this:

printf("Hello, world!");

prints "Hello, world!"

To print variables (which, basically, are data values that vary), the syntax is:

printf("%vartype",varname);

Where %vartype is the type of variable and varname is the actual name of it. For example, this:

printf("%s",strname);

prints out the string called strname.

C's most commonly-used types of variables are:

%s string

%c character

%d int (integer)

%f double (a "double" type variable is a decimal number, as opposed to int, which is an integer, i.e. a number with nothing after the decimal)

%lf double (same as %f except %f is used for printf, while %lf is used for scanf)

The scanf command: (equivalent to BASIC's INPUT command)

Takes input from the keyboard, and stores it in specified variable. Syntax is:

scanf("%vartype", &varname);

For example, this line:

scanf("%s", &strname);

Gets string input, and sticks it in a variable called strname.

You can scanf more than one variable at a time like this:

scanf("%d %d %d", &a &b &c);

This line will scan in three integers, and name them a, b, and c respectively.

The #include command:

This command simply includes another file in the code of the C program. For example, if you had a nice function written in C in a file called FUNCTION.TXT and wanted it used in this program but didn't want to include the function's own code in this program's (for whatever reason), you could just include the FUNCTION.TXT with #include. Syntax is:

#include <filename.ext>

A VERY commonly-seen line near the start of many C programs is:

#include <stdio.h>

What this does is, it includes a file called STDIO.H which defines the printf and scanf functions, as well as several others so that they work! (printf and scanf are not built into C, they must be defined by #including STDIO.H) STDIO.H is what's known as a "header file", a file specifically intended to be #included at the top of C programs. Like STDIO.H, header files usually simply have a letter H for an extension. (STDIO stands for STandarD Input/Output.)

Comments

BASIC uses REM to put remarks in the program to make it easier to read... They actually serve no purpose in the program itself. C programs can contain comments too, but instead of a sensible command, they use weird characters: /* must begin the comment, and */ ends it.

/* This is the correct format for a program comment */

The if command:

As in most programming languages, the if command is used to perform a conditional operation. The syntax is like this:

if (statement here is true)
{
/* do everything here if statement is true */
}
else
{
/* do everything here if statement is not true */
}

If the statement in the parentheses is true, the code between the curly brackets will be executed. You don't need to use an else command with if, but if you do, the code in between the second set of curly brackets will be executed if the statement is not true.

Here's an example:

if (money = 20)
{ printf("You have exactly 20 dollars."); }
else
{ printf("You don't have exactly 20 dollars."); }

(This example code, as you can see, put the commands with their curly brackets on the same lines so the code looks a little less ugly. Generally, C doesn't really care about where you put spaces or new lines.)

typedef

typedef lets you create a new variable type name. For example, suppose you wanted to define an integer using "integer" instead of "int". You would use a line like this:

typedef int integer

Now you could create an integer variable called, say, a, with the line integer a instead of int a. (Note, however, that typedef is usually used to create less typing for the programmer, not more, as in this example.)

(typedef) struct

struct lets you create a "structure", which is basically a new type of variable, with multiple sub-variables in it. For example, suppose you want to create a database of people, along with some vital stats on those people. Let's suppose for this example you have three people: Charlie, Mary, and Bob, and the stats you want to record are age, city of residence, and job. You *could* create separate variables for each person's stat (CharliesAge, MarysCity, BobsJob, etc.), which would be fine if you only have three people, but painful if you had to create multiple variables for a large database of several thousand people, especially if you also had to record more than three pieces of data about each person.

To make this kind of thing easier, you would probably create a data structure, specifying exactly what kind of data you wanted on each person. You could make a variable type called "person", using this code:

typedef struct {
   int age;
   char city[40];
   char job [40];
} person;

This will create a structure called person (which really is a new type of variable), containing separate fields for each person's age, city, and job. Now you could create your people with the following code:

person Charlie;
person Mary;
person Bob;

As you can see, once you create a struct, you declare it in the same way you declare an int or a char variable. Note that each individual instance of a structure is often called an "object". This is where object-oriented programming starts.

So now that you have all these variables created, how do you modify them? With the following format: objectname.variable = value; For example, suppose Mary is a 40-year old vice-president from Los Angeles. You'd use this format to define that:

Mary.age = 40;
Mary.city = "Los Angeles";
Mary.job - "vice-president";

That's about all you need to know for the basics of structures. It probably seems like a lot of unnecessary fuss when you could just create each variable separately, but a lot of programming is about making things easier for the programmer, and you'd much rather be able to define what makes one person's info, then define each person with the line "person (name)" than have to create multiple variables for *each* person. Objects give you an easy way to do that.

Now, I should mention another command which works almost exactly the same way as typedef struct, and which you'll hear about a lot in the programming world: class. struct and class are very similar. However, C only supports struct, not class. class is a feature of C++ only. class has somewhat "extended" functionality over struct, and thus, it's preferred by people who're making their objects in C++. But if you're using just plain C, you have to use typedef struct.


Now, here are some sample programs to get you started with C:

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

This program prints "Hello, world." The main() line needs some explaining: It indicates that the following stuff in the curly brackets ("curly brackets" are the common name for the { and } type of brackets) is the main program function. You can actually have several functions in a program, denoted by simply having their name followed by two "curvy brackets" (regular parentheses), and then the actual code for that function in curly brackets. Most basic C programs just have the main function, however. It simply indicates that that's the main part of the program. (The #include is not part of the main program. It's a command to the C preprocessor, which is the part that comes before the main program code.)

#include <stdio.h>
main()
{
  printf("As you can see, C uses an odd\n");
  printf("syntax which makes even simple\n");
  printf("tasks, like printing to the screen,\n");
  printf("harder than they should be.");
}

This program is much like the first. The only difference is, it prints several lines of text to the screen. The \n things at the end of each line are important: They indicate a new line. This means that the program output appears as four lines, with a new line being created at each \n. Otherwise the program would print the text out all as one line. (Unlike BASIC, which automatically creates a new line for each PRINT command, C does not do the same with printf.)

Now is also a good time to look at indentation style. Notice that the four printf lines in the program above are indented: They have a couple of spaces preceding them. This is done to make them stand out. After all, they are the main program. Individual parts of programs are usually indented in this way, to make it easier to separate them from one another. (The same is done in most programming languages, actually.)

/* Program to add 3 to any number. */
#include <stdio.h>
main()
{
  int n;
  printf("Enter an integer> ");
  scanf("%d", &n);
  n = n + 3;
  printf("That number plus 3 equals %d", n);
}

This program is pretty simple, and you should be able to understand most of it by now. It makes an int (remember, that's integer) type variable called simply n, and adds 3 to it in the line:

n = n + 3

Math is done this way in C, with the result coming FIRST, not LAST. It is not done like n + 3 = n. You put the result n first, then say that it is now itself plus 3. (BASIC does it the same way.)

Yes, the & sign before the n in the scanf is important. Variable names that are read through scanf are preceded by that, always. (See "scanf rant", below, for an elaboration.)

The comment at the top of the above program is also worth noting: It's a common practice to briefly note the program's purpose in a comment at the top like that.

The only other line you need to know about is the int n; one. That is what's called a declaration. It defines the variable n as being an int type of variable. Declarations don't have to always be done, but they help. It's considered good practice to declare all variables you plan to use in the program in this way. You can declare multiple variables of the same type on the same line like this:

int a, b, c;

In this example, you've declared three int-type variables, named a, b, and c.

scanf Rant:

scanf uses the ADDRESSES of variables when it puts input into them. It doesn't accept the ACTUAL VARIABLE NAMES. THIS IS WHY THE AMPERSAND (&) is necessary before each variable name. Like this:

scanf("%d", &age);

That puts whatever input into the variable "age". The & indicates that you want scanf to put the input in the MEMORY LOCATION of age! If you omitted the ampersand, it would instead put the input into a completely different place (specifically, whatever the value of "age" is, would be where the input is stored in the computer's RAM). Putting "&age" instead tells scanf to put the input at the ADDRESS OF age, so everything's peachy. & is C's "address of" operator.

Note that you can also use the address-of operator for output. For example, you can do this to find out just what the address of the age variable really is:

printf(&age);

Be warned, however, that doing this is a sign that you are extremely boring.

Making your own functions

One pretty cool thing that you can do in C is make your own functions. Why would you want to? Well, you'd do it for often-repeated routines so that you can just use one line to do a whole procedure. C already has several functions built into its header files (files ending in .h, like include.h). For example, printf is a function in stdio.h. You can make your own functions fairly easily... All it takes is this:

void funcname(void)
{
    /* FUNCTION CODE GOES HERE! */
}

This makes a function called funcname, which you can then use for your own evil purposes. ;) You can call it like this:

funcname();

...And that's all there is to it! You can put the code for the function anywhere, even before the main program's code. This, by the way, is why you must specify a main function in every C program... Unlike many languages (like BASIC), C does not simply start at the top of the code and work its way down from there; It starts at the function main. So you need to define main so the program knows where to start (even if it's the only function in the whole program).

Well, this isn't exactly everything you need to know about C but it's a good start... So, now you know basic C! Have fun with it.

Back to the main page