Skip to main content

Posts

Showing posts from July, 2012

Strategies

The created wrapped pointer class o®ers no more functionality than any dump pointer. To add some smartness to the code skeleton a strategy needs to be implemented. Before going into an implementation some strategies will be discussed. The list of strategies is not complete but should be su±cient for most applications. Every strategy is entirely de¯ned by the characteristics of the assignment operators and the de- structor. Let ptr1 and ptr2 be smart pointers. Possible strategies for ptr1 = ptr2 and reset() are described for each strategy. Scoped pointer The scoped pointer is rarely used. It stores a pointer to a dynamically allocated object. The object pointed to is guaranteed to be deleted, either on destruction of the scoped pointer, or via an explicit reset(). The assignment ptr1 = ptr2 is forbidden. Since a scoped pointer is noncopyable it is caved within its scope and cannot get out. It's safer than the reference counting or ownership transfer pointers for poin

Wrapping pointers

In the C-library the type void* is used as generic pointer type. But member functions cannot be called without a type and user typecasts would be required to operate on the pointer's data. With C++ templates the user can constitude the type of dump pointer to be stored inside the wrapped pointer instance. Constructors To get the dump pointer inside the wrapped pointer a few constructors are required. Null pointers should indicate an unde¯ned destination for smart pointers like they do for dump pointers.  A null smart pointer can be created with the default constructor that takes no arguments. Example: SmartPtr<std::string> ptr;  A copy constructor need to be de¯ned, to initialize a wrapped pointer from another compatible wrapped pointer instance. Example: SmartPtr<std::vector> ptr(ptr2);  To initialize the wrapped pointer from a dump pointer a constructor is needed with the type of the dump pointer as argument. Example: SmartPtr<int> ptr(new

STL List Container

The Standard Template Library's list container is implemented as a doubly linked list. You might wonder why there are both list and vector containers in the STL -- the reason is that the underlying representations are different, and each representation has its own costs and benefits. The vector has relatively costly insertions into the middle of the vector, but fast random access, whereas the list allows cheap insertions, but slow access (because the list has to be traversed to reach any item). Some algorithms, such as merge sort, even have different requirements when applied to lists instead of vectors. For instance, merge sort on vectors requires a scratch vector, whereas merge sort on lists does not. Using the STL list class is about as simple as the STL vector container. In fact, to declare a list, all you need is to give the type of data to be stored in the list. For instance, the following code declares a list storing integers: std::list<int> integer_list; Like th

Formatting Cout Output in C++ using iomanip

Dealing with Spacing Issues using iomanip A principle aspect of nicely formatted output is that the spacing looks right. There aren't columns of text that are too long or too short, and everything is appropriately aligned. This section deals with ways of spacing output correctly. Setting the field width with setw The std::setw function allows you to set the minimum width of the next output via the insertion operator. setw takes, one argument, the width of the next output (insertion), an integer. if the next output is too short, then spaces will be used for padding. There is no effect if the output is longer than the width--note that the output won't be truncated. The only strange thing about setw is that its return value must be inserted into the stream. The setw function has no effect if it is called without reference to a stream. A simple example is using namespace std; cout<<setw(10)<<"ten"<<"four"<<"four"; The o

Recursion in C and C++

