May 29, 2016 | Author: enselsoftware.com | Category: N/A
What you will find here – • All about returning values, objects, matrices, structures from function/procedu...
Better Understanding of Computer Programming
Better Understanding of Computer Programming
Saikat Basak
Last updated: June 2004
www.enselsoftware.com
-1-
Better Understanding of Computer Programming
© Saikat Basak. All right reserved. First Online Edition: March 2001 Second Online Edition: December 2001 Third Online Edition: June 2004 Electronic version of this book is available at www.enselsoftware.com Downloading the PDF/DOC version of this book is allowed. But any modification of the book is a violation of applicable copyright law. Disclaimer The author had made every effort in the preparation of this book to ensure the accuracy of the information. However, the information contained in this book is provided without warranty, either express or implied. The author will not be held liable for any damage caused or alleged to be caused either directly or indirectly by this book.
For the latest version of this book, please see at the web site. Any suggestion on this book is always welcome.
www.enselsoftware.com
-2-
Better Understanding of Computer Programming
Contents 1.
INTRODUCTION ........................................................................................................................................ 4
2.
HOW TO RETURN A SINGLE VALUE FROM A FUNCTION?.......................................................... 6
3.
HOW TO RETURN MULTIPLE VALUES FROM A FUNCTION? ..................................................... 8
4.
RECURSIVE FUNCTION ........................................................................................................................ 14
5.
WRITING DLL IN VB.NET ..................................................................................................................... 17
6.
WRITING DLL IN C/C++......................................................................................................................... 30
7.
FILE HANDLING ...................................................................................................................................... 46
8.
POINTER PARADOXES IN C ................................................................................................................. 55
9.
STRING HANDLING IN C++ .................................................................................................................. 64
10.
FUNCTION OVERLOADING ............................................................................................................. 66
11.
OBJECT ORIENTED PROGRAMMING SYSTEM (OOPS) ........................................................... 68
12.
THE WORLD OF DISTRIBUTED COMPUTING – COM AND CORBA...................................... 81
13.
DATABASE CONNECTIVITY ............................................................................................................ 92
14.
PROGRAM ARCHITECTURE – LAYERED APPROACH........................................................... 109
15.
WHAT LANGUAGE AND CLIENT/SERVER YOU SHOULD USE? .......................................... 118
16.
SOFTWARE ENGINEERING............................................................................................................ 125
17.
EXPLORING EXTREME PROGRAMMING CONCEPTS ........................................................... 129
18.
PROGRAMMING TIPS ...................................................................................................................... 131
19.
PROGRAMMING IN SPREADSHEET ............................................................................................ 136
20.
REFERENCES ..................................................................................................................................... 140
www.enselsoftware.com
-3-
Better Understanding of Computer Programming
1. Introduction What’s special about this book? Well, a lot! I designed the book to be read online. You can download this book FREE of cost and read at your computer anytime! You can directly copy the source codes from here and run them in your favorite compiler! This book is for a little bit experienced programmers. Here I’ve discussed and tried to clarify some difficulties faced by programmers. I didn’t teach any programming language from scratch here. I assume that you know at least any one of C/C++, Java or Visual Basic or any other standard programming language. Although a large part of this book deals with VB/.NET and C++, other language programmers will also find the information useful. Wherever possible, I tried to make the discussion in language independent way. However, to give examples one must use some languages. So I mainly used VB and C/++. I also made a comparison of object-oriented concept among various languages. Object oriented programming is a hot topic nowadays and very few books discuss them from practical viewpoint. (Such books are available in C++ and Java but they are rare for Visual Basic) Here I presented same object oriented program source code in different languages and discussed how they do differ. I tried to explain everything in a way as much easily as possible. However, in many cases, I assumed your prior knowledge of some concept. If you need to know the basic of any language, please consult any book dedicated to that particular language. All real world programs are huge and they can’t be discussed in a single book. However, I delineated how to write elegant, maintainable code. Whatever be your platform or language, you need to follow certain conventions. While reading the book, I expect active participation from your part. Reading like a storybook won’t help. You must understand each concept properly. If you face any problem, please feel free to contact me. I’m just an email away! My email is
[email protected] and my web site is located at www.enselsoftware.com. You might notice that the chapters in the book have been arranged in a little bit haphazard manner! Well, I deliberately did so in order to make you not feeling bored!
www.enselsoftware.com
-4-
Better Understanding of Computer Programming
You must not forget that nothing is more important than a good algorithm. Your program’s performance mainly depends on the algorithm you adopted rather than on the language you are using for development! Since this book discusses many topics at once, I often advised you to read some other books on those particular topics so that you get a better grasp of the concepts. Now sit back, relax and start reading. Have a happy programming!
www.enselsoftware.com
-5-
Better Understanding of Computer Programming
2. How to return a single value from a function? Functions are one of the most frequently used components in any programming language. Typically a function takes some arguments, performs some calculation and then returns the result to the calling function. However, there are differences between C and VB on how the functions return values. In C, by default, a function always returns a single value (or no value at all i.e. void). But in VB, a function must return a single value. In C, we may force a function returning multiple values by using pointers. But in VB, we shall have to use Sub Procedures to return multiple values. The Sub Procedure can return no value, single value or multiple values. So, in VB, function is a special kind of sub procedure, which returns single value. In C, function always passes argument by value. To make it pass argument by reference, we need to pass the addresses of its arguments, (which is known as pointer). But in VB6, function (and procedures as well) always pass values by reference (i.e. address) unless specifically told to pass by value. However, in VB.NET, it is passed by value by default as in C. In VB.NET, you must specify ByRef explicitly to pass by reference. First we shall see how to return single value from a function in C and then in VB. Study the following simple C code. Code 2-1
/* program to find the area of a rectangle */ #include int find_area(int l,int w); /* prototype optional in C */ void main(void) { int length, width,area; puts("Enter length"); scanf("%d",&length); puts("Enter width"); scanf("%d",&width); area = find_area(length,width); printf("Area is %d\n",area); } /* the prototype of function is return_type function_name (type argument_1,…, type argument_n) */ int find_area(int l,int w) www.enselsoftware.com
-6-
Better Understanding of Computer Programming
{ int a; a = l * w; return a; }
The same function is written in Visual BASIC.NET. Code 2-2
Public Function find_area(length, width) as Integer Return length * width End Function
Assume name of the command button is Button1. Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click l = InputBox("Enter length") w = InputBox("Enter width") area = find_area(l, w) MsgBox ("Area = " & area) End Sub
Universal approach to problem solving – Step 1: Define the problem to be solved. Step 2: Decompose the problem into more easily solved sub-problems. Step 3: Repeat step 2 until the sub-problems can be solved directly. Step 4: Integrate the solutions to solve larger problem.
www.enselsoftware.com
-7-
Better Understanding of Computer Programming
3. How to return multiple values from a function? Remember solution of a quadratic equation? It may have two roots (equal or unequal) or no real root. We shall return two roots of any typical quadratic equation. Study the following C code first. Code 3-1
/* a quadratic equation solver in C */ /* demonstrates returning of multiple values from functions using pointers */ #include #include int solve_quad(int p, int q, int r, float *q1, float *q2); void main(void) { int a,b,c; float root1,root2; int status; puts("Enter a,b,c for ax²+bx+c=0"); scanf("%d,%d,%d",&a,&b,&c); status = solve_quad(a,b,c,&root1,&root2); if(status==1) { puts("The solution is"); printf("%.2f, %.2f\n",root1,root2); printf("Stored at addresses: %x and %x\n", &root1, &root2); } else puts("No real root"); } int solve_quad(int p, int q, int r, float *q1, float *q2) { float determ; determ=q*q-4*p*r; if(determ= 0 Then root1 = (-b + Sqr(determ)) / (2 * root2 = (-b - Sqr(determ)) / (2 * End If End Sub
As Integer, ByVal b As root1 As Single, ByRef
a) a)
Assume name of the command button is Command1 Dim p As Integer, q As Integer, r As Integer Dim s1 As Single, s2 As Single p = InputBox("Enter a for equation ax²+bx+c=0") q = InputBox("Enter b for equation ax²+bx+c=0") r = InputBox("Enter c for equation ax²+bx+c=0") Call solve_quadratic(ByVal p, ByVal q, ByVal r, s1, s2) MsgBox ("Roots are " & s1 & " and " & s2) End Sub
For a sample run, use following values: a = 1, b = -5, c = 6. The roots are 3 and 2.
www.enselsoftware.com
-9-
Better Understanding of Computer Programming
In VB, the arguments of functions or procedures are always passed by reference by default (up to version 6) and by reference from version 7 (i.e. VB.NET). If you want them to be passed by value, then you must use the keyword ‘ByVal’ in front of each argument that you want to be passed by ‘value’. But in VB.NET, arguments are passed by value by default! Another thing, in VB, the keyword ‘Single’ is equivalent to ‘float’ in C/C++! Don’t forget this! Anyway, it is indeed a good practice in VB to always explicitly write either ByVal or ByRef in function or procedure declaration. In VB, a Function always returns a single value. Whereas, Sub procedures can return zero, one or more values. Now we shall see how to write the same program in Java! I am showing here an entire applet code. However, the main part of the multiple value returning is shown blue. Code 3-3
// a quadratic equation solver import import import import
java.awt.*; java.awt.event.*; javax.swing.*; java.applet.*;
/* */ public class QuadSolverApp extends JApplet implements ActionListener { JTextField jtfa,jtfb,jtfc,jtfr1,jtfr2; JLabel jlt,jla,jlb,jlc,jlr1,jlr2; JButton jb; public void init() { resize(160,250); Container contentPane = getContentPane(); contentPane.setLayout(new FlowLayout()); // add text fields & lables jlt = new JLabel("Quadratic Equation Solver"); contentPane.add(jlt); jla = new JLabel("Enter a"); contentPane.add(jla);
www.enselsoftware.com
- 10 -
Better Understanding of Computer Programming
jtfa = new JTextField(8); contentPane.add(jtfa); jlb = new JLabel("Enter b"); contentPane.add(jlb); jtfb = new JTextField(8); contentPane.add(jtfb); jlc = new JLabel("Enter c"); contentPane.add(jlc); jtfc = new JTextField(8); contentPane.add(jtfc); jlr1 = new JLabel("Root 1"); contentPane.add(jlr1); jtfr1 = new JTextField(8); contentPane.add(jtfr1); jlr2 = new JLabel("Root 2"); contentPane.add(jlr2); jtfr2 = new JTextField(8); contentPane.add(jtfr2); // add button JButton jb = new JButton("Solve"); // button label jb.setActionCommand("SolveEquation"); // button action command jb.addActionListener(this); contentPane.add(jb); } public void actionPerformed(ActionEvent ae) { if(ae.getActionCommand()=="SolveEquation") // button action command { // create a new instance of SolveClass SolveClass sc = new SolveClass(); SolveClass sc2; // call Solve method of SolveClass sc2 = sc.Solve(Float.parseFloat(jtfa.getText()),Float.parseFloat(jtf b.getText()),Float.parseFloat(jtfc.getText())); if(sc2.root1==0) { jtfr1.setText("No real root"); jtfr2.setText("No real root"); } else { jtfr1.setText(String.valueOf(sc2.root1));
www.enselsoftware.com
- 11 -
Better Understanding of Computer Programming
jtfr2.setText(String.valueOf(sc2.root2)); } } } } class SolveClass { static double root1,root2; SolveClass Solve(double a, double b, double c) { double determinant; SolveClass scf = new SolveClass(); determinant = b*b-4*a*c; if(determinant > 0) { System.out.println("Two real roots"); scf.root1 = (-b + Math.sqrt(determinant))/(2*a); scf.root2 = (-b - Math.sqrt(determinant))/(2*a); } else { scf.root1 = 0; scf.root2 = 0; System.out.println("No real root"); } return scf; } // end of method Solve } // end of class SolveClass
In Java , basic data types (like integer, float etc.) are always passed by value. Only objects can be passed by reference in Java. Observe that two achieve this task, we had to create two similar object instances inside main. Also, Java doesn’t support pointers. Pretty peculiar, ha!
www.enselsoftware.com
- 12 -
Better Understanding of Computer Programming
What is the difference between a function and a procedure? Consider the following C program. int func (int x) { return x*x; }
It simply returns the square of an integer. Now see the same code written differently. void func (int x, int *y) { *y = x*x; } // value of integer stored at y will be accessible even // outside function because we pass it by reference
Did you now realize the difference? Both functions perform essentially the same thing. In second function, instead of explicitly returning a value, we are passing the same by reference (i.e. why we use pointers!). That means, in C, though we have only functions, using pointers we can perform the same task as those of procedures in VB or Oracle. Since VB, Java, Oracle etc. don't have pointers, they use 'function' and 'procedure' both to perform the essentially same task as I’ve shown above. Internally whenever you use 'procedure' in Java, VB or Oracle, all parameters are passed/returned by reference by default. But in VB you do have the option to control whether you want it to be passed by value or by reference. We’ll see another version of code 3-1 in chapter 24 when we discuss pointers in detail.
www.enselsoftware.com
- 13 -
Better Understanding of Computer Programming
4. Recursive function A recursive function is really a wonderful thing! If you know how to use it, you can save lots of lines of code. Following is a VB code to find out the sum of series 1 + 2 + 3 + … + N. Code 4-1
Option Explicit Public Function Sum(i As Integer) As Integer If i = 1 Then Sum = 1 Else Sum = i + Sum(i - 1) End If End Function
Assume a command button as Command1 in the form. Dim n, Total As Integer n = InputBox("Enter N for 1 + 2 + ... + N") Total = Sum(n) MsgBox ("Sum is " & Total)
Please don’t input –ve value! If you input very large N (say 10000), you might get “Out of Stack space” error. How can you increase stack space? Most books close the chapter on recursion by just giving you factorial program. There are several worthwhile applications of recursions in real life problems. Here I am going to show you how you can recursively traverse a tree using recursion. A tree is a non-linear data structure (ouch)! Arrays are linear data structures. You can travel along an array using a straight line; obviously you can’t do that in case of trees! Consider the tree shown in figure 4-1. We need to visit every node of the tree once and fetch the information from that node. Code 4-2 describes the algorithm for doing that.
www.enselsoftware.com
- 14 -
Better Understanding of Computer Programming
1
3
2
4
10 5
11
6 12 7
8
9
Figure 4-1 Code 4-2
Function TraverseNode (StartNode as Node) If StartNode has Children Then For each Child Get node information Call TraverseNode (Child) Next Else Exit Function End If
The above algorithm makes a pre-order traversal of the tree – in the following sequence – 1, 2, 5, 6, 3, 7, 8, 9, 4, 10, 11, 12. To learn more about Trees and traversal methods, please see a Data Structure textbook. Code 4-3 shows the VB.NET code for above algorithm. To test it – insert a tree view control in a sample VB.NET project. Add one command button as well. Write code to add some elements in the tree view (that code is not shown here). Only the code for tree traversal is shown below. Code 4-3
Private Sub TraverseTree(ByVal n As TreeNode) MessageBox.Show(n.Text) Dim aNode As TreeNode For Each aNode In n.Nodes TraverseTree(aNode)
www.enselsoftware.com
- 15 -
Better Understanding of Computer Programming
Next End Sub
To
check
the
code,
you
can
call
it
(say inside
a
button)
as
TraverseTree(TreeViewName.SelectedNode)
The code adds some sample nodes. You can add some more of your own. The TraverseTree procedure displays information about every node. Instead of msgbox, you can use Print #1, to write the node information in a file so that you can re-load the entire tree by just reading the file. The same procedure, with little modification, can be used to search for an item in the tree. Do you now realize the power of recursion? Exercise 4-1 Write a program for permutation using recursion. For example, if you give input as “abc” it will show all possible permutation of the word i.e. abc, acb, bac, bca, cba, cab.
www.enselsoftware.com
- 16 -
Better Understanding of Computer Programming
5. Writing DLL in VB.NET What is DLL? DLL stands for Dynamic Link Library. This is a feature of Windows family of operating systems and OS/2 that allows executable routines to be stored separately as files with DLL extensions and to be loaded only when needed by a program. A dynamic-link library has several advantages. First, it does not consume any memory until it is used. Second, because a dynamic-link library is a separate file, a programmer can make corrections or improvements to only that module without affecting the operation of the calling program or any other dynamic-link library. Finally, a programmer can use the same dynamic-link library with other programs. Let’s examine the topic in more detail. You’re familiar with writing #include in your C programs. Aren’t you? In a similar way, you can define some of your functions, which you often use in many programs, in your own header file. (Note: I am saying header file for brevity only. It can be any file for example BAS module file in VB etc.) Suppose I often need to solve quadratic equation. So I decided to make it a library function. For this purpose, I thought of including the following code in my own header file “MyFile.h”. Code 5-1
int solve_quad(int p, int q, int r, float *q1, float *q2) { float determ; determ=q*q-4*p*r; *q1=((-q)+sqrt(determ))/(2*p); *q2=((-q)-sqrt(determ))/(2*p); return 1; }
Now I wrote ten applications where I used this solve_quad function by just stating #include “MyFile.h” and then calling the function as status = solve_quad(a,b,c,&root1,&root2). Suddenly I realized that if the determinant is less than zero, then my programs were going to crash! So I updated Code 5-1 as Code 5-2 in file MyFile.h. www.enselsoftware.com
- 17 -
Better Understanding of Computer Programming
Code 5-2
int solve_quad(int p, int q, int r, float *q1, float *q2) { float determ; determ=q*q-4*p*r; if(determ> col1 ; cout row2 >> col2; if(col1 != row2) { cout MoveTo(200,200); pDC->LineTo(300,300); // my code ends here } ////////////////////////////////////////////////////////////// /////////////// // CMyDllExeView diagnostics
www.enselsoftware.com
- 41 -
Better Understanding of Computer Programming
As stated before, from Project – Settings – Link tab, specify the full path of Object/Library module (for the DLL’s LIB file). Now compile the EXE file. Be sure to copy the DLL file into same folder as of the EXE. Run the EXE and you should see some colorful boxes and ellipses! In this example, I used some graphics features of VC++ intentionally to demonstrate a true MFC example. You can also incorporate the same functions as discussed in console mode DLL creation. Study the code carefully and you will realize what is the general procedure to write MFC DLLs! Of course, things may appear Hebrew to you if you are new to VC++. That’s why I recommend that you read a standard Visual C++ learning side by side. In fact, there are lots of more things need to be taken into consideration while developing MFC DLLs. A detail discussion of these topics is beyond the scope of this book. Honestly speaking, I myself don’t know all the features of VC++! What is the meaning of _stdcall? Functions using the standard calling convention remove the parameters from the stack before they return to the caller. In the normal C/++ calling convention, the caller cleans up the stack instead of the function. Most other language such as VB or Pascal use standard calling convention by default. The standard calling convention so named because all Win32 API functions, except few that take variable arguments, use it. Variable argument functions continue to use C calling convention of _cdecl. Virtually all functions offered by COM interfaces on Microsoft platforms use the standard calling convention. Gee! So you learnt to create both console mode and MFC DLLs in C++! So far we only exported functions and variables from a DLL. There remains to learn another important task. How to export classes from a DLL? Can I use DLL in Unix? Yeah! In Unix, DLLs are known as ‘shared objects’ (*.so) – they work much like in the same way as that of DLLs in Windows. Final notes on DLL – all’s not well that ends well Don’t think that DLLs are solutions of all problems! Calling DLLs have traps of their own! As long as you are passing simple data types (e.g. number, string etc.) between C and VB you are fine. Trouble starts when you try to pass complex data types such as array, object etc. Consider code 5-6 again. It showed how to find out matrix product in C/++. Now, suppose you want to make it a DLL. You can easily do that in C/++ by www.enselsoftware.com
- 42 -
Better Understanding of Computer Programming
following the methods discussed (dllexport, stdcall or BOOL API etc.) in this chapter. Calling the DLL from C/++ won’t have any problem. But how do you call it from VB? Observe that the line in C/++ which calls the function p = ProductMatrix(matrix1,matrix2,row1,col1,col2) does not have any direct equivalent in VB! In C/++ when you state matrix1, you are actually passing the address of the first element of the matrix. Also the variable p after calling the function contains an address which stores address of an integer. How do you make VB understand this glitch? How do you return as user defined structure or object from C/++ to VB, which does not support that structure or object? So inter operability among several languages indeed a problem, a big problem. We’ll see in the following program how to pass a matrix through a C function that returns a structure and then calling it in VB. Create a DLL named ArrayStructure using the methodology described already. The code is given. Code 6-16
#include #include #include struct quad { float r1; float r2; char* status; }; quad* _stdcall solve_quad(int *a); quad* _stdcall solve_quad(int *a) { quad *x; x=(quad*)malloc(sizeof(quad)); int p,q,r; float determ; p=*(a+0); q=*(a+1); r=*(a+2); determ=q*q-4*p*r; if(determr1=0; x->r2=0;
www.enselsoftware.com
- 43 -
Better Understanding of Computer Programming
x->status=(char*)malloc(13*sizeof(char)); strcpy(x->status,"No real root"); return x; } else {
/* real root exists */ x->r1=((-q)+sqrt(determ))/(2*p); x->r2=((-q)-sqrt(determ))/(2*p); x->status=(char*)malloc(15*sizeof(char)); strcpy(x->status,"Two real roots"); return x;
} }
Create also the .def file as usual. LIBRARY EXPORTS
ArrayStructure solve_quad
Now use the following code to call the function in VB6. Code 6-17
Private Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" _ (Destination As Any, ByVal Source As Any, ByVal Length As Long) Private Declare Function solve_quad Lib "arraystructure.dll" _ (ByVal m As Long) As Long Private Sub Command1_Click() Dim adr As Long Dim z(3) As Long Dim Root1 As Single Dim Root2 As Single Dim Solution As String z(0) = 1 z(1) = -5 z(2) = 6 adr = solve_quad(VarPtr(z(0))) Call CopyMemory(Root1, adr, 4) Call CopyMemory(Root2, adr + 4, 4) Call CopyMemory(Solution, adr + 8, 4) MsgBox "Root1 = " & Root1 & vbCrLf & "Root2 = " & Root2 _ & vbCrLf & "Solution = " & Solution End Sub
www.enselsoftware.com
- 44 -
Better Understanding of Computer Programming
Execute the VB6 program and you’ll see two roots and status of solution. I understand that code 6-17 requires some clarification. VarPtr is an undocumented V6B function that returns the address of a variable as long. Two similar functions are StrPtr and ObjPtr. In code 17-16, we pass the matrix as the address of its first element i.e. a(0). The quad* indicates that the function solve_quad returns an address which holds a data of type quad. In C/++, an int needs 4 bytes. In VB6, a long needs the same amount of bytes. That’s why we defined z(3) as Long in VB6 instead of Integer. (You may wonder why there is such a discrepancy between C and VB6 data types. Well, it is a logical question. However, this has been rectified in VB.NET where Integer takes 4 bytes as that of in C and Short takes 2 bytes as of earlier Integer!) Anyway, back to our business. The adr stores the memory address of quad structure after calling the solve_quad function. Next the API function CopyMemory(Root1, adr, 4) assigns the content of address adr into variable Root1. It copies 4 bytes of data (since we defined Root1 as Single, which also takes 4 bytes) beginning from address adr. By the way, these direct memory manipulation functions have been removed from VB.NET! Exercise 6-1 Rewrite the code 6-16 using BOOL APIENTRY instead of _stdcall. (Hints: Suppose you want to call this function inside a C main function. Then you can also use prototype as void solve_quad(int *a, quad **m). Inside function, write *m = x instead of return x in code 6-16. While calling the function, use solve_quad(z,&w) where z is defined as int z[3] and w as quad *w. Access structure elements as w->r1, w->status etc. Compare two different types of declarations of same function in conjunction with “difference between function and procedure” as discussed in chapter 3.) Happy exporting!
www.enselsoftware.com
- 45 -
Better Understanding of Computer Programming
7. File handling In this chapter you learn basic file handling in C and QBASIC. You may ask that why I am going to discuss this very basic file handling technique while they are normally available in most beginning programming language books. It’s true. In fact nowadays people rarely use C/++ (leave alone Basic) exclusively for file handling operation in an application. Mostly a backend database and a front end user interface are used. However, in very early days of computing, only one language was used to create everything, from writing to file to presenting data to user as well. If you ever need to maintain some legacy code, you might find this kind of file handling in C. However, I presented the code here in very basic form. For example, the updating/deletion algorithm adopted here is not very efficient. Moreover, in actual practice, the records should be stored in binary tree or b-tree format (normally b-tree format is taken in most large database applications). Code 6-1 shows the how to create binary file in C and then add, modify, display, delete, search records in the file and exporting to ASCII as well. Code 7-1
/* /* /* /*
A SIMPLE DATABASE OPERATION PROGRAM */ (c) Saikat Basak */ COMPILED IN TURBO-C/C++, also compiles in Visual C++ */ the program should also compile in UNIX */
#include #include #include void main(void) { FILE *fp,*ft,*fx; int choice, another,n; struct person { char name[30+1]; char address[50+1]; char phone[10+1]; }; char myname[30+1]; struct person man; long int recsize; fp=fopen("data.dat","rb+");
www.enselsoftware.com
- 46 -
Better Understanding of Computer Programming
if(fp==NULL) { fp=fopen("data.dat","wb+"); if(fp==NULL) { puts("Can't open file"); exit(0); } } recsize=sizeof(man); while(1) { puts("------------------------------"); puts("A simple database application"); puts("------------------------------"); printf("1. Add Record\n"); printf("2. Display\n"); printf("3. Modify\n"); printf("4. Delete\n"); printf("5. Search\n"); printf("6. Export to text\n"); printf("7. Exit\n"); printf("Enter your choice\n"); fflush(stdin); scanf("%d",&choice); switch(choice) { case 1: fseek(fp,0,SEEK_END); another=1; while(another==1) { printf("Enter name\n"); scanf(" %[^\n]s",man.name); printf("Enter address\n"); scanf(" %[^\n]s",man.address); printf("Enter phone\n"); scanf(" %[^\n]s",man.phone); fwrite(&man,recsize,1,fp); printf("Add another? 1 for yes\n"); scanf("%d",&another); } break; case 2: rewind(fp); while(fread(&man,recsize,1,fp)==1)
www.enselsoftware.com
- 47 -
Better Understanding of Computer Programming
printf("%s %s %s\n",man.name,man.address,man.phone); break; case 3: another=1; while(another==1) { printf("Enter name to modify\n"); scanf("%[^\n]s",myname); rewind(fp); while(fread(&man,recsize,1,fp)==1) { if(strcmp(man.name,myname)==0) { printf("Enter new name\n"); scanf(" %[^\n]s",man.name); printf("Enter new address\n"); scanf(" %[^\n]s",man.address); printf("Enter new phone\n"); scanf(" %[^\n]s",man.phone); fseek(fp,recsize,SEEK_CUR); fwrite(&man,recsize,1,fp); break; } } printf("Modify another record? 1 for yes\n"); fflush(stdin); scanf("%d",&another); } break; case 4: another=1; while(another==1) { printf("Enter name to delete\n"); scanf("%s",myname); ft=fopen("temp.dat","wb+"); rewind(fp); while(fread(&man,recsize,1,fp)==1) { if(strcmp(man.name,myname) != 0) fwrite(&man,recsize,1,ft); }
www.enselsoftware.com
- 48 -
Better Understanding of Computer Programming
fclose(fp); fclose(ft); remove("data.dat"); rename("temp.dat","data.dat"); fp=fopen("data.dat","rb+"); printf("Delete another record 1 for yes\n"); fflush(stdin); scanf("%d",&another); } break; case 5: rewind(fp); printf("Enter name to search for (you may input first few characters)\n"); scanf("%s",myname); n=strlen(myname); while(fread(&man,recsize,1,fp)==1) { if(strnicmp(man.name,myname,n)==0) { printf("%s %s %s\n",man.name,man.address,man.phone); } } break; case 6: fx=fopen("data.csv","w+"); rewind(fp); while(fread(&man,recsize,1,fp)==1) fprintf(fx,"%s,%s,%s\n",man.name,man.address,man.phone); fclose(fx); printf("File contents has been exported to data.csv\n"); break; case 7: fclose(fp); exit(1); } } }
Study the above program carefully. There are some new functions. The same program is again made in QBASIC as given in Code 6-2. Here TYPE is equivalent to struct of C. GET and PUT are similar to fread and fwrite of C.
www.enselsoftware.com
- 49 -
Better Understanding of Computer Programming
Code 7-2
REM database handling, structure and file example in QBASIC REM (c) Saikat Basak REM with add, display, search, modify, delete in binary mode ON ERROR GOTO 100 TYPE person myname AS STRING * 30 myaddress AS STRING * 40 myphone AS STRING * 10 END TYPE DIM MyBook AS person DIM whatname AS STRING * 30 DIM deletename AS STRING * 30 5 WHILE (1) COLOR 10, 3, 2 CLS LOCATE 5, 25 PRINT "Simple database application" LOCATE 7, 30 PRINT "1. Add record" LOCATE 8, 30 PRINT "2. Display" LOCATE 9, 30 PRINT "3. Modify" LOCATE 10, 30 PRINT "4. Delete" LOCATE 11, 30 PRINT "5. Search" LOCATE 12, 30 PRINT "6. Export to text" LOCATE 13, 30 PRINT "7. Exit" LOCATE 20, 25 INPUT "Enter your choice"; choice SELECT CASE choice CASE 1 CLS another$ = "y" OPEN "database.dat" FOR BINARY AS #1 LEN = LEN(MyBook) OPEN "database.idx" FOR INPUT AS #10 INPUT #10, i CLOSE #10 DO WHILE another$ = "y"
www.enselsoftware.com
- 50 -
Better Understanding of Computer Programming
INPUT "Enter name: "; MyBook.myname INPUT "Enter address: "; MyBook.myaddress INPUT "Enter phone#: "; MyBook.myphone PUT #1, i, MyBook i = i + 80 INPUT "Add another ? ", another$ LOOP CLOSE #1 OPEN "database.idx" FOR OUTPUT AS #10 PRINT #10, i CLOSE #10
CASE 2 OPEN "database.idx" FOR INPUT AS #10 INPUT #10, i CLOSE #10 CLS PRINT "Displaying records...": PRINT j = 1 OPEN "database.dat" FOR BINARY AS #2 LEN = LEN(MyBook) DO WHILE ((NOT EOF(2)) AND (j < i)) GET #2, j, MyBook PRINT "Name: "; MyBook.myname PRINT "Address: "; MyBook.myaddress PRINT "Phone: "; MyBook.myphone PRINT j = j + 80 LOOP CLOSE #2 INPUT "Press any key to continue", x CASE 3 CLS OPEN "database.dat" FOR BINARY AS #3 LEN = LEN(MyBook) INPUT "Enter name to modify: "; whatname flag = 0 m = 1 DO WHILE NOT EOF(3) GET #3, m, MyBook IF MyBook.myname = whatname THEN flag = 1 INPUT "Enter Name: "; MyBook.myname INPUT "Enter Address: "; MyBook.myaddress INPUT "Enter Phone#: "; MyBook.myphone PUT #3, m, MyBook END IF m = m + 80 LOOP CLOSE #3 IF flag = 0 THEN PRINT "Not found"
www.enselsoftware.com
- 51 -
Better Understanding of Computer Programming
INPUT "Press any key to continue", x CASE 4 CLS OPEN "temp.dat" FOR BINARY AS #11 LEN = LEN(MyBook) OPEN "database.dat" FOR BINARY AS #4 LEN = LEN(MyBook) INPUT "Enter name to delete: "; deletename flag = 0 p = 1 q = 1 DO WHILE NOT EOF(4) GET #4, p, MyBook IF MyBook.myname deletename THEN PUT #11, q, MyBook q = q + 80 ELSEIF MyBook.myname = deletename THEN flag = 1 PRINT ""; deletename; " is being deleted" q = q END IF p = p + 80 LOOP IF flag = 0 THEN PRINT "Record not found" CLOSE #4 CLOSE #11 SHELL "del database.dat" SHELL "ren temp.dat database.dat" OPEN "database.idx" FOR OUTPUT AS #10 PRINT #10, q - 80 CLOSE #10 INPUT "Press any key to continue", x CASE 5 CLS OPEN "database.dat" FOR BINARY AS #5 LEN = LEN(MyBook) INPUT "Enter name to search for: "; whatname flag = 0 k = 1 DO WHILE NOT EOF(5) GET #5, k, MyBook IF MyBook.myname = whatname THEN flag = 1 PRINT "Name: "; MyBook.myname PRINT "Address: "; MyBook.myaddress PRINT "Phone: "; MyBook.myphone END IF k = k + 80 LOOP CLOSE #5
www.enselsoftware.com
- 52 -
Better Understanding of Computer Programming
IF flag = 0 THEN PRINT "Not found" INPUT "Press any key to continue", x CASE 6 CLS OPEN "data.txt" FOR OUTPUT AS #12 OPEN "database.dat" FOR BINARY AS #6 LEN = LEN(MyBook) u = 1 DO WHILE NOT EOF(6) GET #6, u, MyBook PRINT #12, MyBook.myname, PRINT #12, MyBook.myaddress, PRINT #12, MyBook.myphone u = u + 80 LOOP CLOSE #12 CLOSE #6 PRINT "File has been written to file DATA.TXT" INPUT "Press any key to continue", x CASE 7 GOTO 10 CASE ELSE SOUND 1000, 2 END SELECT WEND 10 GOTO 200 100 CLS : PRINT : PRINT PRINT "An error has occurred while accessing the file" PRINT "Make sure that for options other than 1, the file must be created first" INPUT "Press any key to continue", x GOTO 5 200 END
Look, there are some GO TO statements have been used. Do they always violate structured programming concept? Assuming you name the file as DATABASE.BAS, it is necessary that before running this program, you create a text file named DATABASE.IDX with just the number 1 written in it. You can use the above code in VB with just slight modifications! Exercise 7-1
www.enselsoftware.com
- 53 -
Better Understanding of Computer Programming
Re-write the code 6-1 using C++. Use binary search algorithm. Do you think use of class instead of structure will be better? You may need to consult a data structure textbook for the binary tree implementation algorithm. This is a tough exercise but worth doing!
www.enselsoftware.com
- 54 -
Better Understanding of Computer Programming
8. Pointer paradoxes in C If you ask programmers what is the most confusing thing in C programming, I’m sure that they will say ‘pointers’! Indeed pointers are difficult to master at the beginning. In fact, many programmers hate C because of pointers. Surprisingly to placate them modern programming languages such as Visual Basic, Java etc. removed explicit pointer feature. (Though they handle internally everything using pointers!) In this chapter I’ll discuss various topics about pointers and shall try to clarify some of your doubts. Although all C/++ programming books deal with pointers not all of them provides sufficient insight. You may consult Ref. 9 for a dedicated treatment of pointers in C. Did you remember the quadratic equation function in code 3-1? Look, here we write the function in slight different manner. Code 8-1
/* a quadratic equation solver in C++ */ #include #include int solve_quad(int p, int q, int r, float &q1, float &q2); void main(void) { int a,b,c; float root1,root2; int status; cout a >> b >> c; status = solve_quad(a,b,c,root1,root2); if(status==1) { cout