How to set up smartphones and PCs. Informational portal
  • home
  • News
  • Program structure description of the main function in C. Structure of C Programs

Program structure description of the main function in C. Structure of C Programs

Any program written in the C language consists of one or more "functions", which are the basic modules from which it is assembled.

An example of the structure of a simple C program:

General form

Example

preprocessor directives

#include

# define N 10

name main function

start of main function body

variable and array declarations

intx=1; charstr[N];

program statements

puts("Enter name");

gets(str);

printf("\n %s, You %d are my guest!",str,x);

End of main function body

      1. Preprocessor directives

The part of the compiler is a program called preprocessor. The preprocessor works until the program is translated from the language high level into machine language, performing its preliminary transformation. Each preprocessor directive begins with a # (number) character and spans the entire line. Directives that do not fit on one line may be continued on the next line. The line continuation character is the backslash character (\) in the line being continued.

The most commonly used directive is to include a file in a program.

# include < name>

where name is the name of the file included in the program text.

This directive is called substitution directive . It tells the compiler to replace it with the file name. File name called header. It contains declarations of data and functions used in the program. For example, including the directive

# include < math. h>

will allow you to use standard mathematical functions in the program, such as sin x, cos x, ln x, etc. The list of standard mathematical functions will be given below.

Directive

# include < stdio. h>

allows the program to use standard input-output functions.

Another commonly used directive is the definition directive.

#define S1 S2

where S1, S2- strings of characters.

The preprocessor looks for a string of characters in the program text S1 and replaces it with the string S2 . For example, including the directive

# define P printf

allows you to type a letter on the keyboard P instead of a word printf.

This replacement is not performed inside text strings (literals), character constants and comments, i.e. directive action # define does not apply to texts delimited by quotation marks, apostrophes and located inside comments.

      1. Main function

Every C program must contain a function declaration main(), which is called the main function . Typically, this function has no parameters and does not return any value. The word is used to indicate this fact. void. Thus, the line with the name of the main function usually looks like:

void main(void)

void main()

      1. Variables and arrays

An array is a group of variables of the same type with a common name. The name of a variable or array is an identifier - a sequence composed of characters:

a - z, A - Z, 0 - 9,_(underscore),

and the first character cannot be a digit. Lowercase and uppercase characters Latin alphabet are perceived as different characters. Functional words of the C language cannot be used as the name of a variable or array. The main function words of the C language are given in the Appendix.

Array elements are distinguished by their numbers (indexes). The index can only take non-negative integer values. The index is written after the array name in square brackets. There may be several indexes. In this case, each index is written in its own square brackets.

Variables and arrays can be used in C language various types. Each type of data takes up a certain number of bytes of memory and can take values ​​from a certain range. The amount of this memory and, accordingly, the range of accepted values ​​in different implementations of the C language may vary. The number of bytes of memory occupied by a variable of a certain type for a particular implementation of the C language can be determined using the operation sizeof(type of). For example, you can determine the amount of memory allocated for a variable of an integer type as follows:

k = sizeof(int);

printf(“ Under a variable of typeintallocated %d bytes of memory”,k);

In these guidelines, three main types of variables and arrays are considered, typical values ​​​​of the amount of memory occupied and the range of values ​​\u200b\u200bare given (Table 1):

Table 1

Type Specifier (Keyword)

Meaning

Size

memory (byte)

Value range

Integer number

32768 . . . +32767

2147483648 . . . +2147483647

Valid

Real type number

3.4ּ10 -38 . . . 3.4ּ10 38

(modulo)

Symbolic

128 . . . +127

Let's take a closer look at the type variable char. As can be seen from Table. 1, type variable char occupies one byte of memory. One byte of memory can contain either an unsigned integer from the range , or a signed integer from the range [–128, 127]. This number is the code for one of 256 characters. The symbol corresponding to a given code is determined by the code table used. Thus, the value of a variable of type char can be considered either as an integer, or as a character whose code is equal to this number.

