How to set up smartphones and PCs. Informational portal
  • home
  • Iron
  • The structure of the simplest application with. Other output functions PUTS, PUTCHAR

The structure of the simplest application with. Other output functions PUTS, PUTCHAR

In C programs, there is a certain sequence:

First, we add the libraries we need #include If the file is in the current directory of the project, it is indicated in quotes. For a file located in another directory, you must specify the full path in quotes.

#include
#include "math.h"

After which we can add the constants we need #define A 3

After that, the function begins with the Main () command

After everything is done, you can enter getchar ()

2. What is the semicolon for in C?

C uses a semicolon to mark the end of a statement.

3. Do all C compilers require a return statement in the program?

To return an integer value, the line is appended before the end of the function

Also, in most cases, return means exiting the function.

The function body statements are executed before the first return statement. If there is no such operator in the function body (that is, the function does not return any result), then all operators up to the closing operator parenthesis are executed.

The function of outputting array elements to print does not return any result, i.e. there is no return statement in the body of the function.

4. For what purpose are comments entered into the text of the program?

Comments are entered to explain an action

for example Printf (‘’ Hello World ’’); // display Hello World

You can also enter comments with / * - at the beginning * / - at the end of the comment

5. What are parameters used for when calling a function?

A link is essentially the second name of the same object. When an object by reference is passed to a function, this object is actually passed. When we pass an object by value, a copy of it is passed to the function.

void func_1 (int a) // pass by value

6. Do all functions require parameters to be passed when called?

In my opinion, not everything at all, because we can easily write a function of the main () type without passing parameters by value

1. What is the char data type?

The char data type is an integer data type that is used to represent characters. That is, each character corresponds to a certain number from the range. The char data type is also called the character data type, since the graphical representation of characters in C ++ is possible thanks to char. To represent characters in C ++, the char data type is allocated one byte, in one byte - 8 bits, then we raise two to the power of 8 and get the value 256 - the number of characters that can be encoded. Thus, using the char data type, you can display any of the 256 characters. All encoded characters are represented in the ASCII table.

2. How does the symbol "3" differ from the number 3?

character 3 differs from integer 3 in that the character cannot be used in arithmetic operations

3. What is the difference between a constant and a variable?

The difference between a variable and a constant is pretty obvious: during program execution, the value of a variable can be changed (for example, by assignment), but the value of a constant cannot

4. How to define a constant?

Constants in C ++ are similar to constants in C. To represent a constant in C, only the #define preprocessor directive was used:

const type VariableName = InitialValue;

The scope of a constant is the same as that of a regular variable. You can declare a pointer to a constant using the const keyword

5. Does C support the string data type?

C does not support a separate string data type, but it does allow strings to be defined in two different ways. The first uses an array of characters, and the second uses a pointer to the first character of the array.

6. Does the variable retain its value throughout the entire program?

during program execution, the value of a variable can be changed (for example, using an assignment), but the value of a constant cannot

7. How can I change the value of a constant?

1. What are the differences between the \ n and \ r escape sequences?

Roughly speaking, the \ r was supposed to zero out the character number. leaving the line number unchanged (i.e., will move the typewriter carriage to the beginning of the line without touching the paper), and \ n, on the contrary, will jump to the next line, leaving the current print position unchanged (scroll the paper without touching the carriage).

2. How to display the quote character on the screen?

printf ("My text is: \" my text \ "\ n");

3. What are the two parts of the printf () parameter list?

When printing a number or expression, Printf () is first written

In brackets, at the beginning in quotes, we write the data we need, namely

% s - single character
% d - signed decimal integer
% f - floating point number (decimal notation)
% s - character string (for string variables)
% u - unsigned decimal integer
%% - print percent sign

For instance:

printf ("x =% 5i \ ty =% f \ tz =% 7.3f \ n", x, y, z);

4. What are the advantages of the printf () function over puts ()?

5. What is a format indicator?

Reads a floating point value (C99 only)

Same as% a code (C99 only)

Reads one character

Reads a decimal integer

Reads an integer in any format (decimal, octal, or hexadecimal)

Same as% e

Reads a floating point number

Same as% f code (C99 only)

Reads a floating point number

Same as code% g

Reads an octal number

Reads a line

Reads a hexadecimal number

Same as code% x

Reads a pointer

Accepts an integer value equal to the number of characters read so far

Reads an unsigned decimal integer

Looks up a character set

Reads the percent sign

6. How to display the value of a numeric variable?

You can display its value using the Printf () function

printf ("% 7.3f \ t% 7.3f \ n", x, y);

%<количество_позиций_под_значение>.<количество_позиций_под_дробную_часть>f

%<количество_позиций_под_значение>i

The structure of a C program.

Using the C programming language in solving economic problems

Programs and data

Advantages of the C language

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

2) C is an effective language. C programs are compact and fast.

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, an application written in C can often run with little or no modification on a wide variety of computer systems. A computer, despite its speed and computational power, is a simple device that manipulates binary numbers. Some binary numbers are interpreted by the computer as commands, others as data. To get the computer to 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 a prescription that determines the next step.

