# C++ Programming Code Examples

## C++ > Mathematics Code Examples

### Find Greatest Common Divisor (GCD) of two numbers c++ program

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
/* Find Greatest Common Divisor (GCD) of two numbers c++ program What is GCD of two numbers? It means a greatest number which divides both numbers For example: Two numbers are 18 and 24 Numbers which divides both are 1, 2, 3 and 6 in which greatest number is 6 So 6 is the GCD of 18 and 24 Program takes input two numbers A for loop which terminates if loop variable which is 'i' is greater than one of two numbers and operator is used to maintain this condition Within for loop an if condition is used to check if variable 'i'divides both of them it will be saved in GCD variable as value of 'i' is changing during each iteration in increasing order if another number divides both of them it will replace the previous value of GCD After the loop termination our program will show the GCD of two number as the result */ #include<iostream> using namespace std; int main() { int first_number; cout<<"Enter First Number : ";cin>>first_number; int second_number; cout<<"Enter Second Number: ";cin>>second_number; int gcd; for(int i=1;i<=first_number&&i<=second_number;i++){ if(first_number%i==0 && second_number%i == 0 ){ gcd=i; } } cout<<"Greatest Common Divison (GCD):"<<gcd<<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; }
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; }
#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; }
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; }
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; }
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; }
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; }
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; }
If Else Statement in C++
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,
Syntax for If Statement in C++
if (condition) { // body of if 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.
Syntax for If...Else Statement
if (condition) { // block of code if condition is true } else { // block of code if condition is false }
The if..else statement evaluates the condition inside the parenthesis. If the condition evaluates true, the code inside the body of if is executed, the code inside the body of else is skipped from execution. If the condition evaluates false, the code inside the body of else is executed, the code inside the body of if is skipped from execution. The if...else statement is used to execute a block of code among two alternatives. However, if we need to make a choice between more than two alternatives, we use the if...else if...else statement.
Syntax for If...Else...Else If Statement in C++
if (condition1) { // code block 1 } else if (condition2){ // code block 2 } else { // code block 3 }
• If condition1 evaluates to true, the code block 1 is executed. • If condition1 evaluates to false, then condition2 is evaluated. • If condition2 is true, the code block 2 is executed. • If condition2 is false, the code block 3 is executed. There can be more than one else if statement but only one if and else 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.
Syntax for If Else If Ladder in C++
if (condition) statement 1; else if (condition) statement 2; . . else statement;
Working of the if-else-if ladder: 1. Control falls into the if block. 2. The flow jumps to Condition 1. 3. Condition is tested. If Condition yields true, goto Step 4. If Condition yields false, goto Step 5. 4. The present block is executed. Goto Step 7. 5. The flow jumps to Condition 2. If Condition yields true, goto step 4. If Condition yields false, goto Step 6. 6. The flow jumps to Condition 3. If Condition yields true, goto step 4. If Condition yields false, execute else block. Goto Step 7. 7. Exits the if-else-if ladder. • The if else ladder statement in C++ programming language is used to check set of conditions in sequence. • This is useful when we want to selectively executes one code block(out of many) based on certain conditions. • It allows us to check for multiple condition expressions and execute different code blocks for more than two conditions. • A condition expression is tested only when all previous if conditions in if-else ladder is false. • If any of the conditional expression evaluates to true, then it will execute the corresponding code block and exits whole if-else ladder.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
/* If Else Statement in C++ Language */ #include <iostream> using namespace std; int main () { // local variable declaration: int a = 100; // check the boolean condition if( a < 20 ) { // if condition is true then print the following cout << "a is less than 20;" << endl; } else { // if condition is false then print the following cout << "a is not less than 20;" << endl; } cout << "value of a is : " << a << endl; return 0; }
Logical Operators in C++
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:
&&
Called Logical AND operator. If both the operands are non-zero, then condition becomes true. (A && B) is false. The logical AND operator && returns true - if and only if all the operands are true. false - if one or more operands are false.
||
Called Logical OR Operator. If any of the two operands is non-zero, then condition becomes true. (A || B) is true. The logical OR operator || returns true - if one or more of the operands are true. false - if and only if all the operands are false.
!
Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true, then Logical NOT operator will make false. !(A && B) is true. The logical NOT operator ! is a unary operator i.e. it takes only one operand. It returns true when the operand is false, and false when the operand is true.
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
/* The operator ! is the C++ operator for the Boolean operation NOT. It has only one operand, to its right, and inverts it, producing false if its operand is true, and true if its operand is false. Basically, it returns the opposite Boolean value of evaluating its operand. The logical operators && and || are used when evaluating two expressions to obtain a single relational result. The operator && corresponds to the Boolean logical operation AND, which yields true if both its operands are true, and false otherwise. */ #include <iostream> using namespace std; main() { int a = 5; int b = 20; int c ; if(a && b) { cout << "Line 1 - Condition is true"<< endl ; } if(a || b) { cout << "Line 2 - Condition is true"<< endl ; } /* Let's change the values of a and b */ a = 0; b = 10; if(a && b) { cout << "Line 3 - Condition is true"<< endl ; } else { cout << "Line 4 - Condition is not true"<< endl ; } if(!(a && b)) { cout << "Line 5 - Condition is true"<< endl ; } return 0; }