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

Formatted IO using IO manipulators

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
/* Formatted IO using IO manipulators */ #include <iostream> #include <iomanip> using namespace std; int main() { float num[5] = {1.0, -1.2345, 2350.1, 23.4, 45.34}; int i; cout << setiosflags(ios::showpos); cout << setiosflags(ios::scientific); cout << setprecision(2); for(i = 0; i < 5; i++) { cout << setw(20); cout << setfill('$'); cout << num[i] << endl; } return 0; }
Iomanip Library setprecision() Function in C++
Set decimal precision. Sets the decimal precision to be used to format floating-point values on output operations. Behaves as if member precision were called with n as argument on the stream on which it is inserted/extracted as a manipulator (it can be inserted/extracted on input streams or output streams). This manipulator is declared in header <iomanip>.
Syntax for setprecision() Function in C++
#include <iomanip> /*unspecified*/ setprecision (int n);
n
New value for the decimal precision. This method accepts n as a parameter which is the integer argument corresponding to which the floating-point precision is to be set. This function returns an object of unspecified type. The setbase function should only be used as a stream manipulator.
Data races
The stream object on which it is inserted/extracted is modified. Concurrent access to the same stream object may introduce 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 33 34 35 36
/* set the ios library floating point precision based on the precision specified as the parameter to this method by setprecision() function code example. */ // C++ code to demonstrate the working of setprecision() function #include <iomanip> #include <ios> #include <iostream> using namespace std; int main() { // Initializing the decimal double num = 3.142857142857; cout << "Before setting the precision: \n" << num << endl; // Using setprecision() cout << "Setting the precision using" << " setprecision to 5: \n" << setprecision(5); cout << num << endl; // Using setprecision() cout << "Setting the precision using" << " setprecision to 9 : \n " << setprecision(9); cout << num << endl; 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; }
IOS Library precision() Function in C++
The floating-point precision determines the maximum number of digits to be written on insertion operations to express floating-point values. How this is interpreted depends on whether the floatfield format flag is set to a specific notation (either fixed or scientific) or it is unset (using the default notation, which is not necessarily equivalent to either fixed nor scientific). Get/Set floating-point decimal precision. The first form (1) returns the value of the current floating-point precision field for the stream. The second form (2) also sets it to a new value.
Syntax for precision() Function in C++
#include <iostream> //get (1) streamsize precision() const; //set (2) streamsize precision (streamsize prec);
prec
New value for the floating-point precision. streamsize is a signed integral value. Function returns the precision selected in the stream before the call. For the default locale: Using the default floating-point notation, the precision field specifies the maximum number of meaningful digits to display in total counting both those before and those after the decimal point. Notice that it is not a minimum, and therefore it does not pad the displayed number with trailing zeros if the number can be displayed with less digits than the precision. In both the fixed and scientific notations, the precision field specifies exactly how many digits to display after the decimal point, even if this includes trailing decimal zeros. The digits before the decimal point are not relevant for the precision in this case. This decimal precision can also be modified using the parameterized manipulator setprecision. Notice that when places to the right of the decimal point are dropped, the result is rounded off. If the number is too large to be represented in normal notation in that precision, as in the last value, the precision specification is ignored and the value is output in a more general form. The precision stays changed until you change it again.
Data races
Accesses (1) or modifies (2) 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
/* Get/Set floating-point decimal precision by precision() function code example */ #include <bits/stdc++.h> using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); int n, s; cin >> n >> s; map<int, int> graph; for(int i = 0; i < n - 1; ++i) { int a, b; cin >> a >> b; graph[a]++; graph[b]++; } int leaf = 0; for(auto& [key, val] : graph) { if( val == 1) leaf++; } cout.precision(16); // THIS LINE IS ADDED . cout << ( 2. * s ) / leaf << endl; return 0; }
For Loop Statement in C++
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.
Syntax of For Loop Statement in C++
for (initialization; condition; update) { // body of-loop }
initialization
initializes variables and is executed only once.
condition
if true, the body of for loop is executed, if false, the for loop is terminated.
update
updates the value of initialized variables and again checks the condition. A new range-based for loop was introduced to work with collections such as arrays and vectors.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
/* For Loop Statement in C++ Language */ // C++ program to find the sum of first n natural numbers // positive integers such as 1,2,3,...n are known as natural numbers #include <iostream> using namespace std; int main() { int num, sum; sum = 0; cout << "Enter a positive integer: "; cin >> num; for (int i = 1; i <= num; ++i) { sum += i; } cout << "Sum = " << sum << endl; return 0; }
Iomanip Library setw() Function in C++
Set field width. Sets the field width to be used on output operations. The C++ function std::setw behaves as if member width were called with n as argument on the stream on which it is inserted/extracted as a manipulator (it can be inserted/extracted on input streams or output streams). It is used to sets the field width to be used on output operations. This manipulator is declared in header <iomanip>.
Syntax for setw() Function in C++
#include <iomanip> /*undefined*/ setw (int n);
n
Number of characters to be used as field width. This method accepts n as a parameter which is the integer argument corresponding to which the field width is to be set. This function returns an object of unspecified type. The setw function should only be used as a stream manipulator. Like the different functions in C++ the setw() function helps in setting the field width which will be used on output operations. This function will take the member width whenever it will be called as an argument. It will need a stream where this field will be inserted or manipulated. This function will set the width parameter of the stream out or stream in to exactly n times. It will take the parameter which will be the new value of the width to which this has to be set.
Data races
The stream object on which it is inserted/extracted is modified. Concurrent access to the same stream object may introduce 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
/* specify the minimum number of character positions on the output field a variable will consume by setw function() code example. */ // C++ code to demonstrate the working of setw() function #include <iomanip> #include <ios> #include <iostream> using namespace std; int main() { // Initializing the integer int num = 50; cout << "Before setting the width: \n" << num << endl; // Using setw() cout << "Setting the width" << " using setw to 5: \n" << setw(5); cout << num << 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.
#include <header_file>
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; }
Iomanip Library setiosflags() Function in C++
Set format flags. Sets the format flags specified by parameter mask. Behaves as if member setf were called with mask as argument on the stream on which it is inserted/extracted as a manipulator (it can be inserted/extracted on input streams or output streams). See ios_base::fmtflags for more information on the particular flags that can be modified with this manipulator function. This manipulator is declared in header <iomanip>.
Syntax for Iomanip setiosflags() Function in C++
#include <iomanip> /*unspecified*/ setiosflags (ios_base::fmtflags mask);
mask
Mask representing the flags to be set. fmtflags is a bitmask type. This function returns an object of unspecified type. setiosflags function should only be used as a stream manipulator.
Data races
The stream object on which it is inserted/extracted is modified. Concurrent access to the same stream object may introduce 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
/* C++ manipulator setiosflags is used to set the format flag specified by parameter mask. */ /* C++ manipulator setiosflags code example */ #include <iostream> #include <iomanip> int main() { using namespace std; double dNumber = 9287.343535; // Output the value with default settings cout << "Default: " << dNumber << endl; // Output the value with in scientific notation cout << setiosflags(ios_base::scientific); cout << "Scientific notation: " << dNumber << endl; // Keep the window open cin.get(); return 0; }
flags() Function in C++
Get/set format flags. The first form (1) returns the format flags currently selected in the stream. The second form (2) sets new format flags for the stream, returning its former value. The format flags of a stream affect the way data is interpreted in certain input functions and how these are written by certain output functions. See ios_base::fmtflags for the possible values of this function's argument and the interpretation of its return value. The second form of this function sets the value for all the format flags of the stream, overwriting the existing values and clearing any flag not explicitly set in the argument. To access individual flags, see members setf and unsetf.
Syntax for flags() Function in C++
#include <iostream> //get (1) fmtflags flags() const; //set (2) fmtflags flags (fmtflags fmtfl);
fmtfl
Format flags to be used by the stream. ios_base::fmtflags is a bitmask type. Function returns the format flags selected in the stream before the call. ios_base::fmtflags is a bitmask type.
Data races
Accesses (1) or modifies (2) 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 33 34 35 36 37 38 39 40 41
/* Manages format flags. Returns current formatting setting. Replaces current settings with given ones. */ /* code example sets some format flags for cout that affect the insertion operation by printing the value in hexadecimal (0x64) padded right as in a field ten spaces long: */ // demonstrating the flags() member function any format flags() not specified in the argument to flags() are reset. #include <iostream> using namespace std; void main(void) { long p = 2000; double q = 0.00124345; // set a new format state cout<<"The value of flags variable is: " <<cout.flags()<<"\n" <<"Print long int and double in original format:\n" <<p<<"\t"<<q<<"\n\n"; long OriginalFormat = cout.flags(ios::oct | ios::scientific); // save the previous format state cout<<"The value of the flags variable is: " <<cout.flags()<<"\n" <<"Print long int and double in a new format\n" <<"specified using the flags member function:\n" <<p<<"\t"<<q<<"\n\n"; cout.flags(OriginalFormat); return; }
Namespaces in C++ Language
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 namespace is designed to overcome this difficulty and is used as additional information to differentiate similar functions, classes, variables etc. with the same name available in different libraries. Using namespace, you can define the context in which names are defined. In essence, a namespace defines a scope.
Defining a Namespace
A namespace definition begins with the keyword namespace followed by the namespace name as follows:
namespace namespace_name { // code declarations }
To call the namespace-enabled version of either function or variable, prepend (::) the namespace name as follows:
name::code; // code could be variable or function.
Using Directive
You can also avoid prepending of namespaces with the using namespace directive. This directive tells the compiler that the subsequent code is making use of names in the specified namespace.
Discontiguous Namespaces
A namespace can be defined in several parts and so a namespace is made up of the sum of its separately defined parts. The separate parts of a namespace can be spread over multiple files. So, if one part of the namespace requires a name defined in another file, that name must still be declared. Writing a following namespace definition either defines a new namespace or adds new elements to an existing one:
namespace namespace_name { // code declarations }
Nested Namespaces
Namespaces can be nested where you can define one namespace inside another name space as follows:
namespace namespace_name1 { // code declarations namespace namespace_name2 { // code declarations } }
• Namespace is a feature added in C++ and not present in C. • A namespace is a declarative region that provides a scope to the identifiers (names of the types, function, variables etc) inside it. • Multiple namespace blocks with the same name are allowed. All declarations within those blocks are declared in the named scope. • Namespace declarations appear only at global scope. • Namespace declarations can be nested within another namespace. • Namespace declarations don't have access specifiers. (Public or private) • No need to give semicolon after the closing brace of definition of namespace. • We can split the definition of namespace over several units.
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
/* namespaces in C++ language */ // A C++ code to demonstrate that we can define // methods outside namespace. #include <iostream> using namespace std; // Creating a namespace namespace ns { void display(); class happy { public: void display(); }; } // Defining methods of namespace void ns::happy::display() { cout << "ns::happy::display()\n"; } void ns::display() { cout << "ns::display()\n"; } // Driver code int main() { ns::happy obj; ns::display(); obj.display(); return 0; }
Iomanip Library setfill() Function in C++
Set fill character. Sets c as the stream's fill character. Behaves as if member fill were called with c as argument on the stream on which it is inserted as a manipulator (it can be inserted on output streams). The setfill() method of iomaip library in C++ is used to set the ios library fill character based on the character specified as the parameter to this method. This manipulator is declared in header <iomanip>.
Syntax for Iomanip setfill() Function in C++
#include <iomanip> /*unspecified*/ setfill (char_type c);
c
The new fill character for the stream. char_type is the type of characters used by the stream (i.e., its first class template parameter, charT). This function returns an object of unspecified type. The setbase function should only be used as a stream manipulator.
Data races
The stream object on which it inserted is modified. Concurrent access to the same stream object may introduce 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
/* The setfill() function belongs to the <iomanip> header file which consists of functions that are used to manipulate the output of C++ program*/ // C++ code example to demonstrate the working of setfill() function #include <iomanip> #include <ios> #include <iostream> using namespace std; int main() { // Initializing the integer int num = 50; cout << "Before setting the fill char: \n" << setw(10); cout << num << endl; // Using setfill() cout << "Setting the fill char" << " setfill to *: \n" << setfill('*') << setw(10); cout << num << endl; return 0; }


This is a C++ Program to implement Graham Scan algorithm. 'Graham's scan' is a method of computing the convex hull of a finite set of points in the plane with time complexity O(n
The simplest and probably most widely used method to "swap 2 variables" is to use a third temporary variable: In programming, the act of 'swapping' two variables refers to mutually
This algorithm takes the input of the number of vertex. For each pair of vertex ask whether they're connected or not. Print the incidence matrix. Function to print the incidence matrix