Example commands: C = A + B, where A, B are operands, + is an operation.

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

Operands -participants in the operation, then on what and with what the operation is performed. A set of elementary operations from the methods of their descriptions form a command system of a programming language.

Example # 1:

# include

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

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

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

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

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

Using C.

1. Programs and data.

2. Scheme of program execution on a computer:

Example # 1:

# include< stdio.h>

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

Line 1: the include preprocessor command that includes the stdio.h file that describes the printf library function.

Line 2: the definition of a function named main, which does not receive any arguments. The main statement is enclosed in curly braces. The main function calls the printf library function to print the specified character sequence. A forward slash (\ n) is a newline character, a transition to a new line.

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

1) Create a program in a programming language.

2) Broadcast it in the standard of this language.

3) Associate it with the required programs and functions.

4) Load into RAM.

5) Execute and get the result.


COMPLIANCE SCHEME

A translator is a computer program for translating a program written in a programming language into a form that can be understood by a computer. The compiler produces a file with the obj extension. An executable file or load module is a file containing a compiled and ready-to-run program. Borland C ++ is an environment for developing programs that include both a compiler and several other tools.

The structure of a C program.

Any program in the C language consists of one or more functions and elements. The various functions can be given any name. F-tions contain instructions (commands) prescribing actions at a certain stage of execution, and the variable stores the values ​​used in the process of these actions. Such actions can be assignment of values ​​to variables, checking of a certain condition. A function named main. The execution of any program starts with the main function.

a) The general structure of a C program without calling a subroutine:

b) The general structure of a C program with an appeal to the subroutine:

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 the program. Instructions that make up the body of programs from operators and operands. In C, every statement and every function call line ends with a semicolon. The only exceptions are preprocessor commands and function names at the beginning of a program unit. The goal of most programs is to solve the problem by various transformations of the initial data. For this it is necessary.

A C program consists of one or more subroutines called functions.

The C language is block-structured. Each block is enclosed in curly braces ().

The main block in a C console application program is the main function named main ().

Every action in C language ends with a semicolon -; ... An action can be a function call or some operations.

The function name is the collective name of the description group and operators,
enclosed in a block (curly braces). The function parameters are indicated in parentheses after the function name.

C Comments

C language uses symbols for comments

/ * - the beginning of the comment;
* / - end of comment.

The entire sequence between these characters is a comment.

It is convenient to write multi-line comments:

int a; / * whole
variable * /

Multi-line comments are also useful when debugging to hide parts of the code from execution.

In addition, // symbols can be used to write short comments. In this case, a comment is everything that is located after the // symbols and up to the end of the line:

float b; // real variable

Main function

When executing a console application written in C, the computer's operating system transfers control to a function named main (). The main () function cannot be called from other program functions, it is a control function.

Parentheses following the function name are used to indicate parameters (arguments) that are passed to the function when it is called. In this case, the operating system does not pass any arguments to the main () function, so the list of arguments in parentheses is empty.

The main function can be written in different ways:

  • int main ()
  • void main ().

The type of the return value is specified before the name of the function. When the main function is called, the value is returned to the operating system. The last entry will not return values. but void main ()- not quite correct notation, since it tells the compiler that the main () function does not return any value.

In this case, the record int main () tells the compiler to return an integer value that is required by the operating system and tells it that the program terminated correctly. If this value is not returned, then the operating system understands that the program terminated in abnormal mode.
To return an integer value, a line is added before the end of the function

return 0; // real variable