The composition of the languageIn the text in any natural language, four
basic elements: symbols, words, phrases and sentences.
Similar elements are contained in the algorithmic language:
The alphabet of a language, or its symbols, are the basic indivisible signs, with
with which all texts in the language are written.
A lexeme is the smallest unit of a language that has an independent
meaning.
An expression defines a rule for calculating some value.
An operator specifies a complete description of some action.
For description complex action sequence required
operators. Operators can be combined into a compound
statement, or block (a block in the C++ language is
a sequence of statements enclosed in curly braces ( )).
In this case, they are treated as one statement.
Each element of the language is defined by syntax and semantics.
Syntactic definitions establish construction rules
elements of the language, and semantics determines their meaning and rules
use.
Combined by a single algorithm, a set of descriptions and
operators forms a program on algorithmic language.

Program execution process

To run a program, you need to translate it
into a language understandable to the processor - into machine codes. This
the process consists of several stages:
The program is first passed to the preprocessor, which
connects text files, containing a description
elements used in the program.
The resulting full text of the program is input
compiler, which highlights tokens, and then based on
the grammar of the language recognizes expressions and operators,
built from these lexemes. The compiler then detects
syntax errors and, if there are none, builds
object module.
The linker, or linker, generates
executable module of the program, connecting to the object
module other object modules. If the program is
from several source files, they are compiled according to
separately and combined at the link stage.
The executable module has the .exe extension and can be
launched for execution.

C++ language alphabet

The C alphabet includes:
uppercase and lower case Latin alphabet(A,B,...,Z, a, b,..., z) and and
underscore;
digits: 0,1,2,3,4,5,6,7,8,9
special signs: " , {} | () * + - / % \ ; " . :?< = >_ ! & # non-displayable characters ("generalized whitespace characters"),
used to separate lexemes from each other (e.g. space,
tab stop, jump to new line).
From the characters of the alphabet
language lexemes are formed:
identifiers;
key (reserved) words;
operation signs;
constants;
separators (brackets, dot, comma, space characters).
Token boundaries are defined by other tokens, such as
separators or operation marks.

Identifiers

ID is a name program object. AT
Latin identifiers can be used
letters, numbers, and underscores. Uppercase and
lowercase letters are different. First character
identifier can be a letter or a sign
underscores. Wherein:
identifier must not match keywords
words and names of used standard
language objects;
it is not recommended to start identifiers with a character
underscores;
Identifiers can be of any length, but
the compiler takes into account no more than 31 characters from
the beginning of the identifier;
Identifier examples:
KOM_16, size88, _MIN, TIME, time

Keywords

Keywords are reserved identifiers that have
special value for the compiler. They can only be used in
the sense in which they are defined. List keywords C++ is given in
table:
INT
CHAR
FLOAT
DOUBLE
STRUCT
UNION
LONG
SHORT
UNSIGNED
AUTO
CONST
TRUE
EXTERN
REGISTER
TYPEDEF
STATIC
GOTO
RETURN
SIZEOF
BREAK
CONTINUE
IF
VOID
NEW
ELSE
FOR
DO
WHILE
SWITCH
CASE
DEFAULT
ENTRY
AND
STRUCT
TYPEDEF
BOOL

Operations signs

Operation sign is one or more
action symbols
over operands. inside sign
spaces are not allowed.
Operations are divided into unary,
binary and ternary in number
operands involved.

Simple data types

The data type defines:
internal representation of data in memory
computer;
set of values ​​that can
accept values ​​of this type;
operations and functions that can be
apply to values ​​of this type.
The C++ language defines six standard
simple data types to represent
integer, real, character and
logical values.

Data types
Type specifiers include:
char
- symbolic;
double - real double precision floating point;
float - real floating point;
int - integer;
long
- integer of increased length (long integer);
short - reduced length integer (short integer);
signed - signed, i.e. signed integer (most significant bit counts as
iconic);
unsigned - unsigned, i.e. unsigned integer (most significant bit not
considered iconic).
void
- lack of value;
bool - boolean (can only take the values ​​true and false.
The internal representation of false is 0 (zero).
Any other value is interpreted as true.)
To describe constants, use the service word const before
type description. For example, const float g=9.8;

