Студопедия

КАТЕГОРИИ:


Архитектура-(3434)Астрономия-(809)Биология-(7483)Биотехнологии-(1457)Военное дело-(14632)Высокие технологии-(1363)География-(913)Геология-(1438)Государство-(451)Демография-(1065)Дом-(47672)Журналистика и СМИ-(912)Изобретательство-(14524)Иностранные языки-(4268)Информатика-(17799)Искусство-(1338)История-(13644)Компьютеры-(11121)Косметика-(55)Кулинария-(373)Культура-(8427)Лингвистика-(374)Литература-(1642)Маркетинг-(23702)Математика-(16968)Машиностроение-(1700)Медицина-(12668)Менеджмент-(24684)Механика-(15423)Науковедение-(506)Образование-(11852)Охрана труда-(3308)Педагогика-(5571)Полиграфия-(1312)Политика-(7869)Право-(5454)Приборостроение-(1369)Программирование-(2801)Производство-(97182)Промышленность-(8706)Психология-(18388)Религия-(3217)Связь-(10668)Сельское хозяйство-(299)Социология-(6455)Спорт-(42831)Строительство-(4793)Торговля-(5050)Транспорт-(2929)Туризм-(1568)Физика-(3942)Философия-(17015)Финансы-(26596)Химия-(22929)Экология-(12095)Экономика-(9961)Электроника-(8441)Электротехника-(4623)Энергетика-(12629)Юриспруденция-(1492)Ядерная техника-(1748)

B) Create a C++ project that enters input data and calls each of the above two functions from the developed unit

Читайте также:
  1. A variable is a characteristic or property of an individual population unit.
  2. Forced oscillations in linear system with one degree of freedom at power affecting. The linear high-frequency injection unit. A resonance
  3. Functions and stylistic effects
  4. Functions and stylistic effects
  5. Functions of adverbs in English and Ukrainian.
  6. Functions of intonation.
  7. Functions of prosodic features
  8. Functions of rhythm.
  9. Functions of word stress
  10. Intonation: approaches, definitions, functions
  11. Iptables -A INPUT -p tcp -j tcp_packets

A function that takes an array of 5 integers as input parameter and builds the output array including only even elements of the input.

 

We can start our work as usually do: launch C++ Builder ad get a “blank” Form1 (usually, with Unit1.h and Unit1.cpp corresponding to it). In order to start elaborating the new unit do the following:

1) In the main menu line of the Builder, choose:

File Þ New

and in a window that will open find “Unit”, click twice.

2) You will see the following “layout” of a new unit’s .CPP-file (it automatically gets name Unit2.cpp):

 

#include <vcl.h>

#pragma hdrstop

 

#include "Unit2.h"

 

#pragma package(smart_init)

 

You see here two directives #include, the first refers to header file of standard C++-Builder’s library “vcl”, and the second refers to the header file of currently elaborating unit. You see also another directive #pragma that I will not explain now (yet note that it is not a good idea to remove directives not already explained).

3) In order to see the layout of a header file (Unit2.h) of our new unit do the following:

a) Click RIGHT button of the mouse somewhere in Unit2.cpp-window;

b) In the appeared menu choose Open Source/Header File.

You will see the following text:

 

#ifndef Unit2H

#define Unit2H

//---------------------------------------------------------------------------

#endif

You see new directives #ifndef, #define and #endif here. I will explain them later, and now only note that all your modifications of the new header file must be placed AFTER #define and BEFORE #endif .

Though in previous lab works we have make no modifications to automatically built header file Unit1.h, now we must include prototypes of our task’s functions to the new unit (otherwise these functions will be not accessible from another projects).

But at first let us change the “default” name of our new unit:

4) Choose

File Þ Save as

and type some new unit name, e.g. MyLib. You will see that both Unit2.h and Unit2.cpp will be changed for MyLib.h and MyLib.cpp respectively.

5) In connection to our task’s items, I will form the following header file MyLib.h :

 

#ifndef Unit2H

#define Unit2H

//--------------------------------------------------

const int N=7;

typedef int AType[N];

int IndOfLastZero(AType A); //1-st function prototype

 

const int N2=5;

typedef int BType[N2];

void GetEvenElems(BType B, BType &Res, int &LenRes);

//2-nd function prototype

#endif

 

6) The next step is to fill the source file MyLib.cpp. Let me propose the following implementations of the above functions’ prototypes:



 

#include <vcl.h>

#pragma hdrstop

 

#include "Unit2.h"

 

//--------------------------------------------------

 

#pragma package(smart_init)

 

int IndOfLastZero(AType A)

{ int j;

for(j=N-1; j>=0; j--)

if(A[j]==0) return j;

return -1;

}

 

bool AnEvenNumber(int n)

{ if((n==0)||(n%2==1))

return false;

else return true;

}

 

void GetEvenElems(BType B, BType &Res, int &LenRes)

{ int j,

k=0;

for(j=0; j<N2; j++)

if( AnEvenNumber(B[j]) )

{Res[k]=B[j]; k++;}

LenRes=k;

}

 

7) Finally we must compose a project that will call the above two task’s function and check their correctness. Let me propose the following form and corresponding calls in Button1Click and Button2Click:

#include "Unit2.h"

 

void __fastcall TForm1::Button1Click(TObject *Sender)

{AType A;

int j, ind0;

for(j=0; j<N; j++)

A[j]=StrToInt(Memo1->Lines->Strings[j]);

ind0=IndOfLastZero(A);

Edit1->Text=IntToStr(ind0);

}

//--------------------------------------------------

 

void __fastcall TForm1::Button2Click(TObject *Sender)