Recursion is a programming technique that allows the programmer to express operations in terms of themselves. In C++, this takes the form of a function that calls itself. A useful way to think of recursive functions is to imagine them as a process being performed where one of the instructions is to "repeat the process". This makes it sound very similar to a loop because it repeats the same code, and in some ways it is similar to looping. On the other hand, recursion makes it easier to express ideas in which the result of the recursive call is necessary to complete the task. Of course, it must be possible for the "process" to sometimes be completed without the recursive call. A simple example of recursion would be: void recurse() {   recurse(); //Function calls itself } int main() {   recurse(); //Sets off the recursion } This program will not continue forever, however. The computer keeps function calls on a stack and once too many are called without e

Smart Pointer

What are smart pointers? The answer is fairly simple; a smart pointer is a pointer which is smart. What does that mean? Actually, smart pointers are objects which behave like pointers but do more than a pointer. These objects are flexible as pointers and have the advantage of being an object (like constructor and destructors called automatically). A smart pointer is designed to handle the problems caused by using normal pointers (hence called smart).

Program to identify if an input is a symbol, digit or character

#include <iostream.h> #include <conio.h> void main() { clrscr(); char charac; cout << "Enter your input : " << endl; cin>>charac; if(((charac>='A')&&(charac<='Z'))||((charac>='a')&&(charac<='z'))) cout << "Your input " << charac << " is a character." << endl; else if((charac>='0')&&(charac<='9')) cout << "Your input " << charac << " is a digit." << endl; else cout << "Your input " << charac << " is a symbol." << endl; getch(); } This program takes in a character, a digit or a symbol charac as a screen input from the user. It then identifies whether the input is a symbol, a digit or a character and outputs the appropriate message using the 'cout' command. Posted By:- Cplusplusprogramming

Program to draw 2 rectangles and fill 1 of them

#include <iostream.h> #include <conio.h> #include <graphics.h> #include <ctype.h> #include <stdlib.h> #include <stdio.h> void main() {   clrscr();   int gd = DETECT,gm,errorcode; //Requesting auto-detection.   //Initializing graphics and local variables.   initgraph (&gd, &gm, "d:\\bc3\\bgi"); //Path where graphics drivers are installed   //Read result of initialization.   errorcode = graphresult();   //An error occured.   if (errorcode != grOk)     {       cout << "Graphics error occured : \n" << grapherrormsg(errorcode) << endl;       cout << "Press any key to stop : ";       getch();       exit(1);     }   /*Drawing a rectangle having top LHS vertex at (300, 300)   and bottom RHS vertex at (600, 400)*/   rectangle(300, 300, 600, 400);   rectangle(100, 100, 200, 200);   getch();   floodfill(120, 120, WHITE);   getch();   closegraph(); } This graphics

Program to switch between different cases

#include <iostream.h> #include <conio.h> int main() { clrscr(); int choice; cout << "1. Talk" << endl; cout << "2. Eat" << endl; cout << "3. Play" << endl; cout << "4. Sleep" << endl; cout << "Enter your choice : " << endl; cin>>choice; switch(choice) { case 1 : cout << "You chose to talk...talking too much is a bad habit." << endl; break; case 2 : cout << "You chose to eat...eating healthy foodstuff is good." << endl; break; case 3 : cout << "You chose to play...playing too much everyday is bad." << endl; break; case 4 : cout << "You chose to sleep...sleeping enough is a good habit." << endl; break; default : cout << "You did not choose anything...so exit this program." << endl; } getch(); } This program takes in the user

Excellent Work Making An Operating System

This program is the best of all the Programmers , every one should download this and see whats in it and try to learn how to make it so don't wait download now here This program represent a real os but with out background but very well work done by Vinay Danaraddi Here Take A Look Download To use This Your Self OPERATING SYSTEM Administrator Password :-12345

Dynamic Memory Allocation for Arrays

Consider you want to allocate memory for an array of characters i.e. string of 20 characters. Using the same syntax what we have used above we can allocate memory dynamically as shown below. char* pvalue  = NULL;   // Pointer initialized with null pvalue  = new char[20]; // Request memory for the variable To remove the array that we have just created the statement would look like this: delete [] pvalue;        // Delete array pointed to by pvalue Following the similar generic syntax of new operator, you can allocat for a multi-dimensional array as follows: double** pvalue  = NULL;     // Pointer initialized with null pvalue  = new double [3][4]; // Allocate memory for a 3x4 array However the syntax to release the memory for multi-dimensional array will still remain same as above: delete [] pvalue;        // Delete array pointed to by pvalue Posted By:- Cplusplusprogramming If Have Any Problem :- C++ Problem Solve

C++ Dynamic Memory

A good understanding of how dynamic memory really works in C++ is essential to becoming a good C++ programmer. Memory in your C++ program is divided into two parts: The stack: All variables declared inside the function will take up memory from the stack. The heap: This is unused memory of the program and can be used to allocate the memory dynamically when program runs. Many times you are not aware in advance how much memory you will need to store a particular information in a defined variable and the size of required memory can be determined at run time. You can allocate memory at run time within the heap for the variable of a given type using a special operator in C++ which returns the address of the space allocated. This operator is called new operator. If you are not in need of dynamically allocated memory anymore, you can use delete operator, which de-allocates memory previously allocated by new operator. Posted By:- Cplusplusprogramming If Have Any Problem Visit :-

C++ Identifiers

A C++ identifier is a name used to identify a variable, function, class, module, or any other user-defined item. An identifier starts with a letter A to Z or a to z or an underscore (_) followed by zero or more letters, underscores, and digits (0 to 9). C++ does not allow punctuation characters such as @, $, and % within identifiers. C++ is a case sensitive programming language. Thus Manpower and manpower are two different identifiers in C++. Here are some examples of acceptable identifiers: mohd       zara    abc   move_name  a_123 myname50   _temp   j     a23b9      retVal Posted By:- Cplusplusprogramming

Basic Definition

Object - Objects have states and behaviors. Example: A dog has states-color, name, breed as well as behaviors -wagging, barking, eating. An object is an instance of a class. Class - A class can be defined as a template/ blue print that describe the behaviors/states that object of its type support. Methods - A method is basically a behavior. A class can contain many methods. It is in methods where the logics are written, data is manipulated and all the actions are executed. Instant Variables - Each object has its unique set of instant variables. An object's state is created by the values assigned to these instant variables. Posted By:- Cplusplusprogramming

Write a C function to detect loop in a linked list

Use Hashing: Traverse the list one by one and keep putting the node addresses in a Hash Table. At any point, if NULL is reached then return false and if next of current node points to any of the previously stored nodes in Hash then return true. Mark Visited Nodes: This solution requires modifications to basic linked list data structure.  Have a visited flag with each node.  Traverse the linked list and keep marking visited nodes.  If you see a visited node again then there is a loop. This solution works in O(n) but requires additional information with each node. A variation of this solution that doesn’t require modification to basic data structure can be implemented using hash.  Just store the addresses of visited nodes in a hash and if you see an address that already exists in hash then there is a loop. Floyd’s Cycle-Finding Algorithm : This is the fastest method. Traverse linked list using two pointers.  Move one pointer by one and other pointer by two.  If these pointers m

Typecasting in C and C++

Typecasting is making a variable of one type, such as an int, act like another type, a char, for one single operation. To typecast something, simply put the type of variable you want the actual variable to act as inside parentheses in front of the actual variable. (char)a will make 'a' function as a char. For example: #include <iostream> using namespace std; int main()       {   cout<< (char)65 <<"\n";   // The (char) is a typecast, telling the computer to interpret the 65 as a   //  character, not as a number.  It is going to give the character output of   //  the equivalent of the number 65 (It should be the letter A for ASCII).   cin.get(); } One use for typecasting for is when you want to use the ASCII characters. For example, what if you want to create your own chart of all 128 ASCII characters. To do this, you will need to use to typecast to allow you to print out the integer as its character equivalent. #include <iost

What Exactly Is Program Input/Output?

A C program keeps data in random access memory (RAM) while executing. This data is in the form of variables, structures, and arrays that have been declared by the program. The question is where did this data come from, and what can the program do with it? Data can come from some location external to the program. Data moved from an external location into RAM, where the program can access it, is called input. The keyboard and disk files are the most common sources of program input. Data can also be sent to a location external to the program; this is called output. The most common destinations for output are the screen, a printer, and disk files. Input sources and output destinations are collectively referred to as devices. The keyboard is a device; the screen is a device, and so on. Some devices (the keyboard) are for input only, others (the screen) are for output only, and still others (disk files) are for both input and output. Whatever the device, and whether it’s performing inpu

What is a Stream?

A stream is a sequence of characters. More exactly, it is a sequence of bytes of data. A sequence of bytes flowing into a program is an input stream; a sequence of bytes flowing out of a program is an output stream. By focusing on streams, we don’t have to worry as much about where they’re going or where they originated. The major advantage of streams, therefore, is that input/output programming is device independent. Programmers don’t need to write special input/output functions for each device (keyboard, disk, and so on). The program sees input/output as a continuous stream of bytes no matter where the input is coming from or going to. Every C stream is connected to a file. In this context, the term file doesn’t refer to a disk file. Rather, it is an intermediate step between the stream that the program deals with and the actual physical device being used for input or output. For the most part, the beginning C programmer doesn’t need to be concerned with these files, because the

Nested Classes in C++

A nested class is a class which is declared in another enclosing class. A nested class is a member and as such has the same access rights as any other member. The members of an enclosing class have no special access to members of a nested class; the usual access rules shall be obeyed. for example, program 1 compiles without any error and program 2 fails in compilation. Program 1 #include<iostream> using namespace std;  /* start of Enclosing class declaration */ class Enclosing {              int x;        /* start of Nested class declaration */    class Nested {       int y;         void NestedFun(Enclosing *e) {         cout<<e->x;  // works fine: nested class can access                      // private members of Enclosing class       }          }; // declaration Nested class ends here }; // declaration Enclosing class ends here int main() {     } Program 2 #include<iostream> using namespace std;  /* start of Enclosing class

SQL DML and DDL

SQL can be divided into two parts: The Data Manipulation Language (DML) and the Data Definition Language (DDL). The query and update commands form the DML part of SQL: SELECT - extracts data from a database UPDATE - updates data in a database DELETE - deletes data from a database INSERT INTO - inserts new data into a database The DDL part of SQL permits database tables to be created or deleted. It also defines indexes (keys), specifies links between tables, and imposes constraints between tables. The most important DDL statements in SQL are: CREATE DATABASE - creates a new database ALTER DATABASE - modifies a database CREATE TABLE - creates a new table ALTER TABLE - modifies a table DROP TABLE - deletes a table CREATE INDEX - creates an index (search key) DROP INDEX - deletes an index Posted By:-  Cplusplusprogramming

What is SQL?

SQL stands for Structured Query Language SQL lets you access and manipulate databases SQL is an ANSI (American National Standards Institute) standard What Can SQL do? SQL can execute queries against a database SQL can retrieve data from a database SQL can insert records in a database SQL can update records in a database SQL can delete records from a database SQL can create new databases SQL can create new tables in a database SQL can create stored procedures in a database SQL can create views in a database SQL can set permissions on tables, procedures, and views SQL is a Standard - BUT.... Although SQL is an ANSI (American National Standards Institute) standard, there are many different versions of the SQL language. However, to be compliant with the ANSI standard, they all support at least the major commands (such as SELECT, UPDATE, DELETE, INSERT, WHERE) in a similar manner. Note: Most of the SQL database programs also have their own

Class Scope

A name declared within a member function hides a declaration of the same name whose scope extends to or past the end of the member function's class. When the scope of a declaration extends to or past the end of a class definition, the regions defined by the member definitions of that class are included in the scope of the class. Members defined lexically outside of the class are also in this scope. In addition, the scope of the declaration includes any portion of the declarator following the identifier in the member definitions. The name of a class member has class scope and can only be used in the following cases: In a member function of that class In a member function of a class derived from that class After the . (dot) operator applied to an instance of that class After the . (dot) operator applied to an instance of a class derived from that class, as long as the derived class does not hide the name After the -> (arrow) operator applied to a pointer to an instance

What is Statements

A statement, the smallest independent computational unit, specifies an action to be performed. In most cases, statements are executed in sequence. The following is a summary of the statements available in C and C++: labeled statements     identifier labels    case labels    default labels expression statements     block or compound statements    selection statements           if statements         switch statements iteration statements   while statements   do statements   for statements jump statements   break statements   continue statements   return statements   goto statements declaration statements   try blocks

what is Function Declarations?

A function declaration establishes the name of the function and the number and types of its parameters. A function declaration consists of a return type, a name, and a parameter list. In addition, a function declaration may optionally specify the function's linkage. In C++, the declaration can also specify an exception specification, a const-qualification, or a volatile-qualification. A declaration informs the compiler of the format and existence of a function prior to its use. A function can be declared several times in a program, provided that all the declarations agree. Implicit declaration of functions is not allowed: every function must be explicitly declared before it can be called. In C89, if a function is called without an explicit prototype, the compiler provides an implicit declaration. The compiler checks for mismatches between the parameters of a function call and those in the function declaration. The compiler also uses the declaration for argument type checking an

What is a Functions ?

The term function means an assemblage of statements used for computing an output value. The word is used less strictly than in mathematics, where it means a set relating input variables uniquely to output variables. Functions in C or C++ programs may not produce consistent outputs for all inputs, may not produce output at all, or may have side effects. Functions can be understood as user-defined operations, in which the parameters of the parameter list, if any, are the operands. Functions fall into two categories: those written by you and those provided with the C language implementation. The latter are called library functions, since they belong to the library of functions supplied with the compiler. The result of a function is called its return value. The data type of the return value is called the return type. A function identifier preceded by its return type and followed by its parameter list is called a function declaration or function prototype. The term function body refe

Quick hack convert M$ favorites to html list

#include <stdio.h> #include <string.h> #include <unistd.h> #include <stdlib.h> #include <dirent.h> #include <sys/stat.h> #define PACKAGE "forvavo" /* recursion */ void recdir(char *dir); int main(int argc, char *argv[]) {  if(argc != 2)   fprintf(stderr, "%s [directory]\n", PACKAGE), exit(EXIT_FAILURE);  else {   printf("<HTML>\n");   printf(" <HEAD>\n");   printf("  <TITLE>favorites</TITLE>\n");   printf(" </HEAD>\n");   printf("<BODY>\n");   recdir(argv[1]);   printf("</BODY>\n");   printf("</HTML>\n");  }  return 0; } void recdir(char *dir) {  DIR *dp;  FILE *fp;  char *ptr;  char line[1024];  struct dirent *entry;  struct stat statbuf;  if((dp = opendir(dir)) == NULL) {   fprintf(stderr, "Cannot open directory: %s\n", dir);   return;  }  chdir(dir);  wh

Program to write even and odd integers into different files

#include<stdio.h> #include<math.h> void main() { FILE *all,*even,*odd; int number,i,records; printf("INPUT THE TOTAL NUMBER OF RECORDS THAT U WANT TO ENTER "); scanf("%d",& records); all=fopen("ANYNUMBER","w"); for(i=1;i<=records;i++) { scanf("%d",&number); if(number==-1)break; putw(number,all); } fclose(all); all=fopen("ANYNUMBER","r"); even=fopen("EVENNUMBER","w"); odd=fopen("ODDNUMBER","w"); while((number=getw(all))!=EOF) { if(number%2==0) putw(number,even); else putw(number,odd); } fclose(all); fclose(even); fclose(odd); even=fopen("EVENNUMBER","r"); odd=fopen("ODDNUMBER","r"); printf("  THE EVEN NUMBERS ARE"); while((number=getw(even))!=EOF) printf(" %4d",number); printf("  THE ODD NUMBERS ARE"); while((number=getw(odd))!=EOF) printf(&

File Encryption Program in C.

WARNING :                                do not give the have the same sourcefile and                              destinationfile, encrypting or decrypting, this bug will be worked                      out as i get more interested in file encryption #include <stdio.h> #define ENCRYPTION_FORMULA  (int) Byte + 25 #define DECRYPTION_FORMULA  (int) Byte - 25 int Encrypt(char * FILENAME, char * NEW_FILENAME) { //printf("Loaded Encrypt "); FILE *inFile;  //Declare inFile FILE *outFile;  //Declare outFile char Byte; char newByte; int n; printf("1"); int i=0; inFile = fopen(FILENAME,"rb"); outFile = fopen(NEW_FILENAME, "w"); if(inFile==NULL) printf("Error: Can't Open inFile"); if(outFile==NULL) { printf("Error: Can't open outFile. "); return 1; } else { printf("File Opened, Encrypting

Computer Graphics sample source codes

# include <graphics.h> # include <conio.h> # include <dos.h> # include <stdlib.h> void intro() {   clrscr();   int gd=DETECT,gm,i=0;   detectgraph(&gd,&gm);   initgraph(&gd,&gm,"c:\tc\bgi");   rectangle(0,5,630,400);   rectangle(10,15,620,390);       settextstyle(1,0,1);   outtextxy(245,238,"DESIGNER");  while(!kbhit())  {    setcolor(i);        settextstyle(2,0,0);   outtextxy(32,170,"* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *");   outtextxy(32,178,"* *");   outtextxy(32,186,"* *");   outtextxy(32,196,"* *"); outtextxy(32,205,"* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *");    setfillstyle(XHATCH_FILL,i++);    delay(200);    floodfill(2,9,15);    if(i>=15)      i=0;  }   getch();   cleardevice();   closegraph(); } /**************

Count backwards even numbers using a for loop

#include <iostream> using namespace std; int main() { for (int count = 26; count > -1; count -= 2) { cout << count << ", "; } cout << endl; return 0; } OUTPUT 26, 24, 22, 20, 18, 16, 14, 12, 10, 8, 6, 4, 2, 0, Press any key to continue . . .

One dimensional character array (C-string)

  Purpose :   Demonstrate the use of character array.      Ask for the user's name and print it out. #include <iostream> #include <stdlib.h> //for newer compilers, include <cstdlib> using namespace std; int main() { char name[32]; // big enough to hold 32 characters // prompt for the name cout << "What's your name?" << endl; gets(name); // read a string from the key board. cout << "Hello! " << name << "!"  << endl; return 0; } Posted By :- Cplusplusprogramming

How To Avoid Sili Mistake In Programming

To avoid mistake Just follow these steps 1. Make you Program Neat and clean 2. use statements so it can be understood by other also 3. never try to copy any program seen on the internet (not our also) use your own mind to write progam Just Follow all these and u will surly make less mistake now Posted By :- Cplusplusprogramming

Our Top Users On FaceBook Page

1.  Manish soft hard 2. Saurabh.dhormare 3. Ankit.chaudhary And their are many other so be regular on the Facebook Page and Our Blog. Facebook Page :- Cplusplusprogramming

C++ class program to perform rational number arithmetic

#include<stdio.h>  #include<iostream.h>  #include<conio.h>  class rational  { int numer; int denom; public: void getdata() { cout<<"\n enter the numerator part of the rational no."; cin>>numer; cout<<"\n enter the denominator part of the rational no."; cin>>denom; } void operator+(rational); void operator-(rational); void operator *(rational); void operator /(rational);  };  void rational ::operator+(rational c1)  { rational temp; temp.numer=(numer*c1.denom)+(c1.numer*denom); temp.denom=denom*c1.denom; cout<<"\nrational no. after addition"; cout<<"\n numerator="<<temp.numer<<"\n denominator ="<<temp.denom;  }  void raional ::operator -(rational c1)  { rational temp; temp.numer=(numer*c1.denom)-(c1.numer*denom); temp.denom=denom*c1.denom; cout<<"\n rational no. after subtr