# C++ Programming Code Examples

## C++ > Mathematics Code Examples

### Solving Quadratic Equations using Factorisation( Shows SOLUTION

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
/* Solving Quadratic Equations using Factorisation( Shows SOLUTION */ #include <stdlib.h> #include <iostream.h> #include <math.h> #include <conio.h> void main() { cout<<" Quadratic Equation Calculator"<<endl<<" by WWW"<<endl<<endl; float a,b,c,x,y; cout<<" Equation must be in the form of ax²+bx+c=0"<<endl<<endl; cout<<" Please enter the value of a: "; cin>>a; cout<<" Please enter the value of b: "; cin>>b; cout<<" Please enter the value of c: "; cin>>c; x=((-b+sqrt((b*b)-(4.0*a*c)))/(2.0*a)); y=((-b-sqrt((b*b)-(4*a*c)))/(2*a)); clrscr(); cout<<"HERE IS THE SOLUTION USING FACTORISATION "; cout.setf(ios::showpos); float mul=(x*-1)*(y*-1); cout<<" x²"<<(y*-1)+(x*-1)<<"x"<<mul<<"=0 "; cout<<" x²"<<y*-1<<"x"<<x*-1<<"x"<<(x*-1)*(y*-1)<<"=0 "; // x²+2x-1x-2=0 cout<<" x(x"<<y*-1<<")"<<x*-1<<"(x"<<y*-1<<")=0 "; // x(x+2)-1(x+2) cout<<" (x"<<x*-1<<")(x"<<y*-1<<")=0 "; // (x-1) (x+2)=0 cout.unsetf(ios::showpos); cout<<" x="<<x<<" & x="<<y<<" "; exit(EXIT_SUCCESS); }
setf() Function in C++
Set specific format flags. The function setf() sets the io stream format flags of the current stream to fmtfl. The optional mask argument specifies that only the flags that are in both fmtfl and mask should be set. The return value is the previous configuration of io stream format flags.
Syntax for setf() Function in C++
#include <iostream> /* set (1) */ fmtflags setf (fmtflags fmtfl); /* mask (2) */ fmtflags setf (fmtflags fmtfl, fmtflags mask);
fmtfl
Format flags to be set. If the second syntax is used, only the bits set in both fmtfl and mask are set in the stream's format flags; the flags set in mask but not in fmtfl are cleared.
Mask containing the flags to be modified. Member type fmtflags is a bitmask type (see ios_base::fmtflags). Function returns the format flags selected in the stream before the call. The first form (1) sets the stream's format flags whose bits are set in fmtfl, leaving unchanged the rest, as if a call to flags(fmtfl|flags()). The second form (2) sets the stream's format flags whose bits are set in both fmtfl and mask, and clears the format flags whose bits are set in mask but not in fmtfl, as if a call to flags((fmtfl&mask)|(flags()&~mask)). Both return the value of the stream's format flags before the call. The format flags of a stream affect the way data is interpreted in certain input functions and how it is written by certain output functions. See ios_base::fmtflags for the possible values of this function's arguments. The first form of setf (1) is generally used to set independent format flags: boolalpha, showbase, showpoint, showpos, skipws, unitbuf and uppercase, which can also be unset directly with member unsetf. The second form (2) is generally used to set a value for one of the selective flags, using one of the field bitmasks as the mask argument: fmtfl (format flag value) mask (field bitmask) left, right or internal adjustfield dec, oct or hex basefield scientific or fixed floatfield Flags for setf() function: ios::dec -- use decimal base for integer I/O ios::oct -- use octal base for integer I/O ios::hex -- use hexadecimal base for integer I/O ios::basefield -- dec|oct|hex. Useful for masking operations ios::internal -- internal adjustment (adds fill characters to the internal designated point) ios::adjustfield -- left|right|internal. Useful for masking operations ios::floatfield -- scientific|fixed. Useful for masking operations ios::boolalpha -- insert and extract bool type in alphanumeric format ios::showbase -- generate a prefix indicating the numeric base for integer output, require the currency indicator in monetary I/O ios::showpos -- generate a + character for non-negative numeric output ios::skipws -- skip leading whitespace before certain input operations ios::unitbuf -- flush the output after each output operation ios::uppercase -- replace certain lowercase letters with their uppercase equivalents in certain output operations ios::fixed -- to specify that floating-point numbers will be printed in fixed notation. ios::scientific -- to specify that floating-point numbers will be printed in scientific (exponential) notation. ios::showpoint -- specifies that the decimal point will always be printed for floating point types (even if the value is a whole number, like 4.0. ios::right -- right-justifies an output item in a field, if a field width is specified. ios::left -- left-justifies an output item in a field, if a field width is specified.
Data races
Modifies the stream object. Concurrent access to the same stream object may cause data races.
Exception safety
Basic guarantee: if an exception is thrown, the stream is in a valid state.
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
/* set specific format flags by setf() function code example */ #include <iostream> using namespace std; int main(void){ cout << true << " " << false << endl; cout.setf(ios_base::boolalpha); cout << true << " " << false << endl; cout << 192.168 << " "; cout.setf(ios_base::scientific, ios_base::floatfield); cout << 192.168 << endl; cout.width(30); cout << "Saluton, Mundo!" << endl; cout.setf(ios_base::left, ios_base::adjustfield); cout.width(30); cout << "Saluton, Mundo!" << endl; return 0; }
Bitwise Operators in C++
The bitwise operators are the operators used to perform the operations on the data at the bit-level. When we perform the bitwise operations, then it is also known as bit-level programming. It consists of two digits, either 0 or 1. It is mainly used in numerical computations to make the calculations faster. We have different types of bitwise operators in the C++ programming language. The following is the list of the bitwise operators:
&
Bitwise AND operator is denoted by the single ampersand sign (&). Two integer operands are written on both sides of the (&) operator. If the corresponding bits of both the operands are 1, then the output of the bitwise AND operation is 1; otherwise, the output would be 0. This is one of the most commonly used logical bitwise operators. It is represented by a single ampersand sign (&). Two integer expressions are written on each side of the (&) operator. The result of the bitwise AND operation is 1 if both the bits have the value as 1; otherwise, the result is always 0. The bitwise AND operator is a single ampersand: &. A handy mnemonic is that the small version of the boolean AND, &&, works on smaller pieces (bits instead of bytes, chars, integers, etc). In essence, a binary AND simply takes the logical AND of the bits in each position of a number in binary form. 01001000 & 10111000 = 00001000 The most significant bit of the first number is 0, so we know the most significant bit of the result must be 0; in the second most significant bit, the bit of second number is zero, so we have the same result. The only time where both bits are 1, which is the only time the result will be 1, is the fifth bit from the left.
|
Bitwise OR operator is represented by a single vertical sign (|). Two integer operands are written on both sides of the (|) symbol. If the bit value of any of the operand is 1, then the output would be 1, otherwise 0. It is represented by a single vertical bar sign (|). Two integer expressions are written on each side of the (|) operator. The result of the bitwise OR operation is 1 if at least one of the expression has the value as 1; otherwise, the result is always 0. Bitwise OR works almost exactly the same way as bitwise AND. The only difference is that only one of the two bits needs to be a 1 for that position's bit in the result to be 1. (If both bits are a 1, the result will also have a 1 in that position.) The symbol is a pipe: |. Again, this is similar to boolean logical operator, which is ||. 01001000 | 10111000 = 11111000
^
Bitwise exclusive OR operator is denoted by (^) symbol. Two operands are written on both sides of the exclusive OR operator. If the corresponding bit of any of the operand is 1 then the output would be 1, otherwise 0. The bitwise XOR ^ operator returns 1 if and only if one of the operands is 1. However, if both the operands are 0, or if both are 1, then the result is 0. The following truth table demonstrates the working of the bitwise XOR operator. Let a and b be two operands that can only take binary values i.e. 1 or 0. There is no boolean operator counterpart to bitwise exclusive-or, but there is a simple explanation. The exclusive-or operation takes two inputs and returns a 1 if either one or the other of the inputs is a 1, but not if both are. That is, if both inputs are 1 or both inputs are 0, it returns 0. Bitwise exclusive-or, with the operator of a caret, ^, performs the exclusive-or operation on each pair of bits. Exclusive-or is commonly abbreviated XOR. 01110010 ^ 10101010 = 11011000
~
Bitwise complement operator is also known as one's complement operator (unary operator). It is represented by the symbol tilde (~). It takes only one operand or variable and performs complement operation on an operand. When we apply the complement operation on any bits, then 0 becomes 1 and 1 becomes 0. The bitwise complement operator, the tilde, ~, flips every bit. A useful way to remember this is that the tilde is sometimes called a twiddle, and the bitwise complement twiddles every bit: if you have a 1, it's a 0, and if you have a 0, it's a 1. The bitwise complement is also called as one's complement operator since it always takes only one value or an operand. It is a unary operator. When we perform complement on any bits, all the 1's become 0's and vice versa. If we have an integer expression that contains 0000 1111 then after performing bitwise complement operation the value will become 1111 0000. Bitwise complement operator is denoted by symbol tilde (~). The bitwise shift operators are used to move/shift the bit patterns either to the left or right side. Left and right are two shift operators provided by 'C' which are represented as follows: Operand << n (Left Shift), Operand >> n (Right Shift) an operand is an integer expression on which we have to perform the shift operation. 'n' is the total number of bit positions that we have to shift in the integer expression.
<<
Left-shift operator - It is an operator that shifts the number of bits to the left-side. Left shift operator shifts all bits towards left by a certain number of specified bits. The bit positions that have been vacated by the left shift operator are filled with 0. The symbol of the left shift operator is <<. The left shift operation will shift the 'n' number of bits to the left side. The leftmost bits in the expression will be popped out, and n bits with the value 0 will be filled on the right side.
>>
Right-shift operator - It is an operator that shifts the number of bits to the right side. Right shift operator shifts all bits towards right by certain number of specified bits. It is denoted by >>. The right shift operation will shift the 'n' number of bits to the right side. The rightmost 'n' bits in the expression will be popped out, and the value 0 will be filled on the left side. X Y X&Y X|Y X^Y 0 0 0 0 0 0 1 0 1 1 1 0 0 1 1 1 1 1 1 1 Shifts operators can be combined then it can be used to extract the data from the integer expression.
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
/* bitwise operators in C++ language*/ #include <iostream> using namespace std; int main() { // a = 5(00000101), b = 9(00001001) int a = 5, b = 9; // The result is 00000001 cout<<"a = " << a <<","<< " b = " << b <<endl; cout << "a & b = " << (a & b) << endl; // The result is 00001101 cout << "a | b = " << (a | b) << endl; // The result is 00001100 cout << "a ^ b = " << (a ^ b) << endl; // The result is 11111010 cout << "~(" << a << ") = " << (~a) << endl; // The result is 00010010 cout<<"b << 1" <<" = "<< (b << 1) <<endl; // The result is 00000100 cout<<"b >> 1 "<<"= " << (b >> 1 )<<endl; return 0; }
clrscr() Function in C++
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
/* clrscr() function is also a non-standard function defined in "conio.h" header. This function is used to clear the console screen. 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.*/ #include<iostream.h> #include<conio.h> void main() { int a=10, b=20; int sum=0; clrscr(); // use clrscr() after variable declaration sum=a+b; cout<<"Sum: "<<sum; //clear the console screen clrscr(); getch(); }
Standard Input Stream (cin) in C++
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.
Syntax for Standard Input Stream (cin) in C++
cin >> var_name;
>>
is the extraction operator.
var_name
is usually a variable, but can also be an element of containers like arrays, vectors, lists, etc. 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 >> operator can also be used more than once in the same statement to accept multiple inputs. The cin object can also be used with other member functions such as getline(), read(), etc. Some of the commonly used member functions are: • cin.get(char &ch): Reads an input character and stores it in ch. • cin.getline(char *buffer, int length): Reads a stream of characters into the string buffer, It stops when: it has read length-1 characters or when it finds an end-of-line character '\n' or the end of the file eof. • cin.read(char *buffer, int n): Reads n bytes (or until the end of the file) from the stream into the buffer. • cin.ignore(int n): Ignores the next n characters from the input stream. • cin.eof(): Returns a non-zero value if the end of file (eof) is reached. The prototype of cin as defined in the iostream header file is: extern istream cin; The cin object in C++ is an object of class istream. It is associated with the standard C input stream stdin. The cin object is ensured to be initialized during or before the first time an object of type ios_base::Init is constructed. After the cin object is constructed, cin.tie() returns &cout. This means that any formatted input operation on cin forces a call to cout.flush() if any characters are pending for output.
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
/* Standard Input Stream (cin) in C++ language */ // cin with Member Functions #include <iostream> using namespace std; int main() { char name[20], address[20]; cout << "Name: "; // use cin with getline() cin.getline(name, 20); cout << "Address: "; cin.getline(address, 20); cout << endl << "You entered " << endl; cout << "Name = " << name << endl; cout << "Address = " << address; return 0; }
exit() Function in C++
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.
Syntax for exit() Function in C++
void exit (int status);
status
Status code. If this is 0 or EXIT_SUCCESS, it indicates success. If it is EXIT_FAILURE, it indicates failure. 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().) Functions registered with atexit() are called in the reverse order of their registration. A function registered with atexit(), before an object obj1 of static storage duration is initialized, will not be called until obj1's destruction has completed. A function registered with atexit(), after an object obj2 of static storage duration is initialized, will be called before obj2's destruction starts. Normal program termination performs the following (in the same order): • Objects associated with the current thread with thread storage duration are destroyed (C++11 only). • Objects with static storage duration are destroyed (C++) and functions registered with atexit are called. • All C streams (open with functions in <cstdio>) are closed (and flushed, if buffered), and all files created with tmpfile are removed. • Control is returned to the host environment. Note that objects with automatic storage are not destroyed by calling exit (C++). If status is zero or EXIT_SUCCESS, a successful termination status is returned to the host environment. If status is EXIT_FAILURE, an unsuccessful termination status is returned to the host environment. Otherwise, the status returned depends on the system and library implementation. Flushes all buffers, and closes all open files. All files opened with tmpfile() are deleted. Returns control to the host environment from the program. exit() returns no values.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
/* terminate the process normally, performing the regular cleanup for terminating programs by exit() function code example */ #include<iostream> using namespace std; int main() { int i; cout<<"Enter a non-zero value: "; //user input cin>>i; if(i) // checks whether the user input is non-zero or not { cout<<"Valid input.\n"; } else { cout<<"ERROR!"; //the program exists if the value is 0 exit(0); } cout<<"The input was : "<<i; }
Standard Output Stream (cout) in C++
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.
Syntax for cout in C++
cout << var_name; //or cout << "Some String";
The syntax of the cout object in C++: cout << var_name; Or cout << "Some String";
<<
is the insertion operator
var_name
is usually a variable, but can also be an array element or elements of containers like vectors, lists, maps, etc. 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. The << operator can be used more than once with a combination of variables, strings, and manipulators. cout is used for displaying data on the screen. The operator << called as insertion operator or put to operator. The Insertion operator can be overloaded. Insertion operator is similar to the printf() operation in C. cout is the object of ostream class. Data flow direction is from variable to output device. Multiple outputs can be displayed using cout.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
/* standard output stream (cout) in C++ language */ #include <iostream> using namespace std; int main() { string str = "Do not interrupt me"; char ch = 'm'; // use cout with write() cout.write(str,6); cout << endl; // use cout with put() cout.put(ch); return 0; }
main() Function in C++
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.
Syntax for main() Function in C++
void main() { ............ ............ }
void
void is a keyword in C++ language, void means nothing, whenever we use void as a function return type then that function nothing return. here main() function no return any value.
main
main is a name of function which is predefined function in C++ library. In place of void we can also use int return type of main() function, at that time main() return integer type value. 1) It cannot be used anywhere in the program a) in particular, it cannot be called recursively b) its address cannot be taken 2) It cannot be predefined and cannot be overloaded: effectively, the name main in the global namespace is reserved for functions (although it can be used to name classes, namespaces, enumerations, and any entity in a non-global namespace, except that a function called "main" cannot be declared with C language linkage in any namespace). 3) It cannot be defined as deleted or (since C++11) declared with C language linkage, constexpr (since C++11), consteval (since C++20), inline, or static. 4) The body of the main function does not need to contain the return statement: if control reaches the end of main without encountering a return statement, the effect is that of executing return 0;. 5) Execution of the return (or the implicit return upon reaching the end of main) is equivalent to first leaving the function normally (which destroys the objects with automatic storage duration) and then calling std::exit with the same argument as the argument of the return. (std::exit then destroys static objects and terminates the program). 6) (since C++14) The return type of the main function cannot be deduced (auto main() {... is not allowed). 7) (since C++20) The main function cannot be a coroutine.
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
/* simple code example by main() function in C++ */ #include <iostream> using namespace std; int main() { int day = 4; switch (day) { case 1: cout << "Monday"; break; case 2: cout << "Tuesday"; break; case 3: cout << "Wednesday"; break; case 4: cout << "Thursday"; break; case 5: cout << "Friday"; break; case 6: cout << "Saturday"; break; case 7: cout << "Sunday"; break; } return 0; }
sqrt() Function in C++
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. Additional overloads are provided in this header (<cmath>) for the integral types: These overloads effectively cast x to a double before calculations (defined for T being any integral type). This function is also overloaded in <complex> and <valarray> (see complex sqrt and valarray sqrt).
Syntax for sqrt() Function in C++
#include <cmath> double sqrt (double x); float sqrt (float x); long double sqrt (long double x); double sqrt (T x); // additional overloads for integral types
x
Value whose square root is computed. If the argument is negative, a domain error occurs. The sqrt() function takes the following parameter: x - a non-negative number whose square root is to be computed. The sqrt() function returns the square root of the given argument If a negative argument is passed to sqrt(), domain error occurs.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
/* compute square root by sqrt() math function code example */ // C++ code to demonstrate the example of sqrt() function #include <iostream> #include <cmath> using namespace std; // main code section int main() { float x; //input the value cout<<"Enter a number: "; cin>>x; // calculate the square root float result = sqrt(x); cout<<"square root of "<<x<<" is = "<<result; cout<<endl; return 0; }
#include Directive in C++
#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.
Syntax for #include Directive in C++
#include "user-defined_file"
Including using " ": When using the double quotes(" "), the preprocessor access the current directory in which the source "header_file" is located. This type is mainly used to access any header files of the user's program or user-defined files.
Including using <>: While importing file using angular brackets(<>), the the preprocessor uses a predetermined directory path to access the file. It is mainly used to access system header files located in the standard system directories. Header File or Standard files: This is a file which contains C/C++ function declarations and macro definitions to be shared between several source files. Functions like the printf(), scanf(), cout, cin and various other input-output or other standard functions are contained within different header files. So to utilise those functions, the users need to import a few header files which define the required functions. User-defined files: These files resembles the header files, except for the fact that they are written and defined by the user itself. This saves the user from writing a particular function multiple times. Once a user-defined file is written, it can be imported anywhere in the program using the #include preprocessor. • In #include directive, comments are not recognized. So in case of #include <a//b>, a//b is treated as filename. • In #include directive, backslash is considered as normal text not escape sequence. So in case of #include <a\nb>, a\nb is treated as filename. • You can use only comment after filename otherwise it will give error.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
/* using #include directive in C language */ #include <stdio.h> int main() { /* * C standard library printf function * defined in the stdio.h header file */ printf("I love you Clementine"); printf("I love you so much"); printf("HappyCodings"); return 0; }
IOS Library unsetf() Function C++
Clear specific format flags. Clears the format flags selected in mask. Function unsets the formatting flags identified by flags. The parameterized manipulator resetiosflags behaves in a similar way as this member function.
Syntax for IOS unsetf() Function C++
#include <iostream> void unsetf (fmtflags mask);
Bitmask specifying the flags to be cleared. The flags are specified as a combination of flags of the fmtflags member type. This function does not return any value.
Data races
Modifies the stream object. Concurrent access to the same stream object may cause data races.
Exception safety
Basic guarantee: if an exception is thrown, the stream is in a valid state.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
/* IOS Library unsetf is used to clear specific format flags. */ /* The function unsetf() uses flags to clear the io stream format flags associated with the current stream. */ /* modifying flags with setf / unsetf */ // clearing flags #include <iostream> using namespace std; int main () { cout.setf ( ios_base::hex, ios_base::basefield ); // set hex as the basefield cout.setf ( ios_base::showbase ); // activate showbase cout << 100 << endl; cout.unsetf ( ios_base::showbase ); // deactivate showbase cout << 100 << endl; return 0; }
Standard end line (endl) in C++
A predefined object of the class called iostream class is used to insert the new line characters while flushing the stream is called endl in C++. This endl is similar to \n which performs the functionality of inserting new line characters but it does not flush the stream whereas endl does the job of inserting the new line characters while flushing the stream. Hence the statement cout<<endl; will be equal to the statement cout<< '\n' << flush; meaning the new line character used along with flush explicitly becomes equivalent to the endl statement in C++.
Syntax for end line (endl) in C++
cout<< statement to be executed <<endl;
Whenever the program is writing the output data to the stream, all the data will not be written to the terminal at once. Instead, it will be written to the buffer until enough data is collected in the buffer to output to the terminal. But if are using flush in our program, the entire output data will be flushed to the terminal directly without storing anything in the buffer. Whenever there is a need to insert the new line character to display the output in the next line while flushing the stream, we can make use of endl in C++. Whenever there is a need to insert the new line character to display the output in the next line, we can make use of endl in '\n' character but it does not do the job of flushing the stream. So if we want to insert a new line character along with flushing the stream, we make use of endl in C++. Whenever the program is writing the output data to the stream, all the data will not be written to the terminal at once. Instead, it will be written to the buffer until enough data is collected in the buffer to output to the terminal. • It is a manipulator. • It doesn't occupy any memory. • It is a keyword and would not specify any meaning when stored in a string. • We cannot write 'endl' in between double quotations. • It is only supported by C++. • It keeps flushing the queue in the output buffer throughout the process.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
/* Standard end line (endl) in C++ language */ //The header file iostream is imported to enable us to use cout in the program #include <iostream> //a namespace called std is defined using namespace std; //main method is called int main( ) { //cout is used to output the statement cout<< "Welcome to "; //cout is used to output the statement along with endl to start the next statement in the new line and flush the output stream cout<< "C#"<<endl; //cout is used to output the statement along with endl to start the next statement in the new line and flush the output stream cout<< "Learning is fun"<<endl; }
Arithmetic Operators in C++
Arithmetic Operator is used to performing mathematical operations such as addition, subtraction, multiplication, division, modulus, etc., on the given operands. For example: 6 + 3 = 9, 5 - 3 = 2, 3 * 4 = 12, etc. are the examples of arithmetic operators. Let's discuss the different types of Arithmetic Operators in the C programming.
+
Plus Operator is a simple Plus (+) Operator used to add two given operands. We can use Plus Operator with different data types such as integer, float, long, double, enumerated and string type data to add the given operand.
-
The minus operator is denoted by the minus (-) symbol. It is used to return the subtraction of the first number from the second number. The data type of the given number can be different types, such as int, float, double, long double, etc., in the programing language.
*
The multiplication operator is represented as an asterisk (*) symbol, and it is used to return the product of n1 and n2 numbers. The data type of the given number can be different types such as int, float, and double in the C programing language.
/
The division operator is an arithmetic operator that divides the first (n1) by the second (n2) number. Using division operator (/), we can divide the int, float, double and long data types variables.
%
The modulus operator is represented by the percentage sign (%), and it is used to return the remainder by dividing the first number by the second number.
++
Increment Operator is the type of Arithmetic operator, which is denoted by double plus (++) operator. It is used to increase the integer value by 1.
--
Decrement Operator is denoted by the double minus (--) symbol, which decreases the operand value by 1.
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
/* Perhaps you have warm memories of doing arithmetic drills in grade school. You can give that same pleasure to your computer. C++ uses operators to do arithmetic. It provides operators for five basic arithmetic calculations: addition, subtraction, multiplication, division, and taking the modulus. Each of these operators uses two values (called operands) to calculate a final answer. Together, the operator and its operands constitute an expression. */ #include <iostream> using namespace std; int main() { int a, b; a = 7; b = 2; // printing the sum of a and b cout << "a + b = " << (a + b) << endl; // printing the difference of a and b cout << "a - b = " << (a - b) << endl; // printing the product of a and b cout << "a * b = " << (a * b) << endl; // printing the division of a by b cout << "a / b = " << (a / b) << endl; // printing the modulo of a by b cout << "a % b = " << (a % b) << endl; return 0; }

What are "Constants"? Constants refer to as fixed values, unlike variables whose value can be altered, constants -- as the name implies does not change, they remain constant. And
Bipartite Graph is a graph in which the set of 'vertices' can be divided into 2 sets such that all vertex should be present in either set 1 or set 2 but not both, and there should no edge
Program, using recursion, evaluates a Prefix Expression in an "Expression Tree". A binary expression tree is a specific application of a 'binary tree' to evaluate certain expressions.