{BType B,

C;

int j,

LenC;

Memo2->Clear();

for(j=0; j<N2; j++)

B[j]=StrToInt(Memo1->Lines->Strings[j]);

GetEvenElems(B, C, LenC);

if(LenC==0)ShowMessage("No even items");

else

for(j=0; j<LenC; j++)

Memo2->Lines->Add(IntToStr(C[j]));

}

 

Characters (symbols)

I think it is obvious to all you that a number and a symbol (or symbols) that denotes this number are different things. For example, the number 5 can be denoted by either the digit 5, or the Rome V, or simply the word “five”.

So symbols form a special type of data that differs from numbers. In fact there are many symbolic types in C++, but one type – namely

char

– is the basic one. The constants of this type are plain symbols like A, я, + and so on. The variables having this type are declared in the following form:

char c, c1, plus, blank;

Being declared, the char-variables can get concrete values in a usual manner, for instance:

c='A'; c1='я'; plus='+'; blank=' ' ; etc.

So you see that we must use apostrophes in typing the char-type constants. Due to these apostrophes the compiler can distinguish symbols from variables (for example, digits from numbers denoted by them).

In the computer memory each char-type constant or variable occupies exactly one byte. So it is obvious that each symbol has its corresponding 8-bits code (or binary number). The smallest possible code is 00000000, and the biggest is 11111111. So it is clear that there exist exactly 256 different constants of the type char.

The decimal number being equal to the binary code (number) of a given symbol is usually called the decimal number of this symbol. Obviously it is the matter of a convention to assign concrete binary (respectively decimal) numbers to concrete symbols. In Windows operational system there accepted a convention that called ANSI coding table. It looks like follows:

Visual image of a symbol Decimal number Binary number

the blank 32 00100000

0 48 00110000

1 49 00110001

A 65 01000001

B 66 01000010

я 255 11111111

In operating systems different from Windows different code tables may be used. For instance, the Ms DOS system uses another code table named ASCII.

Symbols with decimal numbers from 0 to 31 are usually used for special purposes of operating system. Some of them (like symbol number 0) have no visual image. They all also have no corresponding keys on the keyboard. So if a programmer needs to put any of them in any source code he must use special representations. For instance:

'\0' – the symbol with zero number;

'\n' – the symbol with decimal number 10;

(both '\0' and '\n' are widely used in C++, as we will see soon.)

You see that back slash sign marks the usage of special representation of symbols. So it must be clear that this sign cannot be represented by his own icon, namely '\'. In order to compel the compiler to accept back slash as such, one need to use the representation '\\'.

In any case when you know the number of a given symbol, you can represent it through the hexadecimal code of this number. For instance:

'\x0A' – the symbol with hexadecimal number A (the same to decimal 10, so it is '\n');

'\x5C' – the symbol with hexadecimal number 5C (the same to decimal 92, it is back slash \);

Because of the fact that the decimal number of a symbol in ANSI table equals to binary number contained in corresponding byte, there exists a simple way to get this decimal number. All we need is to tell the compiler to treat this byte as being not of char-type, but of type integer. To do it, one can used so-called type cast operation:

char c; c='?' ; // or c='\x5C'; etc.

int n;

n = int(c); //type cast operation

But there appear two problems. The first is that the integer type values are by default signed ones, that means that the highest bit of their binary representations is treated as sign (0 as plus and 1 as minus). At the same time the number of a symbol is always positive (e.g., the number of 'я' is 255, while its binary code is 11111111).

To avoid the treatment of a character number as a signed integer we must use the type specifier unsigned:

n = (unsigned int)(c); //we need parenthesis rounded the type name

because of the blank in it.

The second problem is that the base type int of C++ reserves for its values not 1, but 4 bytes. To avoid the treatment of a symbol as 4 bytes value we must use another integer type, namely __int8 (it occupies 8 bits, i.e. exactly 1 byte). So the correct type cast for getting the number of a symbol will be:

n = (unsigned __int8)(c);

Analogously we can, having the decimal number of any symbol, get its representation as a character by using the following type cast:

unsigned __int8 n; n=33; // or n=233; etc.

char c;

c = char(n); //type cast operation

Note that the declaration of n as “unsigned __int8”, not as “int”, is important here.

The ANSI code table is arranged so that the order of Latin letters in it is the following:

ABCD…Zabcd…z

Likewise the order of Cyrillic letters is

АБВГ…Яабвг…я

and the order of symbols that are digits are

The arrangement of code table induces a certain order between characters, namely the order “before” or “after”. Symbol S1 stands before symbol S2 just in the case when the number of S1 is less than the number of S2. So there is introduced a sign < for a relation “before” in the set of symbols, and we write:

'0' < '1' ;

'A' < 'B' ;

'Я' < 'я' ;

etc. The relations >, <=, and >= are introduced analogously. There exist also obvious relations S1== S2 and S1!= S2 between two symbols.

These features of the ANSI table give possibility to check whether a given character variable c contains a capital Latin letter, a small Cyrillic letter, an arbitrary Latin letter, a digit, etc.

<== предыдущая лекция | следующая лекция ==>
| B) Create a C++ project that enters input data and calls each of the above two functions from the developed unit

Дата добавления: 2014-01-11; Просмотров: 126; Нарушение авторских прав?;


Нам важно ваше мнение! Был ли полезен опубликованный материал? Да | Нет



ПОИСК ПО САЙТУ:


Читайте также:



studopedia.su - Студопедия (2013 - 2017) год. Не является автором материалов, а предоставляет студентам возможность бесплатного обучения и использования! Последнее добавление ip: 54.224.210.130
Генерация страницы за: 0.024 сек.