![]() |
|
#31
|
||||
|
||||
XVII.Pointers :: Functions & Dynamic AllocationXVII.c)Applications in Functions
XVII.c.i)Reference Arguments A reference argument is nothing but a pointer which holds the address to the actual variable passed. The difference between a normal argument and a reference argument is that in a normal argument, the VALUE is passed, whereas in the reference argument, the address is passed. If the VALUE is passed, all operations done will not affect the actual variable, but if the address is passed, then ALL operations will be done on the passed variable. CPP / C++ / C Code:
As mentioned before, &a refers to the address. XVII.c.ii)Returning by Reference Suppose I set the return type as a reference variable,eg. int&, what could happen? Observe. CPP / C++ / C Code:
Something odd about change()=101, right? Well, seems odd, but it makes sense if you think about it. When I'm returning a reference variable of an integer, it seems as if the statement is actually assigning the value 101 to the memory location specified by the reference argument. So, num should be assigned the value, 101. XVII.d)Dynamic Allocation Dynamic allocation of memory involves allocating memory "dynamically" or during run time. Obviously this has infinitesimal use as it makes the programme very flexible. Dynamic allocation is done with 2 operators, new & delete. Eg: CPP / C++ / C Code:
So, I have a pointer pointing to some memory location. Using new, I can allocate 10 bytes of memory to ptr. delete deallocates memory so that memory block will be deassigned from that programme and restored to the heap. |
||||
|
#32
|
||||
|
||||
XVIII.DOS (BGI) GraphicsAdmitted, those old DOS games may have seemed crappy compared to games like AOK, or Warcraft, but any knowledge of graphics is useful and combined with your new C++ expertise, you can make some USEFUL programmes.
XVIII.a)Syntaxes As you're perfectly capable of understanding how to use a function given it's syntax, I'm just giving the syntaxes of 3 basic figures which can be drawn. XVIII.a.i)Initialization As you can guess all the following graphics functions are stored in graphics.h. To initialize, we use a function initgraph() and 3 variables as argument. Eg. int drv=DETECT,mod; initgraph(&drv,&mod,"c:\\tc\\bgi"); drv holds the constant indicating type of graphics driver used by your system. If you don't know or want to make your programme more portable, use DETECT, which will detect the graphics driver. "C:\\tc\\bgi" is the path of the directory which contains the BGI files; without which you cannot run a graphics programme. So always remember to include the required graphics files with your programme. XVIII.a.ii)Line Syntax: line(int x1, int y1, int x2, int y2); Draws a line from point (x1,y1) to point (x2,y2) where x1,y1,x2,y2 are coordinates. You can set the style of the line using setlinestyle(). XVIII.a.ii)Circle Syntax: circle(int x1,int x2,int r); Draws a circle with centre (x1,x2) and radius r EP7 is a very cool programme you can make using circle(); XVIII.b)Co-ordinate System The co-ordinate system we use here is slightly different from the one we generally use. Although both are used mathematically(the former, Quadrant IV and the latter Quadrant I). CPP / C++ / C Code:
As you can see, the only difference between both systems is that the y-coordinate increases on moving DOWN in II (the one we're using in programming) and it increases on moving UP in I. And the origin is at the upper-right corner for I and the origin is at the lower-right corner for II. |
|
#33
|
||||
|
||||
Example Programme #7EP7:
CPP / C++ / C Code:
|
|
#34
|
||||
|
||||
XIX.Some Things You Ought To Know III :: Manips & Type CastingXIX.a)Manipulators
Manipulators are instructions which modify the way data is displayed on the screen. Some useful manipulators are:you can make with XIX.a.i)setw The setw manipulator has inestimable value is easily giving the appearance of orderly programme. Suppose, I wanted to print a table of items & their respective costs: CODE COST A001 12 A010 37 A100 3 B001 129 B010 1123 Obviously this is a disorderly output. To make it more orderly, wouldn't it be good if we could isolate each number in a calculator-like-display box? setw can be used exactly for that. So, setw(n) would create a box of n characters width, and all the characters would be right-justified. Therefore, CPP / C++ / C Code:
XIX.a.ii)setiosflags & setf These manipulators use ios formatting flags to define how certain text is displayed. ios formatting flags are binary values which define the I/O format. When setiosflags() sets the formatting flags, resetiosflags() resets them. [Appendix E has a list of ios formatting flags] Another manipulator is setprecision(int a) which sets the no. of digits of precision of a decimal number to a. XIX.a.iii)endl endl works in exactly the same way as '\n' but it flushes the output buffer as well. Eg. cout<<"\nPhantom XII"<<endl<<"\nC++"; XIX.b)Type Casting Suppose, I asked you to make a programme which displays a table with ASCII characters and their equivalent values? Being the hardcore-C++ programmers you are, you'd probably do this: CPP / C++ / C Code:
Suppose, float a=4.5, therefore the integer equivalent of a is 4 as an integer cannot store a decimal. Similarly, char a='A', means the integer form of a is, 65, the ASCII equivalent of 'A'. So, how can I make this transformation? Simple, by type casting. CPP / C++ / C Code:
Therefore, the MORE compact programme would be: CPP / C++ / C Code:
[If you have any doubts concerning unsigned refer to Appendix C] |
|
#35
|
||||
|
||||
XIX.Some Things You Ought To Know :: goto, enum & Default VariablesXIX.c)goto
This statement is a special favourite of mine. I transcended to C++ straight from batch file programming, so I carried some knowledge of goto with me. With some experimentation, I made a programme which calculated n! using only goto & if-else...wow..Anyway, goto basically takes the programme flow to a specified label. Suppose: CPP / C++ / C Code:
Pretty simple.. XIX.d)enum enum is an incredibly easy way to make your own data type. Suppose you have a data type, which has a closed set of values, like the days of the week which can only have Sunday, Monday, .. , Saturday. So: enum weekday { MON,TUE,WED,THU,FRI}; And we can use it: CPP / C++ / C Code:
Another use of enum is to quickly define constants. After the above declaration, MON will always have value, 1, TUE, 2 and so on.. You can define them separately, like this: enum weekday { MON=2,TUE,WED=8,THU,FRI}; So, MON=2 TUE=3 WED=8 THU=9 FRI=10 A VERY useful application of enum is the type bool, which only holds TRUE or FALSE. enum bool{FALSE,TRUE}; XIX.e)Default Variables Consider the following programme: CPP / C++ / C Code:
I hope you understood why the programme seems so redundant, i.e. heavy. No? Well, think about..the last 3 variables are unnecessarily repeating themselves as we only deviate once. Basically the function draws a line from one point on the screen to another, with a certain colour. But I DO use a different colour & co-ordinates in the last call, so I CAN'T simply give these values to the function...so what do I do? Well, the fairly obvious thing is to modify the function in such a way that if I DON'T give values, the compiler should assume that I meant 100, 100 and WHITE. So, it would be like this: CPP / C++ / C Code:
There..looks much neater doesn't it? How do we achieve this? Simple..we modify the function void drawLine(int x1, int y1, int x2=100, int y2=100, int colour=WHITE) { --code-- } Btw, the default arguments, (ah yes, that's what x2, y2 and colour are called as there's a default value of them), are always declared at the end of the argument list (also called trailing arguments). |
|
#36
|
||||
|
||||
XIX.Some Things You Ought To Know :: Storage Classes, Constants & BitWise OperatorsXIX.f)Storage Classes
Uptil now, we've been taking variables for granted as we were focussing on the more important concepts of classes, functions, etc. But variables too have their complexities. The storage class of a variable determines various factors like it's scope (visibility), lifetime, etc. There are 3 storage classes: automatic, external and static. Automatic and external variables are nothing but local & global variables. Static Static variable is a combination of a local and global variable. A static variable has the visibility of a local variable but the lifetime of a global variable. In other words, the value of the variable is preserved even after the function has been executed. Static variables can be used in classes too..and are pretty useful. Just like a static variable data never changed even if the function call had ended, a static variable in a class holds the SAME DATA for ALL OBJECTS i.e. a value stored in a static variable is the same for all objects. Example: CPP / C++ / C Code:
XIX.g)Constants A constant is an entity which is like a variable except that it's value can never be changed throughout the course of the programme. A constant is useful as a comparison value as we know that it can never be changed. There are 2 ways to declare a constant. XIX.g.i)const Variables const char failGrade='F'; Therefore, failGrade's value can not be changed from 'F'. Functions Setting an argument as const will ensure that the variable's variable will not be changed while the function is running Member Functions Suppose, in a class, you wanted to make a member variable constant in such a way only a few member functions could modify it? Well, use const. CPP / C++ / C Code:
The pre-processor directive #define permanently assigns a value to an identifier (name). This command must take place before void main(). It is similar to #include. #define failGrade 'F'; Please note that absence of a data type and the '=' sign. XIX.h)Bitwise Operators One of the benefits of C++ is that it is one of the few languages which gives allows you to perform bit-wise operations on variables. Bit-wise operations? What's that? As I said earlier, each character can be resolved into 8 bits. Therefore, 'A' is 1000001. A bitwise operation involves executing AND,OR,XOR,etc. operations on each bits. For example: 1000001 &1010101 ------- 1000001 What happened? I took each bit of both numbers are did an AND operation on them. The first bits were, '1' & '1', therefore 1 && 1 = 1. So, the first bit of the resultant character is 1. At first this may seem useless but it has immense applications in encryption, and cracking. |
|
#37
|
||||
|
||||
Example Programme #8EP8:
->Make a programme to execute bit reversal on an integer. Consider an integer 19, binary, 10011, this programmes reverses it so we get, 11001 or 25 CPP / C++ / C Code:
|
|
#38
|
||||
|
||||
XX.A Brief Introduction To PERLWhew! After that whirlwind tutorial, it's time for some rest, right? Nah..we never rest.
"Perl is a language optimized for scanning arbitrary text files, extracting information from those text files, and printing reports based on that information. It's a good language for many system management tasks. The language is intended to be practical (easy to use, efficient, complete) rather than beautiful (tiny, elegant, minimal)." - ActivePerl Documentation::Core Perl Documentation: erl XX.a)Scalar One thing you have to realize about Perl(Practical Extraction & Report Language) is the total freedom we have. In C++ to use a variable, we had to declare in beforehand, but with Perl you don't need to! You can use a variable(a scalar variable in the following example) anytime you want. The one I'm using below is a scalar, one represented by prefixing a $ before the name. Example: CPP / C++ / C Code:
Shocking isn't it? No header files, no cascading different variables, and a cooky input system. Well, actually it's not so complicated. Some functions like print are built-in and don't need "header files". In Perl we use classes, as I've said before, pre-defined packages and use the objects. Now, the input. You might be wondering about the <>. Well actually, the <> stands for ANY kind of input ranging from what you could read from a file to a socket. But in this case the default source is the keyboard, and even if you don't specify <STDIN> it's ok. XX.b)File Handling File handling is done by a built-in Perl function called open. I'll explain later. CPP / C++ / C Code:
This basically outputs the content of the file. As you can see, I created FILE, an object representing the file in question. <FILE> returns the byte just like obj.get(), incrementing the file pointer etc. Btw,the '<' before file.txt shows that the file is meant for reading. open(FILE,">file.txt"); - for writing XX.c)Default Variables Perl is loaded with default variables. In the previous example, we can omit the $byte by using the default variable $_. Btw, a default variable in Perl and the one in C++ have no connection. CPP / C++ / C Code:
CPP / C++ / C Code:
Suppose you wanted to write to a file..you can directly use the print function. CPP / C++ / C Code:
|
|
#39
|
||||
|
||||
Example Programme #9 & #10EP9:
->Make a programme to copy a file [c]#Example Programme 9 - Copy open(SRC,"<source.txt"); open(DEST,">destiny.txt"); $/=\1; while(<SRC>) { print DEST; } close(SRC); close(DEST);[/u] -=-=-=-=-=---=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- EP10: ->Make a programme to solve the N-Queen Problem As I don't want to unneccessarily lengthen this tutorial, check out the solution at my website. |
|
#40
|
||||
|
||||
ConclusionThis can't be called an exact text on C++ as it presented a quick review of the basic points. I haven't talked about powerful concepts like OOP, polymorphism, inheritance, virtual functions, etc. Nor have I delved into the finer points of pointers and their role in functions. But with the knowledge you hopefully gleaned from this tutorial, you should be able to delve into the magnificent world of C++ and maybe, improve it...over time. And perhaps, I'll update this tutorial..over time.
Mithun Jacob a.k.a. Phantom XXIII Created: September 17th 2003 Modified: June 21st 2004 Contact: mithunjacob@vit.ac.in / phantom@phantom23.tk / mithunjacob@hotmail.com Site : http://www.phantom23.tk Note: I have attached Appendices A-F __________________
[b]There are times when the Phantom walks the streets as an ordinary man...this is one of those times. |
Recent GIDBlog
Programming ebook direct download available by crystalattice
| Thread Tools | Search this Thread |
| Rate This Thread | |
|
|
Network Sites: GIDNetwork · GIDWebHosts · GIDSearch · Learning Journal by J de Silva, The