Descriptions and operators are enclosed in curly braces.

In general, a program can contain several functions. Each function has a list of parameters passed to it, indicated in parentheses, and a set of operations, enclosed in a block, delimited by curly braces.

Example: Displaying the message "Hello, world!" ...

1
2
3
4
5
6
7

#include // Connect the I / O library
int main () // Main function
{
printf ("Hello, world!"); // Display the message
getchar (); // Delay the console window
return 0;
}


The result of the program:

Now let's try to write a text in Russian.

1
2
3
4
5
6
7

#include
int main ()
{
printf ( "Hello world!");
getchar ();
return 0;
}


The result of the program:


The problem with the Russian language in console applications is that the console and the Microsoft Visual Studio code editor support different code pages. In order to see Russian characters in the console, you need to change the code page in the console to match the editor's code page (1251). For this purpose, the system ( "chcp 1251") with the appropriate command line. The system () function prototype is contained in the library .

In this case, the program text will look like this.

Composition of language In a text in any natural language, four
basic elements: symbols, words, phrases and sentences.
The algorithmic language contains similar elements:
The alphabet of the language, or its symbols, are the main indivisible signs, with
with the help of which all texts in the language are written.
Lexeme is a minimal unit of a language that has an independent
meaning.
An expression specifies a rule for calculating a certain value.
The operator specifies a complete description of some action.
A complex action requires a sequence
operators. Operators can be combined into a compound
operator, or block (a block in C ++ is
a sequence of statements enclosed in curly braces ()).
In this case, they are treated as one operator.
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.
A set of descriptions combined by a single algorithm and
operators forms a program in an algorithmic language.

Program execution process

In order to execute the program, you need to translate it
into a language understandable by a processor - into machine codes. This
the process consists of several stages:
First, the program is passed to the preprocessor, which
includes text files containing description
elements used in the program.
The resulting full text of the program is sent to the input
a compiler that extracts tokens and then based on
the grammar of the language recognizes expressions and operators,
built from these tokens. In this case, the compiler detects
syntax errors and, in their absence, builds
object module.
The linker, or linker, generates
the executable module of the program, connecting to the object
module other object modules. If the program consists
from several source files, they are compiled by
separately and combined at the linking stage.
The executable module has the extension .exe and can be
launched for execution.

C ++ alphabet

The C alphabet includes:
uppercase and lowercase letters of the Latin alphabet (A, B, ..., Z, a, b, ..., z) and and
underscore;
digits: 0,1,2,3,4,5,6,7,8,9
special characters: ", () | () * + - /% \;". :?< = >_! & # non-displayable characters ("generic whitespace"),
used to separate tokens from each other (for example, a space,
tabulation, line break).
From the symbols of the alphabet
lexemes of the language are formed:
identifiers;
key (reserved) words;
operation signs;
constants;
delimiters (brackets, period, comma, whitespace).
The boundaries of tokens are defined by other tokens such as
separators or operation signs.

Identifiers

An identifier is the name of a programmatic object. V
identifier can be used in Latin
letters, numbers and underscore. Uppercase and
lowercase letters are different. The first character
identifier can be a letter or sign
underscores. Wherein:
identifier must not match key
the words and names used by the standard
language objects;
it is not recommended to start identifiers with a character
underlining;
Identifiers can be of any length, but
the compiler counts no more than 31 characters from
the beginning of the identifier;
Examples of identifiers:
COM_16, size88, _MIN, TIME, time

Keywords

Keywords are reserved identifiers that have
special meaning to the compiler. They can only be used if
the sense in which they are defined. For a list of C ++ keywords, see
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

Operation signs

An operation sign is one or more
action symbols
over the operands. Inside the sign
operation spaces are not allowed.
Operations are divided into unary ones,
binary and ternary by quantity
operands participating in them.

Simple data types

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

