programarea calculatorului teorie si definitii (en)
TRANSCRIPT
-
8/20/2019 Programarea calculatorului teorie si definitii (EN)
1/28
1.Character data type. Declaration and initialization of a character data
type variable.
-Character variable is defned to be o type char. For example: char ch; One character variable
occupies a single byte which contains the code or the character. This code is a numeric value
and depends on the character coding system being used is machine-dependent!. The most
common system is "#C$$ "merican #tandard Code or $normation $nterchange!. $n C language
does not exist data type string and thereore do not exist variables o string type but it is
possible to process strings. " string in C language represents
a
set o characters stored in
statically or dynamically allocated %-& array o character type and terminated by null byte null
character! and such a set o characters is considered as one ob'ect - a string.
" char can be initiali(ed :
For example: char ch = ’b’
2.Functions for inputting a char from the eyboard.
%. scanf! "#c$% &ch'; )ote using o ormat specifcation #c or character type variable*
+. ch = getchar! '; )ote that ater pressing a character ,ey on the ,eyboard it is necessary to
press also the nter ,ey because unction getchar! ' uses bu/er memory o console as the
unction scanf! ' does*
0. ch = getch! '; )ote that unction getch! ' does not use bu/er memory what is way ater
pressing a character ,ey its value is directly assigned to corresponding character variable ch
without additional pressing the nter ,ey*
1. ch = getche! '; Function getche! ' deers rom unction getch! ' only by showing on the
screen a character echo! introduced rom ,eyboard as unctions scanf! ' and getchar! ' do.
#can and getchar are in the 2stdio.h3 and getch 4 getche are in 2conio.h3
(.Functions for outputting a char from the eyboard
)utput !*riting' a character on the screen is perormed by using standard unctions
printf! '% putchar! ' declared in header fle stdio.h and unction putch! ' declared in header
fle conio.h. For example:
printf!"#c$% ch'; or putchar!ch'; or putch!ch'; or output on the screen a characterstored in the character variable ch;
printf!"#c$% +,’'; or putchar!+,’'; or putch!+,’'; or output on the screen character ,*
printf!"#c$%+-n’'; or putchar!+-n’'; or putch!+-n’'; or moving the cursor at the beginning othe new line.
.)ne dimensional array of characters and strings in C language.
$n C language does not exist data type string and thereore do not exist variables o string type
but it is possible to process strings. " string in C language represents
a
set o characters stored
in statically or dynamically allocated %-& array o character type and terminated by null byte
null character! and such a set o characters is considered as one ob'ect - a string.
%-& statically allocated character array can be initiali(ed as any array during declaration %! by
assigning to it a string literal as we 'ust considered beore
-
8/20/2019 Programarea calculatorului teorie si definitii (EN)
2/28
1.char color/10 = "blue$
+! by assigning to it a set o characters ended by null byte.
For example: char color/10 = +b’% +l’% +u’% +e’% +-0’3;
4.Functions to input a string from eyboard.
5e can use the unction that is stored in the 2stdio.h3 fle 6getsstr!7
$t8s a unction that returns a variable which points to the start o the string.
5nput !reading' a string o characters rom ,eyboard is perormed by using standard unction
scanf! ' and gets! ' declared in header fle stdio.h. For example a string can be introduced
rom ,eyboard as ollows:
scanf! "#s$% str'; or gets!str'; where str is the string name name o character
array or pointer or dynamic array where the string is stored!.
)ote using o ormat specifcation #s in unction scanf! ' call and absence o ampersand &
beore str in both unction calls because name o string is a pointer an address!. $t is alsoimportant that unction scanf! ' inputsreads! a string rom ,eyboard only till the frst space but
unction gets! ' can input a string with spaces. $t is recommended beore unctions scanf! '%
getchar! ' and gets! ' calls to use the unction 6ush!stdin' call or clearing the bu/er
memory.
7.Functions to output a string on the screen.
The unctions print! and puts! can be used to output a literal on the screen. 9ut i we
need to output a string that has a pointer pointing to it8s start we can do it li,e this
printf!"#s$% str'; or puts!str';
)utput !*riting ' a string o characters on the screen is perormed by using standard
unctions printf! ' and puts! ' declared in header fle stdio.h. For example:
printf!"#s$% str'; or puts!str'; or output on the screen a string named str name o
character array or pointer or dynamic character array where the string is stored!*
printf!"8ello% my friends9-n$'; or puts!"8ello% my friends9$'; or output on the screen
the string 8ello% my friends9 and or moving the cursor at the beginning o the new line.
printf!"-n-n$'; or puts!"-n$'; or output one blan, line and or moving the cursor at the
beginning o the new line.
:.tandard library functions for character and string processing.
Character and string processing.
-
8/20/2019 Programarea calculatorului teorie si definitii (EN)
3/28
For character and string processing in C language can be used di/erent unctions rom standard
library header fles ctype.h character handling library or character processing! stdlib.h
general utilities library or string conversion unctions! and string.h string handling library o
string processing!. &escriptions and examples o using o these unctions presented in the elp
option o ;ain menu o Turbo C44 compiler.
The most useul unctions or string processing rom header fle string.h are:strlen! ' < to determine string length returns number n o characters in the string str!* x.:
n=strlen!str'; strcat! ' < to 'oin concatenate! string s1 and string s2 together in one string s1. x.:
strcat!s1% s2'; strcpy! ' < to copy assign! contents o string s2 to string s1* x.: strcpy!s1% s2';
strcmp! ' < to compare string s1 and string s2 returns => i strings are the same 2> istring s1 2 string
s2 upper in dictionary! and 3> i string s1 3 string s2 lower in dictionary!* x.:=strcmp!s1% s2';
stricmp! ' < this unction is the same as strcmp! ' but not case sensitive* x.: =stricmp!s1% s2'; strrev! ' < to reverse the characters in string str* x.: strrev!str'; strupr! ' < to convert all characters in string str rom lowercase to uppercase* x.:
strupr!str';strl*r! ' < to convert all characters in string str rom uppercase to lowercase* x.:
strl*r!str';
.Classi>cation of data types in C ?anguage.
The C language provides many basic types. ;ost o them are ormed rom one o the our basic
arithmetic type specifers in C char int ?oat and double! and optional specifers
signedunsigned short long! . "nd there are data types defned by user : structures and unions.
&ata types in C
%. Fundamental &ata Types
o $nteger types
o Floating Type
o Character types
+. &erived &ata Types
o "rrays
o @ointers
o #tructures
o numeration
#yntax or declaration o a variabledata_type variable_name;
-
8/20/2019 Programarea calculatorului teorie si definitii (EN)
4/28
@.Data types de>ned by user in C language
Data types defined by user in C language are of 2 types. Structures and unions. Basicly structures and unions are used if
a user wants to group many variables together , but they are of different types , so he cannot use arrays, thus he uses
Structures and Unions.
10.Data type truct.Declaration of truct data type speci>cations and
variables. Asing typedef statement.
" structure type is usually defned near to the start o a program using the struct statement or
the typede statement allowing its use throughout the program. These statements usually
occur 'ust ater the Ainclude statements in a program. ere are two examples o the struct and
typede specifcations:
These define new data type names struct student and STUDENT and declare variables of structure type. The
purpose of typedef is to form comple types from more!basic machine types and assign simpler names to
such combinations.
Bse o typede with structs
• typedef is a powerul tool that allows programmers to defne and then use their own data
types. For example:
• typede int $nteger*
• $nteger n#tudents nCourses student$&*
• )ote that in the typede statement the newly defned type name goes in the place wherea variable name would normally go.
• There are a ew benefts o using typede with simple types such as the example above:
o For readability $nteger may be easier to understand than int.
o The typede can be easily changed later say to typede long int $nteger* ! whichwould then a/ect all variables o the defned type.
• owever the real beneft o typede comes into play with complex data structures such asstructs:
•
typedef struct student
{char name[40];
int year;
int clas;
float averae;
! STUDENT;
STUDENT st"# st$ # %&[$']# (ps;
struct student
{char name[40];
int year;
int clas;
float averae;
!;
struct student st"# st$ # %&[$']#(ps;
-
8/20/2019 Programarea calculatorului teorie si definitii (EN)
5/28
11. Fields of struct data type. ,ccess operation to the >elds of structure.
Asing typedef statement.
Fields in a structure can be reerenced by ollowing the name o the structure by a dot and the
name o the feld.
France.population = 0;
Dou can also declare a pointer to type Estruct countryE and use that to reerence the felds in a
structure o that type. $n this case you ollow the pointer name by an arrow and the name o the
feld.
struct country Russia, *sptr;
sptr = &Russia;sptr->population = 0;
$n the example above ussia is o type Estruct countryG* sptr is o type Epointer to struct countryE*
and sptr-3population is o type integer.
"ccessing data felds within structs
• The dot operator period ! is used to access named felds within struct variables:
o!n.n"lasses = #;
total$% '= sue.(pa;
"ssigning one struct to another
• $ two variables are o the same struct type then they can be directly assigned one to theother.
o #ee the variable defnitions above to see why some o these are invalid.
o )ote: There is a potential problem i the structs contain pointers. #ee below ordetails. !
oe = sue; )) e(al, bot! of t!e same type mary = carla; )) lso le(al, bot! of t!e same type alice = bill; )) +till le(al. ot! t!e same unnamed type
alice = c!arlie; )) lle(al. ifferent types, even t!ou(! identical
"$) "*D array of structures) Data+ase in form of "*D array of stuctures) Set of operations on
data+ase)
-
8/20/2019 Programarea calculatorului teorie si definitii (EN)
6/28
Arrays of structures are possible, and are a good way of storing lists of data with regular fields, such as
databases. It is possible to define an array of structures for example if we are maintaining information of all thestudents in the college and if 100 students are studying in the college. We can define an array S of structures as
shown in the following example.
typedef struct student
{ char name[40];
int year;
int clas;
float averae; ! STUDENT;
BADB /100;
"n array of structures in C language can be used or storing and processing inormation o the
same elements structure ob'ects! in a simple database. For creating a database using an array
o structures we have to determine a set o operations on it. Bsually this set of operations on
an array of structures database can be represented as ollows:
%. dynamic memory allocation or an array o n elements o the given structure.
+. input elements o array o structures rom ,eyboard.
0. output elements o array on the screen.
1. searching an element in array.
H. modiying an element o array.
I. swapping two elements o array.
J. sorting elements o array.
K. writing saving! elements o array in fle.
L. reading loading! elements o array rom fle.
%>. reeing memory dynamically allocated or array.
%%. appending an element to the end o array.
%+. inserting an element into array.
%0. deleting an element rom array.
%1. other operations related to determine some inormation statistics! rom database.
"ll these operations options! can be implemented in a C language program or an array o
structures database processing by creating corresponding number o unctions subprograms
and then by calling them rom main! ' unction in some order. Bsually order and number o
these unction calls order and number o options needed to perorm! depend on and are
-
8/20/2019 Programarea calculatorului teorie si definitii (EN)
7/28
determined by user during a wor,ing session with database. 5hat is why it is necessary to
develop appropriate user interace or communication between user and program.
",) -nfinit loop and s.itch statment for menu of operations on "*D array of tructures
"n array of structures in C language can be used or storing and processing inormation o the
same elements structure ob'ects! in a simple database. For creating a database using an array
o structures we have to determine a set o operations on it. Bsually this set of operations on
an array of structures database can be represented as ollows:
%. dynamic memory allocation or an array o n elements o the given structure.
+. input elements o array o structures rom ,eyboard.
0. output elements o array on the screen.
1. searching an element in array.
H. modiying an element o array.
I. swapping two elements o array.
J. sorting elements o array.
K. writing saving! elements o array in fle.
L. reading loading! elements o array rom fle.
%>. reeing memory dynamically allocated or array.
%%. appending an element to the end o array.
%+. inserting an element into array.
%0. deleting an element rom array.
%1. other operations related to determine some inormation statistics! rom database.
"ll these operations options! can be implemented in a C language program or an array o
structures database processing by creating corresponding number o unctions subprograms!
and then by calling them rom main! ' unction in some order. Bsually order and number o
these unction calls order and number o options needed to perorm! depend on and are
determined by user during a wor,ing session with database. 5hat is why it is necessary to
develop appropriate user interace or communication between user and program.
"*hile! 1 ' MM infnite while loop
clrscr! ';
puts!"-n -t -t menuE-n$';
-
8/20/2019 Programarea calculatorului teorie si definitii (EN)
8/28
puts!"-n 1. dynamic memory allocation $';
puts!"-n 2. input an array from eyboard$'; "
14. Data type union. Declaration of union specication and variables.
Using typedef statement.
" union is the eNuivalent o an assembler org or a CO9O &F$). $t allows you tohandle an area o memory that could contain di/erent types o variables. The syntaxor unions is identical to that or structures. Dou can use either typedeEs or instreamdefnitions: simply replace the word struct with the word union.
Dou can contain unions within structures or structures within unions. ither way the Cunion is an unwieldy mechanism.
" union might be used to group di/erent record layouts rom the same fle or to handlea single feld that could contain or example either numeric or character data.
typedef struct transaction
/
int amount;
union
/
int count;
c!ar name#1;
2 udata;
c!ar discount;
2 3ransaction;
" union type defnition contains the union ,eyword ollowed by an optional identifer tag! and a
brace-enclosed list o members.
" union defnition has the ollowing orm:
>>-union--'-identifier--------------------------'-------------->4
5 .-----------. 5
5 6 5 5
-
8/20/2019 Programarea calculatorului teorie si definitii (EN)
9/28
7-'------------'--/----member--;-'--2-7
7-identifier-7
" union declaration has the same orm as a union defnition except that the declaration has no
brace-enclosed list o members.
The identifer is a tag given to the union specifed by the member list. Once a tag is specifed
any subseNuent declaration o the union in the same scope! can be made by declaring the tagand omitting the member list. $ a tag is not specifed all variable defnitions that reer to that
union must be placed within the statement that defnes the data type.
The list o members provides the data type with a description o the ob'ects that can be stored in
the union.
" union member defnition has same orm as a variable declaration.
14. Fields of union data type. ,ccess and assignment operations for union data type.
DiGerenses bet*een struct and union variables.
&i/erence between Bnion and #tructure
A union is a class all of whose data members are mapped to the same address within its obect. The si!e of an
obect of a union is, therefore, the si!e of its largest data member.
In a structure, all of its data members are stored in contiguous memory locations. The si!e of an obect of a
struct is, therefore, the si!e of the sum of all its data members.
This gain in space efficiency, while valuable in certain circumstances, comes at a great cost of safety" the
program logic must ensure that it only reads the field most recently written along all possible execution paths.
The exception is when unions are used for type conversion" in this case, a certain field is written and thesubse#uently read field is deliberately different.
An example illustrating this point is"
'-----'-----'struct / int a; float b; 2 (ives 5 a 5 b 5 '-----'-----' 8 8 5 5 memory location9 :0 :# 5
-
8/20/2019 Programarea calculatorului teorie si definitii (EN)
10/28
'nions are typically used in situation where an obect can be one of many things but only one at a time, such as
a type(less storage system"
typedef enum / +3R, 3 2 t3ype;typedef struct / t3ype typ; )) typ is separate. union / int ival; )) ival and sval occupy same memory. c!ar *sval;
2;2 t6al;
"') /reprocessor directives include and define) 1acro*definition and pseudo*function
The C @reprocessor
ecall that preprocessing is the frst step in the C program compilation stage -- this eature isuniNue to C compilers.
The preprocessor more or less provides its own language which can be a very powerful tool to the programmer.
)ecall that all preprocessor directives or commands begin with a *.
'se of the preprocessor is advantageous since it ma&es"
• programs easier to develop
• easier to read
• easier to modiy
• C code more transportable between di/erent machine architectures.
The preprocessor also lets us customise the language. +or example to replace ... - bloc& statements delimiters
by A$/A li&e be(in ... end we can do"
?define be(in /?define end 2
uring compilation all occurrences of be(in and end (et replaced by correspondin( / or 2 and sot!e subse@uent " compilation sta(e does not AnoB any differenceCCC.
ets looA at ?define in more detail
Adefne'se this to define constants or any macro substitution. 'se as follows"
-
8/20/2019 Programarea calculatorului teorie si definitii (EN)
11/28
?define 4macro> 4replacement name> For Example
?define F+D 0 ?define 3RED CF+D
AincludeThis directive includes a file into code.
It has two possible forms"
?include 4file> or
?include file
4file> tells t!e compiler to looA B!ere system include files are !eld. Esually EG
systems store files in usr include directory.
file looAs for a file in t!e current directory HB!ere pro(ram Bas run fromI
Included files usually contain " prototypes and declarations from !eader files and notHal(orit!micI " code H+DD net "!apter for reasonsI
2acros with arguments must be defined using the *define directive before they can be used. The argument list
is enclosed in parentheses and must immediately follow the macro name. $paces are not allowed between and
macro name and open parenthesis. +or example"
?define JGH,yI HHI > HyI K HI 9 HyII
;acro Caveats:• 2acro definitions are not stored in the obect file. They are only active for the duration of a single
source file starting when they are defined and ending when they are undefined 3using *undef4, redefined
or when the end of the source file is found.
• 2acro definitions you wish to use in multiple source files may be defined in an include file which may
be included in each source file where the macros are re#uired.
Today, ?define is primarily used to handle compiler and platform differences. 5.g., a define might hold a
constant which is the appropriate error code for a system call. The use of ?define should thus be limited unless
absolutely necessary6 typedef statements and constant variables can often perform the same functions more
safely.
-
8/20/2019 Programarea calculatorului teorie si definitii (EN)
12/28
Another feature of the ?define command is that it can ta&e arguments, ma&ing it rather useful as a pseudo(
function creator. /onsider the following code"
?define +LE3D_6EDH I H HHI 4 0I K -HI 9 HI I...int = -:;B!ileH +LE3D_6EDH I I /...2
It7s generally a good idea to use extra parentheses when using complex macros. 8otice that in the above
example, the variable %x% is always within its own set of parentheses. This way, it will be evaluated in whole,
before being compared to 0 or multiplied by (1. Also, the entire macro is surrounded by parentheses, to prevent
it from being contaminated by other code. If you7re not careful, you run the ris& of having the compilermisinterpret your code.
9ecause of side(effects it is considered a very bad idea to use macro functions as described above.
int = -:0;int y = +LE3D_6EDH '' I;
1:. File pointer. Functions fopen!' and fclose!' for opening and closing a >le.
)pening a >le.
$ we want to store data in a fle in the external memory we must use the ollowing general
ormat or opening a fle:
F5? Hfp; fp=fopen!">lename$%$mode$'; if!fp= =A??'puts!">le *as notoppend$'; return;3
The frst statement declares the variable fp called fle pointer to the structure data type F5?
that is defned in the stdio.h. The second statement opens the fle named >lename o
corresponding mode by using standard unction fopen! ' and determines the value o fle
pointer fp or the given fle. This pointer which points to the data stracture F5? that contains all
the inormation about the fle is used as a communication lin, between the operating system
and the program. The third statement verifes i unction fopen! ' returned )B pointer and i
so it means that fle was not opened. The mode o fle can be o three main ,inds:
r- the fle or reading data * *- the fle or writing data* a- the fle or appending data.
Consider the ollowing statements:
F5? Pfp1% P p2; fp1=fopen!"data.tIt$%$r$';
fp2=fopen!"results.tIt$%$*$';
$n these statements the fp1 and fp2 are created and assigned to open the fles data and
results respectively. The fle data is opened or reading and results is opened or writing. $n
case the fle results already exists its contents are deleted and the fle is opened as a new fle.
$ fle data does not exist fp1 recieves
-
8/20/2019 Programarea calculatorului teorie si definitii (EN)
13/28
)B pointer value and fle is not opened.
Closing a >le.
The input output library stdio.h supports the unction to close a fle o the ollowing ormat:
fclose!fp'; " fle must be closed as soon as all operations on it have been completed. The unction fclose! '
closes the fle associated with the fle pointer fp.
Observe the ollowing part o program:
F5? Pfp1 Pfp2; fp1=fopen !"data.tIt$%$r$'; fp2=fopen
!"results.tIt$%$*$';
fclose!fp1'; fclose!fp2';
The above program opens two fles and closes them ater all operations on them are completed.Once a fle is closed its fle pointer can be reversed on other fle.
The getc! ' and putc! ' unctions are analogous to getchar! ' and putchar! ' unctions and
handle one character at a time. The unction call putc!ch% fp1 '; writes the character
contained in character variable ch to the fle associated with the pointer fp1* similarly the
unction getc! ' is used to read a character rom a fle that has been opened in read mode and
than to assign it to character variable ch = getc!fp2';
Bhe fprintf! ' and fscanf! ' formatted functions for *riting in and reading from >le.
The fprintf! ' and fscanf! ' ormatted unctions are identical to printf! ' and scanf! '
ormatted unctions except that they wor, on fles. The frst argument o theses unctions is a fle
pointer fp which specifes the fle to be used. The general orm o fprintf! ' unction call is:
fprintf!fp% $control string$% list';
Where fp is a file pointer associated with a file that has been opened for writing. The control string is file output
specifications, list may include variable, constant and string. +or example"
fprintf2fp# 3s d )$f5n6# name# ae# 7)89;
:ere name is a character array, ae is an integer variable and 7)8 is a float constant.
The general format of fscanf2 9 function call is"
fscanf2fp# 6control strin6# list9;
This statement would cause the reading of items of list conform the control string. +or example"
fscanf2fp# 6sd6# item# :uantity69;
-
8/20/2019 Programarea calculatorului teorie si definitii (EN)
14/28
where item is a character array and Juantity is an integer variable.
1. Functions for input and output operations using >les.
Keading from or *riting to a >leE
;nce a file has been successfully opened, you can read from it using fscanfHI or write to it using fprintfHI.
These functions wor& ust li&e scanfHI and printfHI, except they re#uire an extra first parameter, a FD *
for the file to be read
-
8/20/2019 Programarea calculatorului teorie si definitii (EN)
15/28
5rrors li&e that will at least mess up how the rest of the file is read. In some cases, they will cause an infinite
loop.
;ne solution is to test against the number of values we expect to be read by fscanfHI each time. $ince our
format is Ps Pd, we expect it to read in = values, so our condition could be"
B!ile HfscanfHifp, Ps Pd, username, &scoreI == SI / ...
8ow, if we get = values, the loop continues. If we don7t get = values, either because we are at the end of the file
or some other problem occurred 3e.g., it sees a letter when it is trying to read in a number with Pd4, then the loop
will end.
Another way to test for end of file is with the library function feofHI. It ust ta&es a file pointer and returns a
true
-
8/20/2019 Programarea calculatorului teorie si definitii (EN)
16/28
unction!
setvbu sets the bu/er and its si(e or a fle stream
unction!
&irect inputMoutput
readreads rom a fle
unction!
writewrites to a fle
unction!
Bnormatted inputMoutput)arrow character
getcgetcgets a character rom a fle stream
unction!
getsgets a character string rom a fle stream
unction!
putcputc writes a character to a fle streamunction!
putswrites a character string to a fle stream
unction!
getcharreads a character rom stdin
unction!
gets
until C44%1!
reads a character string rom stdin
unction!
putcharwrites a character to stdout
unction!
putswrites a character string to stdout
unction!
ungetcputs a character bac, into a fle stream
unction!
5ide character
getwcgetwc
gets a wide character rom a fle stream
unction!
getwsgets a wide string rom a fle stream
unction!
putwcputwcwrites a wide character to a fle stream
unction!
putwswrites a wide string to a fle stream
unction!
http://en.cppreference.com/w/cpp/io/c/setvbufhttp://en.cppreference.com/w/cpp/io/c/freadhttp://en.cppreference.com/w/cpp/io/c/fwritehttp://en.cppreference.com/w/cpp/io/c/fgetchttp://en.cppreference.com/w/cpp/io/c/fgetshttp://en.cppreference.com/w/cpp/io/c/fputchttp://en.cppreference.com/w/cpp/io/c/fputshttp://en.cppreference.com/w/cpp/io/c/getcharhttp://en.cppreference.com/w/cpp/io/c/getshttp://en.cppreference.com/w/cpp/io/c/putcharhttp://en.cppreference.com/w/cpp/io/c/putshttp://en.cppreference.com/w/cpp/io/c/ungetchttp://en.cppreference.com/w/cpp/io/c/fgetwchttp://en.cppreference.com/w/cpp/io/c/fgetwshttp://en.cppreference.com/w/cpp/io/c/fputwchttp://en.cppreference.com/w/cpp/io/c/fputwshttp://en.cppreference.com/w/cpp/io/c/setvbufhttp://en.cppreference.com/w/cpp/io/c/freadhttp://en.cppreference.com/w/cpp/io/c/fwritehttp://en.cppreference.com/w/cpp/io/c/fgetchttp://en.cppreference.com/w/cpp/io/c/fgetshttp://en.cppreference.com/w/cpp/io/c/fputchttp://en.cppreference.com/w/cpp/io/c/fputshttp://en.cppreference.com/w/cpp/io/c/getcharhttp://en.cppreference.com/w/cpp/io/c/getshttp://en.cppreference.com/w/cpp/io/c/putcharhttp://en.cppreference.com/w/cpp/io/c/putshttp://en.cppreference.com/w/cpp/io/c/ungetchttp://en.cppreference.com/w/cpp/io/c/fgetwchttp://en.cppreference.com/w/cpp/io/c/fgetwshttp://en.cppreference.com/w/cpp/io/c/fputwchttp://en.cppreference.com/w/cpp/io/c/fputws
-
8/20/2019 Programarea calculatorului teorie si definitii (EN)
17/28
getwcharreads a wide character rom stdin
unction!
putwcharwrites a wide character to stdout
unction!
ungetwcputs a wide character bac, into a fle stream
unction!
Formatted inputMoutput)arrowMmultibyte character
scan/scansscan reads ormatted input rom stdin a fle stream or a bu/er
unction!
vscanvscanvsscan
C44%%!C44%%!C44%%!
reads ormatted input rom stdin a fle stream or a bu/er
using variable argument list
unction!
print/printsprintsnprint
C44%%!
prints ormatted output to stdout a fle stream or a bu/er
unction!
vprintvprintvsprintvsnpri
nt
C44%%!
prints ormatted output to stdout a fle stream or a bu/er
using variable argument list
unction!
5ide character
wscan/wscanswscan
reads ormatted wide character input rom stdin a fle stream or a
bu/er
unction!
vwscanvwscanvswscan
C44%%!C44%%!C44%%!
reads ormatted wide character input rom stdin a fle streamor a bu/er using variable argument list
unction!
wprint/wprintswprint
prints ormatted wide character output to stdout a fle stream or a
bu/er
unction!
vwprintvwprintvswprint
prints ormatted wide character output to stdout a fle stream
or a bu/er using variable argument list
unction!
File positioning
tellreturns the current fle position indicator
unction!
getposgets the fle position indicator
unction!
see,moves the fle position indicator to a specifc location in a fle
unction!
http://en.cppreference.com/w/cpp/io/c/getwcharhttp://en.cppreference.com/w/cpp/io/c/putwcharhttp://en.cppreference.com/w/cpp/io/c/ungetwchttp://en.cppreference.com/w/cpp/io/c/fscanfhttp://en.cppreference.com/w/cpp/io/c/vfscanfhttp://en.cppreference.com/w/cpp/io/c/fprintfhttp://en.cppreference.com/w/cpp/io/c/vfprintfhttp://en.cppreference.com/w/cpp/io/c/vfprintfhttp://en.cppreference.com/w/cpp/io/c/fwscanfhttp://en.cppreference.com/w/cpp/io/c/vfwscanfhttp://en.cppreference.com/w/cpp/io/c/fwprintfhttp://en.cppreference.com/w/cpp/io/c/vfwprintfhttp://en.cppreference.com/w/cpp/io/c/ftellhttp://en.cppreference.com/w/cpp/io/c/fgetposhttp://en.cppreference.com/w/cpp/io/c/fseekhttp://en.cppreference.com/w/cpp/io/c/getwcharhttp://en.cppreference.com/w/cpp/io/c/putwcharhttp://en.cppreference.com/w/cpp/io/c/ungetwchttp://en.cppreference.com/w/cpp/io/c/fscanfhttp://en.cppreference.com/w/cpp/io/c/vfscanfhttp://en.cppreference.com/w/cpp/io/c/fprintfhttp://en.cppreference.com/w/cpp/io/c/vfprintfhttp://en.cppreference.com/w/cpp/io/c/vfprintfhttp://en.cppreference.com/w/cpp/io/c/fwscanfhttp://en.cppreference.com/w/cpp/io/c/vfwscanfhttp://en.cppreference.com/w/cpp/io/c/fwprintfhttp://en.cppreference.com/w/cpp/io/c/vfwprintfhttp://en.cppreference.com/w/cpp/io/c/ftellhttp://en.cppreference.com/w/cpp/io/c/fgetposhttp://en.cppreference.com/w/cpp/io/c/fseek
-
8/20/2019 Programarea calculatorului teorie si definitii (EN)
18/28
setposmoves the fle position indicator to a specifc location in a fle
unction!
rewindmoves the fle position indicator to the beginning in a fle
unction!
rror handling
clearerrclears errors
unction!
eo chec,s or the end-o-fle
unction!
errorchec,s or a fle error
unction!
perror
displays a character string corresponding o the current error to
stderr
unction!
Operations on fles
removeerases a fle
unction!
renamerenames a fle
unction!
tmpflecreates and opens a temporary auto-removing fle
unction!
tmpnamreturns a uniNue flename
unction!
Types
&efned in header 4cstdio>
Type &efnition
F$ type capable o holding all inormation needed to control a C $MO stream
posRtnon-array type capable o uniNuely speciying a position in a fle including its multibyte
parse state
1@. Lit*ise operations in C language
9itwise operators are special types of operators that are used in programming the processor. In processor,
mathematical operations li&e" addition, subtraction, addition and division are done using the bitwise operators
which ma&es processing faster and saves power.
The 9itwise operators supported by / language are listed in the following table. Assume variable A holds >0and variable 9 holds 1?, then"
http://en.cppreference.com/w/cpp/io/c/fsetposhttp://en.cppreference.com/w/cpp/io/c/rewindhttp://en.cppreference.com/w/cpp/io/c/clearerrhttp://en.cppreference.com/w/cpp/io/c/feofhttp://en.cppreference.com/w/cpp/io/c/ferrorhttp://en.cppreference.com/w/cpp/io/c/perrorhttp://en.cppreference.com/w/cpp/io/c/removehttp://en.cppreference.com/w/cpp/io/c/renamehttp://en.cppreference.com/w/cpp/io/c/tmpfilehttp://en.cppreference.com/w/cpp/io/c/tmpnamhttp://en.cppreference.com/w/cpp/io/c/fsetposhttp://en.cppreference.com/w/cpp/io/c/rewindhttp://en.cppreference.com/w/cpp/io/c/clearerrhttp://en.cppreference.com/w/cpp/io/c/feofhttp://en.cppreference.com/w/cpp/io/c/ferrorhttp://en.cppreference.com/w/cpp/io/c/perrorhttp://en.cppreference.com/w/cpp/io/c/removehttp://en.cppreference.com/w/cpp/io/c/renamehttp://en.cppreference.com/w/cpp/io/c/tmpfilehttp://en.cppreference.com/w/cpp/io/c/tmpnam
-
8/20/2019 Programarea calculatorului teorie si definitii (EN)
19/28
1 which is 0011
1101
B9inary C;) ;perator copies the bit if it is set in one
operand but not both.
3A B 94 will give DE which is 0011
0001
F 9inary ;nes /omplement ;perator is unary and has theeffect of 7flipping7 bits.
3FA 4 will give (>1 which is 1100 0011in =7s complement form due to asigned binary number.
GG9inary eft $hift ;perator. The left operands value is moved
left by the number of bits specified by the right operand.
A GG = will give =D0 which is 1111
0000
HH
9inary )ight $hift ;perator. The left operands value is
moved right by the number of bits specified by the right
operand.
A HH = will give 1 which is 0000
1111
=0. ;perators for bitwise logical operations
+our of the bitwise operators have e#uivalent logical operators. They are e#uivalent in that they have the same
truth tables. :owever, logical operators treat each operand as having only one value, either true or false, rather
than treating each bit of an operand as an independent value. ogical operators consider !ero false and any
non!ero value true. Another difference is that logical operators perform short(circuit evaluation.
The table below matches e#uivalent operators and shows a and b as operands of the operators.
Lit*ise ?ogical
a & b a && b
a 5 b a 55 b
a 8 b a C= b
Ta Ca
C= has the same truth table as 8 but unli&e the true logical operators, by itself C= is not strictly spea&ing a logical
operator. This is because a logical operator must treat any non!ero value the same. To be used as a logical
operator C= re#uires that operands be normali!ed first. A logical not applied to both operands wonJt change the
truth table that results but will ensure all non!ero values are converted to the same value before comparison.
This wor&s because C on a !ero always results in a one and C on any non!ero value always results in a !ero.
The example below shows that the truth tables for these 9itwise and ogical operators are identical but also
demonstrates how they act on their operands differently. The need to normali!e operands for C= can be
demonstrated by introducing a c!ar 3S = 00S and pac&ing it in an array. 2ixing 3S with 3 will show them
being treated the same unless the operand 8;Ts around C= are removed.
http://en.wikipedia.org/wiki/Short-circuit_evaluationhttp://en.wikipedia.org/wiki/Short-circuit_evaluation
-
8/20/2019 Programarea calculatorului teorie si definitii (EN)
20/28
=1. ;perators for bitwise shifting operations
In /(inspired languages, the left and right shift operators are %44% and %>>%, respectively. The number of places
to shift is given as the second argument to the shift operators. +or example,
= y 44 S;
assigns x the result of shifting y to the left by two bits.
In /, the result of right(shifting a negative value is implementation(defined, and the result of left(shifting a
signed value is undefined if the result cannot be represented in the result type.
&eft shift
K iterally shifts the bits of the operand to the left.
K +or example, if +" and +$ are unsined char then
+$ > +" ?? $;
results in
+" 000""0"0 =>
+$ 0""0"000 10D
K 9its shifted out of the 2$9 are lost, bits shifted in through the $9 are always !ero.
8otice +$ is e#ual to +"(4. eft shift performs multiplication by $@n.
Aiht shift
K )ight shift is a little more complicated.
K $hifts bits of the operand to the right. = BB n
K 9its shifted out of the $9 are lost.
K 9its shifted in through the 2$9 are
L always 0 if the number is unsined
L either " 3%right shift arithmetic%4
or 0 3%right shift logical%4 if the sign bit is " 3i.e. sined4
sined char = > *78; C( "0"" 0"0" (C
sined char y > = BB $; C( 00"0 ""0" 2loical shift9 (C
-
8/20/2019 Programarea calculatorului teorie si definitii (EN)
21/28
C( """0 ""0" 2arithmetic shift9 (C
K )esult is implementation dependent 3ie, different on different machines4. Above example is D on
logical(shift machine, and (1E on an arithmetic shift machine.
K It is usually preferred to use unsigned types for bitwise operations to avoid non(portable behaviour.
K 8ote" right shift is e#uivalent to division by $@n if operand is non(negative or machine uses arithmeticright(shift.
==. rument of function main29
@assing "rguments to mainHI
mainHI is passed two arguments from the shell" an integer and a pointer to an array of strings. Traditionally
these are declared as follows"
int mainHint ar(c,c!ar *ar(v1I
:erear(c
3MMargument count774 contains one plus the number of arguments passed to the program from the
command line and ar(v 3MMargument vector774 contains a series of c!ar pointers to these arguments. The first
element in ar(v is always the name of the program itself, so ar(c is always at least 1. The library function
(etoptHI can perform simple parsing of command(line arguments6 see the listing in section ?c of the man
pages. :ere7s a more simple example of passing two numbers and a string. 8ote the error trapping to force the
user to conform to the expected usage"
?include 4stdio.!> ?include 4stdlib.!> )* for atoiHI *)
int mainHint ar(c,c!ar *ar(v1I /
int m,n; if Har(c C= #I / printfHEsa(e9 Ps m n filenameQn,ar(v01I; return :; 2 m = atoiHar(v:1I; )* convert strin(s to inte(ers *) n = atoiHar(vS1I; printfHPs received m=Pi n=Pi filename=PsQn,ar(v01,m,n,ar(vU1I; return 0; 2
2(. Dynamic memory allocation 1MD array
To allocate dynamically a similar %-& array having number o elements introduced rom ,eyboard
the
ollowing code is recommended:
int *, n;
printfHVDnter number of elements of array9 VI;
-
8/20/2019 Programarea calculatorului teorie si definitii (EN)
22/28
scanfHVPdW, &nI;
= Hint*I mallocH n* sieofHintI I; )) or = Hint*I mallocH n*sieofH*I I;
if H == EI )) or s!orter if H CI
/
putsH VQn Jemory Bas not allocatedWI; )) or usin( !ere return statement
2
"ter this code it is possible to use allocated memory having access to it by means o pointer "
which
can be used as name o dynamic array.
There are + ,inds o memory allocation in CMC44 languages: a! static memory allocation and b!dynamic memory allocation.#tatic memory allocation reers to the process o allocating memory or the named variables at
compile time beore the corresponding program is executed. #tatic memory allocation isperormed by compiler conorm variable declaration statements or global and local variables.Slobal variables constants specifed by ,eyword const! and static memory class local variablesspecifed by ,eyword static! having lietime o a whole program are allocated in fxed memorybut automatic memory class local variables specifed by ,eyword auto or by deault! havinglietime o a unction call are allocated on the stac, is a part o computer memory where data isadded and removed in a ast-$n-First-Out $FO! manner!. ;emory allocated statically can not bereallocated or reed deallocated! by program itsel by programmer!.&ynamic memory allocation is the allocation memory or the unnamed dynamic variables atruntimeduring program execution. $n C language dynamic memory allocation is perormed by programitsel by programmer! using special unctions o standard library header fle stdlib.h . &ynamic
memory is allocated rom a large part o unused memory area called the heap also called theree store !. &ynamic memory is allocated accessed managed reallocated and reed at runtimeby using pointer variables 'ust allocated statically beore at compile time.
Functions malloc ! and ree !. The unction malloc ! is the basic unction used to allocate memory on the heap on the reestore! in C language. $ts prototype is:
voidP mallocint si(e!* where voidP is the type o unction which represents void pointer type o returning value andsi(e is the parameter variable name which represents the si(e o the bloc, o memory needed inbytes.$ the allocation is perormed successully unction malloc ! returns the beginning address o
void pointer type! o the bloc, o memory allocated. )ote that because malloc ! unction returnsa void pointer it is recommended to cast the type o returning value o unction malloc ! to aneeded pointer type especially or compatibility o C language programs with C44 languageprograms.$ the allocation is not perormed successully unction malloc ! returns the )B pointer valueto indicate that no memory was allocated and usually in this case the program execution isterminated. ;emory allocated by malloc ! unction will continue to exist until the program terminates orthe memory explicitly deallocated by the programmer that is the bloc, is said to be Greed8!.
This is achieved by use o the unction ree !. $ts prototype is: void ree voidP p!*
-
8/20/2019 Programarea calculatorului teorie si definitii (EN)
23/28
where p is the void pointer parameter or the beginning address o the bloc, o memory 'ustallocated beore by malloc ! unction or other unctions used or dynamic memory allocation."ter ree ! unction call the memory pointed to by p is not more available or the program andwhat is why it is strictly recommended to assign )B pointer value to the pointer p immediatelyater ree ! unction call.
2.Nointers and ,rrays
$n CMC44 languages the name identifer! o an array is eNuivalent to the address o its frst
element so in act they are the same concept. For example supposing these two declarations:
int ,/20; int P p;
The ollowing assignment operations would be valid and eNuivalent: a! p=,; b! p=&,/0;
"ter that p and , would be the same and would have the same properties so that name o
pointer p can be used as another name o array ,. The only di/erence is that we could change
the value o pointer p by another one whereas , will always point to the frst o the +> elements
o type int with which it was defned. Thereore unli,e p% which is an ordinary pointer , is anarray and an array can be considered a constant pointer .
Thereore the ollowing assignments would not be valid: ,=p; ,=,O1*
9ecause , is an array so it operates as a constant pointer and we cannot assign values to
constants.
Concerning %-& arrays we used sNuare brac,ets / in order to speciy the index subscript! o
an element o the %-& array to which we wanted to reer. 5ell this sNuare brac,ets operator /
or the indexation operator is also a dereerencing operator ,nown as ofset operator . $t
dereerences the variable name o array or pointer! it ollows 'ust as the dereerencing pointeroperator P does ater adding the subscript to the name o array and thus obtaining the memory
address o the corresponding element.
#o the expression ,/4 is eNuivalent to the expression P !,O4' both represents the value
o the I-th element o int type counted rom the starting address ,. "nalogically expressions
&,/4 and !,O4' are eNuivalent and both represent the address o the memory where this
element is stored.
Nointers to NointersC allo*s the use of pointers that point to pointers% that these% in its turn% point todata !or even to other pointers'. 5n order to do that% *e only need to add an asteris!H' for each level of reference in their declarationsEchar a;char H b;char HH c;a = PzP;b = &a;c = &b;
Bhis% supposing the randomly chosen memory locations for each variable of :2(0%0@2 and 10402% could be represented asE
-
8/20/2019 Programarea calculatorului teorie si definitii (EN)
24/28
Bhe value of each variable is *ritten inside each cell; under the cells are theirrespective addresses in memory.
Bhe ne* thing in this eIample is variable c% *hich can be used in three diGerent levelsof indirection% each one of them *ould correspond to a diGerent valueE
M c has type charHH anda value of 0@2
M Hc has type charH anda value of :2(0
M HHc has type char anda value of PzP
, A?? pointer is a regular pointer of any pointer type *hich has a special value thatindicates that it is not pointing to any valid reference or memory address.
int H p;p = A??;QQ p has a A?? pointer value
Do not confuse A?? pointers *ith void pointers. , null pointer is a value that anypointer may tae to represent that it is pointing to Rno*hereR% *hile a void pointer isa special type of pointer that can point to some*here *ithout a speci>c type.
+J. Dynamically llocatin 1ultidimensional rrays
We7ve seen that it7s straightforward to call malloc to allocate a bloc& of memory which can simulate an array,
but with a si!e which we get to pic& at run(time. /an we do the same sort of thing to simulate multidimensional
arraysN We can, but we7ll end up using pointers to pointers.
If we don7t &now how many columns the array will have, we7ll clearly allocate memory for each row 3as many
columns wide as we li&e4 by calling malloc, and each row will therefore be represented by a pointer. :ow willwe &eep trac& of those pointersN There are, after all, many of them, one for each row. $o we want to simulate an
array of pointers, but we don7t &now how many rows there will be, either, so we7ll have to simulate that array 3of pointers4 with another pointer, and this will be a pointer to a pointer.
This is best illustrated with an example"
?include 4stdlib.!>
int **array;array = mallocHnroBs * sieofHint *II;ifHarray == EI
/fprintfHstderr, out of memoryQnI;exit or return
2forHi = 0; i 4 nroBs; i''I
/arrayi1 = mallocHncolumns * sieofHintII;ifHarrayi1 == EI
/fprintfHstderr, out of memoryQnI;exit or return
22
-
8/20/2019 Programarea calculatorului teorie si definitii (EN)
25/28
array is a pointer(to(pointer(to(int" at the first level, it points to a bloc& of pointers, one for each row. That
first(level pointer is the first one we allocate6 it has nroBs elements, with each element big enough to hold a
pointer(to(int, or int *. If we successfully allocate it, we then fill in the pointers 3all nroBs of them4 with a
pointer 3also obtained from malloc4 to ncolumns number of ints, the storage for that row of the array. If this
isn7t #uite ma&ing sense, a picture should ma&e everything clear"
;nce we7ve done this, we can 3ust as for the one(dimensional case4 use array(li&e syntax to access our
simulated multidimensional array. If we write
arrayi11
we7re as&ing for the i7th pointer pointed to by array, and then for the 7th int pointed to by that inner pointer.
3This is a pretty nice result" although some completely different machinery, involving two levels of pointerdereferencing, is going on behind the scenes, the simulated, dynamically(allocated two(dimensional MMarray77 can
still be accessed ust as if it were an array of arrays, i.e. with the same pair of brac&eted subscripts.4
If a program uses simulated, dynamically allocated multidimensional arrays, it becomes possible to write
MMheterogeneous77 functions which don't have to &now 3at compile time4 how big the MMarrays77 are. In otherwords, one function can operate on MMarrays77 of various si!es and shapes. The function will loo& something li&e
funcSHint **array, int nroBs, int ncolumnsI/2
This function does accept a pointer(to(pointer(to(int, on the assumption that we7ll only be calling it with
simulated, dynamically allocated multidimensional arrays. 3We must not call this function on arrays li&e theMMtrue77 multidimensional array aS of the previous sections4. The function also accepts the dimensions of the
arrays as parameters, so that it will &now how many MMrows77 and MMcolumns77 there are, so that it can iterate overthem correctly. :ere is a function which !eros out a pointer(to(pointer, two(dimensional MMarray77"
void eroitHint **array, int nroBs, int ncolumnsI/int i, ;forHi = 0; i 4 nroBs; i''I
/forH = 0; 4 ncolumns; ''I
arrayi11 = 0;2
2
+inally, when it comes time to free one of these dynamically allocated multidimensional MMarrays,77 we must
remember to free each of the chun&s of memory that we7ve allocated. 3Oust freeing the top(level pointer, array,
wouldn7t cut it6 if we did, all the second(level pointers would be lost but not freed, and would waste memory.4
:ere7s what the code might loo& li&e"
forHi = 0; i 4 nroBs; i''IfreeHarrayi1I;
freeHarrayI;
-
8/20/2019 Programarea calculatorului teorie si definitii (EN)
26/28
2. "s we defned beore see lecture +! a composed or structured variable represents named
location in the memory o computer where more than one value can be stored. There are
di/erent ,inds o composed variables which are also called data structures. One o these ,inds is
an array.
$n programming an array is a composed variable or a data structure which represents
named set of values also called elements or components! of the same type% located in the
memory o computer
continuously one after one. "rrays are very oten used in programming or storing and
processing data.
$n mathematics arrays are ,nown as matrices and are used or solving di/erent problems.
Bsually in computer programming are used one-dimensional %-&! and two-dimensional be
dimensional! arrays +-&!. &imension o an array depends on the number o integer values called
indices subscripts! used or determining the position o a given element and or accessing to the
corresponding element. One subscript is used or indicating elements o %-& array vector! and
two subscripts are used or elements o +-& arraymatrix!. $n mathematics %-& arrays also called
vectors represent special ,ind o
matrices +-& arrays! having only one line row! or one column.
$n CMC44 languages indices subscripts! are enclosed in sNuare brac,ets U represented the
indexation
operator. $n CMC44 languages values o subscripts start by >.
x.: ">U is the frst element o an %-& array named "*
90U is the orth element o an %-& array named 9*
C+U0U is an element o the third rowline! and o the ourth column o an +-& array
named C*
,rray declaration and initialization
The general orm o an array declarations in CMC44 languages are ollowing:
or %-& array is type name/size!length' of array or number of elements;
and or +-& array type name/number of ro*s!lines'/number of columns;
x.: int "+>U*
?oat 9H>U*
-
8/20/2019 Programarea calculatorului teorie si definitii (EN)
27/28
char C%>U0>U*
"rrays can be initiali(ed during declaration in such a way:
int "HU=V0-HIJ >W*
?oat 9+U0U=V V0.+ +.H >WV-H.0 L 1J.HH W W*
or ?oat 9+U0U=V 0.+ +.H > -H.0 L 1J.HH W*
Asually initialization of arrays is eGectuated in run time by diGerent *ays% for
eIample by input elements from eyboard or from eIisting >le or by using special
random function!program' for generating elements of an array.
(0. Kecursive function
" unction can be called not only rom by other unction by also by itsel. #uch unctions
are called recursive . " recursive unction must have mandatory some condition to stop
the recursion otherwise it will call itsel till stac, over?ow occurs.
Dample9
unsi(ned int Factorial Hunsi(ned int aI
/
if Ha4SI return a;
return a*FactorialHa-:I;
2
-
8/20/2019 Programarea calculatorului teorie si definitii (EN)
28/28
The unction actorial! gets called rom main! with number having the value 1 as theargument.
5ithin the actorial! unction itsel because the argument is greater than % thestatement executed is: return aPFactoriala-%!*
This is the second return statement in the unction and it calls actorial! again with theargument value 0 rom within the arithmetic expression. This expression can8t beevaluated and the return can8t be completed until the value is returned rom this call tothe unction actorial! with the argument 0.
This continues until the argument in the last call o the actorial! unction is %. $n thiscase the frst return statement return a* is executed and the value % is returned to theprevious call point. This call point is in act inside the second return in the actorial!unction which can now calculate + P % and return to the previous call.
$n this way the whole process unwinds ending up with the value reNuired being returnedto main!.