10. Structure of a C program

A C++ program is
one or more functions. One of the functions
should be called main(). It is from this
function starts executing the program, and from
this function, as needed,
other functions are called.
The simplest function definition has the following format:
return_type name ([ parameters ])
{
statements that make up the function body
}
As a rule, the function is used to calculate some
values, so the function name is preceded by its type. If
the function must not return a value, the void type is specified.
Wherein:
– The body of the function is enclosed in curly braces.
– Functions cannot be nested.
– Each statement ends with a semicolon (except
compound operator).

11. Structure of a C program

A program may consist of several modules (source files) and, as a rule,
contains preprocessor directives. An example of a program structure containing
main, f1 and f2 functions:
preprocessor directives
descriptions
int main()
{
main function operators
}
int f1() (
operators of the function f1
}
int f2() (
operators of the function f2
}
/* Example of a simple program */
#include
int main()
{
printf("Hello World!");
return 0;
}

12. C-style I/O functions

Basic C-style I/O functions:
int scanf (const char* format...) // input
int printf(const char* format...) // output
They perform formatted input and output of an arbitrary number of values ​​according to the string
format. The format string contains characters that are copied to the stream (to the screen) or
are requested from the stream (from the keyboard) on input, and conversion specifications beginning with
% sign, which are replaced by specific values ​​during input and output.
#include
int main() (
int i;
printf("Enter an integer\n");
scanf("%d", &i);
printf("You entered the number %d, thanks!", i);
return 0; )
The first line of this program is a preprocessor directive that inserts into the program text
header file , containing a description of the input/output functions used in the program. Everybody
preprocessor directives begin with a # sign.
The third line is a description of an integer type variable named i .
printf function on the fourth line displays the prompt Enter an integer and moves to a new line in
according to the \n escape sequence.
The scanf function stores the integer entered from the keyboard into the variable i, and the following statement prints to
screen the string it contains, replacing the conversion specification with the value of that number.

13. I/O functions in C++ style

The same program using the library
C++ classes :
#include
using namespace std;
int main()
{
int i;
cout<< "Введите целое число\n";
cin >> i;
cout<< "Вы ввели число" << i << ", спасибо!"; return 0;
}

14. Standard Libraries

The C language has rich support in the form
more than 450 library routines of functions and macros that you can
call from your C programs to solve
a wide range of tasks, including I/O
low and high level, work with
lines and files, memory allocation,
process management, transformation
data, mathematical calculations and
much more.

15. Preprocessor directives

The first phase is called the preprocessor.
compiler. Preprocessor Instructions
are called directives. They must
begin with a # character, preceded by
line can contain only spaces
symbols.
Search for a file if the full path is not specified,
maintained in standard catalogs
included files. Instead of angular
brackets, quotation marks (" ") can be used
- in this case, the search for the file is carried out in
directory containing the source file, and
then already in standard directories.
Header files usually have
extension.h .

16. Preprocessor Directive #include

To connect libraries, use
preprocessor directive
# include [filename]
#include directive<имя_файла>inserts
the contents of the specified file to that point
the source file where it is written.
For example:
#include
#include "mylib.h"

17. #define preprocessor directive

The #define directive defines a substitution in the text
programs. It is used to determine
symbolic constants.
Symbolic constant definition format:
#define name substitution_text /*All occurrences
names are replaced with the substitution text */
Examples:
#define M 1000
#define Vasia “Vasily Ivanovich”

18. Some Standard Libraries

ALLOC.H
Description of memory management functions
(allocation, deallocation, etc.)
BIOS.H
Description of the various functions used in
accessing BIOS subroutines (basic
I/O system).
CONIO.H Description of the various functions used in
accessing DOS I/O routines with
keyboards.
GRAPHICS.H Contains graphics function prototypes.
MATH.H Contains a description of the prototypes of mathematical
functions
STDIO.H Defines the types and macros needed for
standard I/O package. Also defines
standard input/output streams stdin, stdout and
describes I/O subroutines.
STDLIB.H Describes some general purpose routines:
subroutines for transformation, search, sorting, and others.
STRING.H
Describes several string processing routines and
memory work.

