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++ > Algorithms Code Examples

Quadratic Equation

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141
/* Quadratic Equation */ #include <math.h> #include <iostream> using namespace std; struct graphPoint{ double x, y; }; class QuadraticEquation{ public: QuadraticEquation(double A = 0.0, double B = 0.0, double C = 0.0) : a(A), b(B), c(C){ xintercepts[0].x = 0.0; xintercepts[0].y = 0.0; xintercepts[1].x = 0.0; xintercepts[1].y = 0.0; } ~QuadraticEquation(){} int getxintercepts(){ double temp = (b * b) - (4 * a * c); if(temp < 0){ cout << "##-Square Root Error:\n" << " ##- SquareRoot ( " << temp << " )\n"; return 1; } temp = sqrt ( temp ); xintercepts[0].x = (b * -1) - temp; xintercepts[0].x = xintercepts[0].x / (2 * a); xintercepts[1].x = (b * -1) + temp; xintercepts[1].x = xintercepts[1].x / (2 * a); return 0; } void displayequation(){ if(a != 0){ cout << a; cout << "x^2";} if(b >= 1 & a != 0) cout << "+"; if(b != 0) cout << b << "x"; if(c > 0) cout << "+"; if(c != 0) cout << c; if(a == 0 & b == 0 & c == 0) cout << 0; cout << "=0" << endl; } double a, b, c; graphPoint xintercepts[2]; }; void creditsHelp(); void wierdGetch(); int main(int argc, char *argv[]){ cout << "@-Quadratic Equation Solver\n" << " @-Karlan Mitchell karlanmitchell-at-comcast-dot-net\n" << " @-For Credits/Help enter 0 for A\n"; double a,b,c; cout << "Enter in values for equation\n"; for(;;){ cout << "A: "; cin >> a; if(a == 0.0){ creditsHelp(); continue; } break; } cout << "B: "; cin >> b; cout << "C: "; cin >> c; QuadraticEquation test(a,b,c);//create the class test.displayequation();//display the equation with the class function switch(test.getxintercepts()){/* I am using a switch here instead of * an if because I constanly add/remove * error messages to this function*/ case 1: cout << "!!-Equation not possible\n" << " !!-If you know that it is possible, please contact me about a bug\n"; exit(1); break; } cout << "x = " << test.xintercepts[0].x << " | " << test.xintercepts[1].x << endl; cout << "(" << test.xintercepts[0].x << ", 0) & (" << test.xintercepts[1].x << ", 0)\n"; wierdGetch(); return 0; } void creditsHelp(){ cout << "\nThis program was created by me to make my math homework easier\n\n" << "What it does:\n" << "It takes in the 'a', 'b', and 'c' values for a quadratic equation\n" << "which equals zero.\n" << "EX: \"x^2 - 3x + 2 = 0\" is equal to \"(x - 2)(x - 1) = 0\"\n" << " ax^2 + bx + c = 0\n" << " The 'a','b', and 'c' values for the equation would be 1, -3, and 2\n" << " The x intercepts for this would be (2, 0) and (1, 0)\n" << " 2^2 - 3(2) + 2 = 0 and 1^2 - 3(1) + 2 = 0\n\n" << "Why would I use this:\n" << "1) You are in Algebra I/II or Geometry\n" << "2) Your too lazy to do the quadratic equation on your own which is:\n" << " x=( -b +/- sqrt(bb - 4ac) ) / (2a)\n"; wierdGetch(); exit(0); } void wierdGetch(){ cout << "Press enter to exit..."; getchar();getchar();//Why do I need, two? The world may never know }

Compute square root. Returns the square root of x. The sqrt() function in C++ returns the square root of a number. This function is defined in the cmath header file. There are various functions available in the C++ Library to calculate the square root of a number. Most prominently, sqrt is used. It takes double as an argument. The <cmath> header defines two more inbuilt functions for calculating the square root of a number (apart from sqrt) which has an argument of type float and long double. Therefore, all the functions used for calculating square root in C++ are. Mathematically, sqrt(x) = √x.

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().)

