Learn C Programming Tutorial Lesson 1 Hello World
Learn C Programming Tutorial Lesson 1 Hello World
Hello World
What is C and why learn it
C was developed in the early 1970s by Dennis Ritchie at Bell Laboratories. C was originally
designed for writing system software but today a variety of software programs are written in C.
C can be used on many different types of computers but is mostly used with the UNIX operating
system.
It is a good idea to learn C because it has been around for a long time which means there is a lot
of information available on it. Quite a few other programming languages such as C++ and Java
are also based on C which means you will be able to learn them more easily in the future.
What you will need
This tutorial is written for both Windows and UNIX/Linux users. All the code in the examples
has been tested and works the same on both operating systems.
If you are using Windows then you need to download borland C++ compiler from
http://www.borland.com/cbuilder/cppcomp. Once you have downloaded and installed it you need
to add "C:\Borland\BCC55\Bin" to your path. To add it to your path in Windows 95/98/ME you
need to add the line "PATH=C:\Borland\BCC55\Bin" to c:\autoexec.bat using notepad. If you
are using Windows NT/2000/XP then you need to open the control panel and then double click
on "system". Click on the "Advanced" tab and then click "Environment Variables". Select the
item called "Path" and then click "Edit". Add ";C:\Borland\BCC55\Bin" to "Variable value" in
the dialog box that appears and then click Ok and close everything.
All Windows users will now have to create a text file called "bcc32.cfg" in
"C:\Borland\BCC55\Bin" and save the following lines of text in it:
-I"C:\Borland\BCC55\include"
-L"C:\Borland\BCC55\lib"
If you are using UNIX/Linux then you will most probably have a C compiler installed called
GCC. To check if you have it installed type "cc" at the command prompt. If for some reason you
don't have it then you can download it from http://gcc.gnu.org.
Your first program
The first thing we must do is open a text editor. Windows users can use Notepad and
UNIX/Linux users can use emacs or vi. Now type the following lines of code and then I will
explain it. Make sure that you type it exactly as I have or else you will have problems. Also don't
be scared if you think it is too complicated because it is all very easy once you understand it.
#include<stdio.h>
int main()
{
printf("Hello World\n");
return 0;
}
#include<stdio.h>
This includes a file called stdio.h which lets us use certain commands. stdio is short for Standard
Input/Output which means it has commands for input like reading from the keyboard and output
like printing things on the screen.
int main()
int is what is called the return value which will be explained in a while. main is the name of the
point where the program starts and the brackets are there for a reason that you will learn in the
future but they have to be there.
{}
The 2 curly brackets are used to group all the commands together so it is known that the
commands belong to main. These curly brackets are used very often in C to group things
together.
printf("Hello World\n");
This is the printf command and it prints text on the screen. The data that is to be printed is put
inside brackets. You will also notice that the words are inside inverted commas because they are
what is called a string. Each letter is called a character and a series of characters that is grouped
together is called a string. Strings must always be put between inverted commas. The \n is called
an escape sequence and represents a newline character and is used because when you press
ENTER it doesn't insert a new line character but instead takes you onto the next line in the text
editor. You have to put a semi-colon after every command to show that it is the end of the
command.
Table of commonly used escape sequences:
\a Audible signal
\b Backspace
\t Tab
\n Newline
\v Vertical tab
\f New page\Clear screen
\r Carriage return
return 0;
The int in int main() is short for integer which is another word for number. We need to use the
return command to return the value 0 to the operating system to tell it that there were no errors
while the program was running. Notice that it is a command so it also has to have a semi-colon
after it.
Save the text file as hello.c and if you are using Notepad make sure you select All Files from the
save dialog or else you won't be able to compile your program.
You now need to open a command prompt. If you are using Windows then click Start->Run and
type "command" and Click Ok. If you are using UNIX/Linux and are not using a graphical user
interface then you will have to exit the text editor.
Using the command prompt, change to the directory that you saved your file in. Windows users
must then type:
C:\>bcc32 hello.c
UNIX/Linux users must type:
$cc hello.c -ohello
The -o is for the output file name. If you leave out the -o then the file name a.out is used.
This will compile your C program. If you made any mistakes then it will tell you which line you
made it on and you will have to type out the code again and this time make sure you do it exactly
as I did it. If you did everything right then you will not see any error messages and your program
will have been compiled into an exe. You can now run this program by typing "hello.exe" for
Windows and "./hello" for UNIX/Linux.
You should now see the words "Hello World" printed on the screen. Congratulations! You have
just made your first program in C.
Indentation
You will see that the printf and return commands have been indented or moved away from the
left side. This is used to make the code more readable. It seems like a stupid thing to do because
it just wastes time but when you start writing longer, more complex programs, you will
understand why indentation is needed.
Using comments
Comments are a way of explaining what a program does. They are put after // or between /* */.
Comments are ignored by the compiler and are used by you and other people to understand your
code. You should always put a comment at the top of a program that tells you what the program
does because one day if you come back and look at a program you might not be able to
understand what it does but the comment will tell you. You can also use comments in between
your code to explain a piece of code that is very complex. Here is an example of how to
comment the Hello World program:
/* Author: Your name
Date: yyyy/mm/dd
Description:
Writes the words "Hello World" on the screen */
#include<stdio.h>
int main()
{
printf("Hello World\n"); //prints "Hello World"
return 0;
}
int main()
{
int a;
scanf("%d",&a);
a = a * 2;
printf("The answer is %d",a);
return 0;
}
The %d is for reading or printing integer values and there are others as shown in the following
table:
%d or %i int
%c char
%f float
%lf double
%s string
The if statement
So far we have only learnt how to make programs that do one thing after the other without being
able to make decisions. The if statement can be used to test conditions so that we can alter the
flow of a program. The following example has the basic structure of an if statement:
#include<stdio.h>
int main()
{
int mark;
char pass;
scanf("%d",&mark);
if (mark > 40)
pass = 'y';
return 0;
}
In the above example the user enters the mark they got and then the if statement is used to test if
the mark is greater than 40. Make sure you remember to always put the conditions of the if
statement in brackets. If the mark is greater than 40 then it is a pass.
Now we must also test if the user has failed. We could do it by adding another if statement but
there is a better way which is to use the else statement that goes with the if statement.
#include<stdio.h>
int main()
{
int mark;
char pass;
scanf("%d",&mark);
if (mark > 40)
pass = 'y';
else
pass = 'n';
return 0;
}
The if statement first tests if a condition is true and then executes an instruction and the else is
for when the result of the condition is false.
If you want to execute more than 1 instruction in an if statement then you have to put them
between curly brackets. The curly brackets are used to group commands together.
#include<stdio.h>
int main()
{
int mark;
char pass;
scanf("%d",&mark);
if (mark > 40)
{
pass = 'y';
printf("You passed");
}
else
{
pass = 'n';
printf("You failed");
}
return 0;
}
It is possible to test 2 or more conditions at once using the AND (&&) operator. You can use the
OR (||) operator to test if 1 of 2 conditions is true. The NOT (!) operator makes a true result of a
test false and vice versa.
#include<stdio.h>
int main()
{
int a,b;
scanf("%d",&a);
scanf("%d",&b);
if (a > 0 && b > 0)
printf("Both numbers are positive\n");
if (a == 0 || b == 0)
printf("At least one of the numbers = 0\n");
if (!(a > 0) && !(b > 0))
printf("Both numbers are negative\n");
return 0;
}
Boolean operators
In the above examples we used > and < which are called boolean operators. They are called
boolean operators because they give you either true or false when you use them to test a
condition. The following is table of all the boolean operators in c:
== Equal
!= Not equal
> Greater than
>= Greater than or equal
< Less than
<= Less than or equal
&& And
|| Or
! Not
int main()
{
char fruit;
printf("Which one is your favourite fruit:\n");
printf("a) Apples\n");
printf("b) Bananas\n");
printf("c) Cherries\n");
scanf("%c",&fruit);
switch (fruit)
{
case 'a':
printf("You like apples\n");
break;
case 'b':
printf("You like bananas\n");
break;
case 'c':
printf("You like cherries\n");
break;
default:
printf("You entered an invalid choice\n");
}
return 0;
}
What are loops
Sometimes you will want to do something a lot of times. An example would be printing a
character at the beginning of each line on the screen. To do this you would have to type out 24
printf commands because there are 25 rows on the screen and the 25th row will be left blank. We
can use a loop to do this for us and only have to type 1 printf command. There are 3 basic types
of loops which are the for loop, while loop and do while loop.
The for loop
The for loop lets you loop from one number to another number and increases by a specified
number each time. This loop is best suited for the above problem because we know exactly how
many times we need to loop for. The for loop uses the following structure:
for (starting number;loop condition;increase variable)
command;
With loops you also have to put commands between curly brackets if there is more than one of
them. Here is the solution to the problem that we had with the 24 printf commands:
#include
int main()
{
int i;
for (i = 1;i <= 24;i++)
printf("H\n");
return 0;
}
A for loop is made up of 3 parts inside its brackets which are separated by semi-colons. The first
part initializes the loop variable. The loop variable controls and counts the number of times a
loop runs. In the example the loop variable is called i and is initialized to 1. The second part of
the for loop is the condition a loop must meet to keep running. In the example the loop will run
while i is less than or equal to 24 or in other words it will run 24 times. The third part is the loop
variable incrementer. In the example i++ has been used which is the same as saying i = i + 1.
This is called incrementing. Each time the loop runs i has 1 added to it. It is also possible to use
i-- to subtract 1 from a variable in which case it's called decrementing.
The while loop
The while loop is different from the for loop because it is used when you don't know how many
times you want the loop to run. You also have to always make sure you initialize the loop
variable before you enter the loop. Another thing you have to do is increment the variable inside
the loop. Here is an example of a while loop that runs the amount of times that the user enters:
#include<stdio.h>
int main()
{
int i,times;
scanf("%d",×);
i = 0;
while (i <= times)
{
i++;
printf("%d\n",i);
}
return 0;
}
int main()
{
int i,times;
scanf("%d",×);
i = 0;
do
{
i++;
printf("%d\n",i);
}
while (i <= times);
return 0;
}
int main()
{
int i;
while (i < 10)
{
i++;
if (i == 5)
break;
}
return 0;
}
You can use continue to skip the rest of the current loop and start from the top again while
incrementing the loop variable again. The following example will never print "Hello" because of
the continue.
#include<stdio.h>
int main()
{
int i;
while (i < 10)
{
i++;
continue;
printf("Hello\n");
}
return 0;
}
Multi-dimensional arrays
The arrays we have been using so far are called 1-dimensional arrays because they only have
what can be thought of a 1 column of elements. 2-dimensional arrays have rows and columns.
Here is a picture which explains it better:
1-dimensional array
01
12
23
2-dimensional array
012
0123
1456
2789
You do get 3-dimensional arrays and more but they are not used as often. Here is an example of
how you declare a 2-dimensional array and how to use it. This example uses 2 loops because it
has to go through both rows and columns.
int a[3][3],i,j;
for (i = 0;i < 3;i++)
for (j = 0;j < 3;j++)
a[i][j] = 0;
int main()
{
Hello();
return 0;
}
Parameters
Parameters are values that are given to a function so that it can perform calculations with them.
The "Hello\n" which we used in the Hello function is a parameter which has been passed to the
printf function.
You need to declare variables inside the parameter brackets to store the values of the parameters
that are passed to the function. Here is an Add function which adds the 2 parameters together and
then returns the result.
#include<stdio.h>
int main()
{
int answer;
answer = Add(5,7);
return 0;
}
You can pass the address of a variable to a function so that a copy isn't made. For this you need a
pointer.
#include<stdio.h>
int main()
{
int answer;
int num1 = 5;
int num2 = 7;
answer = Add(&num1,&num2);
printf("%d\n",answer);
return 0;
}
// Global variables
int a;
int b;
int Add()
{
return a + b;
}
int main()
{
int answer; // Local variable
a = 5;
b = 7;
answer = Add();
printf("%d\n",answer);
return 0;
}
Command-line parameters
Sometimes you also pass parameters from the command-line to your program. Here is an
example:
$ myprogram -A
To be able to access the command line parameters you have to declare variables for them in the
brackets of the main function. The first parameter is the number of arguements passed. The name
of the program also counts as a parameter and is parameter 0. The second parameter is the
arguements in a string array.
#include<stdio.h>
struct person
{
char *name;
int age;
};
int main()
{
struct person p;
return 0;
}
To access the string or integer of the structure you must use a dot between the structure name and
the variable name.
#include<stdio.h>
struct person
{
char *name;
int age;
};
int main()
{
struct person p;
p.name = "John Smith";
p.age = 25;
printf("%s",p.name);
printf("%d",p.age);
return 0;
}
Type definitions
You can give your own name to a variable using a type definition. Here is an example of how to
create a type definition called intptr for a pointer to an integer.
#include<stdio.h>
int main()
{
intptr ip;
return 0;
}
int main()
{
PERSON p;
p.name = "John Smith";
p.age = 25;
printf("%s",p.name);
printf("%d",p.age);
return 0;
}
Pointers to structures
When you use a pointer to a structure you must use -> instead of a dot.
#include<stdio.h>
int main()
{
PERSON p;
PERSON *pptr;
PERSON pptr = &p;
pptr->name = "John Smith";
pptr->age = 25;
printf("%s",pptr->name);
printf("%d",pptr->age);
return 0;
}
Unions
Unions are like structures except they use less memory. If you create a structure with a double
that is 8 bytes and an integer that is 4 bytes then the total size will still only be 8 bytes. This is
because they are on top of each other. If you change the value of the double then the value of the
integer will change and if you change the value of the integer then the value of the double will
change. Here is an example of how to declare and use a union:
#include<stdio.h>
int main()
{
NUM n;
n.d = 3.14;
n.i = 5;
return 0;
}
int main()
{
FILE *f;
return 0;
}
You must then open the file using the fopen function. fopen takes 2 parameters which are the file
name and the open mode. fopen returns a file pointer which we will assign to the file pointer
called f.
#include<stdio.h>
int main()
{
FILE *f;
f = fopen("test.txt","w");
return 0;
}
The above example will create a file called test.txt. The "w" means that the file is being opened
for writing and if the file does not exist then it will be created. Here are some other open modes:
r Open for reading
r+ Open for reading and writing
w Open for writing and create the file if it does not exist. If the file exists then make it blank.
Open for reading and writing and create the file if it does not exist. If the file exists then make
w+
it blank.
a Open for appending(writing at the end of file) and create the file if it does not exist.
a+ Open for reading and appending and create the file if it does not exist.
To write a string to the file you must use the fprintf command. fprintf is just like printf except
that you must use the file pointer as the first parameter.
#include<stdio.h>
int main()
{
FILE *f;
f = fopen("test.txt","w");
fprintf(f,"Hello");
return 0;
}
When you are finished using a file you must always close it. If you do not close a file then some
of the data might not be written to it. Use the fclose commmand to close a file.
#include<stdio.h>
int main()
{
FILE *f;
f = fopen("test.txt","w");
fprintf(f,"Hello");
fclose(f);
return 0;
}
The fgets command is used when reading from a text file. You must first declare a character
array as a buffer to store the string that is read from the file. The 3 parameters for fgets are the
buffer variable, the size of the buffer and the file pointer.
#include<stdio.h>
int main()
{
FILE *f;
char buf[100];
f = fopen("test.txt","r");
fgets(buf,sizeof(buf),f);
fclose(f);
printf("%s\n",buf);
return 0;
}
Data files
A data file is used to store types of data such as integers. When you open a data file you must
add the letter b to the open mode parameter of fopen.
#include<stdio.h>
int main()
{
FILE *f;
f = fopen("test.dat","wb");
fclose(f);
return 0;
}
fwrite is used to write to a file. The first parameter of fwrite is a pointer to the variable that you
want to write to the file. The second parameter is the size of the variable that must e written. The
third parameter is the number of variables to be written. The fourth parameter is the file pointer
of the file you want to write to.
#include<stdio.h>
int main()
{
FILE *f;
int buf;
f = fopen("test.dat","wb");
buf = 100;
fwrite(&buf,sizeof(buf),1,f);
fclose(f);
return 0;
}
fread is used to read from a file and is the same as fwrite except that the data is read into the
variable instead of writing from it. You must remember to change the file mode to read.
#include<stdio.h>
int main()
{
FILE *f;
int buf;
f = fopen("test.dat","rb");
fread(&buf,sizeof(buf),1,f);
printf("%d\n",buf);
fclose(f);
return 0;
}
struct
{
char name[100];
int age;
} p;
int main()
{
FILE *f;
strcpy(p.name,"John");
p.age = 25;
f = fopen("test.dat","wb");
fwrite(&p,1,sizeof(p),f);
fclose(f);
return 0;
}