Content of the lesson:
The development of the C programming language began in 1969 – 1972 in laboratories of AT&T. Several years later, in 1978, the first standard of C was created. The authors were Brian W. Kernighan & Dennis M. Ritchie who described this language in the book The C programming language.
Later other versions were formed (ANSI C, C99, ...) and these versions were standardized. This language is used not only for personal computers but also for mobile devices, microcomputers or in industry.
You can use many development environments for developing applications in this programming language. These samples were created using the software Microsoft Visual C++ Express 2010.
Before describing the basic structure of program we can take look at a simple example. The result of the following program is output of text "Hello, World!".
Header files
#include <stdio.h>
Main functions of program
int main()
{
Command part
printf("Hello, World!");
fflush(stdin);
getchar();
Return value of function
return 0;
}
If you look at the program you can see that the directive #include with a link to file stdio.h was used. This directive is used to insert libraries (header files) which contain declaration of functions which can be used in C. The previously mentioned file stdio.h contains functions for writing output to console, loading data from user or for working with files. There are lots of libraries and you will meet them in the following lessons.
The main function of program is located on the next line. The program in C is structured by dividing it to parts - even the simplest program contains at least one function main which is the main function of the program. The main function should be written like this:
int main()
{
single commands of program will be placed here
return 0;
}
The keyword main is the name of function. There are empty brackets on the right side of the name. These brackets can contain input parameters (we will talk about them in one of the following lessons). There is also the keyword int on the left side of the name. This is the data type of return value of function (result of the function). In this case it is an integer number (int).
There are braces behind the header of the function and single commands of program are placed in them as well as the return command which is used to pass the return value of the function. In case of the main function this keyword terminates the program.
If you look at the return value of this function you can see that its value is 0 in our case. In the main function this value tells that the program ended correctly and will be terminated (you can use different values for several error states).
The command which has not been described yet is the line "printf("Hello, World!");" . This is not a compulsory part of the basic structure of program but it is a command which writes text to console. There is one more line behind this function which contains the function getchar(); - this is added to prevent program from being terminated immediately (at this moment it waits for a key press).
You should also know one more thing - all commands of C programming language are ended by a semicolon at the end of line.
In general, each program has the following structure:
Header files
#include <stdio.h>
#include <nameofnextfile.h>
…
Main functions of program
int main()
{
Commands of program
...
Return value of function
return 0;
}
Structure of program can be different from the code above. Especially the header of the main function can be different because there can be different input values - the line int main() can look like this: int main(int argc, char* argv[]). In case the development environment offers you this structure you can leave it without changes. The meaning of these parameters will be explained later.
Another difference can be found in development environments MS Visual Studio and MS Visual C++ Express. the line #include <stdio.h> is replaced by the line #include "stdafx.h" and the line int main() is replaced by the line int _tmain(int argc, _TCHAR* argv[]). In case your development environment offers you this structure leave it without changes.
We are going to use mostly the program MS Visual Studio so the next source code will use the modifications which were described.
Header files
#include "stdafx.h"
#include <nameofnextfile
.h>
…
Main functions of program
int _tmain(int argc, _TCHAR* argv[])
{
Commands of program
...
Return value of function
return 0;
}
Other important parts of program are comments. They allow you to write notes into program which can be used to simplify the orientation in you program.
There are two types of comments in C:
/*
example of basic structure of program in C
*/
#include "stdafx.h"
// main function of program
int _tmain(int argc, _TCHAR* argv[])
{
printf("Hello, World!"); // output of text into console
fflush(stdin);
getchar();
return 0;
}
To be able to store any value inside your program (for example number x which is equal to five), you need to declare a variable of a data type. For example in mathematics you often use the notation x=5. This notation tells that the x variable is equal to the number 5.
If you want to be able to create such a variable and store a value inside it, you have to declare it.
You can also see from the mathematical notation x=5 that x can store any numerical values (in this case a natural or whole number 5). You have to tell the name of your variable to computer but also the fact which values can be stored inside it (or what data type does it use = which type of data can be stored into it - that means if you plan to store numbers, characters, letters, ...). Declaration can be done by writing the data type and then the name of your variable (you have already seen one data type for an integer number - int). For our case we can use the notation int x; - this means that the variable x can store almost any integer number.
If you want to add a variable x which can store integer data type, you have to declare it using the following syntax:
#include "stdafx.h"
int _tmain(int argc, _TCHAR* argv[])
{
int x;
return 0;
}
You can declare almost unlimited amount of variables (you are limited by the operating memory). In case you declare more variables of the same data type, you can separate them with commas, you do not have to write them below each other.
#include "stdafx.h"
int _tmain(int argc, _TCHAR* argv[])
{
int x, y;
int a;
int b;
return 0;
}
Apart from the integer data type you can also use other data types in C. The list of data types is shown in the following table:
Data type |
Allowed shortcut |
Description |
Range |
Integer data types with sign |
|||
signed int |
int |
Integer number with sign |
from - 2 147 483 648 |
signed short int |
short int or short |
Short integer number with sign |
from - 32 768 |
signed long int |
long int or long |
Long integer number with sign |
from - 2 147 483 648 |
signed char |
char |
Char with sign |
from - 128 |
Integer data types without sign |
|||
signed int |
|
Integer number without sign |
from 0 |
signed short int |
signed short |
Short integer number without sign |
from 0 |
signed long int |
signed long |
Long integer number without sign |
from 0 |
signed char |
|
Char without sign |
from 0 |
Real data types |
|||
float |
|
Real number with single accuracy |
from 3.4×10-38 |
double |
|
Real number with double accuracy |
from 1.7×10-308 |
long double |
|
Real number with extended accuracy |
from 3.4×10-38 |
You can start using a variable after declaring it. Using the assignment operator = (character "equal to") you can insert a value inside it:
x = 7;
Input is represented by data which enter a program (usually as values of variables). To enter an input value into program we will use the scanf function. This function requires at least 2 parameters. The first parameter is a string which sets the way and format how the values should be read, other parameters are addresses of single variables which should be used to store the values. The first question is how to get the address of a variable. In this case we can use operator which should be inserted before the name of variable. To get an address you have to use the character "&" (to get the address of x variable you should use &x).
Let's get back to the first parameter. This contains so called control string. The way how to get data from a user, which formatting should be used and the correct data type are defined inside the first string. Each value is marked by the character "%" and by one letter according to the following table.
String |
Data type |
%c |
Character |
%d |
Number int, decimal |
%u |
Number int, decimal |
%x |
Number int, hexadecimal with lower-case letters |
%X |
Number int, hexadecimal with upper-case letters |
%o |
Number int, octal |
%ld |
Number long int, decimal |
%f |
Number float |
%lf |
Number double |
%s |
String |
The following code demonstrates the possibility of using scanf to load values (to simplify the basic structure of program in C was skipped. To be able to try it, you have to place these lines into the main function):
int x, y;
float z;
scanf("%d",&x); // načte 1 celé číslo a uloží do proměnné x
scanf("%f",&z); // načte 1 racionální číslo a uloží do z
scanf("%d %d",&x,&y); // načtou se dvě celá čísla oddělená mezerou
// první se uloží do proměnné x, druhé do y
By output we mean information which is provided by a program. This means results of calculations or just text messages. The output will be written to the screen. To be able to write anything on the screen we have to use the function printf. You probably remember this function from the beginning - we used it in the first program "Hello, World!" (there was the line with command printf("Hello, World!"); in the program).
The function printf has similar syntax to the function scanf which is used to get data from a user. The first parameter is again a string which contains data which should be written as output. This string contains text which is bordered by quotation marks. You can also use groups of special characters which begin with the character % (same as for the scanf function). The % character is then followed by characters which set the output format of data. The list of these characters is available in the previous part about the scanf function.
The other parameters contain variables, constants or values which should be inserted instead of these control characters. However, there is one large difference - we do not insert the address of a variable but directly the variable, that means we do not write the & character.
printf("Ahoj");
Apart from common characters these strings can contain special charactes which can be used for example to wrap a line. There characters are being called "escape sequences" and are inserted using the character "\" which is followed by the special character.
List of these sequences is available in the following table:
Sequence |
Meaning |
\n |
New line |
\r |
Return to the begging of line (carriage return) |
\f |
New page |
\t |
Tabulator |
\b |
Movement to the left |
\a |
Whistle |
\\ |
Backslash |
\’ |
Apostrophe |
\0 |
Null character |
printf("1. radek\n2. radek\n3. radek\n");
If you want to output the value of any variable you have to insert the required control character (see the previous description of the printf command) and then add the name of variable as the next parameter.
int x;
x = 5;
printf("%d",x);
int x;
x = 5;
printf("Hodnota x je %d!",x);
We should improve our sample program for entering value for the x variable and inform user about the result (you can see the whole source code including the structure of program).
#include "stdafx.h"
int _tmain(int argc, _TCHAR* argv[])
{
int x;
printf("Zadejte prosím hodnotu x: ");
scanf("%d",&x);
printf("Proměnná x má hodnotu: %d.",x);
fflush(stdin);
getchar();
return 0;
}
As you have seen we are able to write a program which can compute sum of any two assigned numbers. We might also want to solve more complex mathematical expressions and formulas. Especially we need additional commonly used operations for calculations.
Task: Compute surface and volume of a dube.
#include "stdafx.h"
int _tmain(int argc, _TCHAR* argv[])
{
int a;
printf("Zadejte prosím velikost strany krychle:");
scanf("%d", &a);
printf("Objem krychle o straně a= %d má hodnotu %d.\n", a, (a*a*a));
writeln("Povrch krychle o straně a= %d má hodnotu %d.\n', a, 6*(a*a));
getchar();
return 0;
}
Write a program for computing surface and volume of a cuboid.