Happy Codings - Programming Code Examples
Html Css Web Design Sample Codes CPlusPlus Programming Sample Codes JavaScript Programming Sample Codes C Programming Sample Codes CSharp Programming Sample Codes Java Programming Sample Codes Php Programming Sample Codes Visual Basic Programming Sample Codes

C++ Programming Code Examples

C++ > Data Structures Code Examples

Files and Folders using Data structure

/* Files and Folders using Data structure */ #include<stdio.h> #include<string.h> #include<stdlib.h> #include<conio.h> #include<dir.h> #include<dos.h> struct node { char *name; /* used to get file / folder name. */ int attrib; /* used to get it's attribute. */ struct node *next; /* concept of Linked list */ }; void main() { struct node *head,*head1; struct node *list,*list1; struct node * place(struct ffblk ff,struct node *first,int don); void display(struct node *first); void print(struct node *list,int *i); int i,c,c1,done,done1; struct ffblk f,f1; head=NULL; head1=NULL; clrscr(); done=findfirst("*.*",&f,FA_DIREC|FA_RDONLY|FA_HIDDEN|FA_SYSTEM|FA_ARCH); /* struct variable "f" contains all files and folders information */ done1=findfirst("*.*",&f1,FA_RDONLY|FA_HIDDEN|FA_SYSTEM|FA_ARCH); /* struct variable "f1" contains all files information */ head=place(f,head,done); /* content of f is placed in struct head */ display(head); /* Note : f contains name of files and folders with their attributes in f.ff_name, f.ff_attrib which is assigned to name, attrib in the struct node */ printf("******************************************"); getch(); head1=place(f1,head1,done1); /* content of f1 is placed in struct head1 */ display(head1); /* Note : f1 contains name of files and folders with their attributes in f1.ff_name, f1.ff_attrib which is assigned to name, attrib in the struct node */ printf("**********************************"); getch(); i=0; c1=0; /* Here, head and head1 are compared so that we could extract only the folders. */ list=head; /* head is assigned to list */ while(list!=NULL) { list1=head1; /* head1 is assigned to list1 */ if(list1==NULL) /* if there are 0 files */ print(list,&i); /* then display content of list */ else { while(list1!=NULL) { if(strcmp(list->name,list1->name)==0) /* compare list and list1 */ c1=1; list1=list1->next; } if(c1==0) /* if folder found both in list and list1*/ print(list,&i); /* then display content of list */ } c1=0; list=list->next; } printf(" FOLDERS = %d",i); printf("***********************************"); printf(" Where,"); printf(" H - Hidden"); printf(" D - Directory"); printf(" R - Read only"); printf(" S - System"); printf(" A - Archive"); getch(); free(list1); free(list); free(head); free(head1); } void print(struct node *list,int *i) { void property(struct node *list); /* to display folders other than default folders (. and ..) */ if((strcmp(list->name,"."))!=0 && (strcmp(list->name,".."))!=0) { *i=*i+1; /* counts number of folders */ property(list); printf(" %s ",list->name); } } void property(struct node *list) { /* finds their attribute */ if(list->attrib & FA_HIDDEN) printf("(H)"); if(list->attrib & FA_DIREC) printf("(D)"); if(list->attrib & FA_RDONLY) printf("(R)"); if(list->attrib & FA_SYSTEM) printf("(S)"); if(list->attrib & FA_ARCH) printf("(A)"); } struct node * place(struct ffblk ff,struct node *first,int don) { static int j; void create(struct node *first,char *ch,int d); void insert(struct node *first,char *ch,int d); int i=0,c=0; char *p; if(don!=0) first=NULL; else { while(don==0) { if(i==0) { first=(struct node *)malloc(sizeof(struct node)); if ((p = (char *) malloc(14)) == NULL) exit(1); strcpy(p,ff.ff_name); create(first,p,ff.ff_attrib); i=1; } else { if ((p = (char *) malloc(14)) == NULL) exit(1); strcpy(p,ff.ff_name); insert(first,p,ff.ff_attrib); } don=findnext(&ff); c=c+1; } } if(j==0) { printf("***************************************"); printf(" %d FILES & FOLDERS ",c); j+=1; } else printf(" %d FILES ",c); return(first); } void create(struct node *first,char *ch,int d) { char *p; if ((p = (char *) malloc(sizeof(ch))) == NULL) exit(1); p=ch; first->name=p; first->attrib=d; first->next=NULL; return; } void insert(struct node *first,char *ch,int d) { struct node *temp,*list; char *p; list=first; while(list->next!=NULL) list=list->next; if ((p = (char *)malloc(sizeof(ch))) == NULL) exit(1); p=ch; temp=(struct node *)malloc(sizeof(struct node)); temp->name=p; temp->attrib=d; temp->next=NULL; list->next=temp; return; } void display(struct node *first) { struct node *list; void property(struct node *list); list=first; if(list==NULL) printf(" NULL"); else { while(list->next!=NULL) { property(list); printf("%s %d ",list->name,list->attrib); list=list->next; } property(list); printf("%s %d ",list->name,list->attrib); } return; }

