C++ Programming Code Examples
C++ > Pyramid Patterns Code Examples
Inverted half pyramid using numbers
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/* Inverted half pyramid using numbers */
#include <iostream>
using namespace std;
int main()
{
int rows;
cout << "Enter number of rows: ";
cin >> rows;
for(int x = rows; x >= 1; --x)
{
for(int j = 1; j <= x; ++j)
{
cout << j << " ";
}
cout << endl;
}
return 0;
}
Return Statement in C++
A return statement ends the processing of the current function and returns control to the caller of the function. A value-returning function should include a return statement, containing an expression.
If an expression is not given on a return statement in a function declared with a non-void return type, the compiler issues an error message.
If the data type of the expression is different from the function return type, conversion of the return value takes place as if the value of the expression were assigned to an object with the same function return type.
Syntax for Return Statement in C++
return[expression];
return; /* Returns no value */
return result; /* Returns the value of result */
return 1; /* Returns the value 1 */
return (x * x); /* Returns the value of x * 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
/* illustrate Methods returning a value using return statement in C++ code example */
#include <iostream>
using namespace std;
// non-void return type
// function to calculate sum
int SUM(int a, int b)
{
int s1 = a + b;
// method using the return
// statement to return a value
return s1;
}
// Driver method
int main()
{
int num1 = 10;
int num2 = 10;
int sum_of = SUM(num1, num2);
cout << "The sum is " << sum_of;
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;
}
Nested Loop Statement in C++
C supports nesting of loops in C. Nesting of loops is the feature in C that allows the looping of statements inside another loop. Any number of loops can be defined inside another loop, i.e., there is no restriction for defining any number of loops. The nesting level can be defined at n times. You can define any type of loop inside another loop; for example, you can define 'while' loop inside a 'for' loop.
A loop inside another loop is called a nested loop. The depth of nested loop depends on the complexity of a problem. We can have any number of nested loops as required. Consider a nested loop where the outer loop runs n times and consists of another loop inside it. The inner loop runs m times. Then, the total number of times the inner loop runs during the program execution is n*m.
Syntax for Nested Loop Statement in C++
Outer_loop
{
Inner_loop
{
// inner loop statements.
}
// outer loop statements.
}
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
/* nested loop statement in C++ language */
// C++ program that uses nested for loop to print a 2D matrix
#include <bits/stdc++.h>
using namespace std;
#define ROW 3
#define COL 3
// Driver program
int main()
{
int i, j;
// Declare the matrix
int matrix[ROW][COL] = { { 4, 8, 12 },
{ 16, 20, 24 },
{ 28, 32, 36 } };
cout << "Given matrix is \n";
// Print the matrix using nested loops
for (i = 0; i < ROW; i++) {
for (j = 0; j < COL; j++)
cout << matrix[i][j];
cout << "\n";
}
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;
}
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;
}
#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;
}
Relational Operators in C++
A relational operator is used to check the relationship between two operands. C++ Relational Operators are used to relate or compare given operands. Relational operations are like checking if two operands are equal or not equal, greater or lesser, etc.
Relational Operators are also called Comparison Operators.
• == Is Equal To 4 == 9 gives us false
• != Not Equal To 4 != 9 gives us true
• > Greater Than 4 > 9 gives us false
• < Less Than 4 < 9 gives us true
• >= Greater Than or Equal To 4 >= 9 give us false
• <= Less Than or Equal To 4 <= 9 gives us true
==
Equal To Operator (==) is used to compare both operands and returns 1 if both are equal or the same, and 0 represents the operands that are not equal.
The equal to == operator returns
true - if both the operands are equal or the same
false - if the operands are unequal
int x = 10;
int y = 15;
int z = 10;
x == y // false
x == z // true
The relational operator == is not the same as the assignment operator =. The assignment operator = assigns a value to a variable, constant, array, or vector. It does not compare two operands.
!=
Not Equal To Operator (!=) is the opposite of the Equal To Operator and is represented as the (!=) operator. The Not Equal To Operator compares two operands and returns 1 if both operands are not the same; otherwise, it returns 0.
The not equal to != operator returns
true - if both operands are unequal
false - if both operands are equal.
int x = 10;
int y = 15;
int z = 10;
x != y // true
x != z // false
>
Greater than Operator (>) checks the value of the left operand is greater than the right operand, and if the statement is true, the operator is said to be the Greater Than Operator.
The greater than > operator returns
true - if the left operand is greater than the right
false - if the left operand is less than the right
int x = 10;
int y = 15;
x > y // false
y > x // true
<
Less than Operator (<) is used to check whether the value of the left operand is less than the right operand, and if the statement is true, the operator is known as the Less than Operator.
The less than operator < returns
true - if the left operand is less than the right
false - if the left operand is greater than right
int x = 10;
int y = 15;
x < y // true
y < x // false
>=
Greater than Equal To Operator (>=) checks whether the left operand's value is greater than or equal to the right operand. If the statement is true, the operator is said to be the Greater than Equal to Operator.
The greater than or equal to >= operator returns
true - if the left operand is either greater than or equal to the right
false - if the left operand is less than the right
int x = 10;
int y = 15;
int z = 10;
x >= y // false
y >= x // true
z >= x // true
<=
Less than Equal To Operator (<=) checks whether the value of the left operand is less than or equal to the right operand, and if the statement is true, the operator is said to be the Less than Equal To Operator.
The less than or equal to operator <= returns
true - if the left operand is either less than or equal to the right
false - if the left operand is greater than right
int x = 10;
int y = 15;
x > y // false
y > x // 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
42
43
44
/* Relational Operators are used for the comparison of the values of two operands. For example, checking if one operand is equal to the other operand or not, an operand is greater than the other operand or not, etc. Some of the relational operators are (==, >= , <= ). */
#include <iostream>
using namespace std;
main() {
int a = 21;
int b = 10;
int c ;
if( a == b ) {
cout << "Line 1 - a is equal to b" << endl ;
} else {
cout << "Line 1 - a is not equal to b" << endl ;
}
if( a < b ) {
cout << "Line 2 - a is less than b" << endl ;
} else {
cout << "Line 2 - a is not less than b" << endl ;
}
if( a > b ) {
cout << "Line 3 - a is greater than b" << endl ;
} else {
cout << "Line 3 - a is not greater than b" << endl ;
}
/* Let's change the values of a and b */
a = 5;
b = 20;
if( a <= b ) {
cout << "Line 4 - a is either less than \ or equal to b" << endl ;
}
if( b >= a ) {
cout << "Line 5 - b is either greater than \ or equal to b" << 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;
}
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;
}
We have to enter some set of numbers. Now to find occurrence of positive, negative, zero from the given set of numbers, just check all the numbers using for loop whether number
The problem takes E edges as input and then outputs whehter vertex cover of size K of the graph exists or not. 'Vertex Cover of a Graph' is, a set of vertices S, such that for every edge