GIDForums  

Go Back   GIDForums > Computer Programming Forums > C++ Forum
User Name
Password
Register FAQ Members List Calendar Search Today's Posts Mark Forums Read

 
 
Thread Tools Search this Thread Rating: Thread Rating: 5 votes, 5.00 average.
  #31  
Old 20-Jun-2004, 19:55
mithunjacob's Avatar
mithunjacob mithunjacob is offline
Junior Member
 
Join Date: Jun 2004
Location: Vellore, India
Posts: 65
mithunjacob will become famous soon enough

XVII.Pointers :: Functions & Dynamic Allocation


XVII.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:
void change(int& integer)
	{
	++integer;
	}

void main()
{
int a=6;
change(&a);
cout<<a;
}

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:
int num=0;

int& change()
	{
	return num;
	}
void main()
{
change()=101;
cout<<num;
}

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:
char *ptr;
ptr=new char[10];
for(int i=0;i<10;++i) ptr[10]=i+48;
delete ptr;

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  
Old 20-Jun-2004, 19:57
mithunjacob's Avatar
mithunjacob mithunjacob is offline
Junior Member
 
Join Date: Jun 2004
Location: Vellore, India
Posts: 65
mithunjacob will become famous soon enough

XVIII.DOS (BGI) Graphics


Admitted, 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:
 

				|
				|
				|
				|
				|
				|
				|_ _ _ _ _ _ _ _
			Origin(0,0)	

				    SYSTEM I


		              Origin(0,0)_ _ _ _ _ _ _ _
				|
				|
				|
				|
				|
				|
				|

				    SYSTEM II

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  
Old 20-Jun-2004, 19:58
mithunjacob's Avatar
mithunjacob mithunjacob is offline
Junior Member
 
Join Date: Jun 2004
Location: Vellore, India
Posts: 65
mithunjacob will become famous soon enough

Example Programme #7


EP7:

CPP / C++ / C Code:
//Psychdelic Circles
#include <graphics.h>
#include <conio.h>

void main()
{
int r=0,c=0;
int drv=DETECT,mod;
initgraph(&drv,&mod,"d:\\tc\\bgi");

while(!kbhit())
        {
                setcolor(c);
                circle(getmaxx()/2,getmaxy()/2,r);
                if(r>getmaxy()/2) r=0;
                if(c>15) c=2;
                ++r,++c;
        }
}
  #34  
Old 20-Jun-2004, 20:00
mithunjacob's Avatar
mithunjacob mithunjacob is offline
Junior Member
 
Join Date: Jun 2004
Location: Vellore, India
Posts: 65
mithunjacob will become famous soon enough

XIX.Some Things You Ought To Know III :: Manips & Type Casting


XIX.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:
#include <iostream.h>
#include <iomanip.h>

void main()
{
char *item[5]={"A001","A010","A100","B001","B010"};
int cost[5]={12,37,3,129,1123};

cout<<setw(4)<<"\nCODE "<<setw(4)<<"COST";

for(int i=0;i<5;++i) cout<<"\n"<<setw(4)<<item[i]<<" "<<setw(4)<<cost[i];
}

Which would give:

CODE COST
A001   12
A010   37
A100    3
B001  129
B010 1123

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:
#include <iostream.h>

void main()
{
unsigned char ch=0;
for(int i=0;i<255;++i,++ch) cout<<"\n"<<i<<" - "<<ch;
}
Ah, what a nice, compact programme! You remembered that there are only 256 characters and they can be accessed by just incrementing the character as basically characters are just integers...hark, what's that? Characters are just integers? Yes, characters are just integers. So, suppose I wanted to forcibly convert one type to another say, the integer form of a float...what am I talking about? We'll see..

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:
Eg.
float a=4.5
cout<<int(a);	//Output: 4
Eg.
char a='A';
cout<<int(a);	//Output: 65
Eg.
int a=65;
cout<<char(a);	//Output: 'A'

Therefore, the MORE compact programme would be:
CPP / C++ / C Code:
void main()
{
for(unsigned char ch=0;ch<255;++ch) cout<<"\n"<<int(ch)<<" - "<<ch;
}

[If you have any doubts concerning unsigned refer to Appendix C]
  #35  
Old 20-Jun-2004, 20:01
mithunjacob's Avatar
mithunjacob mithunjacob is offline
Junior Member
 
Join Date: Jun 2004
Location: Vellore, India
Posts: 65
mithunjacob will become famous soon enough

XIX.Some Things You Ought To Know :: goto, enum & Default Variables


XIX.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:
void main()
{
int ch;
cout<<"\nGo to where? ";
cin>>ch;
if(ch==1) goto label1;
else goto label2;
label1:
cout<<"\nLabel 1";
label2:
cout<<"\nLabel 2";
}

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:
void chores(weekday day)
	{
	switch(day)
		{
		case MON: cout<<"\nBathroom";
				break;
		case TUE: cout<<"\nKitchen";
				break;
		case WED: cout<<"\nDining Hall";
				break;
		case THU: cout<<"\nBedroom";
				break;
		case FRI: cout<<"\nGarbage";
		}
	}

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:
#include <graphics.h>
#include <conio.h>