The getch() is a predefined non-standard function that is defined in conio.h header file. It is mostly used by the Dev C/C++, MS- DOS's compilers like Turbo C to hold the screen until the user passes a single value to exit from the console screen. It can also be used to read a single byte character or string from the keyboard and then print. It does not hold any parameters. It has no buffer area to store the input character in a program. The getch() function does not accept any parameter from the user. It returns the ASCII value of the key pressed by the user as an input.

The exit function terminates the program normally. Automatic objects are not destroyed, but static objects are. Then, all functions registered with atexit are called in the opposite order of registration. The code is returned to the operating system. An exit code of 0 or EXIT_SUCCESS means successful completion. If code is EXIT_FAILURE, an indication of program failure is returned to the operating system. Other values of code are implementation-defined. Calls all functions registered with the atexit() function, and destroys C++ objects with static storage duration, all in last-in-first-out (LIFO) order. C++ objects with static storage duration are destroyed in the reverse order of the completion of their constructor. (Automatic objects are not destroyed as a result of calling exit().)

Deallocate memory block. A block of memory previously allocated by a call to malloc, calloc or realloc is deallocated, making it available again for further allocations. If ptr does not point to a block of memory allocated with the above functions, it causes undefined behavior. If ptr is a null pointer, the function does nothing. Notice that this function does not change the value of ptr itself, hence it still points to the same (now invalid) location. free() function in C++ <cstdlib> library is used to deallocate a memory block in C++. Whenever we call malloc, calloc or realloc function to allocate a memory block dynamically in C++, compiler allocates a block of size bytes of memory and returns a pointer to the start of the block. The new memory block allocated is not initialized but have intermediate values. free() method is used to free such block of memory. In case the pointer mentioned does not point to any memory block then it may lead to an undefined behavior, but does nothing in case of null

In C++, classes and structs are blueprints that are used to create the instance of a class. Structs are used for lightweight objects such as Rectangle, color, Point, etc. Unlike class, structs in C++ are value type than reference type. It is useful if you have data that is not intended to be modified after creation of struct. C++ Structure is a collection of different data types. It is similar to the class that holds different types of data. A structure is declared by preceding the struct keyword followed by the identifier(structure name). Inside the curly braces, we can declare the member variables of different types.

The sizeof() is an operator that evaluates the size of data type, constants, variable. It is a compile-time operator as it returns the size of any variable or a constant at the compilation time. The size, which is calculated by the sizeof() operator, is the amount of RAM occupied in the computer. The sizeof is a keyword, but it is a compile-time operator that determines the size, in bytes, of a variable or data type. The sizeof operator can be used to get the size of classes, structures, unions and any other user defined data type. The data_type can be the data type of the data, variables, constants, unions, structures, or any other user-defined data type.

Check whether eofbit is set. Returns true if the eofbit error state flag is set for the stream. This flag is set by all standard input operations when the End-of-File is reached in the sequence associated with the stream. Note that the value returned by this function depends on the last operation performed on the stream (and not on the next). Operations that attempt to read at the End-of-File fail, and thus both the eofbit and the failbit end up set. This function can be used to check whether the failure is due to reaching the End-of-File or to some other reason.

Copy string. Copies the C string pointed by source into the array pointed by destination, including the terminating null character (and stopping at that point). To avoid overflows, the size of the array pointed by destination shall be long enough to contain the same C string as source (including the terminating null character), and should not overlap in memory with source. strcpy() is a standard library function in C/C++ and is used to copy one string to another. In C it is present in string.h header file and in C++ it is present in cstring header file. It copies the whole string to the destination string. It replaces the whole string instead of appending it. It won't change the source string.

Compare two strings. Compares the C string str1 to the C string str2. This function starts comparing the first character of each string. If they are equal to each other, it continues with the following pairs until the characters differ or until a terminating null-character is reached. This function performs a binary comparison of the characters. For a function that takes into account locale-specific rules, see strcoll. The strcmp() function in C++ compares two null-terminating strings (C-strings). The comparison is done lexicographically. It is defined in the cstring header file.

In while loop, condition is evaluated first and if it returns true then the statements inside while loop execute, this happens repeatedly until the condition returns false. When condition returns false, the control comes out of loop and jumps to the next statement in the program after while loop. The important point to note when using while loop is that we need to use increment or decrement statement inside while loop so that the loop variable gets changed on each iteration, and at some point condition returns false. This way we can end the execution of while loop otherwise the loop would execute indefinitely. A while loop that never stops is said to be the infinite while loop, when we give the condition in such a way so that it never returns false, then the loops becomes infinite and repeats itself indefinitely.