19. PRINTF format output function

We have already used the most common
the output function in C is the printf subroutine. Her
the purpose is to write information to the screen.
Its format is both simple and flexible:
printf(<строка формата>, <объект>, <объект>, ...);

20. SCANF format input function

For interactive input mode, probably can be used in
in most cases, the scanf function. scanf is an input function, by definition
equivalent to printf; its format looks like this:
scanf(<строка формата>,<адрес>,<адрес>,...)
However, scanf has one very important difference: the objects following
format string must be addresses, not values. For example, in
The program contains the following call:
scanf("%d %d", &a, &b);
This call tells the program that it should expect input from you.
two decimal (integer) numbers separated by a space; the first will
assigned to a, and the second to b. Note that here we use the operation
addresses (&) to pass addresses a and b to scanf.

21. Format string

The format string is the string that begins
and ends with double quotes ("like this one");
the purpose of printf is to write this line to the screen. Before
the output of printf replaces everything extra
listed objects in line according to
with the format specifications specified in
the line itself. An example of a printf statement:
printf(“ d= %f \n",d);

22. Format string

The %f in the format string is the format specification. Everybody
format specifications start with a percent sign (%) and
(usually) followed by a single letter denoting the type
data and how to transform it.
%f used in the spec says what is expected
some real number. Here are a few other commonly used format specifications:
- %u unsigned integer
- %ld long integer
- %p pointer value
- %d integer
- %e floating point number in exponential form
- %c character
- %s string
- %x or %X integer in hexadecimal format.

23. Format string

You can set the field width by putting it in
between % and letter, e.g. decimal field
width 4 is given as %4d. The value will be
printed shifted to the right (in front of
spaces), so the total field width is 4.
Or for example %6.2f would mean that
allotted 6 positions for a real number,
and 2 - under the fractional part.
If you want to print a % sign, then insert %%.

24. Format string

\n in a string is not a format specification, but
used (for historical reasons) as
escape sequence, and represents
a special character inserted into a string. In this case
\n inserts a character at the start of a newline, so
after the line is output, the cursor will move to the beginning of the new line
lines.
- \f (format translation or clear screen)
- \t (tab)
- \b (backspace<-)
- \xhhh (insert character with ASCII code hhh, where hhh
contains 1 to 3 hexadecimal digits)
If you need to print a backslash then
insert \\.

25. An example of a C program

#include
#include
main()
{
float x1,y1,x2,y2;
printf("Enter two numbers: ");
scanf("%f %f %f %f",&x1,&y1,&x2,&y2);
float d = sqrt(pow((x2-x1),2)+pow((y2-y1),2));
printf("d= %f \n", d);
}

26. Other output functions PUTS, PUTCHAR

There are two other output functions that can help you
of interest: puts and putchar. The puts function outputs a string to
screen and terminates the output with a newline character.
Consider an example program:
#include
main()
{
puts("Hi, student of VKI NSU");
}
Note that \n is omitted at the end of the line; this is not necessary, because
puts itself adds this character.
Conversely, the putchar function writes a single character to
screen and doesn't add \n. putchar(ch) is equivalent to
printf("%c",ch).

27. GETS, GETCH functions

main()
{
char name ;
printf("What is your name: ");
scanf("%s",name);

}
If you enter a last name and a first name, only the last name will be displayed. Because
the space you enter after the name signals to scanf the end of the input
lines.
You can solve this problem using the gets function.
main()
{
char name ;
printf("What is your name: ");
gets(name);
printf("Hi, %s\n", name);
}

28. GETS, GETCH functions

#include
#include
main()
{
clrscr();
char name ;
printf("What is your name: ");
gets(name);
printf("Hi, %s\n", name);
getch();
}
Here the getch function waits for any character to be entered.
The getch function reads a single character from the keyboard without issuing
it to the screen (unlike scanf and gets). Note that she does not have
parameter. If we assign the function to a symbolic variable, then
it will get the value of the pressed character.
For example: c=getch();

29. Assignment operation

The most common operation is assignment,
for example, p=a/b or ch = getch(). In C
assignment is denoted by a single sign
equality (=); while the value to the right of the sign
equality is assigned to the variable on the left.
You can also use sequential
assignments, for example: sum=a= b. Such
cases, the assignment is made on the right
to the left, that is, b will be assigned to a, which in
in turn will be assigned to sum, so all
three variables will get the same value (and
namely, the initial value b).

30. Arithmetic operations. Increment. Decrement.

C supports the usual set of arithmetic operations:
- multiplication (*)
- division (/)
- determination of the remainder of the division (%)
- addition (+)
- subtraction (-)
To increase the value of a variable by one, use the increment (++),
decrement (--) to decrease by one.
So:
x++; // increment x by one
y--; // decrement y by one
Examples of postfix and prefix operations:
a=2;
a=2;
x=18-2*a++;
x=18-2*(++a);
We get:
a=3
a=3
x=14
x=12

31. Combined operations

Following are some examples of expressions
and ways to reduce them:
a = a + b abbreviated to a += b;
a = a - b; abbreviated to a -= b;
a = a * b; abbreviated to a *= b;
a = a / b; abbreviated to a /= b;
a = a % b; reduced to a %= b;

32. Example 1

Calculate X3 and X10 using four multiplications for
given integer value X.
#include
int x,x2,x3,x5,x10;
main() (
printf("\n X^3 and X^10 calculation program\n");
puts("Enter value X");
scanf("%i",&x);
x2=x*x;
x3=x*x2;
x5=x2*x3;
x10=x5*x5;
printf("%i to the 3rd power = %i \n",x,x3);
printf("%i to the 10th power = %i",x,x10);
}

33. Example 2

Given an angle in radians. Calculate the sine and cosine of an angle.
#include
#include
float Angle,Result1,Result2;
main()
{
printf("\n Program for calculating sin and cos angle\n");
puts("Set the angle value in radians");
scanf("%f",&Angle);
Result1=sin(Angle);
Result2=cos(Angle);
printf("The sine of the angle is %f \n",Result1);
printf("The cosine of the angle is %f",Result2);

Before you start writing programs, you need to study the structure of programs in the C++ programming language. In other words, the structure of programs is the markup of the work area (code area) in order to clearly define the main blocks of programs and syntax. The structure of programs is slightly different depending on the programming environment. We focus on the Microsoft Visual Studio IDE, and therefore the sample programs will be shown specifically for MVS. If you are using a different IDE, then it will not be difficult for you to port code from MVS to other development environments, and you will understand how to do it over time.

Structure of programs for Microsoft Visual Studio.

// struct_program.cpp: defines the entry point for the console application. #include "stdafx.h" // here we include all the necessary preprocessor directives int main() ( // the beginning of the main function named main // your program code will be located here )

Line 1 refers to the entry point for a console application, which means that this program can be run through the Windows command line by specifying the program name, such as struct_program.cpp . Line 1 is a single-line comment because it starts with // characters, more about comments will be discussed in the next article. Line 2 includes the header file "stdafx.h" . This file is similar to a container, since the main preprocessor directives are connected in it (those that the compiler connected when creating the console application), auxiliary directives (connected by the programmer) can also be connected right there.

include is a preprocessor directive, i.e. a message to the preprocessor. Lines starting with the # symbol are processed by the preprocessor before the program is compiled.

Preprocessor directives can also be included in lines, starting after the #include "stdafx.h" entry before the start of the main function. Moreover, this way of connecting libraries is the main one, and using "stdafx.h" is an additional possibility to connect header files, which is available only in MVS. From the 4th to the 6th lines, the main function is declared. Line 4 is the function header, which consists of the return type (in this case, int) of this function, and the name of the function, as well as the parentheses that declare the function's parameters.

int - integer data type

Between the curly brackets is placed the main program code, also called the body of the function. This is the simplest program structure. This structure is written in Microsoft Visual Studio. All of the above is also true for other compilers, except for line 2. There is no "stdafx.h" container anywhere except MVS.

Program structure for C++ Builder.

When you create a console application, the New Project Wizard automatically generates the following code:

//preprocessor directive automatically included by the project creation wizard #include int main() ( return 0; )

We see that the function data type is int . This tells us that the function will return some integer value upon completion, in our case 0. Integer because int is the data type for integers such as 4, 5, 6, 456, 233, etc.

The main thing to remember is that if the return data type of the main function is int or any other except void , then you should write a line like this: return<возвращаемое значение>;

In line 2, the vcl.h library is connected - it is automatically connected by the application creation wizard, so you should not delete it, otherwise the project will not be working.

In general, the wizard automatically creates a program structure that is slightly different from those that we have considered, but the essence remains the same.

For example:

int main(int argc, char* argv) ( return 0; )

Such an example structure is generated by the wizard in MVS2010. This main is slightly different. We’ll look at it in more detail later, but I’ll say that this main has this form, since it was originally designed to support Unicode.

Unicode is a character encoding standard that can represent the characters of almost all written languages. We'll talk more about Unicode later.

There are different versions of main , but there's nothing wrong with that, since main was the main function, so it remains so, so everything said above remains relevant.

An example of the structure of an MVS program with linked libraries.

#include "stdafx.h" #include using namespace std; int main() ( )

The name of the connected libraries is written inside the greater than, less than signs. Header files and the name of the included libraries are synonyms.

The syntax for including header files is:

#include<имя заголовочного файла>

Older header files are included like this (this style of including libraries is inherited from the C programming language):

#include<имя заголовочного файла.h>

The difference is that the name is followed by the .h extension.

The C++ programming language is case sensitive. For example:
return 0; - wrong, there will be a compilation error.
return 0; - right!!!

This article discusses the structures of C++ programs in such environments as MVS and Borland. And as you have already noticed, these structures are almost the same. Therefore, this article is relevant for any IDE. If you have not yet decided on the choice of IDE, read.

Structure of a C program.

Using the C programming language in solving economic problems

Programs and data

Advantages of the C language

1) C is a modern language, its structure encourages the programmer to use methods in his work: top-down design, structured programming, modular structure of programs.

2) C is an efficient language. C programs are compact and fast to execute.

