C++ Programming Code Examples
C++ > Beginners Lab Assignments Code Examples
This program in CPP, demonstrates the array implementation of Circular Queue.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
/* This program in CPP, demonstrates the array implementation of Circular Queue. */
#include<iostream.h>
#include<stdlib.h>
#include<stdio.h>
#include<conio.h>
// Defining class CQUEUE
class cqueue
{
int q[10],num,front,rear;
public :
cqueue();
void insert();
void remove();
void menu();
void display();
};
cqueue :: cqueue()
{
front=rear=0;
}
void cqueue :: insert()
{
if(((rear+1)%10)==front)
{
cout<<"Queue is full
";
}
else
{
cout<<"Please enter a number :
";
cin>>
q[rear];
rear=(rear+1)%10;
}
}
void cqueue :: remove()
{
if(rear==front)
{
cout<<"Queue is empty
";
}
else
{
int num=q[front];
cout<<"You deleted "<<num<<"
";
front=(front+1)%10;
getch();
}
}
void cqueue::display()
{
int i=front;
if(front==rear)
{
cout<<"Queue is empty, No elements to display !!!!!!
";
}
else
{
cout<<"Queue's elements are :
";
cout<<"Front = ";
while( i!=rear)
{
if(i==(rear-1)) cout<<"Rear = ";
cout<<q[i]<<"
";
i=i++%10;
} // end while.
}// end elseif.
getch();
}
void cqueue :: menu()
{
int ch=1;
clrscr();
while (ch)
{
clrscr();
cout<<"Enter your Choice
1 : insert
2 : remove
3 : display
0
:
exit
";
cin >>ch;
switch (ch)
{
case 1 : insert();
break;
case 2 : remove();
break;
case 3 : display();
break;
case 0 : exit(0);
}
}
}
void main()
{
cout<<"Program to demonstrate Circular Queue
";
cqueue q1;
q1.menu();
}
Classes and Objects in C++ Language
The main purpose of C++ programming is to add object orientation to the C programming language and classes are the central feature of C++ that supports object-oriented programming and are often called user-defined types.
A class is used to specify the form of an object and it combines data representation and methods for manipulating that data into one neat package. The data and functions within a class are called members of the class.
C++ Class Definitions
When you define a class, you define a blueprint for a data type. This doesn't actually define any data, but it does define what the class name means, that is, what an object of the class will consist of and what operations can be performed on such an object.
A class definition starts with the keyword class followed by the class name; and the class body, enclosed by a pair of curly braces. A class definition must be followed either by a semicolon or a list of declarations. For example, we defined the Box data type using the keyword class as follows:
class Box {
public:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};
Define C++ Objects
A class provides the blueprints for objects, so basically an object is created from a class. We declare objects of a class with exactly the same sort of declaration that we declare variables of basic types. Following statements declare two objects of class Box:
Box Box1; // Declare Box1 of type Box
Box Box2; // Declare Box2 of type Box
Accessing the Data Members
The public data members of objects of a class can be accessed using the direct member access operator (.).
It is important to note that private and protected members can not be accessed directly using direct member access operator (.).
Classes and Objects in Detail
There are further interesting concepts related to C++ Classes and Objects which we will discuss in various sub-sections listed below:
• Class Member Functions: A member function of a class is a function that has its definition or its prototype within the class definition like any other variable.
• Class Access Modifiers: A class member can be defined as public, private or protected. By default members would be assumed as private.
• Constructor & Destructor: A class constructor is a special function in a class that is called when a new object of the class is created. A destructor is also a special function which is called when created object is deleted.
• Copy Constructor: The copy constructor is a constructor which creates an object by initializing it with an object of the same class, which has been created previously.
• Friend Functions: A friend function is permitted full access to private and protected members of a class.
• Inline Functions: With an inline function, the compiler tries to expand the code in the body of the function in place of a call to the function.
• this Pointer: Every object has a special pointer this which points to the object itself.
• Pointer to C++ Classes: A pointer to a class is done exactly the same way a pointer to a structure is. In fact a class is really just a structure with functions in it.
• Static Members of a Class: Both data members and function members of a class can be declared as static.
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
/* using public and private in C++ Class */
// Program to illustrate the working of
// public and private in C++ Class
#include <iostream>
using namespace std;
class Room {
private:
double length;
double breadth;
double height;
public:
// function to initialize private variables
void initData(double len, double brth, double hgt) {
length = len;
breadth = brth;
height = hgt;
}
double calculateArea() {
return length * breadth;
}
double calculateVolume() {
return length * breadth * height;
}
};
int main() {
// create object of Room class
Room room1;
// pass the values of private variables as arguments
room1.initData(42.5, 30.8, 19.2);
cout << "Area of Room = " << room1.calculateArea() << endl;
cout << "Volume of Room = " << room1.calculateVolume() << endl;
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;
}
getch() Function in C++
The getch() is a predefined non-standard function that is defined in conio.h header file. It is mostly used by the Dev C/C++, MS- DOS's compilers like Turbo C to hold the screen until the user passes a single value to exit from the console screen. It can also be used to read a single byte character or string from the keyboard and then print. It does not hold any parameters. It has no buffer area to store the input character in a program.
Syntax for getch() Function in C++
#include <conio.h>
int getch(void);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/* wait for any character input from keyboard by getch() function code example. The getch() function is very useful if you want to read a character input from the keyboard. */
// C code to illustrate working of
// getch() to accept hidden inputs
#include<iostream.h>
#include<conio.h>
void main()
{
int a=10, b=20;
int sum=0;
clrscr();
sum=a+b;
cout<<"Sum: "<<sum;
getch(); // use getch() befor end of main()
}
While Loop Statement in C++
In while loop, condition is evaluated first and if it returns true then the statements inside while loop execute, this happens repeatedly until the condition returns false. When condition returns false, the control comes out of loop and jumps to the next statement in the program after while loop.
The important point to note when using while loop is that we need to use increment or decrement statement inside while loop so that the loop variable gets changed on each iteration, and at some point condition returns false. This way we can end the execution of while loop otherwise the loop would execute indefinitely. A while loop that never stops is said to be the infinite while loop, when we give the condition in such a way so that it never returns false, then the loops becomes infinite and repeats itself indefinitely.
Syntax for While Loop Statement in C++
while (condition) {
// body of the loop
}
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
/* While Loop Statement in C++ language */
// program to find the sum of positive numbers
// if the user enters a negative number, the loop ends
// the negative number entered is not added to the sum
#include <iostream>
using namespace std;
int main() {
int number;
int sum = 0;
// take input from the user
cout << "Enter a number: ";
cin >> number;
while (number >= 0) {
// add all positive numbers
sum += number;
// take input again if the number is positive
cout << "Enter a number: ";
cin >> number;
}
// display the sum
cout << "\nThe sum is " << sum << endl;
return 0;
}
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;
}
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
}
Syntax for If...Else Statement
if (condition) {
// block of code if condition is true
}
else {
// block of code if condition is false
}
Syntax for If...Else...Else If Statement in C++
if (condition1) {
// code block 1
}
else if (condition2){
// code block 2
}
else {
// code block 3
}
Syntax for If Else If Ladder in C++
if (condition)
statement 1;
else if (condition)
statement 2;
.
.
else
statement;
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;
}
If Else If Ladder in C/C++
The if...else statement executes two different codes depending upon whether the test expression is true or false. Sometimes, a choice has to be made from more than 2 possibilities. The if...else ladder allows you to check between multiple test expressions and execute different 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 of if...else Ladder in C++
if (Condition1)
{ Statement1; }
else if(Condition2)
{ Statement2; }
.
.
.
else if(ConditionN)
{ StatementN; }
else
{ Default_Statement; }
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
/* write a C program which demonstrate use of if-else-if ladder statement */
/* Program to Print Day Names using Else If Ladder in C++*/
#include <iostream>
using namespace std;
int main()
{
int day;
cout << "Enter Day Number: ";
cin >> day;
cout << "Day is ";
if (day == 1)
cout << "Sunday" << endl;
else if (day == 2)
cout << "Monday" << endl;
else if (day == 3)
cout << "Tuesday" << endl;
else if (day == 4)
cout << "Wednesday" << endl;
else if (day == 5)
cout << "Thursday" << endl;
else if (day == 6)
cout << "Friday" << endl;
else
cout << "Saturday" << endl;
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;
}
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;
}
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;
}
Constructors in C++ Language
In C++, constructor is a special method which is invoked automatically at the time of object creation. It is used to initialize the data members of new object generally. The constructor in C++ has the same name as class or structure.
Constructors are special class functions which performs initialization of every object. The Compiler calls the Constructor whenever an object is created. Constructors initialize values to object members after storage is allocated to the object.
Whereas, Destructor on the other hand is used to destroy the class object.
• Default Constructor: A constructor which has no argument is known as default constructor. It is invoked at the time of creating object.
Syntax for Default Constructor in C++
class_name(parameter1, parameter2, ...)
{
// constructor Definition
}
Syntax for Parameterized Constructor in C++
class class_name
{
public:
class_name(variables) //Parameterized constructor declared.
{
}
};
Syntax for Copy Constructors in C++
classname (const classname &obj) {
// body of constructor
}
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
/* A constructor is a special type of member function that is called automatically when an object is created. In C++, a constructor has the same name as that of the class and it does not have a return type. */
#include <iostream>
using namespace std;
// declare a class
class Wall {
private:
double length;
double height;
public:
// initialize variables with parameterized constructor
Wall(double len, double hgt) {
length = len;
height = hgt;
}
// copy constructor with a Wall object as parameter
// copies data of the obj parameter
Wall(Wall &obj) {
length = obj.length;
height = obj.height;
}
double calculateArea() {
return length * height;
}
};
int main() {
// create an object of Wall class
Wall wall1(10.5, 8.6);
// copy contents of wall1 to wall2
Wall wall2 = wall1;
// print areas of wall1 and wall2
cout << "Area of Wall 1: " << wall1.calculateArea() << endl;
cout << "Area of Wall 2: " << wall2.calculateArea();
return 0;
}
What is an Array in C++ Language
An array is defined as the collection of similar type of data items stored at contiguous memory locations. Arrays are the derived data type in C++ programming language which can store the primitive type of data such as int, char, double, float, etc. It also has the capability to store the collection of derived data types, such as pointers, structure, etc. The array is the simplest data structure where each data element can be randomly accessed by using its index number.
C++ array is beneficial if you have to store similar elements. For example, if we want to store the marks of a student in 6 subjects, then we don't need to define different variables for the marks in the different subject. Instead of that, we can define an array which can store the marks in each subject at the contiguous memory locations.
By using the array, we can access the elements easily. Only a few lines of code are required to access the elements of the array.
Properties of Array
The array contains the following properties.
• Each element of an array is of same data type and carries the same size, i.e., int = 4 bytes.
• Elements of the array are stored at contiguous memory locations where the first element is stored at the smallest memory location.
• Elements of the array can be randomly accessed since we can calculate the address of each element of the array with the given base address and the size of the data element.
Advantage of C++ Array
• 1) Code Optimization: Less code to the access the data.
• 2) Ease of traversing: By using the for loop, we can retrieve the elements of an array easily.
• 3) Ease of sorting: To sort the elements of the array, we need a few lines of code only.
• 4) Random Access: We can access any element randomly using the array.
Disadvantage of C++ Array
• 1) Allows a fixed number of elements to be entered which is decided at the time of declaration. Unlike a linked list, an array in C++ is not dynamic.
• 2) Insertion and deletion of elements can be costly since the elements are needed to be managed in accordance with the new memory allocation.
Declaration of C++ Array
To declare an array in C++, a programmer specifies the type of the elements and the number of elements required by an array as follows
type arrayName [ arraySize ];
double balance[10];
Initializing Arrays
You can initialize an array in C++ either one by one or using a single statement as follows
double balance[5] = {850, 3.0, 7.4, 7.0, 88};
double balance[] = {850, 3.0, 7.4, 7.0, 88};
Accessing Array Elements
An element is accessed by indexing the array name. This is done by placing the index of the element within square brackets after the name of the array.
double salary = balance[9];
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
/* arrays in C++ Language */
#include <iostream>
using namespace std;
int main() {
// initialize an array without specifying size
double numbers[] = {7, 5, 6, 12, 35, 27};
double sum = 0;
double count = 0;
double average;
cout << "The numbers are: ";
// print array elements
// use of range-based for loop
for (const double &n : numbers) {
cout << n << " ";
// calculate the sum
sum += n;
// count the no. of array elements
++count;
}
// print the sum
cout << "\nTheir Sum = " << sum << endl;
// find the average
average = sum / count;
cout << "Their Average = " << average << 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();
}
#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;
}
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;
}
'Insert element' into the vector. Deleting last element of the vector. Size of the vector and Display by index. "Dislplay by iterator". Clear the vector. Enter value to be inserted. Display
To add digits of any number in C++, we enter the number to add their digits & displays the "Addition Result" of the digits of the entered number on the output screen as shown here
This program decodes any message encoded by the technique of traditional playfair cipher. "The Playfair Cipher" is a 'Manual Symmetric' Encryption Technique and was the first literal
This represents the queue dequeue function. Every time another object or customer enters the line to wait, they join the "end of the line" and represent the "enqueue function". Queue