Break statement in C++ is a loop control statement defined using the break keyword. It is used to stop the current execution and proceed with the next one. When a compiler calls the break statement, it immediately stops the execution of the loop and transfers the control outside the loop and executes the other statements. In the case of a nested loop, break the statement stops the execution of the inner loop and proceeds with the outer loop. The statement itself says it breaks the loop. When the break statement is called in the program, it immediately terminates the loop and transfers the flow control to the statement mentioned outside the loop.

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.

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

The main purpose of C++ programming is to add object orientation to the C programming language and classes are the central feature of C++ that supports object-oriented programming and are often called user-defined types. A class is used to specify the form of an object and it combines data representation and methods for manipulating that data into one neat package. The data and functions within a class are called members of the class.

In computer programming, loops are used to repeat a block of code. For example, when you are displaying number from 1 to 100 you may want set the value of a variable to 1 and display it 100 times, increasing its value by 1 on each loop iteration. When you know exactly how many times you want to loop through a block of code, use the for loop instead of a while loop. A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times.

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.

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.

Get character from stdin. Returns the next character from the standard input (stdin). It is equivalent to calling getc with stdin as argument. The getchar() function is equivalent to a call to getc(stdin). It reads the next character from stdin which is usually the keyboard. getc() can read from any input stream, but getchar() reads from standard input. So getchar() is equivalent to getc(stdin). This function does not accept any parameter. On success, the character read is returned (promoted to an int value).

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.

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.

Switch statement in C tests the value of a variable and compares it with multiple cases. Once the case match is found, a block of statements associated with that particular case is executed. Each case in a block of a switch has a different name/number which is referred to as an identifier. The value provided by the user is compared with all the cases inside the switch block until the match is found. If a case match is NOT found, then the default statement is executed, and the control goes out of the switch block. • The expression can be integer expression or a character expression. • Value-1, 2, n are case labels which are used to identify each case individually. Remember that case labels should not be same as it may create a problem while executing a program. Suppose we have two cases with the same label as '1'. Then while executing the program, the case that appears first will be executed even though you want the program to execute a second case. This creates problems in the program and

Continue statement is used inside loops. Whenever a continue statement is encountered inside a loop, control directly jumps to the beginning of the loop for next iteration, skipping the execution of statements inside loop's body for the current iteration. The continue statement works somewhat like the break statement. Instead of forcing termination, however, continue forces the next iteration of the loop to take place, skipping any code in between. For the for loop, continue causes the conditional test and increment portions of the loop to execute. For the while and do...while loops, program control passes to the conditional tests.

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.

Return bit value. Returns whether the bit at position pos is set (i.e., whether it is one). C++ bitset test() function is used to test whether the bit at position p is set or not. The C++ bitset::test function is used to check if the bit at specified position is set or not. It returns true if the bit at specified position is set, else returns false. Unlike the access operator (operator[]), this function performs a range check on pos before retrieveing the bit value, throwing out_of_range if pos is equal or greater than the bitset size.

In C++, constructor is a special method which is invoked automatically at the time of object creation. It is used to initialize the data members of new object generally. The constructor in C++ has the same name as class or structure. Constructors are special class functions which performs initialization of every object. The Compiler calls the Constructor whenever an object is created. Constructors initialize values to object members after storage is allocated to the object. Whereas, Destructor on the other hand is used to destroy the class object. • Default Constructor: A constructor which has no argument is known as default constructor. It is invoked at the time of creating object.

A destructor is a special member function that works just opposite to constructor, unlike constructors that are used for initializing an object, destructors destroy (or delete) the object. Destructors in C++ are members functions in a class that delete an object. They are called when the class object goes out of scope such as when the function ends, the program ends, a delete variable is called etc. Destructors are different from normal member functions as they don't take any argument and don't return anything. Also, destructors have the same name as their class and their name is preceded by a tilde(~).

Internal method to test if a positive number is prime. Not efficient algorithm. Using Internal method to return a prime number at least as large as n. Assumes "n > 0". Insert item x into

To convert temperature from "Fahrenheit" to centigrade in C++, enter the "temperature" in Fahrenheit to convert it to centigrade to print equivalent temperature value in "centigrade"

C++ Program to "Print Preorder Traversal" of a given binray tree without using recursion. A binary tree node has data, left child and right child. "Helper Function" that allocates a new