3) C - portable or mobile language.

4) C is a powerful and flexible language.

5) Programs written in C are used to solve problems of various levels. C has a number of powerful assembler constructs.

6) C is a convenient language, it is structured and at the same time does not limit the freedom of programmers too much.

7) C is a compiling type language. Because C is a standardized, device-independent, widely available language, applications written in C can often run with little or no modification on a wide variety of computer systems. The computer, despite its speed and computing power, is a simple device that manipulates binary numbers. Some binary numbers are interpreted by the computer as commands, others as data. To make a computer do something useful, you need to write a program.

Programming programming activities.

Program is a description of the algorithm for solving a problem given in the computer language.

Command instructions for the next step.

Example teams: С=А+В, where А, В-operands, +- operation.

Operation is what the computer must do according to each command.

operands -participants of the operation, then over what and with what the operation is performed. A set of elementary operations from the ways of their descriptions form a system of commands of the programming language.

Example #1:

#include

(void main(void) //header of the main function of the program

сout<< “Здравствуй, С!\ n”;

1 line: connection of auxiliary libraries focused on input and output of data of different types to the stream.

2nd line: header of the program's main function. Cout statement to output information<< – помещение в класс данных, \n-переход к новой строке вывода.

Program is a sequence of instructions that implement an algorithm, a set of prescriptions that uniquely determine the content and sequence of operations for solving problems.

The use of S.

1. Programs and data.

2. Scheme of program execution on a computer:

Example #1:

#include< stdio.h>

printf ("I study at BSUIR\ n");

1 line: command include preprocessor, which includes the stdio.h file, which describes the printf library function.

Line 2: definition of a function named main that takes no arguments. The main statement is enclosed in curly braces. The main function calls the printf library function to print, given in character sequence. Slash (\n) - literal newline, transition to newline.

To execute the program on PVEM, you must do the following:

1) Write a program in a programming language.

