 In this lecture, we are first going to look at several miscellaneous facilities that are provided by C++ but not fully discussed so far. You might like to use some of these during your projects. So, as I said, we are going to discuss some useful features of C++ which will be necessary mostly during your project phase and therefore, we need to complete the discussion on those items. More importantly, we start discussion on the object-oriented programming paradigm and extremely powerful mechanism of programming where we take our current notion of modularizing our programs through functions, structure definitions, etcetera, etcetera to its full-blown logical conclusion where separation of entities and their behavior is taken to a level where the programming language itself supports such separation and we will see how exactly we can define and use object classes, instantiate objects and work on those objects with absolute guarantee that nothing else in our program will be affected whenever we operate upon these objects. We are specifically going to look at graphics objects because many of your projects will involve use of some kind of graphics or something. We will be using a open-source rudimentary graphics library called EZ Windows. It has all been installed already on all your OSL machines. In the next week, we will be working with these EZ Windows. We will have more examples in the next lecture when we continue our discussion on object-oriented program. First there is something that we had very briefly seen but I am elaborating it. When we define variables, we know that we can initialize variables at the time of their definition. In exactly the same fashion, arrays can also be initialized. The array initialization is done in a peculiar syntax. So for example, if you have an evaluated marks array of five elements, you can initialize all five elements by putting five values separated by commas in a curly bracket pair. So start a curly bracket pair 5, 5, 20, 35, 35. Please note that this is not an assignment statement. It can only be done when you define the array. So it is one time initialized. Similarly if you want to initialize, let's say a character array with different characters, you can do so by writing let's say a character who always five as an array and define these five elements. You can define an array without defining the size in which case the compiler automatically takes the number of values which are given as initial set of values to be the size of the array. Alternatively, you can have a large size. So you can, for example, have this is a perfectly valid statement. It does declare array to be of size 20. However, it initializes only three elements to given values. Based on the compiler implementation, the remaining elements may either be initialized to zero or left hand. There is one error in this declaration and initialization. Can you point it out? There is no syntax error, but there is a semantic error. Remember that character arrays are typically used to store strings. And how do we store strings in a character array? We put all the characters of the string and at the end put a backslash zero as a null terminator because every valid string is required to have a null terminator. It is important whenever you use string functions like string compare, concatenate strings, etc. Do you think that care over five is a correct declaration? What will be the impact of this declaration? This has five elements, zero, one, two, three, four. The initialization says put these five values in the five elements. Is there any space for backslash zero? No. So, while this initialization is correct, please understand that it is not obligatory that every character array be used only as a valid string. It is required to be a valid string. If you treat that particular array as a valid string in either function calls or anything else. But you can of course store any five values or five ASCII values in that. But generally since a character array has a connotation of being a character string which is null terminated, it is only proper that you put the array size to be one larger than the actual number of elements that you wish to. In case you want to treat this as an array. So you might want to make this as six for example and put an additional backslash zero as an additional sixth character in the initialization. As a very special case, since character arrays invariably are used to store null terminated strings, the following initialization is valid and permitted. This initialization is that if you declare some care array, say line 80, you can say hello world, how are you? Semicolor. This is initialization during definition. I again repeat, you cannot use it as an assignment statement anywhere else in this program. Only when you define the array, you can give the initial value. In case you assign a double coated character string as an initial value to the array, the backslash zero is automatically insulted because C++ understand that you are trying to put a valid string there. Obviously, the size of the array should be one larger than the number of characters that you put. Of course, if you put in less number of characters, it will be null terminated at the appropriate point. Next we revisit the way we define our structures and functions. Ordinarily, structures, functions would be defined as a part of our main program only. But in the last few occasions, we had seen that we could define the struct definition outside the main program before the main program. We could define the function prototypes outside the main program or even full function definitions. This is one example where I have defined a struct mPinfo, which has two parts, integer, employee ID, and float salary. Then I have defined, just like I had a print student info kind of function last time, I have print m data function, which has structure info type m as the parameter. And for this EMP dot EMP ID, an EMP dot salary is printed out by this one. So it is merely a function whenever somebody calls it, it will print those two values. As I said, ordinarily, I could write these just before the int main. I could write these even inside int main. It is perfectly fine. As long as I write these before defining anything. The function definitions usually precede int main. If I want to code the function definition at the end of int main, then I will have to give at least the function prototype here. That is the standard practice. So there is nothing new in this. Once we define it like it, we can use the struct info type to define a new variable, say E, assign values to E, and print that value, whatever. The issue is that suppose we are doing a group project and I want to use this struct info, but I am not the partner who has defined this struct info in this function. This has been defined by someone else, some other member of my team. Now that member of my team will define it in a separate file. How do I say that I want that file to be included when my program is compiled? Otherwise, my program will not compile for. I therefore look for a facility by which I could define these things somewhere else. So suppose my friend has created a file called EMP.ed. I don't want to retype the entire definition and everything. Secondly, why should I do that don't give up? Somebody else has done it already in my team. Suppose I ensure that this EMP.ed I copy as it is. He mails it to me and I put it in my working directory. Can I tell the compiler that look, when you compile my main program, please include that EMP.ed file also before you start compiling? If I can say that, it will save a lot of things. Then a group could depute one of the members to maintain the repository of several such .h files for whatever function definition structure definitions are required. And anybody who is writing a program which requires those definitions can simply tell the compiler that before compiling my program, take this header file. It is called a header file. That is what .h signifies. So suppose I created such a header file, there is indeed a facility available in all compiler systems, certainly in GCC, whereby we can direct the compiler to include this file in our group. The way this is done is very simple and you would have guessed it because you have already seen some include statements appearing in your programs all by of a different nature. So just as I say include IO stream, include CSTD lib, I can say include double quote EMP.h. The moment I say this, the file of course EMP.h is expected to be in your current directory. If it is not, if it is supposed in your friends directory, then it is possible for you to give an absolute path of that file also in the string because after all what this string contains is nothing but the file name and file name can include the relative path where the file belong. Needless to add once I do that, this file will be included. How it will be included? It will be included by a stage in the compilation called pre-processing. In the pre-processing stage, the compiler does not immediately start translating your program into machine code. It actually looks at the entire text and if there is any missing text such as the one in EMP.h which is somewhere else, it will actually copy that EMP.h physically into your program. It is like you using a g-edit window and copy-pasting that EMP.h and then saving it and then asking it to be compiled. It is almost like that. So physically compiler will do that job for you automatically. This is done by using compiler directives. Hash include is one such directive. When you say hash include, the corresponding file is included. So whenever the compiler actually starts compiling your program, it sees the entire text including whatever was written in EMP.h and that is how things are perfectly fine. There is still another alternative. Suppose in my team project, the friend of mine who has written this EMP.h, he not only writes the EMP.h, student.h, something else.h, giving the definition of the structures, but he does something smarter. He has written let's say 20 functions which operate upon these structures like print employee info, print student info, update student's mark. What he is worried about is that if people have access to the source code of those functions, somebody may be tempted to make some small change in the function. Now if five members of the team make five small changes in the functions, ultimately there will be no single definition available. Therefore he says I will give you the structure definitions because that you need in order to understand what is the prototype definition of function, what are the structures, etc. But as far as the actual function code is concerned, I will not expose that to you. Instead I will compile all those functions and keep them separated. Is that feasible? We are not talking now of a preprocessor directive which can get the entire source code from EMP.h or such files and include it for compilation. He's going one step forward. He says you write your program, you compile your program. After you compile, somehow make sure that your compiled program and my compiled functions are linked together so that when you get an A.out file, it is a total file containing compiled versions of everything. That way you will save some time because you don't have to recompile the functions which have been compiled. After all the same functions are going to be used by all five members of the team. So if functions are written by someone else and have been already compiled and are kept elsewhere, they are kept as a library. The example that I gave you is a small scenario where a group of 5, 6, 7 people are working on a project. In larger life, such functions are written constantly by many people in the world. As a matter of fact, there is no programming language which permits you to write effective programs well without a group of people having written a large number of functions and kept them compiled somewhere. Imagine our own plight. Suppose you want to do some mathematical computations. You have to calculate sine theta, cos theta, tan theta. You remember a library called CMath? When you say include CMath, somebody who has written these functions, sine, cos, log, etcetera, etcetera, they are all suddenly available to you. Is the source code getting included? No. What that somebody has done is that somebody has compiled all these functions. Keep them somewhere as in the form of a library of functions. So somewhere you should be able to tell the compiler that as far as header files are concerned, include them in my program. As far as these compiled versions are concerned, first compile my program and the compiled version you link it to that particular function. So this is what we need to do whenever there are functions which are pre-compiled and kept somewhere else in a library. Similarly the functions are kept in the library. Please understand that the prototype definitions of those functions must be included during my compilation. Otherwise compiler will not understand when I say sine of x. If compiler has no clue what function sine is, what parameters it requires, floating point, fixed point, etcetera, etcetera, it would not be able to compile. So even though people have compiled these functions and kept them in separate library, in the library also there are two separate components which are to be maintained. One component is a text header file which may have definition of type, structures, etcetera and it will also have prototype definition of all functions which are later on available as a separate compiler. So when you say include CST lib for example or include CMAP, two things happen. In the pre-processing phase from that library, the equivalent text header files are picked up and brought and put together in your text file so that when you compile, compile and all that. And finally at the end of compilation, those retranslated functions are linked into your program. It is therefore important for us to understand the compilation process in a slightly detailed fashion. So what do we do ordinarily? We use a command c plus plus myprog dot cpp all of your familiar. What happens? It creates an executable file a dot out and then you say dot slash a dot out your program gets executed. It appears to you as if it is a one step process c plus plus myprog dot cpp, flash comes out a dot out. That does not work like that in real practice. In real practice, the compilation process is a multi stage process. In the first stage, the program first includes all the header files etcetera etcetera that is called the pre-processing stage. It is not written here because we just discussed it. So there is a pre-processing stage in which all the compiler directives are expanded or executed to make actually a text file of your dot cpp which includes all the header files etcetera that is the pre-processing stage. After the pre-processing stage, your program is compiled and this compiled version becomes what is known as an object code. Typically, if I have a program called myprog dot cpp, the corresponding object code will be kept in a file called myprog dot o. This object code is you can say semi translated version of your program. By semi translated, it is still in the final machine language form, but it is not ready to execute. It is not ready to execute, it is semi cooked form. Something else has to be done and what is that something else? That something else is assembling that code and linking it to other pre-compiled programs which are included from the library. As a matter of fact, not a single c plus plus program can run without linking something or the other from the standard library. Remember include IO stream, that is the basic that you need to include in anything. In general, in real life, you will be including a whole lot of libraries. Some standard libraries from c plus plus and some others which you yourselves have written. We shall later on see how to create such libraries or your own. You are already familiar how to create such external header files, simple g edit and say EMP dot h and write down all the headers and then include that is simple. But if I have written functions, how do I compile? In what form do I keep? How do I tell my compiler later when it is compiling my program to include this particular library? So, the library must have some name like c math, c std lib, I may call it c my lib or whatever. Incidentally, it is not necessary that we always use only a dot out as the output file produced by the final stage of the compilation. I can give it any name that I wish. Indeed, professional programmers never work on a dot out for a simple reason that at any one time, you may be working with five or six different programs. You might want to keep all five or six compiled, said you run one, then immediately run another, then test third. Remember that if you run one and try to run another, that another does not have any a dot out because it has been overwritten by the latest program that you have compiled. There can be only one a dot out in your file. So, it would be nice if you compile your programs always to produce the equivalence of a dot out for every program that you compile. And the easiest thing to do that is to give this command c plus plus myprog dot c p p minus o minus o stands for output. The final output that you create should not be a dot out, but should be, let us say myprog. The extension is immaterial by the way, a dot out is only a ease of a somebody standardized on a dot out. So, it need not be myprog dot out. It is not necessary. Any name you can. It is customary to give the same name as the name of the program for the simple reason that all programs that you will write will have unique names. And therefore, if the same name is given, there is no confusion that is possible. So, is this clear how the compilation process works? The notion of libraries is very, very important. As I said, first of all, you get the more power in the programming language because these libraries, second, these libraries also isolate issues and keep them separate. While computing Sime, you are not wondering how to calculate logarithm. While computing matrix inverse, you are not worried about something else. So, you localize the problems and put all your code and data structures at one place related to whatever problem you are solving. The libraries which are pre-written and pre-compiled come in different forms. For most unique systems, they take the form of one of the two forms. One is called the archive files. These are the traditional library files which have an extension dot a. If you go in Ubuntu or any unique system to a directory slash lib or slash user slash lib, you will find a lot of dot a files there. The other type is called shared object which has an extension dot SO. These are less generic than dot a, but that is immaterial as far as we are concerned. These would be files that would be used invariably in much of your programming world. The corresponding nomenclature used by the Microsoft environment is dynamically linked libraries. They are similar to shared object kind of. So, they have an extension dot DLL. Those of you who have worked on Microsoft OS environment and in C, C++ or any programming language, you will find that the operating system environment consists of a large number of such dynamically linked library files dot DLL files. Indeed, the operating system itself whether it is Unix or Microsoft or HP UX or IBM AIX or whatever, the operating system itself is millions of lines of code as I said. Nobody writes a single monolith million line program. So, there are separate functions, a major function, handle file system, another major function, handle memory allocation, third major function, allocate processing resources to different executing program within that thousands of other functions. Much of these are also written in terms of files. So, the operating system itself when you install an operating system which is an executable file actually, before that you take the operating system source code which itself could be written in any language, compile and link it with various libraries and install. It is slightly problematic because it says chicken and egg store. Without the operating system, how do you put a compiler and compile? Without a compiler, how do you do the operating system compilation? We are not going into those details. Suffice it to say that libraries constitute 90 percent of the power of computation that you get when you express yourself in any programming language. So, all standard libraries of C++ provide an interface. What is your interface? Another interface for example, is to be able to say when in your program you write such a statement, you are using an interface called SIL in bracket parameters. A function called methodology is nothing but an interface. Somebody else has written that function and he is telling you how to use that. So, whether a function has one parameter or 20 parameters, how the function is invoked is all depends on how the function is written. This is how you get the power. So, you write your own programs. In addition, you use programs written by others through a programmer's interface. Libraries provide such programmer's interface. Such interfaces by the way whereby you can call other functions or call other things are known as APIs and the power of any environment, whether it is operating system, whether it is some library, whether it is this or that is always judged by the power of the APIs that is available. Note that a library such as CMath could again contain hundreds of thousands of lines of code. If someone told you, read all those 100,000 lines of code and then figure out how to calculate sign, how to calculate cost, you go math. Therefore, these application programmer's interfaces are separated out. The use of functions is given somewhere. How to call a function is given? What does that function return is given? And that is your interface. You need not know then how somebody is calculating sign or x or cost or whatever inside. So, the beauty of API is they filter the knowledge of usage of certain pre-written programs and they give you that filtered knowledge in terms of an interface that you can use, that your application software can use. This particular fact, this particular feature is carried to its logical end when we discuss the object-oriented paradigm which has emerged as the most popular programming paradigm these days. We will do that later. So, is this clear? Some additional features we often require debugging help. So, whenever we write statements, we are not sure whether something is working or not. Say for example, I have opened a file. So, I have defined an in-file, it is called data.txt, and I open it as a read file. Ordinarily, I expect the file to be open, but there could be various reasons. File may not exist in my directory. File may exist, but I may not have read permission to that file. File may be corrupted. Whatever, if for some reason the file cannot be opened, the file pointer will not be assigned a valid value, it will have a null value. We have seen earlier in our programming examples that after opening a file, we will invariably look at that pointer, and if it is equal to null, we will say error, return. So, we terminate a program. This is not the only situation. There could be other situation where I expect, let us say somewhere in my program, some value of x should be greater than y, and only then it should work. But suppose my program while testing it bombs, and I do not know what is happening. So, what I will say? If x is not greater than y, get out. I want x to be greater than y. If that other solution is wrong, I want to get out. But while getting out, I want to print an error message where something has gone. I might create such 20, 30 debugging exits that something goes wrong, come out. However, once I get a hang, I find out, oh, I made a mistake in this logic here, that something there, etcetera, and correct the program. I would not like such arbitrary error handling messages to remain there in my program. But on the other hand, when I return once, I compile, they will always be compiled. I have two choices. A, physically remove all of those, or B, comment all of those. But suppose I comment 20 such messages. Now, after some time, my friends decide some additional functionality should be given. I write that. And that additional functionality while writing it, I make changes. The whole thing collapses again. And I want to again start debugging. So, I will have to hurriedly remove all those comments from all the 20 statements that I had written. That will amount to too much of unnecessary. There are multiple facilities in programming languages which permit you to write such debugging code. But automatically, tell the compiler that if I am satisfied with the status of my program, do not bother compiling this technique. But if I tell you I am not satisfied, please compile and execute. One of such features is called the Azert library. The Azert library is a macro. We shall study more about macros in the next class. It is a useful diagnostic tool. In order to use this library, you have to include a special library called C Azert. So, in your include statement, if you say C Azert, the Azert provides the same functionality in a compact form. I can, for example, write Azert in file equal to f open something not equal to not. Azert means I am stating an assertion. Assertion is I believe this is true. What do I believe to be true? I believe that whenever I open this file, it will be properly opened and therefore it will not be a null pointer. So, my assertion is this pointer is not null. There are two possibilities. One, the assertion is true in which case I want to continue. Second, the assertion is false. That means the file was not open. In which case I want to do what I did earlier, print an error message and get out. That is exactly what the Azert statement does. So, if this assertion turns out to be false, an error message is given. It is not set out onto your std out, but it is put on std err. You will remember we discussed the OS environment and we said every time your program is executed, it gets three files attached to it. One std in for keyboard input and the other std out and std err both of which go to terminal. So, actually when you see an output coming on the terminal, you cannot figure out whether this is coming from std out or is it coming from std err. You will see both of that coming here. But in case an assert statement fails, you will come to std err. The advantage of std err is as follows. You remember we discussed file redirection. I can say execute this program greater than some file. So, all output goes there. That greater than applies to std out. If I have an assert statement, my errors will still come. Error messages will still come on my screen. They will not go to that. Pure output will go to that. So, I can sort of separate out these two. There is one problem with this statement. Okay, first let us discuss. Suppose I have such 20 assertions in my program, not necessarily related to file. As I said I want to assert that x should be greater than y at this point. If it is not, I want to terminate the problem. Somewhere else, I want to do some other complicated test. Any test, any condition. You say I assert that this condition is true. The assert statement will check that condition at that point in time. And if it is false, it will give an std err message. That message is by the way quite comprehensive. For example, in this case, suppose this is a statement in line number 12 in your main program. The output will read something like this. In a.out int main line 10 colon assertion fade. And then it will write the entire condition that you have written. You can very easily see where a problem has occurred. In a 500 line program, you can very easily see. Now as I was saying, suppose you have cleaned up your program. No mess there. Everything is working fine. Now you do not want these assert fellows to be implicated. Because you have taken care of error handling in some special fashion. That is the purpose of writing good professional code. You do not want errors only to go in a professional program. Errors to go to std err. After all, the end user is playing a game of snakes and ladders. For example, now you suddenly do not want to say, assert snake not found or some such thing during the game. It has to work properly and that error has to come separate. And that you would like to give a proper error message even in case the program bomb. Which says that sorry my dear friend, your original definition of snakes and ladders is not proper. Because there is a snake where a ladder ends. And there is a ladder where that snake ends. So I have detected a loop. You will keep moving around perpetually in that board. Now we are going up and down. So when I detect such error initially during debugging, I could have used that assert statement. But later because I am getting into an infinite loop sometimes. But later on I would have handled that thing situation separately. I would like to suppress this error. To suppress all asserts in your program, there is a simple mechanism. You can include another macro definition by using a word hash defined n debug. N debug means no debugging. Remember I told you an error in a program is a bug. Removing that bug is called debug. So when I say no debug, then even though assert statements are there, they will not be compiled by my compiler. Because I have said no debug. Of course I must state that before the inclusion of C assert. There are many other facilities. There are actual debuggers. One debugger we will discuss in the next lecture. Whereby you can actually execute your program step by step. And at every step you can see what is the value of this variable, what is the value of this pointer, what is the value of this structure element, whatever. Here is another compiler directive for macro definitions. Consider this hash defined max size 2000. Here I am not declaring a variable. And I am not initializing a variable far from it. Instead I am declaring what you may call a symbol, which is M A X S I Z E. And I am declaring a token, which is supposed to be the value of that symbol, which is 2000. This is a preprocessing definition. This definition is handled at the preprocessing level. What the compiler does is that it works as if you have opened a g edit window. And in that g edit you have said find and replace. Max size, find max size replaced by 2000. Physically wherever max size appears in your program, it will be replaced by 2000. It might appear for example in your program where you have said M I D max size. Remember what I had said. Time and again you cannot declare an array with a size which is not pre-known. Therefore you cannot say M E M P I D say size where size is itself read as an input. Because that input will not be available unless the program is executed. So that is wrong. Why it is right here? It is right here because before compilation itself M A X S I Z E would have been replaced by 2000. Because that is what this definition says. Why is this important? I could have written it 2000 itself. This is important for the following reason. I might later on in my program I might have an iteration which says something like for I equal to 0 I less than max size plus plus. Somewhere else I might simply say C out. So you see the size of an array is an important component that may be used at 10 different places in my program. Now imagine that for some reason you decided that your array should be 200. Size should be 200. Then what would you do? You would declare your array to always say int E M P I D 200 for I equal to 0 to 200 less than 200. You would not of course print because 200 is not. But basically the number 200 will occur at 10 different places in your program. Now when you sit together and discuss the project further somebody points out boss this size 200 is not sufficient. The solution that I want to seek of this complicated matrix equation may have an order greater than 200 may be 500 is the right place. Then what I will have to do? I will have to change wherever I have said 200 I will have to change it to 500. I might forget to change at one place causing lot of problem. If I have used a macro like this has defined max size 200 let's say initially it would when I compile it it will compile with size 200 it will print 200 it will run this loop for 200. But the moment this decision is made I will simply say define max size 2000 and recompile the program. What the compiler will do is it will replace max size by 2000. Suppose I use this to say has defined C 28. Wherever C appears C will be replaced by 28. You have to be very careful with what symbol you will define and what you replace it with. The defined symbol should be uniquely identifiable otherwise something very funny could happen. There was a I don't know whether I shared this with you or not in the SQL programming language somebody wrote a program to find out whether the customers had in their description of where they are let us say members of something whether they are members of any public limited company so somebody searched for a string called public. What he wanted to check was whether members have LIC policy. So he actually gave a string called LIC. P-U-B-L-I-C also contains LIC. So in the search everything that was public also came out with people not having any LIC policy. So the marketing people who were given those customer ideas saying this fellow has a LIC policy go and call him they started calling everybody and people started wrapping them are nothing to do with LIC. Now this kind of thing should not happen in your program so you better be careful about what symbols you define and what you represent. That is the reason why macros usually have typical thumb rule define a macro symbol to be all caps because it is unlikely that you will use all of them as caps a normal variable scenario. We look at another important function which is extremely useful whenever you are doing simulation of games of chance you want to generate random numbers. There is a random number generator function called R-A-N-D this generates successive calls to this function will generate a sequence of numbers which are apparently unrelated to each other and therefore they are called random numbers. Of course this sequence is generated by some algorithm and that algorithm will generate a number based on some previous number some steps in the algorithm. So obviously if you give a starting point that algorithm will always generate the same sequence. The trick is whether I can cause a different starting point to be given to that sequence. We shall see that in a moment but this function is used in this fashion. When I say num equal to R-A-N-D bracket no parameter is required every call to R-A-N-D is guaranteed to give a new number in the sequence. It will never return the same number. It will return the next random number. So if I want to generate let's say 9 random numbers I can generate 1, 2, 3, 4, 5, 6, 7, 8, 9 and print them I will get separate random numbers generated. You are all familiar with these? Anybody who has played next-hand ladders or Ludo or something will know. Games of chance you just throw a dice a dice has 6 faces and each face has a unique number 3, 4, 5, 6. Now when you want to simulate a board game then you would like to simulate the throw of a dice. The point in throwing a dice is every time you throw randomly some number will come up. How do you simulate such randomly generated numbers? Well you can use R-A-N-D. For example if I generate a random number I know the number generated is an integer number between 0 and some arbitrary max number called landmarks. If I take a modulo 6 I will get a number between 0, 1, 2, 3, 4, 5 and if I add 1 to it I got a dice value. So I can generate a large number of such dice value. I can for example simulate a game of next-hand ladders where the computer plays player 1 computer also plays player 2. So I start it and I may have some graphical display of how my coins are moving on that board. Every time a number is generated I can display player 1 generated 4, player 2 generated 6 played again, generated 1 somewhere you got into Snake, onto Ladder whatever. The point is I run this program it runs perfectly well. Tomorrow when I run it will I get the same sequence? Unfortunately yes. That is because the starting point when you first call the random number it will have some fixed algorithm to give that sequence will be generated. So if in your game for the first time player 1 wins and player 2 loses for eternity player 1 will win. That is not simulation. You would like different sequences of random numbers to be generated. That is one. The second issue is are these random numbers really good? How do you define a good random number? A good random number in a throw-off dice for example is an equiprobable random number. That is one is likely to come as many times as 2 as many times as 3 etc. So suppose you throw a dice say 60 times on an average you expect 1 to come 10 times 2 to come 10 times 3 to come 10 times give or take 1 or 2. I would like to check the property of this random number generator whether it generates uniformly distributed random numbers or not. And second and most important now I would like to ensure that because of a certain way in which the first sequence comes my player 1 does not always win every time I run the program. There is a good probability chance that any player can win. We shall see how both of these things are tacked. First of all as I told you there is an internal algorithm which generates a random number and that algorithm depends upon some starting point. At any time of the point when you call this for the first time there is a fixed starting point that algorithm has which it uses every time. Subsequent calls will of course the algorithm internally will remember in its own data structure what was the last value given and will give you an example. If you could break these jinx by giving a initial seed value yourself saying I do not like to start every time from that point I will give a different value. After all there are large number of possible values that you can start with. So collect a value from me. I will say give seed value for random sequence. I collect the seed. How do I inform the random number generator that I want you to use this as the seed value? There is another function called srand which is like saying set the seed for this random number generator. So when I call srand I have to give a parameter which is a number and this is the number which will be used for random number. Consequently when I generate nice values I will get a sequence which will be initiated by this seed. Every time I run a program I give a different seed it will generate a different seed. Any time I run a program giving the same seed I am guaranteed to generate the same sequence that was generated last night. Only one hitch here I every time I now play a game of snakes and ladders in the class game distribution of playing cards whatever which I want to do randomly I have a problem every time it ask me give me a seed value in a professional program I write such game of snakes and ladders something give it to you play now he is expecting snakes and ladders suddenly say give a seed he will say who is seed the end user is executing I would like automatically a new seed value to be given which is guaranteed to be different how can I guarantee should I generate a random number and use it as a seed yes seems to be sensible option will it work because every time I run the program the first random number generated will be same and therefore it will change the original seed will it change it with the same value every time so randomly generating the seed guarantees non-random numbers generated every time you run I need to give a seed which is dependent on something which changes guaranteed fashion it changes every time you execute a program there is only one commodity in the whole universe which changes in a guaranteed fashion that is time time always goes ahead even if I run the program now and immediately run it in 2 seconds 2 seconds I will ask how nice it would be if I could somehow get the time of the day today and say use this time of course every day the time recycles from 0 to 24 hours suppose I said time of the year again the year will recycle next year again somebody will get this there is a mechanism every computer system maintains what is known as a real-time clock inside the computer hardware that real-time clock is usually set to current date and time from that real-time clock which is managed by the operating system any programming language can make a function call through a API called a system call and say give me the current time if I could get the current time then I would be able to use that as a seed value provided I appropriately convert it into integer if it is not an integer apparently such a facility exists the value of time is available in other set of libraries called C time so if I include C time then there is a function called time time can be invoked with different parameters to give different things fundamentally if time is invoked with a parameter value 0 then it returns a large integer which is the number of seconds that have passed or elapsed since midnight of 111970 Greenwich Mean Time somebody decided Greenwich Mean Time 111970 is the base date now from then seconds are passing large number of seconds have already elapsed as we speak more seconds pass any time you make a call at time 0 it will return an integer saying at this juncture so many seconds have passed since 111970 you agree that this number will be different any time you execute the problem except in one peculiar case the real time of your computer has got stuck it is not running say every time the operating operating system cannot tell you time by looking at a watch it will make a call to this real time clock suppose the battery has gone coupled you might have seen some of you might have noticed that when battery of the real time goes coupled when you boot your system you will typically get today's data or some such thing what it will mean is time 0 will always return a fixed number of seconds but in more self-respecting computers where batteries are working properly you will get a normal real time in all your machines in the lab you will get a normal real time if you therefore say s ran time 0 this time 0 will go to the clock and get time in seconds from this point and that will become the seed value guaranteeing you will generate a different sequence of time is that clear in the process you also learned the call for time for various purposes you can use it in your program even other way it is not uncommon for example for people who write very large computational programs to find out how long a particular portion of their algorithm is taking let's say you are inverting 500 by 500 matrix so somewhere before you begin that inversion process time something and print that time or store that value somewhere execute that part of the algorithm again call time and then the difference between the two will tell you so many seconds were required to do this computation as a matter of fact you remember we had seen a operating system command where we say dot slash a dot out instead if we say time dot slash a dot out it will print three different times execution time where do those times come operating system also makes a call to this time and gets the value next is the second question do I get uniformly distributed random numbers so here is a program it sets count six elements it wants to count how many times one occurs how many times two occurs how many times three occurs it sets up a random number seed generates a large number of random numbers say 60,000 numbers it will generate a random number it will take module of six and add one that is the dice value since the arrays are 0 to 5 it will subtract one and use the dice value itself as an index you remember associative array so if one comes the 0th element is incremented if five comes fourth element is incremented six comes fifth element is incremented so these six elements of array automatically incremented every time a number is generated at the end when all 60,000 numbers have been generated you would expect each one of them to be roughly around 10,000 if that is so then you have a uniformly distributed random number set so you print out these counts I have run this program for 60,000 and for six lakhs and these are the count that I got depending upon when you run this program you may get a different count because remember seed is set to time 0 and therefore every time there will be a different sequence so you look at it first time 9,085 10,000, 10,135 9,992 9,999,896 you will agree that roughly it is uniformly distributed you run it for 6 lakhs you would expect every number to be 1 lakh times coming it is 99,716 1 lakh something 99,000 something 1 lakh something again this tells us that the C++ random number generator is reasonable this also tell you that professionally when somebody gives you saying that I have a very good random number generator you might want to run such test quickly to ascertain whether the random number generated are truly uniformly distributed or not because these are not strictly random numbers they are called pseudo random numbers since they are generated by an algorithm later on some of you will work on stochastic models stochastic models are useful not only in engineering systems but even in financial system models which determine you know the flow of funds in large economies stock market models share price models so these stochastic models require you to use what is known as queuing theory events that occur they arrive as per certain probability distribution and mostly those probability distributions are not uniform probabilities those could be they are called poisson arrival so basically different types of distribution it is possible to map the arbitrary type of distribution function of random numbers on to a uniformly distributed number generate uniformly distributed numbers and convert them into a sequence which actually has a probability distribution something else it is not the topic of the discussion here I am just telling you that such things are feasible and that is why the random number generated generation becomes a very very important point in any kind of task that you do random sampling yeah sure no no no please remember time is used only once in my program I am never coming back to that point again this is the s-rand time 0 that is the only time that the setting is done in that algorithm by s-rand time 0 I do not mean every time you generate a random number you use that time no s-rand is executed only once and that is to set the starting point of that algorithm subsequently you will call only rand and subsequently all the calls will generate a random number based on the previous number that was generated and so on typical so setting is done only once in life time in the execution of your program when you re-execute the program then only it will be done not with this we now move over to a preliminary discussion on object oriented programming we will of course be discussing this a lot more but here we are just understanding some simple concepts to tell you this logical isolation and logical construction of real life objects I have shown here an example of a cell those of you who have studied preliminary biology will know that every living organism has cells all of us have cells which are different kinds of cells eyes have rod cells, cone cells etcetera cells all cells have a peculiar property they have an external membrane and there is fluid inside this membrane and inside this fluid there is a nucleus the entire behavior of the cell is determined by properties which are hidden inside that nucleus the interaction between this cell and other cells happens only at the membrane level there is no way any external entity or any other cell can find out what is there inside the nucleus there is no direct access to that the nucleus therefore is a private component of a cell it contains its own information how does the cell interact with the other cell well when the cells interact across membranes and the modeling that human beings have done on that is to say that a cell sends a message to another cell for example take human mechanism of sending a signal let say I want to open my hand the brain will pass a signal by which perhaps the cells are being instructed to expand all cells will follow that the message is going from some mechanism through those membranes but the actual expansion is happening because inside the cell the nucleus has decided to do something such that the fluid expands or whatever this is how it has provided isolation as well as segregation of activities compare that with our programming parallel in our programs originally we started by saying define variables arrays and then read some values compute something print some when our programs became larger we realized that oh I have defined this 38 variables 22 arrays and I am doing something with this here something with that there etc etc it is becoming clumsy for then I realized that suppose I am handling let say student data it would make far more sense for me to define a student dot h5 or a student info data structure and then define members of that data structure such that when I operate I am not operating upon arbitrary variables but I am operating upon those components of a student and I know I am changing the student's marks or I am changing the student's hostel room or something like that what I have done I have achieved two things A I have sort of isolated student from rest of the information that is there in my program B I am now very sure that whenever I say student dot marks equal to 28.5 then those marks are not being assigned to somebody else it is being assigned to a particular member student of a group if I consider a student to be a cell and all students to be a class of cells then I am trying to do exactly what I was doing here except there is one difference my data structures might be separated of student employee this that that but my program structures the behavior of the elements of these student structure etc etc all across my code I can do anything anywhere and I can do it any which way somebody can change that program to say grade is equal to A everybody will get an A grade there is no safety in that mechanism whereas in a cell I cannot know how to let's say make significant changes in the nucleus of the cell the only mechanism I have is can pass this message and cell will react like this beyond that I have no confidence a similar paradigm in programming has been prepared has been created understanding that objects are independent entities each of which has properties and behavior and similar objects form a single class such as a class of students once a class is defined I can define properties of a class it is like defining student structure structure so these are the properties student has role number student has hostel number student has mark student has CPI whatever but there is also a behavior student CPI will be calculated like this students hostel number will change from this to this in this fashion so these properties are also part of that class today we are able to put the properties in an isolated fashion for students for employee but we are not able to put the behavior and tag it with these properties in an object oriented paradigm I can take my programming constructs to a level where I can say that these are the properties of these objects of a class and this is exactly how the behavior of every object will be that student CPI will be calculated in this fashion only and to the external world I will not permit to define CPI in any which way so I can define what interfaces external world has with any object and I will say you are permitted to interact with the object of this class only using this interface and nothing else please remember today in your C++ program it is not possible because in your program you can arbitrarily take fifth element of an array and set it to anything that you want no matter what that fifth element defines such a independence and freedom is detrimental to proper systematic program so you try to utilize the object oriented concepts and try to define what we call an object oriented programming the cornerstone of the object oriented programming is the ability to define classes to define properties and behavior for every class to ensure that all elements of that class inherit the same properties and same behavior these properties usually will describe data elements and the behavior is defined through member functions what is guaranteed is other than these member functions nothing else in the world can ever change any value of the data element of that object that is the guarantee so you do not have the liberty of going and changing any element of changing any value of variable as you please it is not possible but it is also called methods let us see some examples very quickly we will of course be elaborating on this in the rest of the course so these member functions are brought to operate whenever a member is instantiated it is like defining a variable you are given struct info struct student info something something later on in int man you say struct student info s now s is one student technology s is one object the moment you create s not only memory is allocated to various data elements but s now becomes ready to work with all the functions which have been defined for that class it is not just the data element but also the function so behavior also gets defined when you define a class you define also the member functions sending parameters to a function is like passing a message across the save only that is the only mechanism to do anything with those member functions member data element and you can do so only using public functions that is why when you define a class you can define private functions and public functions there is a third category called protected functions or protected access will not go into that most importantly all private data members of an object are hidden from us we do not know what is the name of a variable which contains cpi of a student we do not know that we cannot change it we can only call a function saying please calculate recalculate cpi and I can send some parameters grades in various courses whatever whatever what it does internally its own problem so let us quickly see some preliminary example you say class class name it is very much like some name the only difference is in a struct we will define only data elements in a structure here you define data elements and functions which are all private then you say public colon and you define public member functions these public member functions are the ones which rest of your program can use to do anything with the object then there is a class called protected protected access will not go into the details of this I have included only the complete one should define this class at the beginning of your program or before your program you can then instantiate an object by writing class name c1 it will create just like a variable c1 is created by saying int c1 class name c1 will create an object c1 clist thousand will create an array of thousand objects each one of which is an object how do I use member functions how do I initialize values etc etc here is an example employee class I am defining class of employee class employee care EMP name float EMP salary just two parameters each employee has salary each employee has a name I define public functions please note I am not defining the complete function I am defining only the prototype in a class definition the prototype is sufficient at the beginning I have to define these functions in details which I can do immediately following the class definition notice the four names set name get name set salary get salary and there are parameters set name there is a character string get name there is a character string which is an array when I send an array character string pointer I will get back the name in that itself in set salary I send a floating point value which is to be set to salary in get salary there is no parameter it returns a floating point back these are the four functions with which I can operate upon this object please note that I have EMP name and EMP salary these are not visible to me in my program there is no way I can assign a value to EMP salary of any person this is very much unlike that struct EMP info struct EMP info if I said that and then later on said struct EMP info say even then even dot EMP salary equal to something I could write that is not visible here anything that you want to do with values inside the object has to be done through the public functions here are the definition of two or three four for public functions here void employee colon colon this is called a qualifier because employee is the name of the class set name care star name or what I do simple string copy name name name set salary what do I do whatever is the parameter I get assign it to EMP salary notice that public functions are capable of collecting parameters which come from messages from outside world and access the private members to set their values or get their value so our interface is to these functions but when we call these functions we do not see the internal names remember how will we call this we will get name some array get name some array set sales some array here is an example of what happens here here is the main program I have said employee E this is a I have created an object called E I have defined two E name 60 and float E salary these are my local variables they have nothing to do with the actual employee in these local variables I read the name and the way I invoke the public function is to say if this is a object E I say E dot set name so object name dot any public function will invoke that public function for that object please remember when employee E is defined the space is created in the memory for that employee the data elements are put there and also the prototype definitions are logically available along with that employee every object inherits all properties not just the data elements but also the behavior so when I say E dot set name when I pass E name it will set that name E dot set salary E salary it will take the E salary execute that public function we know what it does later on in my program if I say E dot get name and give some E name it will get the value of the name of the employee E it will get the value of the salary of the employee I can print it logically what has happened we are doing similar programming but we are isolated things now very well object class is now an independent thing I have defined the functions appropriately utilizing these functions is very easy I say E dot something and that something happens here is the issue the modern programming languages which have this object oriented features such as C plus plus and java which are most popular C sharp is a similar object oriented programming language in the Microsoft environment there are some scripting languages such as Python object oriented programming is not new in 60s people have thought of object oriented programming without naming it like that when they were working on artificial intelligence problems and had defined a programming language called list subsequently there were languages called module law there was a number of other programming languages but today object oriented programming has become the mainstay of professional programming in most case I will just take five more minutes to tell you about an interesting class library so far we talked about function libraries in C plus plus actually you have class libraries apart from this function library and these class libraries come with predefined classes and with predefined public functions for those classes all implemented so when you compile your program using these class libraries and include these class libraries you can invoke any of those functions to get variety of things there what we are very quickly looking at it and we will elaborate this in the next class is the graphic object displaying capability we want several windows on our screen this is one window what you see we want to draw graphical shapes such as rectangle circles we want to plot graphs we want to show bitmap images like the ones which we saw earlier and we want to write textings in window these are the various things I want to do I do not even know how to draw graphics by any program but suppose I use a graphics package the one which we shall be using is called ezwindows it contains several classes here for example this is one basic thing called windows class so if you use a windows class it is possible for you to define a window on the screen what you see in the white is a window it has two parts a title at the top now if I want to create a window I do not write any graphic program I have to call a member function what will I have to send as a message to that member function various parameters which are the parameters first of all where this window should be located so I will need to say what is this displacement and what is this displacement please note that the origin is always left most corner of an object and the x y coordinates work in a funny fashion y increases downwards that is the method that ezwindows uses so I will have to specify these two things let us say I call this some x naught sorry y naught and x naught then I will have to give the coordinates a height and width of the window and I may have to say what I want to be written here say I want to call it my window so five parameters which are those five parameters x naught y naught the position of this corner is h n w and what string I want to give I would like a facility by which say I have defined my window as say m w and I would like to say m w open and I will give these parameter values I would like somebody to immediately draw this window for me in exactly the same fashion I could actually draw variety of other for example I may say draw a triangle I may say draw a triangle which is all red I may say draw a line I may want to say draw a sine wave how can a graph of sine x be drawn I have to draw various points actually right it so happens that ezwindows does not have a function to draw a point it can draw a point it can draw a line it can draw a rectangle it can draw a circle the way of forcing it to draw a point is to draw a line from a point to itself you are cheating the system actually if you do that that point is not even visible but if you draw a point from that to some point 0 0 5 centimeter or something you will actually get a point we shall see all such things in the subsequent class in greater details ok thank you so much