void drawLine(int x1, int y1, int x2, int y2,int colour)
        {
        setcolor(colour);
        line(x1,y1,x2,y2);
        }

void main()
{
int drv=DETECT,mod;
initgraph(&drv,&mod,"d:\\tc\\bgi");
drawLine(0,0,100,100,WHITE);
drawLine(0,200,100,100,WHITE);
drawLine(200,200,100,100,WHITE);
drawLine(100,100,200,0,RED);
getch();
closegraph();
}

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:
--	drawLine(0,0);
	drawLine(200,200);
	drawLine(90,90);
	drawLine(90,90,0,0,RED);
--

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  
Old 20-Jun-2004, 20:02
mithunjacob's Avatar
mithunjacob mithunjacob is offline
Junior Member
 
Join Date: Jun 2004
Location: Vellore, India
Posts: 65
mithunjacob will become famous soon enough

XIX.Some Things You Ought To Know :: Storage Classes, Constants & BitWise Operators


XIX.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:
class someClass
{
public:
static int a;

someClass() : a(0) {}

void change(int _a)
	{
	a=_a;
	}
void display()
	{
	cout<<a;
	}
};

void main()
{
someClass obj1;
someClass obj2;
obj1.change(90);
obj2.display();
}

Output:
90

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:
class someClass
{
public:
int value;
/*
void funcA() const
	{
	value++;
	}
This is invalid as by typing const no member variables can be modified in that function*/

void funcB()
	{
	value++;
	}
};
XIX.g.ii)#define
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  
Old 20-Jun-2004, 20:04
mithunjacob's Avatar
mithunjacob mithunjacob is offline
Junior Member
 
Join Date: Jun 2004
Location: Vellore, India
Posts: 65
mithunjacob will become famous soon enough

Example Programme #8


EP8:
->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:
//Example Programme 8: Bit Reversal
#include <iostream.h>
#include <math.h>
void main()
{
int bits=100,stib=0;
int cmpBits=0,bit=0,bitNo=0;

for(int i=bits;i;++bitNo) { i/=2;}

for(i=0;i<bitNo;++i)
	{
	cmpBits=pow(2,i);
	bit=bits&cmpBits;
	bit= (bit==cmpBits);

	if(bit)
		{
		cmpBits=0;
		for(int j=0;j<bitNo-i-1;++j) cmpBits+=pow(2,j);
		stib+=(cmpBits+bit);
		}
	}
cout<<bits<<" reversed is "<<stib;
}
  #38  
Old 20-Jun-2004, 20:05
mithunjacob's Avatar
mithunjacob mithunjacob is offline
Junior Member
 
Join Date: Jun 2004
Location: Vellore, India
Posts: 65
mithunjacob will become famous soon enough

XX.A Brief Introduction To PERL


Whew! 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:
print "\nEnter name: ";
$name=<>;
print "\nHello $name!";

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:
open(FILE,"<file.txt");
while($byte=<FILE>)
	{
	print $byte;
	}
close(FILE);

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:
open(FILE,"<file.txt");
while(<FILE>)
	{
	print;
	}
close(FILE);
Here, (<$_=<FILE>), as $_ is a default variable we can omit mentioning it. Another interesting default variable is $/. In C++ when we input something with C++, the object stops taking in data when it encounters a '\n' or a white space. Of course the whitespace can be modified with a manipulator... But in Perl, the delimiting symbol is stored in the default variable $/. So, suppose you want to store the full file at one go (not advised) in one scalar variable. All you have to do is.
CPP / C++ / C Code:
open(FILE,"<file.txt");
undef $/;
$datum=<FILE>;
print $datum;
Here, I've used a unary operator undef which undefines the operand. So, the delimiting symbol is an undefined variable, which is exactly what you get if you cross the EOF of a file. So, it works both times when reading the FILE as well as printing $datum.

Suppose you wanted to write to a file..you can directly use the print function.
CPP / C++ / C Code:
open(FILE,">file.txt");
print "\nName? ";
$name=<>;
print FILE $name;
close(FILE);
Pretty simple once you get the hang of it..
  #39  
Old 20-Jun-2004, 20:07
mithunjacob's Avatar
mithunjacob mithunjacob is offline
Junior Member
 
Join Date: Jun 2004
Location: Vellore, India
Posts: 65
mithunjacob will become famous soon enough

Example Programme #9 & #10


EP9:
->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  
Old 20-Jun-2004, 20:09
mithunjacob's Avatar
mithunjacob mithunjacob is offline
Junior Member
 
Join Date: Jun 2004
Location: Vellore, India
Posts: 65
mithunjacob will become famous soon enough

Conclusion


This 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
Attached Files
File Type: txt A-F.txt (15.8 KB, 17 views)
__________________
[b]There are times when the Phantom walks the streets as an ordinary man...this is one of those times.
 
 

Recent GIDBlogProgramming ebook direct download available by crystalattice

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Forum Jump

Network Sites: GIDNetwork · GIDWebHosts · GIDSearch · Learning Journal by J de Silva, The

All times are GMT -6. The time now is 18:19.


vBulletin, Copyright © 2000 - 2009, Jelsoft Enterprises Ltd.