Data types
Type specifiers include:
char
- symbolic;
double - real double precision floating point;
float - real floating point;
int - integer;
long
- a whole of increased length (long whole);
short - reduced length integer (short integer);
signed - signed, i.e. signed integer (the most significant bit is
iconic);
unsigned - unsigned, i.e. unsigned integer (most significant bit is not
considered iconic);
void
- lack of meaning;
bool - boolean (can only take the values ​​true and false.
The internal form of the false value is 0 (zero).
Any other value is interpreted as true.)
To describe constants, use the const keyword 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 with this
function starts executing the program, and from
this function, as required,
other functions are called.
The simplest function definition has the following format:
return_type name ([options])
{
the operators that make up the body of the function
}
Typically, a function is used to calculate some
values, so the type is indicated before the name of the function. 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 can consist of several modules (source files) and, as a rule,
contains preprocessor directives. An example of the structure of a program containing
functions main, f1 and f2:
preprocessor directives
descriptions
int main ()
{
main function operators
}
int f1 () (
operators of function f1
}
int f2 () (
operators of function f2
}
/ * An example of a simple program * /
#include
int main ()
{
printf (“Hello World!”);
return 0;
}

12.C-style I / O functions

Basic C-style I / O features:
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 format. The format string contains characters that are copied to the stream (to the screen) on output, or
are requested from the stream (from the keyboard) on input, and conversion specifications starting with
% signs, which are replaced with specific values ​​during input and output.
#include
int main () (
int i;
printf ("Please 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, according to which it is inserted into the program text
header file containing a description of the input / output functions used in the program. Everything
preprocessor directives start with a # sign.
The third line is the description of an integer variable named i.
The printf function on the fourth line prints the prompt Enter an integer and continues to a new line in
according to the escape sequence \ n.
The scanf function puts the integer entered from the keyboard into the variable i, and the next statement outputs to
screen the specified string, replacing the conversion specification with the value of this 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 function routines and macros that you can
call from your C programs to solve
a wide range of tasks, including input / output
low and high level, work with
lines and files, memory allocation,
process control, 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
start with the # character, preceded by
line can only contain whitespace
symbols.
Search for a file if the full path is not specified,
maintained in standard catalogs
include files. Instead of corner
brackets can use quotes ("")
- in this case, the file is searched for in
the directory containing the source file, and
then in standard catalogs.
Header files usually have
extension .h.

16. # include preprocessor directive

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

17. The #define preprocessor directive

#Define directive defines substitution in the text
programs. It is used to determine
symbolic constants.
The format for defining a symbolic constant is:
#define name substitution_text / * All occurrences
names are replaced with 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
Descriptions of the various functions used in
access to BIOS routines (basic
input-output system).
CONIO.H Description of the various functions used in
accessing DOS I / O routines with
keyboard.
GRAPHICS.H Contains graphical function prototypes.
MATH.H Contains a description of mathematical prototypes
functions
STDIO.H Defines the types and macros required for
standard I / O package. Defines the same
standard I / O streams stdin, stdout and
describes the input / output routines.
STDLIB.H Describes some general purpose routines:
routines for transformation, search, sorting and others.
STRING.H
Describes several string processing routines and
work with memory.

19. Format output function PRINTF

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

20. SCANF format input function

For interactive input mode can probably be used in
in most cases, scanf. scanf is an input function, within the meaning
equivalent to printf; its format looks like this:
scanf (<строка формата>,<адрес>,<адрес>,...)
However, scanf has one very important difference: 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 to expect input from you.
two decimal (whole) numbers separated by a space; the first will be
assigned to a, and the second to b. Note that the operation is used here
addresses (&) to pass addresses a and b to scanf.

21. Format string

A format string is a string that begins
and ends with double quotes ("like this");
the purpose of printf is to write this line to the screen. Front
with printf output replaces everything additionally
listed objects per line according to
with format specifications given in
the line itself. Example printf statement:
printf (“d =% f \ n", d);

22. Format string

The% f in the format string is a format specification. Everything
format specifications start with a percent character (%) and
(usually) followed by a single letter indicating the type
data and how they are converted.
The% f used in the spec indicates 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 is an integer in hexadecimal format.

23. Format string

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

24. Format string

The \ n on the line is not a format specification, but
used (for historical reasons) as
an escape sequence, and represents
a special character to be inserted into the string. In this case
\ n inserts a character at the beginning of a newline, so
after displaying a line, the cursor will move to the beginning of a new one
strings.
- \ f (format translation or clear screen)
- \ t (tab)
- \ b (backspace<-)
- \ xhhh (insert character with ASCII code hhh, where hhh
contains from 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
interest: puts and putchar. The puts function prints the string to
screen and terminates the output with a newline character.
Let's look at an example program:
#include
main ()
{
puts ("Hello, student of VKI NSU");
}
Note that \ n is omitted at the end of the line; it is not necessary as
puts itself adds this character.
Conversely, the putchar function writes a single character to
screen and doesn't add \ n. The putchar (ch) statement is equivalent to
printf ("% c", ch).

27. Functions GETS, GETCH

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

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

28. Functions GETS, GETCH

# include
# include
main ()
{
clrscr ();
char name;
printf ("What's your name:");
gets (name);
printf ("Hello% s \ n", name);
getch ();
}
Here the getch function expects any character to be input.
Getch reads a single character from the keyboard without printing
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. Operation of assignment

The most common operation is assignment,
for example p = a / b or ch = getch (). In Xi
assignment is denoted by one character
equality (=); 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 from the right
to the left, that is, b will be assigned to a, which 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 from division (%)
- addition (+)
- subtraction (-)
To increase the values ​​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; shortened to a + = b;
a = a - b; is reduced to a - = b;
a = a * b; shortened to a * = b;
a = a / b; is reduced to a / = b;
a = a% b; is reduced to a% = b;

32. Example 1

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

33. Example 2

The angle is given 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 in radians");
scanf ("% f", & Angle);
Result1 = sin (Angle);
Result2 = cos (Angle);
printf ("The sine of an angle is% f \ n", Result1);
printf ("Cosine of angle is% f", Result2);

Please suspend 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.

We will fill in a simple card. At the moment we know that there are programs, but how they are arranged inside we do not know. 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. Do not be alarmed! Below is the source code for three simple programs. Your task is to look at them carefully and try to find some pattern in their code (something common that every program has).

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 rest of the lesson and the correct answer to this problem. First, try answering yourself. After that press the button "Watch the continuation!"

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

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

Int main (void) (return 0;)

What is this design. This is the declaration of the main function. Such a function is a must in every program that is written in C. A large program or a small one, a computer game or the "Hello, World!" Program, written by you or by 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 may think that we are running the main function of this program.

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

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

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

Let me tell you a little about the main function and 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". This notation means that when the main function completes its work, it must return some integer to the calling program (in our case, it is the operating system). Usually, for the main function, this is the number zero, which notifies the operating system: "Like, everything is fine. No incidents happened."

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

The word void is written in parentheses after the function name. In general, function arguments are usually written in parentheses, but in our case, when they write void in parentheses, this means that the function has no arguments. In other words, for the main function to start working, it does not need any additional data from the outside. 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 braces there is a description of the main function, i.e. directly 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.

Why exactly zero, you may ask? And the devil only knows! They usually do it just like that. You can, in principle, return some other integer, for example 100, or -236. If only it was a whole number. Remember int? Therefore the whole.

So we figured out the main function. One more point. 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 now go back to our first "Hello, World" program and see what's what.

Listing 5. The "Hello, World" program

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

We already understand something 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, beginning with the # character, are called compiler directives. Literally: "include the stdio.h file". At compile time, 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 English STanDart Input Output) is a header file, it describes various standard functions related to input and output.

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

Here's the thing. Before using anything in our program, we need to describe it first. Imagine a situation, you were asked to bring a candelabrum, and you do not know what it is. It is not clear what to do.

So is the compiler. When he encounters a function, he 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. Therefore, we connect it. But when we connect it, the compiler will be able to find the printf () function, otherwise it will throw an error.

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

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

Let's continue to deal with our program.

Listing 7. printf () function

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

In this line, we call the standard printf () display function. In this simplest case, we pass it one parameter, a quoted string that needs to be displayed, in our case it is Hello, World! \ n. But wait, what is this \ n? There weren't any \ 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 move 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 with the character "\" - a backslash. These special characters are called control characters. I will show you them later. Otherwise, the screen will display exactly what you wrote in double quotes.

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

To call any function, you need to write its name and indicate 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 parentheses. For example, above we called the printf () function and passed it one parameter a string to be printed to the screen.

By the way, useful advice. Since every program has a main function, 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 stub for C programs.

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

Well, that seems to be all. This first lesson can be considered complete. 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 didn’t seem to know anything at all, but even that would be enough to, for example, make a small gift to my mother on March 8th.


The source code for the postcard program is in the source code archive for this tutorial. Experiment! You will succeed.

Top related articles