How to set up smartphones and PCs. Informational portal
  • home
  • Windows 8
  • The main sections of the program in the language with. Internal structure of the program

The main sections of the program in the language with. Internal structure of the program

C, such as static and local variables, arrays, pointers, functions, etc., are as close as possible to the architecture of real computers. So, a pointer is just a memory address, an array is a contiguous area of ​​memory, local variables are variables located on the hardware stack, static variables are in static memory. A C programmer always has a fairly accurate idea of ​​how the program he creates will work on any particular architecture. In other words, the C language gives the programmer complete control over the computer.

Originally, C was conceived as a replacement for Assembly for writing operating systems. Because C is a high-level, architecture-independent language, operating system text was easily portable from one platform to another. The first operating system, written almost entirely in C, was the Unix system. Nowadays, almost all operating systems in use are written in C. In addition, programming tools that operating system provides developers of application programs (the so-called API - Application Program Interface) - a set of system functions in the C language.

However, the scope of the C language was not limited to the development of operating systems. The C language turned out to be very convenient in word processing and image processing programs, in scientific and engineering calculations. C-based object-oriented languages ​​are great for programming in windowed environments.

In this section, only the basic concepts of the C language (and partially C ++) will be given. It does not replace reading a complete C or C ++ textbook, such as books and.

We will use the C ++ compiler instead of the C compiler. The fact is that the C language is almost entirely included in C ++, i.e. a normal C program is a valid C ++ program. The word "normal" means that it does not contain bad constructs left over from earlier versions of C and not used today. The C ++ compiler is preferred over the C compiler because it has stricter error control. In addition, some C ++ constructs that are not related to object-oriented programming are very convenient and, in fact, are improvements to the C language. These are, first of all, comments //, the ability to describe local variables at any point in the program, not just at the beginning of a block, and also setting constants without using the #define preprocessor operator. We will use these features of C ++, while remaining essentially within the framework of the C language.

The structure of a C program

Any sufficiently large C program (programmers use the term project) consists of files. The files are compiled by the C compiler independently of each other and then combined by the task builder program, resulting in a file with the program ready for execution. The files containing the texts of the C program are called initial.

In the C language, source files are of two types:

  • header, or h-files;
  • implementation files, or C files.

Header file names have a ".h" extension. Implementation file names have the extensions ".c" for C and ".cpp", ".cxx", or ".cc" for C ++.

Unfortunately, unlike the C language, programmers have not been able to agree on a single name extension for files containing C ++ programs. We will use the ".h" extension for the header files and the ".cpp" extension for the implementation files.

Header files contain only descriptions. First of all, these are function prototypes. Function prototype describes the function name, return type, number and types of its arguments. The text of the function itself is not contained in the h-file. Also, h-files describe the names and types of external variables, constants, new types, structures, etc. In general, h-files contain only interfaces, i.e. information necessary to use programs already written by other programmers (or by the same programmer before). Header files only provide information about other programs. When translating header files, as a rule, no objects are created. For example, in the header file you cannot define a global variable. Description line

defining an integer variable x is an error. The description should be used instead

meaning that the variable x is defined somewhere in the implementation file (which is unknown). The word extern (external) only communicates information about an external variable, but does not define that variable.

Implementation files, or C files, contain function texts and global variable definitions. In simple terms, C files contain the programs themselves, and h files only contain information about the programs.

Presentation of source texts in the form of header files and implementation files is necessary to create large projects with a modular structure. Header files are used to transfer information between modules. Implementation files are separate modules that are developed and translated independently of each other and are combined to create an executable program.

Implementation files can include descriptions contained in header files. The header files themselves can use other header files as well. The header file is included using the #include preprocessor directive. For example, descriptions of standard I / O functions are included with the line

#include

(stdio - from the words standard input / output). The name of the h-file is written in angle brackets, if this h-

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.

STRUCTURE OF A SIMPLE PROGRAM

Now that we've covered a specific example, you're ready to get familiar with a few general rules about C programs. A program consists of one or more functions, and some of them must be called main ()... The function description consists of a title and a body. The header, in turn, consists of preprocessor directives like #include and so on and the name of the function.

RICE. 2.4. Function structure in C language: header and body.

From the C ++ book by Hill Murray

1.6 Program structure A C ++ program usually consists of a large number of source files, each of which contains descriptions of types, functions, variables and constants. To be able to use a name in different source files to refer to the same object, it must

From the book Home Architect. Preparing for repair and construction on a computer author Bulat Vitaly

The structure of the Super Home Suite program Let us consider the main window of the Super Home Suite program (demo version 3.5.2) (Fig. 2.1). Rice. 2.1. The main window of the Super Home Suite program At the top is the system menu, which includes sections of commands for managing the program, editing data,

From the book Computer Science and Information Technology: Lecture Notes author Tsvetkova AV

Program structure The PromOffice Euroremont program window (Fig. 3.1) consists of several parts. At the top there is a horizontal panel with the main menu, below it is the toolbar. The rest of the window area is occupied by panels for working with data. In the latest version of the program in the right

