# C++ Programming Code Examples

## C++ > Sorting Searching Code Examples

### Search Sorted Sequence Using Divide and Conquer with the Aid of Fibonacci Numbers

/* Search Sorted Sequence Using Divide and Conquer with the Aid of Fibonacci Numbers - It implements a Divide and Conquer approach using Fibonacci numbers. - Using Fibonacci numbers we calculate mid of data array to search the data item. - The time complexity is O(log(n)). - Calculate the mid of the array. - Divide the array into two sub-array. - Compare the item with mid element and proceed accordingly. - Exit. C++ program to implement Fibonacci Search. */ #include<iostream> using namespace std; void FibonacciSearch(int *a, int start, int end, int *fab, int index, int item) { int i, mid; // Assigning middle of the array using Fibonacci element. mid = start+fab[index-2]; // Return if item found at mid index. if(item == a[mid]) { cout<<"\n item found at "<<mid<<" index."; return; } // Return if item found at start index. else if(item == a[start]) { cout<<"\n item found at "<<start<<" index."; return; } // Return if item found at end index. else if(item == a[end]) { cout<<"\n item found at "<<end<<" index."; return; } // If mid becomes start or end of the sub-array then element not found. else if(mid == start || mid == end) { cout<<"\nElement not found"; return; } // According to the item value choose the partion to proceed further. else if(item > a[mid]) FibonacciSearch(a, mid, end, fab, index-1, item); else FibonacciSearch(a, start, mid, fab, index-2, item); } main() { int n, i, biter, fab[20], a[20]={2, 9, 19, 23, 25, 36, 39, 43, 49, 57, 59, 66, 69, 74, 75, 77, 88, 89, 96, 97}; char ch; fab[0] = 0; fab[1] = 1; i = 1; while(fab[i] < 20) { i++; fab[i] = fab[i-1]+fab[i-2]; } up: cout<<"\nEnter the Element to be searched: "; cin>>n; // Implement Fibonacci search. FibonacciSearch(a, 0, 19, fab, i, n); // Ask user to enter choice for further searching. cout<<"\n\n\tDo you want to search more...enter choice(y/n)?"; cin>>ch; if(ch == 'y' || ch == 'Y') goto up; return 0; }

Logical Operators are used to compare and connect two or more expressions or variables, such that the value of the expression is completely dependent on the original expression or value or variable. We use logical operators to check whether an expression is true or false. If the expression is true, it returns 1 whereas if the expression is false, it returns 0. Assume variable A holds 1 and variable B holds 0:

Compute natural logarithm. Returns the natural logarithm of x. The natural logarithm is the base-e logarithm: the inverse of the natural exponential function (exp). For common (base-10) logarithms, see log10. The C/C++ library function double log(double x) returns the natural logarithm (base-e logarithm) of x. Function returns natural logarithm of x. If x is negative, it causes a domain error. If x is zero, it may cause a pole error (depending on the library implementation).

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.

In C++, goto is a jump statement and sometimes also referred as unconditional jump statement. It can be used to jump from goto to a labeled statement within the same function. The target label must be within the same file and context. Please note that the use of goto statement is highly discouraged in any programming language because it makes difficult to trace the control flow of a program, making hard to understand and modify the program.

Consider a situation, when we have two persons with the same name, jhon, in the same class. Whenever we need to differentiate them definitely we would have to use some additional information along with their name, like either the area, if they live in different area or their mother's or father's name, etc. Same situation can arise in your C++ applications. For example, you might be writing some code that has a function called xyz() and there is another library available which is also having same function xyz(). Now the compiler has no way of knowing which version of xyz() function you are referring to within your code.

A relational operator is used to check the relationship between two operands. C++ Relational Operators are used to relate or compare given operands. Relational operations are like checking if two operands are equal or not equal, greater or lesser, etc. Relational Operators are also called Comparison Operators.

#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.

Search range for subsequence. Searches the range [first1,last1) for the first occurrence of the sequence defined by [first2,last2), and returns an iterator to its first element, or last1 if no occurrences are found. The elements in both ranges are compared sequentially using operator== (or pred, in version (2)): A subsequence of [first1,last1) is considered a match only when this is true for all the elements of [first2,last2). This function returns the first of such occurrences. For an algorithm that returns the last instead, see find_end. The function shall not modify any of its arguments.

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.

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.

An array is defined as the collection of similar type of data items stored at contiguous memory locations. Arrays are the derived data type in C++ programming language which can store the primitive type of data such as int, char, double, float, etc. It also has the capability to store the collection of derived data types, such as pointers, structure, etc. The array is the simplest data structure where each data element can be randomly accessed by using its index number. C++ array is beneficial if you have to store similar elements. For example, if we want to store the marks of a student in 6 subjects, then we don't need to define different variables for the marks in the different subject. Instead of that, we can define an array which can store the marks in each subject at the contiguous memory locations.

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.

The cin object is used to accept input from the standard input device i.e. keyboard. It is defined in the iostream header file. C++ cin statement is the instance of the class istream and is used to read input from the standard input device which is usually a keyboard. The extraction operator(>>) is used along with the object cin for reading inputs. The extraction operator extracts the data from the object cin which is entered using the keyboard. The "c" in cin refers to "character" and "in" means "input". Hence cin means "character input". The cin object is used along with the extraction operator >> in order to receive a stream of characters.

The cout is a predefined object of ostream class. It is connected with the standard output device, which is usually a display screen. The cout is used in conjunction with stream insertion operator (<<) to display the output on a console. On most program environments, the standard output by default is the screen, and the C++ stream object defined to access it is cout. The "c" in cout refers to "character" and "out" means "output". Hence cout means "character output". The cout object is used along with the insertion operator << in order to display a stream of characters.

To 'write' some content in a file in C++, enter the file name with extension to open that file using the function open(), then after opening the desired file, again ask to the user to enter