![]() |
|
#21
|
||||
|
||||
XIII.Some Things You Ought To Know II :: Switch, Time, FunctsXIII.a)Switch
I'm sure EP4 seems tremendously pathetic and is totally out of place with the compact, efficent world of C++, well, using "switch” can easily simplify things. CPP / C++ / C Code:
CPP / C++ / C Code:
break; is used to exit switch. If break isn’t there, the compiler will go on executing the code until it encounters a break statement. default accounts for any possibility not listed in case. doX(); can be any piece of code. XIII.b)Useful Functions These functions are called library functions. They are functions defined in files called library file ( files containing machine-executable code accessed by the compiler - one of the things I was referring to in II.b). i)getch() Pauses until the user hits a key. The character is returned. getch() doesn't show the the character, getche() does. ii)clrscr() Clears the screen, equivalent to cls in DOS iii)sizeof(data type) Returns the amount of memory reserved for the data type. CPP / C++ / C Code:
Similarly, sizeof can be used for arrays. Example: char name[30]; cout<<sizeof(name); //Output:30 iv)kbhit() Very useful function. Doesn't hold up the programme like getch() but waits for a key to be pressed. If a key is pressed the function returns TRUE. The character can be retrieved with getch(); v)exit(int arg) Exits the programme. Arg=0, implies a normal exit, whereas a non-zero value means there was some error. Useful in understanding code. vi)delay(int), sleep(int) Pauses the programme for the no.of seconds(for sleep) or milliseconds(for delay) specified in the argument. Please note: CPP / C++ / C Code:
III.c)TIME_T The time_t data type is used...you can guess..to store time. The function clock() returns the number of CLOCK TICKS taken place from the beginning of the programme. My compiler says that 18.2 clock ticks takes place per second. The data type time_t stores time in clock ticks, so to convert it into seconds, you have to divide it by 18.2 or CLK_TCK, the constant which comes in the header file <time.h> and holds the number of clock ticks per second. CPP / C++ / C Code:
|
||||
|
#22
|
||||
|
||||
XIII.Some Things You Ought To Know :: Infinite Loops, int main()XIII.d)Infinite Loops
When do you think this loop will end? CPP / C++ / C Code:
Never. It's an infinite loop...as there are no conditions for it to break, it will go on for ever....well as long as the programme can be run.. CPP / C++ / C Code:
Of course, an alternative is: CPP / C++ / C Code:
But if you don't want the "Enter favourite number" question to appear if the age<18, a possible solution is with the infinite loop. Similarly: CPP / C++ / C Code:
XIII.e)Use of int main() A good question: What's the use of the int in int main()? I mean, we aren't returning anything are we? Well, the return statement in a function ENDS the function. eg. CPP / C++ / C Code:
I could have done this with an else statement, but if ch=='F', the function will end due to the return statement. So, as main is also a function, return can be used to prematurely end the programme. CPP / C++ / C Code:
|
|
#23
|
||||
|
||||
XIII.Some Things You Ought To Know About :: ASCII Vals, ?:XIII.f)Some Important ASCII values
ASCII values and their corresponding characters have been very useful to me while programming with an old compiler like Turbo C++ 3.0 (available on my site) so here's a few: '\r' : 13 : Return '\n' : 10 : Newline '\a' : 7 : Beep '\t' : 9 : Tab backspace : 8 Esc : 27 '0' : 48 'A' : 65 'a' : 97 Btw, ASCII characters can be displayed using their ASCII values in DOS..just type ALT+X where X is the ASCII value of the character. Suppose you wanted to enter a slash into your cout statement....try it and you'd be surprised..the reason why you don't see the slash is the '\' is used to tell the compiler that coupled with the next character, they represent something special..like '\n' or '\r'. So to get '\' we throw in another, or '\\'. Btw, these are called escape sequences. The reason why it's called an escape sequence, is because it adds more meaning to the letter used, or it's an "escape" from the normal use of the respective letter. Another useful escape sequence is '\xDD', using this we can output hexadecimal values. Eg. cout<<'\x41'; //41 is the hexadecimal equivalent of 'A' XIII.g)The Conditional Operator Here's another way to compact a (sometimes) unneccesarily large if-else situation. Consider this: if( a>b) c=a else c=b; This can be compacted to one line: c= (a>b)? a:b; Which means, if (a>b) go for the first one, i.e. a else if the condition is false, go for the second choice, b. |
|
#24
|
||||
|
||||
Example Programme #5EP5:
->Make a progarmme which calculates the typing speed of the user in words per minute. CPP / C++ / C Code:
|
|
#25
|
||||
|
||||
XIV.Classes :: Concepts & Defining themXIV.a)Some Concepts
The most important data structure. A struct containes variables of different types; an array of the same type; but..a class can contain ANYTHING, an array, structure, functions absolutely ANYTHING. Suppose I wish to manufacture a car...assume I'm the manager of building section. I know that workers A,B & C will "take care" of the motor installation section. I know that workers D,E & F will "take care" of the steering and brake installation. I know that they will DO these things but I really don't know HOW they do it....but the point is, I don't NEED to know how they do it. It's not neccesary for me to have the knowledge of each individual task force assigned to the car. Now let's take a proper example...functions..in the previous programme, a programmer could blindly use each function without even knowing HOW they work. He might not have a clue as to what cout is but he knows that the function menu() will display it. This is data abstraction..hiding data. Another important feature is data encapsulation..using classes we can combine or "encapsulate" all the essential features requires into one compact package. XIV.b)Defining a class A class can be broadly divided into 3 sections: public, private and protected. Remember data abstraction? Well, these 3 zones make it happen. IF you declare a function, structure, variables {these entities inside a class are called member functions, etc.} inside the Public zone then these members can be accessed directly. Maybe you didn't understand that, so I'm going to define a class in the public zone. [c]class (name) { zone1: <-Members-> zone2: <-Members-> zone3: <-Members-> };[/u] Looks a lot like a structure right? A class is basically a structure with functions...in fact C++ was actually going to be called C with Classes. Anyway, forget the trivia, here's an example: CPP / C++ / C Code:
As you can see calling and declaration is just like a structure's. We create an object (Phantom) using the class name (student)and access it's members with the '.' operator. The great thing about an object is that each one is a self-contained entity with it's own data untouched by other objects. Memory locations are created for each variable in the object..but for the member functions, only one memory block is assigned, which is accessed by all objects of the same class. |
|
#26
|
||||
|
||||
XIV.Classes :: Con&Des, Visibility, Cout&CinXIV.c)Hail the Constructor! Down with the Destructor!
Here's the CalcPer() function again: CPP / C++ / C Code:
Another use of the constructor is to pass values into the class. Suppose I didn't want to use a function to input the marks, and I wanted to enter them when I create the object..another use of the constructor. And the destructor....sounds ominous, but that's what it really does...destroys the object from the face of the...memory bank. There is a default destructor with each object which releases the memory allocated to it by the compiler...but we can also add to the destructor. The usefulness of the destructor will be shown in Pointers. A class can only have one destructor but many constructors; this will be explained in Overload. The constructor and destructor functions have the same name as the class but we add a '~' before the destructor. Constructors & destructors return nothing...not even void. Alright, here's the modified programme where the data is taken in with a constructor & displayed with a destructor. CPP / C++ / C Code:
Here's a much better way to initialize variables: CPP / C++ / C Code:
Btw, even if you don't have a constructor, there's an automatic built-in constructor known as a default construcor which will create your object. XIV.d)Visibility Visibility of an object (an object in the common sense) refers to the locations in a programme it can access. XIV.e)The Truth Behind cout & cin So far, we've been blindly using cout & cin...but what are they? Well, they're nothing more than objects of 2 classes, respectively ostream & istream each of them defined in IOSTREAM.H. __________________
[b]There are times when the Phantom walks the streets as an ordinary man...this is one of those times. |
|
#27
|
||||
|
||||
XV.Overload :: Functions & OperatorsGenerally, there would've been an EP after such an important concept...but I've always felt that without overloading, a class isn't really complete..for C++ is really made up of functions and classes, and for YOUR class to be compatible with classes like cout & cin, you must learn to overload operators. But first, functions:
XV.a)Overloading Functions What is the use of overloading? It gives the programme flexibility. You see, REAL programmers create easy to handle packages used by normal users, like cout for example. And to increase the ease, we have features like classes, functions, etc. Now, consider the following: CPP / C++ / C Code:
Now, I can use these functions to calculate the volumes of the specified 3 objects. But look at how cumbersome it is! For the same concept, i.e. volume, we have 3 different functions! And in this case there's a difference in each volume...for the cuboid we need 3 dimenrsions, the sphere, 1 and the cylinder, 2. So, wouldn't it be more convenient if we had a function with the same name? CPP / C++ / C Code:
A good question would be: Suppose overloaded a function with the same number of argument? Then it won't work...the compiler will say that the 2 functions are ambigous. Now, a constructor is a special type of function..which qualifies it for overloading. Therefore, you can overload the constructor to make your class more flexible. XV.b)Overloading Operators Alright! The real stuff! Let's make a silly class: CPP / C++ / C Code:
So to display and assuming the object's name is Phantom...nah, let's name the object Kit, to display the contents: Kit.display(); Now, wouldn't it be infinitely easier if we could use cout? Wouldn't cout<<Kit, be much cooler? Well, if you think about it, cout was created to handle known data types like char, int or float...so what you have to do to make it display the contents of your object is....OVERLOAD IT! So, how do I overload an operator? Simple. (return type) operator (operator to be overloaded-symbol) (arguments) { --code-- } So can you guess the operator we have to overload? It's '<<'. CPP / C++ / C Code:
As you can see, cout is nothing but an object of ostream. Under the ostream class we have various classes, like iostream and (coming up) fstream {used for file handling}. Another confusing concept might be the order of the arguments, these are important as they determine the way we can use the operator. The first argument comes before the operator and the next one after the operator (in this example with a binary operator like <<). Please note that all operators can't be overloaded. And yet, another confusing concept might be the & before, xout. This will be explained in XVII (Pointers). __________________
[b]There are times when the Phantom walks the streets as an ordinary man...this is one of those times. |
|
#28
|
||||
|
||||
XV.File HandlingNow, to access a file we use the class "fstream" is FSTREAM.H. Note that cout & cin are already declared in IOSTREAM.H as we're performing the I/O operations on stanard output and input devices like a monitor or a keyboard. But for fstream, we're working with a file..so we have to declare separate objects for each file.
XV.a)Declaring the object, Opening & Closing a file Declaring: fstream (name of object); Example: fstream fil; Opening: fil.open( (name of file) , (parameters) ); Now, the parameters are as follows: ios::in | the file can be read ios: ios::binary | will be able to process binary characters ios::append | Instead of overwriting, it starts at the end of the file The above are one-bit flags which determines which operation to carry out. You'll see more ios flags in Manipulators (XIX.a). If you want to have a file with more than one parameter (eg.reading & writing is possible) you should use '|'. Example: fil.open("names.txt", ios::in|ios: Closing: Simple enough. Example: fil.close(); XV.b)Writing & Reading The simplest way of reading and writing to a file is by using the get() and put() functions. To simplify data insertion and extraction, reading and writing is done with the help of a file pointer which "points" to the current byte the object is reading/writing. Suppose, I read a byte from a file using fil.get(), then the pointer automatically shifts to the next byte. Similarly, suppose I was writing a file, then the byte will be written to the file, and the pointer automatically moves to the next byte, so that the next character written will be after the previous. CPP / C++ / C Code:
The byte number the pointer is on is returned by tellg(), and to set the pointer we use seekg(): both member functions of the fstream class. CPP / C++ / C Code:
|
|
#29
|
||||
|
||||
Example Programme #6EP6
->Make a programme to copy a file CPP / C++ / C Code:
|
|
#30
|
||||
|
||||
XVII.Pointers :: Variables & ArraysAs I've said before, what the programmer actually has at his disposal is a vast array or boxes or memory locations. Now, obviously each box must have an address? Or how else can we efficiently locate it? Therefore, a memory location has 2 aspects to it; it's address and the value it contains.
Now, we've already seen a way to create memory locations with only the value stored in them as the primary aspect, i.e. ordinary (automatic) variables. Now we're going to see another type of variable, a pointer variable which concerns itself with the address of the memory location XVII.a)Variables A pointer variable is declared like this: Syntax: ------- (data type)* (name); Eg.char *name; Hmmm...looks familiar? Like a string perhaps..? Yep, that's what a string is..a pointer variable. Remember when I said all we had in a string was the addres of the memory block storing the first character (IX.Arrays)? Well, that address is stored in the pointer. Actually, for any array..alright, that's the next topic. So, how about an integer pointer? Why not? int *num; cout<<num; Output: Some hexadecimal number Why? Because, num stores an address and if we want to see what it contains, we'll see the address it "points" to. Suppose, I wanted to access the value stored in the box or memory block. I should use, * CPP / C++ / C Code:
Now how do I link non-pointer variables with normal variables? With the previous definition ANY variable must have a memory block where the value is stored in, therefore, that block must have an address. So, if we could access the address and make a pointer with the same address, we can actually link both variables in a fantastic way. int num=5; int *ptr=# //Use * to bring out the value of a pointer and use & to bring the address of //an automatic variable Here, I use & to bring out the address of a normal or automatic variable. Now, guess the output of the following bit of code: int num=5; int *ptr=# (*ptr)++; cout<<num; If you guessed 5...sorry, as 6 is the right answer. Why? Because, ptr now points to the memory location of num, so any modification done to the memory location ptr points to actually modifies num! Now, if you remember the data type void, you can apply the same concept here. The benefit of a void pointer is you can use it to point to any sort of value. Let me explain: If you've noticed, the addresses we assign to the pointers are of variables of the same data type. Try this: int *ptr; float a; ptr=&a; //ERROR! As float & int are 2 different data types. But the specialty of the void pointer is that, we can use it to point to any data type, hence making it useful in places where we want to make something applicable to all data types. CPP / C++ / C Code:
XVII.b)Arrays As I said before, an array actually holds the address of the first element of the array. The rest of the elements are consecutively stored. Suppose: CPP / C++ / C Code:
How? *str refers to the value held in the location pointed to by str, i.e. the first element or P. By incrementing the pointer ptr, I move to the consecutive memory location which stores the second element and then display it. |
Recent GIDBlog
Problems with the Navy (Chiefs) by crystalattice
| Thread Tools | Search this Thread |
| Rate This Thread | |
|
|
Network Sites: GIDNetwork · GIDWebHosts · GIDSearch · Learning Journal by J de Silva, The