2) Broadcast it in the standard of this language.

3) Associate it with the necessary programs and functions.

4) Load into RAM.

5) Run and get the result.


COMPILATION SCHEME

A translator is a computer program that translates a program written in a programming language into a form that a computer can understand. The output of the compiler is a file with the extension obj. An executable file or load module is a file that contains a compiled and ready-to-execute program. Borland C++ is a development environment for programs that include both a compiler and some other tools.

Structure of a C program.

Any C program consists of one or more functions and elements. Different functions can be given any names. Functions contain instructions (commands) that prescribe actions at a certain step of execution, and the variable stores the values ​​used in the process of these actions. Such actions can be assigning values ​​to variables, checking some condition. The function named main. The execution of any program begins with the main function.

a) The general structure of a C program without referring to a subroutine:

b) The general structure of a C program with reference to subprojects:

Arguments are one of the mechanisms for interaction between functions. The list of arguments in parentheses follows the function name. Curly braces frame the beginning and end of a program. Instructions that make up the body of programs from operators and operands. In C, every statement and every line of function calls ends with a semicolon. The exception is preprocessor commands and function names that appear at the beginning of a program unit. The goal of most programs is to solve the problem through various transformations of the source data. For this it is necessary.

Please pause AdBlock on this site.

I hope you have already installed some IDE on your computer and learned how to compile programs in it. If not, then