C supports nesting of loops in C. Nesting of loops is the feature in C that allows the looping of statements inside another loop. Any number of loops can be defined inside another loop, i.e., there is no restriction for defining any number of loops. The nesting level can be defined at n times. You can define any type of loop inside another loop; for example, you can define 'while' loop inside a 'for' loop. A loop inside another loop is called a nested loop. The depth of nested loop depends on the complexity of a problem. We can have any number of nested loops as required. Consider a nested loop where the outer loop runs n times and consists of another loop inside it. The inner loop runs m times. Then, the total number of times the inner loop runs during the program execution is n*m.

Static is a keyword in C++ used to give special characteristics to an element. Static elements are allocated storage only once in a program lifetime in static storage area. And they have a scope till the program lifetime. In C++, static is a keyword or modifier that belongs to the type not instance. So instance is not required to access the static members. In C++, static can be field, method, constructor, class, properties, operator and event. Advantage of C++ static keyword: Memory efficient. Now we don't need to create instance for accessing the static members, so it saves memory. Moreover, it belongs to the type, so it will not get memory each time when instance is created.

In computer programming, we use the if statement to run a block code only when a certain condition is met. An if statement can be followed by an optional else statement, which executes when the boolean expression is false. There are three forms of if...else statements in C++: • if statement, • if...else statement, • if...else if...else statement, The if statement evaluates the condition inside the parentheses ( ). If the condition evaluates to true, the code inside the body of if is executed. If the condition evaluates to false, the code inside the body of if is skipped.

As the name already suggests, these operators help in assigning values to variables. These operators help us in allocating a particular value to the operands. The main simple assignment operator is '='. We have to be sure that both the left and right sides of the operator must have the same data type. We have different levels of operators. Assignment operators are used to assign the value, variable and function to another variable. Assignment operators in C are some of the C Programming Operator, which are useful to assign the values to the declared variables. Let's discuss the various types of the assignment operators such as =, +=, -=, /=, *= and %=. The following table lists the assignment operators supported by the C language:

The if...else statement executes two different codes depending upon whether the test expression is true or false. Sometimes, a choice has to be made from more than 2 possibilities. The if...else ladder allows you to check between multiple test expressions and execute different statements. In C/C++ if-else-if ladder helps user decide from among multiple options. The C/C++ if statements are executed from the top down. As soon as one of the conditions controlling the if is true, the statement associated with that if is executed, and the rest of the C else-if ladder is bypassed. If none of the conditions is true, then the final else statement will be executed.

Allocate memory block. Allocates a block of size bytes of memory, returning a pointer to the beginning of the block. The content of the newly allocated block of memory is not initialized, remaining with indeterminate values. If size is zero, the return value depends on the particular library implementation (it may or may not be a null pointer), but the returned pointer shall not be dereferenced. Malloc function in C++ is used to allocate a specified size of the block of memory dynamically uninitialized. It allocates the memory to the variable on the heap and returns the void pointer pointing to the beginning address of the memory block. The values in the memory block allocated remain uninitialized and indeterminate. In case the size specified in the function is zero then pointer returned must not be dereferenced as it can be a null pointer, and in this case, behavior depends on particular library implementation. When a memory block is allocated dynamically memory is allocated on the heap but the pointer is

#include is a way of including a standard or user-defined file in the program and is mostly written at the beginning of any C/C++ program. This directive is read by the preprocessor and orders it to insert the content of a user-defined or system header file into the following program. These files are mainly imported from an outside source into the current program. The process of importing such files that might be system-defined or user-defined is known as File Inclusion. This type of preprocessor directive tells the compiler to include a file in the source code program.

It is a predefined function in "conio.h" (console input output header file) used to clear the console screen. It is a predefined function, by using this function we can clear the data from console (Monitor). Using of clrscr() is always optional but it should be place after variable or function declaration only. It is often used at the beginning of the program (mostly after variable declaration but not necessarily) so that the console is clear for our output.

A program shall contain a global function named main, which is the designated start of the program in hosted environment. main() function is the entry point of any C++ program. It is the point at which execution of program is started. When a C++ program is executed, the execution control goes directly to the main() function. Every C++ program have a main() function.

C++ sample ask to enter a number to reverse it, then check whether reverse is equal to its "original or not", if "it is equal" then it will be palindrome else it will be not be palindrome:

Insert x. Remove x (unimplemented). Return item that matches x. Return "smallest item". Return largest item. Return true if empty or else false. Print tree in sorted order. Return

It is an improvement in BST by adding 2 more key functions - 'rank()' and 'select()'. The time complexity of Order-Statistic tree generation is O(n+n*log(n)). Once the tree is constructed