C / C++ Tutorial Part 1


Background

This tutorial is intended to be a walk through the most used bits and bobs of the two languages. The main difference between the two languages is the structure of software that you will write. C is a procedural language whereas C++ is an object oriented language.

One thing I would like to find out is why you want to learn to program. I write software for a living and generally when I am home I will write software when I can't get hold of something that does what I want. When I first started out I was interested in how these things worked. Please e-mail me and tell me why you want to learn and what you want to learn. This will be a great help in compiling these pages.

I've had a good walk round the following newgroup alt.comp.lang.learn.c-c++ and found that people posting on there are asking for a free guide to programming in C and C++. I hope this may be of some help.

There are three sets of people that I primarily see on this newsgroups

  1. People who are experts and are kindly answerring peoples questions
  2. People who have made a small start and want to know how to move forward ( some with very great ambition )
  3. People who want to know where to start.

My aim is at 2. and 3.


Introduction

The starting point for this article is with C and elementary constructs. This means that we are going to be creating little programs that run at the command line. They do not rely on any platform dependant code, you will be able to do this on Dos, Mac, Linux, Unix with a standard C compiler. These things will be useful for you in the future whether you are writing a Win32 application for NT4, MAC application or anything. The first stage is always the handiest.

If you don't have a C/C++ compiler then you will need one to usefully use this tutorial. There are free compilers available for most compilers so you should be able to download one. If you have a 'C' only compiler then you will be fine for the first few tutorials.

All source code throughout the tutorial is embedded in the HTML. This means that you can print out all the pages in one go including the source in the right places, just like a book. Source is also avaliable for download.


Program Structure

Download Source

The classic Hello World - line by line


/* Include Files                  */
#include<stdio.h>

/* Program entry point            */
void main(void)
{
    /* Lets say Hello             */
    printf("Hello World\n");
}

Create a file that contains the above , build it and run it. It should say "Hello" to you. This may be a bit boring for the first go. "What possible use could this be to me ?", you might be saying. Well consider how many programs you see tell you something ?

OK the structure of this program.
The first thing you'll see is a comment surrounded by /* and */. Use comments to state, in plain language, what the code is trying to do.

#include is a preprocessor directive. In this case we are includeing information stored in the file stdio.h . Contained in the stdio.h file is a description of some functions. If you were to compile the above without the #include then you would get errors that would include the following "Undeclared function printf". As you go along writing code you will find that you need to include more than just stdio.h, there will be things for maths in math.h and things to do with memory in memory.h. So as we go through this article, the examples will start to have more #include files.

Next. We have one function in this program, called main. The structure of a function is :

"Return Type" "FunctionName" ( " Function Arguments" )

Our function has void for both the arguments and its return type. This means main takes no arguments and returns nothing.

main is a special function. It is the entry point of any 'C' program This is not strictly true, later on you will find that Winmain is the entry point into a windows program.

So we've got a function. It happens to be a special function - it's the first thing that will get called in our program. If you want to do anything in your program then this is the place to do it - "In main".

The body of the function is surrounded by "curly" brackets.

What do we do in main ? We call other functions !

The only function we call in this program is printf. This function outputs text to the screen at the current cursor position. I know I said that we would cover functions that would be useful whatever you do, I am afraid I have started with something that isn't. printf is only really useful is you are creating a command line program ( a program that runs in a text mode such as a DOS prompt). The thing is there are a couple of really handy functions that work just like printf but are applicable in any environment. Anyway this program does something so as to show something interesting on the screen.

In C and C++ we mark the end of a line of code with a semicolon ";". C and C++ ingores linfeeds ( when you press enter ) so we have to mark the end of a line of code explicitly. This is not true for comments.

We will go over a little later how to get more out of printf. For now I am very interested in whether you got that program to run. It is not really worthwhile going much further if this program did not compile, link and run. The way you know if it worked is if your computer came up with the text :
"Hello World" when you ran it.

If it worked then lets move on. I think we learned a lot there. We can now modify this program to do handy stuff. What about maths ?

In C there are several different variable types. Let's start off with the common ones :

Let's modify our program so it does some maths.

/* Include Files       */
#include<stdio.h>

/* Program entry point */
void main(void)
{
    /* Set up Variable  */
    int iMyWeight       = 150 ;
    int iRequiredWeight = 165 ;

    int iWeightToGain   = iRequiredWeight - iMyWeight;

    /* Lets say Hello */
    printf("My Current Weight %d\n",iMyWeight);
    printf("Required Weight   %d\n",iRequiredWeight);
    printf("Weight to Gain    %d\n",iWeightToGain);
}

OK so far ?. The major change is that we've used printf in a different way. printf is a special function in as much it have a variable input argument. The %d in the text means we want to embed a decimal value in the ouput text. The \n means new line. Think of the printf function as having many versions. We will cover exactly why you can pass a variable number of arguments later on.

I would have liked to do some user input. There is one thing we need to go over before we do that.

Arrays

Take for example the char type. If we had a string then we would want a whole bunch of chars. We would want an array.

char acString[10];

The above line shows the declaration of a variable which is an array of chars. Notice how I name the variables. In the weight example I named anything that was an int to to be iSomething. A char would be cSomething. The above array of chars is known as acSomething. This is known as Hungarian notation and is a standard to which a lot of programmers stick to. It means that anyone can look at a variable somewhere in a program ( which could be massive ) and not strain their brain figuring out what the variable type is. Anyway back to the array. See Good Practice

An array is exactly what we want, it's a hole bunch of types ( in this case chars ) all following one after the other.

If we say :

acString[0] = 'H';
acString[1] = 'E';
acString[2] = 'L';
acString[3] = 'L';
acString[4] = 'O';
acString[5] = 0 ; /* This is zero !! */

We have just filled up the array. We can now put that our to the screen using printf :

printf("%s\n",acString);

Note %s means we want to embed a string in the output text. Also printf works through the array until it finds a 0 ( zero ). If we have not set acString[5] to be zero then we would have seen :
HELLO followed by a whole bunch of garbage on the screen. Unless you are lucky !

Now let's ask the user to input something.

 

/* Include Files       */
#include<stdio.h>

/* Program entry point */
void main(void)
{
    /* Create a buffer for input*/
    char acInputTextBuffer[25];

    printf("Enter your text : ");

    /* Get the text from the user */
    gets(acInputTextBuffer);

    /* Tell the user what they typed */
    printf("\n You typed %d \n",acTextBuffer);
}

The function gets does "get string" into the buffer that you supply it.

Try it out.

NOTE: We only created an array of 25 chars. What would happen if we typed in too much, i.e. more than 25 characters ? Well we would end up scribbling, writing in nowheresville over who knows what. This is really bad ! We only asked for space for 25 characters therefore we can only use that. The compiler will not tell you that you have done wrong. You will find out if your computer hangs or comes up with an error.

Right we can right simple programs now.

Now lets make our computer make some decisions.

if is what we need. Every program you ever see or run will have an if in it ( if it's written in C or C++ that is)..

Part 2

Index


Counter Last Updated 3 January 1998 by Nik Swain (email: nikswain@geocities.com)

This page hosted by Geocities Icon Get your own Free Home Page

1