All programs written in C have a common structure. Which we will talk about in this lesson. Our first program written in the previous step will help us with this.

Let's fill in a simple map. At the moment, we know that programs exist, but we do not know how they are arranged inside. Therefore, our map will look like this.

Fig.1 Map "Structure of C programs." First level.

Throughout the course, we will return to this map, refine it, supplement it with new elements and blocks.

Now attention. Don't be scared! Below is the source code of three simple programs. Your task is to look at them carefully and try to find some pattern in their code (something that is common in every program).

Listing 1. Program 1. Prints "Hello, World!"

#include

Listing 2. Program 2

int main(void) ( int a, b, c; a = 5; b = 10; c = a+b; return 0; )

Listing 3. Program 3

#include int main(void) ( FILE *fp; fp = fopen("input.txt", "w"); fprintf(fp, "This is Sparta!"); fclose(fp); return 0; )

Take your time to watch the continuation of the lesson and the correct answer to this problem. First, try to answer yourself. After that, click the button "Watch the continuation!"

So, the answer is: In all programs above, there is the following construction:

Listing 4. The main function of any C program is the main function.

int main(void) ( return 0; )

What kind of design is this. This is the declaration of the main function. Every program that is written in C has such a function. Whether it is a big program or a small one, a computer game or a "Hello, World!" program written by you or Bill Gates -- if the program is written in C -- it has a main function. . This is the main function of our program, so to speak. When we run a program, we can think of ourselves as running the program's main function.

Let's stop for a second. We seem to have already figured out something about the structure of programs in the C language. Any C program must contain a main function. Let's display this fact on our knowledge map "Structure of C Programs."

Fig.2 Map "Structure of C programs." main function.

Now the map does not bother us with its gaping emptiness. Let's continue our research.

Let me talk a little about the main function and about functions in general.

The function name is preceded by int, which is an abbreviation for the word integer, which is translated from English as "whole". Such a notation means that when the main function completes its work, it must return an integer to the calling program (in our case, this is the operating system). Usually, for the main function, this is the number zero, which notifies the operating system: "They say, everything is fine. There were no incidents."

Have you ever seen error messages on your computer screen? Usually they write something like "The program crashed ... blah blah blah ... Code -314." Here it is about the same. The difference is that when problems occur, the operating system notifies us about this, and when everything is fine, it does not bother us again.

