C++ Programming Code Examples
C++ > Mathematics Code Examples
Calculator - A division, multiplication, adding, subtracting 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
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
/* Calculator - A division, multiplication, adding, subtracting program. */
#include<iostream>
#include<string>
using namespace std;
float mult(float num1,float num2);
float add(float num1,float num2);
float sub(float num1,float num2);
float divide(float num2,float num2);
int main()
{
int choice;
float num1,num2;
cout<<" CALCULATOR "<<endl;
cout<<" Make a selction:"<<endl;
cout<<" 1.Division"<<endl;
cout<<" 2.Adding"<<endl;
cout<<" 3.Subtraction"<<endl;
cout<<" 4.multiplication"<<endl;
cout<<"
YOUR CHIOCE IS: ";
cin>>choice;
switch(choice){
case 1:
cout<<"Please enter the two numbers you want to
divide, divisor first!: ";
cin>>num1>> num2;
cin.ignore();
cout<<"
"<<num1<<"/"<<num2<<"="<<divide(num1,num2)<<endl;
break;
case 2:
cout<<"Please enter the two numbers
you
want to add: ";
cin>>num1>> num2;
cin.ignore();
cout<<"
"<<num1<<"+"<<num2<<"="<<add(num1,num2)<<endl;
break;
case 3:
cout<<"Please enter
the
two numbers you want to subtract, The number you want to subtract from
first!: ";
cin>>num1>> num2;
cin.ignore();
cout<<"
"<<num1<<"-"<<num2<<"="<<sub(num1,num2)<<endl;
break;
case 4:
cout<<"Please
enter the two numbers you want to multiply: ";
cin>>num1>>
num2;
cin.ignore();
cout<<"
"<<num1<<"*"<<num2<<"="<<mult(num1,num2)<<endl;
break;
default:
cout<<"Invalid Entry!, BYE!!!"<<endl;
cin.ignore();
break;
}
cin.ignore();
return 0;
}
float mult(float num1,float num2){
return (num1*num2);
}
float add(float num1,float num2){
return (num1+num2);
}
float sub(float num1,float num2){
return (num1-num2);
}
float divide(float num1,float num2){
return (num1/num2);
}
Switch Case Statement in C++
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.
Syntax for Switch Case Statement in C++
switch( expression )
{
case value-1:
Block-1;
Break;
case value-2:
Block-2;
Break;
case value-n:
Block-n;
Break;
default:
Block-1;
Break;
}
Statement-x;
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
/* the switch statement helps in testing the equality of a variable against a set of values */
#include <iostream>
using namespace std;
int main () {
// local variable declaration:
char grade = 'D';
switch(grade) {
case 'A' :
cout << "Excellent!" << endl;
break;
case 'B' :
case 'C' :
cout << "Well done" << endl;
break;
case 'D' :
cout << "You passed" << endl;
break;
case 'F' :
cout << "Better try again" << endl;
break;
default :
cout << "Invalid grade" << endl;
}
cout << "Your grade is " << grade << 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;
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;
}
Basic Ios Library ignore() Function in C++
Extract and discard characters. Extracts characters from the input sequence and discards them, until either n characters have been extracted, or one compares equal to delim.
The function also stops extracting characters if the end-of-file is reached. If this is reached prematurely (before either extracting n characters or finding delim), the function sets the eofbit flag.
Internally, the function accesses the input sequence by first constructing a sentry object (with noskipws set to true). Then (if good), it extracts characters from its associated stream buffer object as if calling its member functions sbumpc or sgetc, and finally destroys the sentry object before returning.
Syntax for Basic Ios ignore() Function in C++
#include <iostream>
istream& ignore (streamsize n = 1, int delim = EOF);
n
Maximum number of characters to extract (and ignore). If this is exactly numeric_limits<streamsize>::max(), there is no limit: As many characters are extracted as needed until delim (or the end-of-file) is found.
streamsize is a signed integral type.
delim
Delimiting character: The function stops extracting characters as soon as an extracted character compares equal to this. Note that the delimiting character is extracted, and thus the next input operation will continue on the character that follows it (if any).
If this is the end-of-file value (EOF), no character will compare equal, and thus exactly n characters will be discarded (unless the function fails or the end-of-file is reached).
Function returns the istream object (*this).
Errors are signaled by modifying the internal state flags:
• eofbit: The function stopped extracting characters because the input sequence has no more characters available (end-of-file reached).
• failbit: The construction of sentry failed (such as when the stream state was not good before the call).
• badbit: Error on stream (such as when this function catches an exception thrown by an internal operation).
When set, the integrity of the stream may have been affected.
Multiple flags may be set by a single operation.
If the operation sets an internal state flag that was registered with member exceptions, the function throws an exception of member type failure.
Data races
Modifies the stream object. Concurrent access to the same stream object may cause data races, except for the standard stream object cin when this is synchronized with stdio (in this case, no data races are initiated, although no guarantees are given on the order in which extracted characters are attributed to threads).
Exception safety
Basic guarantee: if an exception is thrown, the object is in a valid state. It throws an exception of member type failure if the resulting error state flag is not goodbit and member exceptions was set to throw for that state.
Any exception thrown by an internal operation is caught and handled by the function, setting badbit. If badbit was set on the last call to exceptions, the function rethrows the caught exception.
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
/* basic_istream::ignore is used to extracts characters from the input sequence and discards them, until either n characters have been extracted, or one compares equal to delim. */
/* Extracts and discards characters from the input stream until and including delim by basic_istream::ignore function code example. */
#include <bits/stdc++.h>
using namespace std;
// Driver Code
int main()
{
// Input String
istringstream input(
"12\n"
"It is a string\n"
"14\n");
for (;;) {
int n;
// Taking input streamed string
input >> n;
// Check for end of file or if
// any bad bit occurs
if (input.eof() || input.bad()) {
break;
}
// If any failbit occurs
else if (input.fail()) {
// Clear the input
input.clear();
// Use ignore to stream the given
// input as per delimeter '\n'
input.ignore(
numeric_limits<streamsize>::max(),
'\n');
}
// Else print the integer in
// the string
else {
cout << n << '\n';
}
}
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 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;
}
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";
<<
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;
}
Break Statement in C++
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.
Syntax for Break Statement in C++
// jump-statement;
break;
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
/* break statement with while loop code example */
// program to find the sum of positive numbers
// if the user enters a negative numbers, break ends the loop
// the negative number entered is not added to sum
#include <iostream>
using namespace std;
int main() {
int number;
int sum = 0;
while (true) {
// take input from the user
cout << "Enter a number: ";
cin >> number;
// break condition
if (number < 0) {
break;
}
// add all positive numbers
sum += number;
}
// display the sum
cout << "The sum is " << 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"
#include <header_file>
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;
}
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
}
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
}
}
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;
}
Full form of Ascii is American Standard Code for Information Interchange. It is a character "Encoding Scheme". Originally based on the English alphabet, every character or number
Write a simple C++ program which have four different functions for "basic operations" like addition, subtraction, division, multiplication. It should be menu based asking user to enter
To check whether the input year is a leap year or not a "leap year" in C++ Programming, you have to enter the year and start checking for the leap year. To check that the year is a leap