From the book Computer Science and Information Technology author Tsvetkova AV

1. Structure of an assembly language program An assembly language program is a collection of blocks of memory called memory segments. A program can consist of one or several such block-segments. Each segment contains a collection of language sentences,

From the book The C # 2005 Programming Language and the .NET 2.0 Platform. author Troelsen Andrew

47. The structure of an assembly language program An assembly language program is a collection of blocks of memory called memory segments. A program can consist of one or more such block-segments. Each segment contains a collection of sentences

From the book The C Programming Language for the Personal Computer author Bochkov S.O.

The Structure of a Simple C # Program C # requires that all program logic be contained within a type definition (remember from Chapter 1 that the term type is used to refer to any element of a set (class, interface, structure, list, delegate)). V

From the book Create a Virus and Antivirus the author Gulyev Igor A.

PROGRAM STRUCTURE Source program A source program is a collection of the following elements: preprocessor directives, compiler instructions, declarations and definitions. Preprocessor directives specify the conversion actions of the preprocessor

From the book C Language - A Beginner's Guide by Prata Stephen

The structure and process of loading a COM program What is a COM program, how is it loaded into memory and launched? The structure of a COM program is extremely simple - it contains only the code and data of the program, without even having a header. The size of the COM program is limited

From the book Linux and UNIX: Shell Programming. Developer's guide. by Teinsley David

The structure and loading process of EXE programs Unlike COM programs, EXE programs can consist of several segments (codes, data, stack). They can be larger than 64KB. The EXE file has a header that is used when loading it. The title consists of

From the book The End of Holivar. Pascal vs C author Krivtsov M.A.

EXAMPLE OF A SIMPLE C PROGRAM Let's take a look at a simple C program. It should be said right away that we only need such an example to identify some of the main features of any program written in the C language. Below we will explain each line, but before

From the book Linux and everything, everything, everything ... Articles and columns in LinuxFormat, 2006-2013 the author Alexey Fedorchuk

18.5.1. Simple for loop This loop simply displays a list that consists of "1 2 3 4 5". To access each variable, use "loop" as the variable_name parameter. $ Pg for_i #! / Bin / sh # for_ifor loop in 1 2 3 4 5doecho $ LOOP done The above script outputs the following: $

From the book Description of the PascalABC.NET language the author RuBoard team

1. Structure of a Pascal Program In a Pascal program, the following main sections are distinguished: program title, descriptions, operators. Sections are separated from each other by semicolons. A full stop is put at the end of the program. Each section starts with its own key

From the author's book

1. The structure of a program in C A program can consist of one or several interconnected functions, the main of which is called main - it is from this that the execution of the program begins. Therefore, the presence of a function with this name in any program

From the author's book

Creating a Simple Pool Having mastered the basic concepts earlier, we learned how to understand ZFS. For the reverse problem - for ZFS to understand us - you need to familiarize yourself with its commands. The main ones are two: zpool for creating and managing pools, and zfs for creating and managing datasets.

From the author's book

Program structure Program structure: overview The program contains keywords, identifiers, comments. Keywords are used to highlight syntax and are highlighted in bold in the editor. Identifiers are names

From the author's book

Program structure: overview The program contains keywords, identifiers, comments. Keywords are used to highlight syntax and are highlighted in bold in the editor. Identifiers are the names of program objects and cannot

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 example:
#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);

Before you start writing programs, you need to study the structure of programs in the C ++ programming language. In its own words, the structure of programs is the markup of the work area (area of ​​code) in order to clearly define the main blocks of programs and syntax. The structure of the programs differs slightly depending on the programming environment. We are focusing 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 your code from MVS to other development environments, and you will understand over time how to do it.

The 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 talks about the entry point for the console application, which means that this program can be launched through the Windows command line by specifying the program name, for example, this is struct_program.cpp. Line 1 is a one-line comment, since it starts with // characters, more on comments will be discussed in the next article. Line 2 includes the "stdafx.h" header file. This file is similar to a container, since the main preprocessor directives are connected in it (those that the compiler connected when creating a console application), and auxiliary directives (connected by the programmer) can be connected immediately.

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

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

int - integer data type

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

Program structure for C ++ Builder.

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

// preprocessor directive automatically connected by the wizard for creating projects #include int main () (return 0;)

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

The main thing to remember is that if the return type of the main function is int or anything other than 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 work.

In general, the wizard automatically creates the structure of the program, 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 will consider in more detail later, but I will say that this main looks like this, since it was originally designed to support Unicode.

Unicode is a character encoding standard that allows characters to be represented in virtually all written languages. We'll talk more about Unicode later.

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

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

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

The name of the linked libraries is written inside the more, less characters. Header files and the name of the linked libraries are synonyms.

Header files connection syntax:

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

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

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

The difference is that the .h extension is added after the name.

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

This article discusses the structure of C ++ programs in environments such 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 are still undecided about your IDE, read on.

Top related articles