After the function name, the word void is written in parentheses. In general, function arguments are usually written in brackets, but in our case, when void is written in brackets, this means that the function has no arguments. In other words, the main function does not need any additional input from outside to get started. We'll talk about all this in more detail, but for now, just remember that the word void instead of function arguments means that no arguments are required for this function.

Inside the curly brackets is the description of the main function, i.e. exactly what this function is supposed to do.

Before the closing curly brace, we see the return command. It is this command that is responsible for returning the value from the function. Those. look, if the program reached this point, then everything was fine and no errors occurred, which means you can return the value zero.

You may ask, why exactly zero? And the devil knows! It's just the way they usually do it. You can, in principle, return some other integer, such as 100, or -236. As long as it's an integer. Remember int? Therefore, the whole.

So we figured out the main function. One more moment. What is written in curly braces is usually called the "function body" (or function description), and the first part, the one before the curly braces, is called the function header.

Let's go back to our first "Hello, World" program and see what's what.

Listing 5. "Hello, World" program

#include int main(void) ( printf("Hello, World!\n"); return 0; )

Something we now understand in this program. Only two lines remain unclear, let's go in order.

Listing 6. The include directive

#include

This line is a message to the compiler. These messages, which start with the # character, are called compiler directives. Literally: "connect the file stdio.h". During compilation, the contents of the stdio.h file will be inserted instead of this line. Now let's talk a little about this file. stdio.h (from STanDart Input Output) is a header file that describes various standard functions related to input and output.

A reasonable question arises, "Why do we need to write this line? Why do we even need to insert this file here?" This is necessary so that in our program we can use the standard printf () screen output function.

The point is this. Before we use something in our program, we first need to describe it. Imagine the situation, you were asked to bring a chandelier, but you don’t know what it is. It's not clear what to do.

So is the compiler. When it encounters a function, it looks for its description (i.e., what it should do and what it means) at the beginning of the program (from the very beginning until the moment it is used in the program). So, the printf() function is described in the stdio.h file. That's why we connect it. But when we connect it, the compiler will be able to find the printf () function, otherwise it will give an error.

By the way, it is time to supplement our knowledge map. Before the main function, let's add one more block, the block for connecting header files.

Fig.3 Map "Structure of C programs." Header files connection block.

Let's continue with our program.

Listing 7. printf() function

Printf("Hello, World!\n");

In this line, we call the standard printf() function for displaying to the screen. In this simplest case, we pass it one parameter, a string written in quotes, which must be displayed on the screen, in our case it is Hello, World! \n But wait, what is this \n? There was no \n on the screen when the program started. Why then did we write this here? This sequence is a special character that is a command to go to the next line. It's like pressing the Enter key in MS Word. There are several such special characters, all of them are written using the "\" character - a backslash. These special characters are called control characters. Then I will show them to you. Otherwise, exactly what you wrote in double quotes will appear on the screen.

By the way, note that every C command ends with a ";" (semicolon). It's like a dot at the end of a sentence in Russian. In a normal language, we separate sentences with a dot, and in the C programming language, a semicolon separates commands from each other. Therefore, a semicolon is mandatory. Otherwise, the compiler will swear and give an error.

To call a function, you must write its name and specify the parameters passed to it in parentheses. A function can have one or more parameters. Or there may be no parameters at all, in which case you do not need to write anything in brackets. For example, above we called the printf() function and passed it one parameter, the string to be printed to the screen.

By the way, good advice. Since the main function is always present in every program, and literally in every program we need to display something on the screen, I recommend that you immediately create a file with the following blank so that you do not write the same thing every time.

Listing 8. Standard template for C programs.

#include int main(void) ( return 0; )

Well, that seems to be all. This first lesson can be considered completed. Although no, there is one more thing.

The most important thing in this lesson is, of course, the general structure of the program. But in addition, we learned how to display arbitrary text on the screen. It seems that they did not learn anything at all, but even this is enough to, for example, make a small gift to your mother on March 8th.


The source code of the postcard program is in the archive with the source codes of this lesson. Experiment! You will succeed.

Top Related Articles