C++ is a cross-platform language that can be used to create high-performance applications. It was developed by Bjarne Stroustrup, as an extension to the C language. The language was updated 3 major times in 2011, 2014, and 2017 to C++11, C++14, and C++17.
Why Use C++?
- C++ is one of the world's most popular programming languages.
- C++ can be found in today's operating systems, Graphical User Interfaces, and embedded systems.
- C++ is an object-oriented programming language that gives a clear structure to programs and allows code to be reused, lowering development costs.
- C++ is portable and can be used to develop applications that can be adapted to multiple platforms.
- C++ is fun and easy to learn!
- As C++ is close to C# and Java, it makes it easy for programmers to switch to C++ or vice versa.
C++ Basic Program
C++
// C++ Hello World Program
#include <iostream>
using namespace std;
int main()
{
cout << "Hello World!\n";
return 0;
}
Components of a C++ Code:
- Comments: The two slash(//) signs are used to add comments in a program. It does not have any effect on the behavior or outcome of the program. It is used to give a description of the program you’re writing.
- #include<iostream>: #include is the pre-processor directive that is used to include files in our program. Here we are including the iostream standard file which is necessary for the declarations of basic standard input/output library in C++.
- Using namespace std: All elements of the standard C++ library are declared within a namespace. Here we are using the std namespace.
- int main(): The execution of any C++ program starts with the main function, hence it is necessary to have a main function in your program. ‘int’ is the return value of this function. (We will be studying functions in more detail later).
- {}: The curly brackets are used to indicate the starting and ending point of any function. Every opening bracket should have a corresponding closing bracket.
- cout<<”Hello World!\n”; This is a C++ statement. cout represents the standard output stream in C++. It is declared in the iostream standard file within the std namespace. The text between quotations will be printed on the screen. \n will not be printed, it is used to add a line break. Each statement in C++ ends with a semicolon (;).
- return 0; return signifies the end of a function. Here the function is main, so when we hit return 0, it exits the program. We are returning 0 because we mentioned the return type of the main function as integer (int main). A zero indicates that everything went fine and one indicates that something has gone wrong.
Input and Output in C++
The header file iostream must be included to make use of the input/output (cin/cout) operators.
Standard Output (cout)
- By default, the standard output of a program points at the screen. So with the cout operator and the “insertion” operator (фф) you can print a message onto the screen.
- To print the content of a variable the double quotes are not used.
- The << operator can be used multiple times in a single statement.
- It is possible to combine variables and text:
- The cout operator does not put a line break at the end of the output. So if you want to print two sentences you will have to use the new-line character ( \n ).
- It is possible to use the endl manipulator instead of the new-line character.
Below is the C++ program to illustrate standard output:
C++
// C++ program to implement
// standard output
#include <iostream>
using namespace std;
int main()
{
cout << "Geeks For Geeks";
return 0;
}
Standard input (cin)
- In most cases, the standard input device is the keyboard. With the cin and >> operators, it is possible to read input from the keyboard.
- The cin operator will always return the variable type that you use with cin. So if you request an integer you will get an integer and so on. This can cause an error when the user of the program does not return the type that you are expecting. (Example: you ask for an integer and you get a string of characters.)
- The cin operator is also chainable. In this case, the user must give two input values, that are separated by any valid blank separator (tab, space, or new-line).
Below is the C++ program to illustrate standard input:
C++
// C++ program to implement
// standard input
#include <iostream>
using namespace std;
int main()
{
int a;
cout << "Enter a number" << endl;
// User can input an integer
cin >> a;
cout << "User entered number " << a << endl;
}
OutputEnter a number
User entered number 0
Data types are declarations for variables. This determines the type and size of data associated with variables which are essential to know since different data types occupy the different sizes of memory.
Data Type | Meaning | Size (in Bytes) |
---|
int | Integer | 4 |
float | Floating-point | 4 |
double | Double Floating-point | 8 |
char | Character | 1 |
wchar_t | Wide Character | 2 |
bool | Boolean | 1 |
void | Empty | 0 |
1. int
- This data type is used to store integers.
- It occupies 4 bytes in memory.
- It can store values from -2147483648 to 2147483647.
- Eg. int age = 18
2. float and double
- Used to store floating-point numbers (decimals and exponential)
- The size of a float is 4 bytes and the size of double is 8 bytes.
- Float is used to store up to 7 decimal digits whereas double is used to store up to 15 decimal digits.
- Example:
- float pi = 3.14.
- double distance = 24E8 // 24 x 108
3. char
- This data type is used to store characters.
- It occupies 1 byte in memory.
- Characters in C++ are enclosed inside single quotes ' ' ASCII code is used to store characters in memory.
- Example: char ch ='a'
4. bool
- This data type has only 2 values true and false.
- It occupies 1 byte in memory.
- True is represented as 1 and false as 0.
- Example: bool flag = false
C++ Type Modifiers
Type modifiers are used to modify the fundamental data types.
Data Type | Size (in Bytes) | Meaning |
---|
signed int | 4 | used for integers (equivalent to int) |
unsigned int | 4 | can only store positive integers |
short | 2 | used for small integers (range -32768 to 32767) |
long | at least 4 | used for large integers (equivalent to long int) |
long long int | 8 | used for very large integers (equivalent to long long int). |
unsigned long long(equivalent to unsigned long long int) | 8 | used for very large positive integers or 0 |
long double | 8 | used for large floating-point numbers |
signed char | 1 | used for characters (guaranteed range -127 to 127) |
unsigned char | 1 | used for characters (range 0 to 255) |
Below is the C++ program to implement Data types:
C++
// C++ program to implement
// data types
#include <iostream>
using namespace std;
int main()
{
cout << "Size of bool is: " <<
sizeof(bool) <<
" bytes" << endl;
cout << "Size of char is: " <<
sizeof(char) <<
" bytes" << endl;
cout << "Size of int is: " <<
sizeof(int) <<
" bytes" << endl;
cout << "Size of short int is: " <<
sizeof(short int) <<
" bytes" << endl;
cout << "Size of long int is: " <<
sizeof(long int) <<
" bytes" << endl;
cout << "Size of signed long int is: " <<
sizeof(signed long int) <<
" bytes" << endl;
cout << "Size of unsigned long int is: " <<
sizeof(unsigned long int) <<
" bytes" << endl;
cout << "Size of float is: " <<
sizeof(float) <<
" bytes" << endl;
cout << "Size of double is: " <<
sizeof(double) <<
" bytes" << endl;
cout << "Size of wchar_t is: " <<
sizeof(wchar_t) << " bytes" << endl;
return 0;
}
OutputSize of bool is: 1 bytes
Size of char is: 1 bytes
Size of int is: 4 bytes
Size of short int is: 2 bytes
Size of long int is: 8 bytes
Size of signed long int is: 8 bytes
Size of unsigned long int is: 8 bytes
Size of float is: 4 bytes
Size of double is: 8 bytes
Size of wchar_t is: 4 bytes
These are the data types that are derived from fundamental (or built-in) data types. For example arrays, pointers, function, reference.
Below is the C++ program to implement derived data types:
C++
// C++ program to implement
// derived data types
#include <iostream>
using namespace std;
// Function definition
int sum(int n1, int n2)
{
return n1 + n2;
}
int main()
{
// array declaration and
// initialization
int arr[5] = {2, 4, 6, 8, 10};
cout << "Array elements are : ";
for (int i = 0; i < 5; i++)
{
// printing array elements
cout << arr[i] << " ";
}
// pointers
int a = 10;
// Declared a pointer of
// type int
int* p;
// Pointer p points the address
// of a
p = &a;
cout << "\n" << "Value of a is " <<
a << endl;
// address of a will be printed
cout << "Value of p is " << p <<
endl;
// value of a will be printed
cout << "Value of *p is " << *p <<
endl;
// function calling from main
cout << "Sum is:" << sum(5, 2) <<
endl;
// reference
int x = 10;
int& ref = x;
// Value of x is now changed
// to 30
ref = 30;
cout << "x = " << x << endl;
// Value of x is now changed
// to 40
x = 40;
cout << "ref = " << ref << endl;
return 0;
}
OutputArray elements are : 2 4 6 8 10
Value of a is 10
Value of p is 0x7ffd0ec3c084
Value of *p is 10
Sum is:7
x = 30
ref = 40
These are the data types that are defined by the user themselves.
For example, class, structure, union, enumeration, etc.
Below is the C++ program to implement class user-defined data types:
C++
// C++ program to implement
// user-defined data types
#include <iostream>
using namespace std;
class GFG
{
public:
string gfg;
void print()
{
cout << "String is: " <<
gfg;
}
};
// Driver code
int main()
{
GFG obj1;
obj1.gfg = "GeeksForGeeks is the best Technical Website";
obj1.print();
return 0;
}
OutputString is: GeeksForGeeks is the best Technical Website
Below is the C++ program to implement structure user-defined data type:
C++
// C++ program to implement
// struct
#include <iostream>
using namespace std;
struct Geeks
{
int a, b;
};
// Driver code
int main()
{
struct Geeks arr[10];
arr[0].a = 30;
arr[0].b = 40;
cout << arr[0].a << ", " <<
arr[0].b;
return 0;
}
Below is the C++ program to implement union user-defined data type:
C++
// C++ program to implement
// union
#include <iostream>
using namespace std;
union gfg
{
int a, b;
};
// Driver code
int main()
{
union gfg g;
g.a = 5;
cout << "After changing a = 5:" <<
endl << "a = " << g.a <<
", b = " << g.b << endl;
g.b = 15;
cout << "After changing b = 15:" <<
endl << "a = " << g.a <<
", b = " << g.b << endl;
return 0;
}
OutputAfter changing a = 5:
a = 5, b = 5
After changing b = 15:
a = 15, b = 15
Below is the C++ program to implement enumeration data type:
C++
// C++ program to implement
// enum
#include <iostream>
using namespace std;
enum season
{
Autmn, Spring, Winter, Summer
};
// Driver code
int main()
{
enum season month;
month = Summer;
cout << month;
return 0;
}
Operators are nothing but symbols that tell the compiler to perform some specific operations. Operators are of the following types -
1. Arithmetic Operators
Arithmetic operators perform some arithmetic operations on one or two operands. Operators that operate on one operand are called unary arithmetic operators and operators that operate on two operands are called binary arithmetic operators.
- +,-,*,/,% are binary operators.
- ++, -- are unary operators.
Suppose: A=5 and B=10
Operator | Operation | Example |
---|
+ | Adds two operands | A+B = 15 |
- | Subtracts right operand from the left operand | B-A = 5 |
* | Multiplies two operands | A*B = 50 |
/ | Divides left operand by right operand | B/A = 2 |
% | Finds the remainder after integer division | B%A = 0 |
++ | Increment | A++ = 6 |
-- | Decrement | A-- = 4 |
Below is the C++ program to implement arithmetic operators:
C++
// C++ program to implement
// arithmetic operators
#include <iostream>
using namespace std;
// Driver code
int main()
{
int a = 5;
int b = 10;
cout << "Sum of a and b is" <<
" " << a + b << endl;
cout << "Difference of b and a is" <<
" " << b - a << endl;
cout << "Multiplication of a and b is" <<
" " << a * b << endl;
cout << "Division of b and a is" <<
" " << b / a << endl;
cout << "Modulo of b and a is" <<
" " << b % a << endl;
return 0;
}
OutputSum of a and b is 15
Difference of b and a is 5
Multiplication of a and b is 50
Division of b and a is 2
Modulo of b and a is 0
- Pre-incrementer: It increments the value of the operand instantly.
- Post-incrementer: It stores the current value of the operand temporarily and only after that statement is completed, the value of the operand is incremented.
- Pre-decrementer: It decrements the value of the operand instantly.
- Post-decrementer: It stores the current value of the operand temporarily and only after that statement is completed, the value of the operand is decremented.
Below is the C++ program to implement Post-incrementer and Post-decrementer:
C++
// C++ program to implement
// post-incrementer and
// post-decrementer
#include <iostream>
using namespace std;
// Driver code
int main()
{
int a = 10;
int b;
int c;
b = a++;
cout << a << " " <<
b << endl;
c = a--;
cout << a << " " <<
c << endl;
return 0;
}
Below is the C++ program to implement Pre-incrementer and Pre-decrementer:
C++
// C++ program to implement
// pre-incrementer and
// pre-decrementer
#include <iostream>
using namespace std;
// Driver code
int main()
{
int a = 10;
int b;
int c;
b = ++a;
cout << a << " " <<
b << endl;
c = --a;
cout << a << " " <<
c << endl;
return 0;
}
2. Relational Operators
Relational operators define the relation between 2 entities. They give a boolean value as result i.e true or false.
Suppose: A=5 and B=10
Operator | Operation | Example |
---|
== | Gives true if two operands are equal | A==B is not true |
!= | Gives true if two operands are not equal | A!=B is true |
> | Gives true if the left operand is more than the right operand | A>B is not true |
< | Gives true if the left operand is less than the right operand | A<B is true |
>= | Gives true if the left operand is more than the right operand or equal to it | A>=B is not true |
<= | Gives true if the left operand is less than the right operand or equal to it | A<=B is true |
Below is the C++ program to implement relational operators:
C++
// C++ program to implement
// relational operators
#include <iostream>
using namespace std;
// Driver code
int main()
{
int a = 5;
int b = 10;
if (a == b)
{
cout << "a==b is not equal to true" <<
endl;
}
if (a != b)
{
cout << "a != b is true" <<
endl;
}
if (a > b)
{
cout << "a > b is not true" <<
endl;
}
if (a < b)
{
cout << "a < b is true" << endl;
}
if (a >= b)
{
cout << "a >= b is not true" <<
endl;
}
if (a <= b)
{
cout << "a <= b is true" <<
endl;
}
return 0;
}
Outputa != b is true
a < b is true
a <= b is true
3. Logical Operators
Logical operators are used to connecting multiple expressions or conditions together. We have 3 basic logical operators.
Suppose: A=0 and B=1
Operator | Operation | Example |
---|
&& | AND operator. Gives true if both operands are non-zero | (A && B) is false |
|| | OR operator. Gives true if at least one of the two operands are non-zero | (A || B) is true |
! | NOT operator. Reverse the logical state of the operand | !A is true |
Below is the C++ program to implement the logical operators:
C++
// C++ program to implement
// the logical operators
#include <iostream>
using namespace std;
// Driver code
int main()
{
int a = 0;
int b = 1;
if (a && b)
{
cout << "a && b is false" <<
endl;
}
if (a || b)
{
cout << "a || b is true" <<
endl;
}
if (!a)
{
cout << "!a is true" <<
endl;
}
return 0;
}
Outputa || b is true
!a is true
Example:
- If we need to check whether a number is divisible by both 2 and 3, we will use the AND operator: (num%2==0) && num(num%3==0)
- If this expression gives true value then that means that num is divisible by both 2 and 3. (num%2==0) || (num%3==0)
- If this expression gives true value then that means that num is divisible by 2 or 3 or both.
4. Bitwise Operators
Bitwise operators are the operators that operate on bits and perform bit-by-bit operations.
Suppose: A = 5(0101) and B = 6(0110)
Operator | Operation | Example |
---|
& | Binary AND. Copies a bit to the result if it exists in both operands. |
0101
& 0110
----------
0100
|
| | Binary OR. Copies a bit if it exists in either operand. |
0101
| 0110
---------
0111
|
^ | Binary XOR. Copies the bit if it is set in one operand but not both. |
0101
^ 0110
----------
0011
|
~ | Binary One's Complement. Flips the bit. | ~0101 => 1010 |
<< | Binary Left Shift. The left operand's bits are moved left by the number of places specified by the right operand |
4 (0100)
4 << 1
= 1000 = 8
|
>> | Binary Right Shift Operator. The left operand's bits are moved right by the number of places specified by the right operand. |
4 >> 1
= 0010 = 2
|
If shift operator is applied on a number N then,
- N<<a will give a result N*2^a
- N>>a will give a result N/2^a
Below is the C++ program to implement bitwise operators:
C++
// C++ program to implement
// bitwise operators
#include <iostream>
using namespace std;
// Driver code
int main()
{
// Binary representation
// of 5 is 0101
int a = 5;
// Binary representation
// of 6 is 0110
int b = 6;
cout << (a & b) << endl;
cout << (a | b) << endl;
cout << (a ^ b) << endl;
cout << (a << 1) << endl;
cout << (a >> 1) << endl;
return 0;
}
5. Assignment Operators
Operator | Operation | Example |
---|
= | Assigns the value of right operand to left operand. | A=B will put the value of B in A |
+= | Adds the right operand to the left operand and assigns the result of the left operand. | A+=B means A=A+B |
-= | Subtracts the right operand from the left operand and assigns the result to the left operand. | A-=B means A=A-B |
*= | Multiplies the right operand with the left operand and assigns the result to the left operand. | A*=B means A=A*B |
/= | Divides left operand with the right operand and assign the result to the left operand. | A/=B means A=A/B |
Below is the C++ program to implement assignment operator:
C++
// C++ program to implement
// assignment operator
#include <iostream>
using namespace std;
// Driver code
int main()
{
// a is assigned value 5
int a = 5;
// a becomes 5
cout << a << endl;
// this is same as a=a+2
a += 2;
// a becomes 5+2 =7
cout << a << endl;
// this is same as a=a-2
a -= 2;
// a becomes 7-2 =5
cout << a << endl;
// this is same as a=a*2
a *= 2;
// a becomes 5*2 =10
cout << a << endl;
// this is same as a=a/2
a /= 2;
// a becomes 10/2 =5
cout << a << endl;
return 0;
}
6. Misc Operators
Operator | Operation | Example |
---|
sizeof() | Returns the size of the variable. | If a is an integer then sizeof(a) will return 4. |
Condition?X:Y | Conditional operator. If the condition is true, then returns the value of X or else the value of Y. | A+=B means A=A+B |
Cast | The casting operator convert one data type to another | int(4.350) would return 4. |
Comma(,) | Comma operator causes a sequence of operations to be performed. The value of the entire comma expression is the value of the last expression of the comma-separated list. | |
Below is the C++ program to implement miscellaneous operator:
C++
// C++ program to implement
// miscellaneous operator
#include <iostream>
using namespace std;
// Driver code
int main()
{
int a = 4;
// sizeof () returns the size
// of variable in bytes
cout << sizeof(a) << endl;
int x = 5;
int y = 8;
// ternary or conditional operator
int min = x < y ? x : y;
cout << "Minimum value from x and y is " <<
min << endl;
// casting from float to int
cout << int(4.350) << endl;
// comma operator is used for
int d = 2, b = 3, c = 4;
// multiple declarations
cout << d << " " << b << " " <<
c << " " << endl;
return 0;
}
Output4
Minimum value from x and y is 5
4
2 3 4
Precedence of Operators
Category | Operator | Associativity |
---|
Postfix | () [] -> . ++ -- | Left to right |
Unary | + - ! ~ ++ __ (type) * & sizeof | Right to left |
Multiplicative | * / % | Left to right |
Additive | + - | Left to right |
Shift | << >> | Left to right |
Relational | < <= > >= | Left to right |
Equality | == != | Left to right |
Bitwise AND | & | Left to right |
Bitwise XOR | ^ | Left to right |
Bitwise OR | | | Left to right |
Logical AND | && | Left to right |
Logical OR | || | Left to right |
Conditional | ?: | Right to left |
Assignment | = += -= /= %= >>= <<= &= ^= |= | Right to left |
Comma | , | Left to right |
1. if/else
The if block is used to specify the code to be executed if the condition specified in it is true, the else block is executed otherwise. Below is the C++ program to implement if-else:
C++
// C++ program to implement
// if-else
#include <iostream>
using namespace std;
// Driver code
int main()
{
int age;
cin >> age;
if (age >= 18)
{
cout << "You can vote.";
}
else
{
cout << "Not eligible for voting.";
}
return 0;
}
OutputNot eligible for voting.
2. else if
To specify multiple if conditions, we first use if and then the consecutive statements use else if. Below is the C++ program to implement else if:
C++
// C++ program to implement
// else if
#include <iostream>
using namespace std;
// Driver code
int main()
{
int x, y;
cin >> x >> y;
if (x == y)
{
cout << "Both the numbers are equal";
}
else if (x > y)
{
cout << "X is greater than Y";
}
else
{
cout << "Y is greater than X";
}
return 0;
}
OutputY is greater than X
3. nested if
To specify conditions within conditions we make the use of nested ifs. Below is the C++ program to implement nested if:
C++
// C++ program to implement
// nested if
#include <iostream>
using namespace std;
// Driver code
int main()
{
int x, y;
cin >> x >> y;
if (x == y)
{
cout << "Both the numbers are equal";
}
else
{
if (x > y)
{
cout << "X is greater than Y";
}
else
{
cout << "Y is greater than X";
}
}
return 0;
}
OutputY is greater than X
4. Switch Statement
Switch case statements are a substitute for long if statements that compare a variable to multiple values. After a match is found, it executes the corresponding code of that value case.
Syntax:
switch (n)
{
case 1: // code to be executed if n == 1;
break;
case 2: // code to be executed if n == 2;
break;
default: // code to be executed if n doesn't match any of the above cases
}
- The variable in the switch should have a constant value.
- The break statement is optional. It terminates the switch statement and moves control to the next line after the switch.
- If the break statement is not added, the switch will not get terminated and it will continue onto the next line after the switch.
- Every case value should be unique.
- The default case is optional. But it is important as it is executed when no case value could be matched.
Basic Calculator Using Switch Statement:
C++
// C++ program to implement
// the switch statement
#include <iostream>
using namespace std;
// Driver code
int main()
{
int n1, n2;
char op;
cout << "Enter 2 numbers: ";
cin >> n1 >> n2;
cout << "Enter operand: ";
cin >> op;
switch (op)
{
case '+':
cout << n1 + n2 << endl;
break;
case '-':
cout << n1 - n2 << endl;
break;
case '*':
cout << n1 * n2 << endl;
break;
case '/':
cout << n1 / n2 << endl;
break;
case '%':
cout << n1 % n2 << endl;
break;
default:
cout << "Operator not found!" <<
endl;
break;
}
return 0;
}
OutputEnter 2 numbers: Enter operand: Operator not found!
A loop is used for executing a block of statements repeatedly until a particular condition is satisfied. A loop consists of an initialization statement, a test condition, and an increment statement.
1. for loop
The syntax of the for loop is
for (initialization; condition; update)
{
// body of-loop
}
Below is the C++ program to implement for loop:
C++
// C++ program to implement
// for loop
#include <iostream>
using namespace std;
// Driver code
int main()
{
for (int i = 1; i <= 5; i++)
{
cout << i << " ";
}
return 0;
}
Explanation:
The for loop is initialized by the value 1, the test condition is i<=5 i.e the loop is executed till the value of i remains lesser than or equal to 5. In each iteration, the value of i is incremented by one by doing i++.
2. while loop
The syntax for while loop is
while (condition)
{
// body of the loop
}
Below is the C++ program to implement while loop:
C++
// C++ program to implement
// while loop
#include <iostream>
using namespace std;
// Driver code
int main()
{
int i = 1;
while (i <= 5)
{
cout << i << " ";
i++;
}
return 0;
}
Explanation:
The while loop is initialized by the value 1, the test condition is i<=5 i.e the loop is executed till the value of i remains lesser than or equal to 5. In each iteration, the value of i is incremented by one by doing i++.
3. do͙ while loop
The syntax for while loop is
do {
// body of loop;
}
while (condition);
Below is the C++ program to implement do-while loop:
C++
// C++ program to implement
// do-while loop
#include <iostream>
using namespace std;
// Driver code
int main()
{
int i = 1;
do {
cout << i << " ";
i++;
} while (i <= 5);
return 0;
}
Explanation:
The do-while loop variable is initialized by the value 1, in each iteration, the value of i is incremented by one by doing i++, the test condition is i<=5 i.e the loop is executed till the value of i remains lesser than or equal to 5. Since the testing condition is checked only once the loop has already run so a do-while loop runs at least once.
Jumps in Loops
Jumps in loops are used to control the flow of loops. There are two statements used to implement jump in loops - Continue and Break. These statements are used when we need to change the flow of the loop when some specified condition is met.
1. Continue
The continue statement is used to skip to the next iteration of that loop. This means that it stops one iteration of the loop. All the statements present after the continue statement in that loop are not executed.
Below is the C++ program to implement the Continue statement:
C++
// C++ program to implement
// the continue statement
#include <iostream>
using namespace std;
// Driver code
int main()
{
int i;
for (i = 1; i <= 20; i++)
{
if (i % 3 == 0)
{
continue;
}
cout << i << endl;
}
}
Output1
2
4
5
7
8
10
11
13
14
16
17
19
20
Explanation:
In this for loop, whenever i is a number divisible by 3, it will not be printed as the loop will skip to the next iteration due to the continue statement. Hence, all the numbers except those which are divisible by 3 will be printed.
2. Break
The break statement is used to terminate the current loop. As soon as the break statement is encountered in a loop, all further iterations of the loop are stopped and control is shifted to the first statement after the end of the loop.
Below is the C++ program to implement the break statement:
C++
// C++ program to implement
// the break statement
#include <iostream>
using namespace std;
// Driver code
int main()
{
int i;
for (i = 1; i <= 20; i++)
{
if (i == 11)
{
break;
}
cout << i << endl;
}
}
Output1
2
3
4
5
6
7
8
9
10
Explanation:
In this loop, when i becomes equal to 11, the for loop terminates due to break statement, Hence, the program will print numbers from 1 to 10 only.
Similar Reads
C++ Programming Language C++ is a computer programming language developed by Bjarne Stroustrup as an extension of the C language. It is known for is fast speed, low level memory management and is often taught as first programming language. It provides:Hands-on application of different programming concepts.Similar syntax to
5 min read
C++ Overview
Introduction to C++ Programming LanguageC++ is a general-purpose programming language that was developed by Bjarne Stroustrup as an enhancement of the C language to add object-oriented paradigm. It is considered as a middle-level language as it combines features of both high-level and low-level languages. It has high level language featur
3 min read
Features of C++C++ is a general-purpose programming language that was developed as an enhancement of the C language to include an object-oriented paradigm. It is an imperative and compiled language. C++ has a number of features, including:Object-Oriented ProgrammingMachine IndependentSimpleHigh-Level LanguagePopul
5 min read
History of C++The C++ language is an object-oriented programming language & is a combination of both low-level & high-level language - a Middle-Level Language. The programming language was created, designed & developed by a Danish Computer Scientist - Bjarne Stroustrup at Bell Telephone Laboratories (
7 min read
Interesting Facts about C++C++ is a general-purpose, object-oriented programming language. It supports generic programming and low-level memory manipulation. Bjarne Stroustrup (Bell Labs) in 1979, introduced the C-With-Classes, and in 1983 with the C++. Here are some awesome facts about C++ that may interest you: The name of
2 min read
Setting up C++ Development EnvironmentC++ runs on lots of platforms like Windows, Linux, Unix, Mac, etc. If you do not want to set up a local environment you can also use online IDEs for compiling your program.Using Online IDEIDE stands for an integrated development environment. IDE is a software application that provides facilities to
8 min read
Difference between C and C++C++ is often viewed as a superset of C. C++ is also known as a "C with class" This was very nearly true when C++ was originally created, but the two languages have evolved over time with C picking up a number of features that either weren't found in the contemporary version of C++ or still haven't m
3 min read
C++ Basics
Understanding First C++ ProgramThe "Hello World" program is the first step towards learning any programming language and is also one of the most straightforward programs you will learn. It is the basic program that demonstrates the working of the coding process. All you have to do is display the message "Hello World" on the outpu
4 min read
C++ Basic SyntaxSyntax refers to the rules and regulations for writing statements in a programming language. They can also be viewed as the grammatical rules defining the structure of a programming language.The C++ language also has its syntax for the functionalities it provides. Different statements have different
4 min read
C++ CommentsComments in C++ are meant to explain the code as well as to make it more readable. Their purpose is to provide information about code lines. When testing alternative code, they can also be used to prevent execution of some part of the code. Programmers commonly use comments to document their work.Ex
3 min read
Tokens in CIn C programming, tokens are the smallest units in a program that have meaningful representations. Tokens are the building blocks of a C program, and they are recognized by the C compiler to form valid expressions and statements. Tokens can be classified into various categories, each with specific r
4 min read
C++ KeywordsKeywords are the reserved words that have special meanings in the C++ language. They are the words that have special meaning in the language. C++ uses keywords for a specifying the components of the language, such as void, int, public, etc. They can't be used for a variable name, function name or an
2 min read
Difference between Keyword and Identifier in CIn C, keywords and identifiers are basically the fundamental parts of the language used. Identifiers are the names that can be given to a variable, function or other entity while keywords are the reserved words that have predefined meaning in the language.The below table illustrates the primary diff
3 min read
C++ Variables and Constants
C++ VariablesIn C++, variable is a name given to a memory location. It is the basic unit of storage in a program. The value stored in a variable can be accessed or changed during program execution.Creating a VariableCreating a variable and giving it a name is called variable definition (sometimes called variable
4 min read
Constants in CIn C programming, const is a keyword used to declare a variable as constant, meaning its value cannot be changed after it is initialized. It is mainly used to protect variables from being accidentally modified, making the program safer and easier to understand. These constants can be of various type
4 min read
Scope of Variables in C++In C++, the scope of a variable is the extent in the code upto which the variable can be accessed or worked with. It is the region of the program where the variable is accessible using the name it was declared with.Let's take a look at an example:C++#include <iostream> using namespace std; //
7 min read
Storage Classes in C++ with ExamplesC++ Storage Classes are used to describe the characteristics of a variable/function. It determines the lifetime, visibility, default value, and storage location which helps us to trace the existence of a particular variable during the runtime of a program. Storage class specifiers are used to specif
6 min read
Static Keyword in C++The static keyword in C++ has different meanings when used with different types. In this article, we will learn about the static keyword in C++ along with its various uses.In C++, a static keyword can be used in the following context:Table of ContentStatic Variables in a FunctionStatic Member Variab
5 min read
C++ Data Types and Literals
C++ Data TypesData types specify the type of data that a variable can store. Whenever a variable is defined in C++, the compiler allocates some memory for that variable based on the data type with which it is declared as every data type requires a different amount of memory.C++ supports a wide variety of data typ
7 min read
Literals in CIn C, Literals are the constant values that are assigned to the variables. Literals represent fixed values that cannot be modified. Literals contain memory but they do not have references as variables. Generally, both terms, constants, and literals are used interchangeably. For example, âconst int =
4 min read
Derived Data Types in C++The data types that are derived from the primitive or built-in datatypes are referred to as Derived Data Types. They are generally the data types that are created from the primitive data types and provide some additional functionality.In C++, there are four different derived data types:Table of Cont
4 min read
User Defined Data Types in C++User defined data types are those data types that are defined by the user himself. In C++, these data types allow programmers to extend the basic data types provided and create new types that are more suited to their specific needs. C++ supports 5 user-defined data types:Table of ContentClassStructu
4 min read
Data Type Ranges and Their Macros in C++Most of the times, in competitive programming, there is a need to assign the variable, the maximum or minimum value that data type can hold but remembering such a large and precise number comes out to be a difficult job. Therefore, C++ has certain macros to represent these numbers, so that these can
3 min read
C++ Type ModifiersIn C++, type modifiers are the keywords used to change or give extra meaning to already existing data types. It is added to primitive data types as a prefix to modify their size or range of data they can store.C++ have 4 type modifiers which are as follows:Table of Contentsigned Modifierunsigned Mod
4 min read
Type Conversion in C++Type conversion means converting one type of data to another compatible type such that it doesn't lose its meaning. It is essential for managing different data types in C++. Let's take a look at an example:C++#include <iostream> using namespace std; int main() { // Two variables of different t
4 min read
Casting Operators in C++The casting operators is the modern C++ solution for converting one type of data safely to another type. This process is called typecasting where the type of the data is changed to another type either implicitly (by the compiler) or explicitly (by the programmer).Let's take a look at an example:C++#
5 min read
C++ Operators
Operators in C++C++ operators are the symbols that operate on values to perform specific mathematical or logical computations on given values. They are the foundation of any programming language.Example:C++#include <iostream> using namespace std; int main() { int a = 10 + 20; cout << a; return 0; }Outpu
9 min read
C++ Arithmetic OperatorsArithmetic Operators in C++ are used to perform arithmetic or mathematical operations on the operands (generally numeric values). An operand can be a variable or a value. For example, â+â is used for addition, '-' is used for subtraction, '*' is used for multiplication, etc. Let's take a look at an
4 min read
Unary Operators in CIn C programming, unary operators are operators that operate on a single operand. These operators are used to perform operations such as negation, incrementing or decrementing a variable, or checking the size of a variable. They provide a way to modify or manipulate the value of a single variable in
5 min read
Bitwise Operators in CIn C, bitwise operators are used to perform operations directly on the binary representations of numbers. These operators work by manipulating individual bits (0s and 1s) in a number.The following 6 operators are bitwise operators (also known as bit operators as they work at the bit-level). They are
6 min read
Assignment Operators in CIn C, assignment operators are used to assign values to variables. The left operand is the variable and the right operand is the value being assigned. The value on the right must match the data type of the variable otherwise, the compiler will raise an error.Let's take a look at an example:C#include
4 min read
C++ sizeof OperatorThe sizeof operator is a unary compile-time operator used to determine the size of variables, data types, and constants in bytes at compile time. It can also determine the size of classes, structures, and unions.Let's take a look at an example:C++#include <iostream> using namespace std; int ma
3 min read
Scope Resolution Operator in C++In C++, the scope resolution operator (::) is used to access the identifiers such as variable names and function names defined inside some other scope in the current scope. Let's take a look at an example:C++#include <iostream> int main() { // Accessing cout from std namespace using scope // r
4 min read
C++ Input/Output
C++ Control Statements
Decision Making in C (if , if..else, Nested if, if-else-if )In C, programs can choose which part of the code to execute based on some condition. This ability is called decision making and the statements used for it are called conditional statements. These statements evaluate one or more conditions and make the decision whether to execute a block of code or n
7 min read
C++ if StatementThe C++ if statement is the most simple decision-making statement. It is used to decide whether a certain statement or block of statements will be executed or not executed based on a certain condition. Let's take a look at an example:C++#include <iostream> using namespace std; int main() { int
3 min read
C++ if else StatementThe if statement alone tells us that if a condition is true it will execute a block of statements and if the condition is false, it wonât. But what if we want to do something else if the condition is false. Here comes the C++ if else statement. We can use the else statement with if statement to exec
3 min read
C++ if else if LadderIn C++, the if-else-if ladder helps the user decide from among multiple options. The 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. I
3 min read
Switch Statement in C++In C++, the switch statement is a flow control statement that is used to execute the different blocks of statements based on the value of the given expression. It is a simpler alternative to the long if-else-if ladder.SyntaxC++switch (expression) { case value_1: // code to be executed. break; case v
5 min read
Jump statements in C++Jump statements are used to manipulate the flow of the program if some conditions are met. It is used to terminate or continue the loop inside a program or to stop the execution of a function.In C++, there is four jump statement:Table of Contentcontinue Statementbreak Statementreturn Statementgoto S
4 min read
C++ LoopsIn C++ programming, sometimes there is a need to perform some operation more than once or (say) n number of times. For example, suppose we want to print "Hello World" 5 times. Manually, we have to write cout for the C++ statement 5 times as shown.C++#include <iostream> using namespace std; int
7 min read
for Loop in C++In C++, for loop is an entry-controlled loop that is used to execute a block of code repeatedly for the given number of times. It is generally preferred over while and do-while loops in case the number of iterations is known beforehand.Let's take a look at an example:C++#include <bits/stdc++.h
6 min read
Range-Based for Loop in C++In C++, the range-based for loop introduced in C++ 11 is a version of for loop that is able to iterate over a range. This range can be anything that is iteratable, such as arrays, strings and STL containers. It provides a more readable and concise syntax compared to traditional for loops.Let's take
3 min read
C++ While LoopIn C++, the while loop is an entry-controlled loop that repeatedly executes a block of code as long as the given condition remains true. Unlike the for loop, while loop is used in situations where we do not know the exact number of iterations of the loop beforehand as the loop execution is terminate
3 min read
C++ do while LoopIn C++, the do-while loop is an exit-controlled loop that repeatedly executes a block of code at least once and continues executing as long as a given condition remains true. Unlike the while loop, the do-while loop guarantees that the loop body will execute at least once, regardless of whether the
4 min read
C++ Functions
Functions in C++A Function is a reusable block of code designed to perform a specific task. It helps break large programs into smaller, logical parts. Functions make code cleaner, easier to understand, and more maintainable.Just like in other languages, C++ functions can take inputs (called parameters), execute a b
8 min read
return Statement in C++In C++, the return statement returns the flow of the execution to the function from where it is called. This statement does not mandatorily need any conditional statements. As soon as the statement is executed, the flow of the program stops immediately and returns the control from where it was calle
4 min read
Parameter Passing Techniques in CIn C, passing values to a function means providing data to the function when it is called so that the function can use or manipulate that data. Here:Formal Parameters: Variables used in parameter list in a function declaration/definition as placeholders. Also called only parameters.Actual Parameters
3 min read
Difference Between Call by Value and Call by Reference in CFunctions can be invoked in two ways: Call by Value or Call by Reference. These two ways are generally differentiated by the type of values passed to them as parameters.The following table lists the differences between the call-by-value and call-by-reference methods of parameter passing.Call By Valu
4 min read
Default Arguments in C++A default argument is a value provided for a parameter in a function declaration that is automatically assigned by the compiler if no value is provided for those parameters in function call. If the value is passed for it, the default value is overwritten by the passed value.Example:C++#include <i
5 min read
Inline Functions in C++In C++, inline functions provide a way to optimize the performance of the program by reducing the overhead related to a function call. When a function is specified as inline the whole code of the inline function is inserted or substituted at the point of its call during the compilation instead of us
6 min read
Lambda Expression in C++C++ 11 introduced lambda expressions to allow inline functions which can be used for short snippets of code that are not going to be reused. Therefore, they do not require a name. They are mostly used in STL algorithms as callback functions.Example:C++#include <iostream> using namespace std; i
4 min read
C++ Pointers and References
Pointers and References in C++In C++ pointers and references both are mechanisms used to deal with memory, memory address, and data in a program. Pointers are used to store the memory address of another variable whereas references are used to create an alias for an already existing variable. Pointers in C++ Pointers in C++ are a
5 min read
C++ PointersA pointer is a special variable that holds the memory address of another variable, rather than storing a direct value itself. Pointers allow programs to access and manipulate data in memory efficiently, making them a key feature for system-level programming and dynamic memory management. When we acc
8 min read
Dangling, Void , Null and Wild Pointers in CIn C programming pointers are used to manipulate memory addresses, to store the address of some variable or memory location. But certain situations and characteristics related to pointers become challenging in terms of memory safety and program behavior these include Dangling (when pointing to deall
6 min read
Applications of Pointers in CPointers in C are variables that are used to store the memory address of another variable. Pointers allow us to efficiently manage the memory and hence optimize our program. In this article, we will discuss some of the major applications of pointers in C. Prerequisite: Pointers in C. C Pointers Appl
4 min read
Understanding nullptr in C++Consider the following C++ program that shows problem with NULL (need of nullptr) CPP // C++ program to demonstrate problem with NULL #include <bits/stdc++.h> using namespace std; // function with integer argument void fun(int N) { cout << "fun(int)"; return;} // Overloaded fun
3 min read
References in C++In C++, a reference works as an alias for an existing variable, providing an alternative name for it and allowing you to work with the original data directly.Example:C++#include <iostream> using namespace std; int main() { int x = 10; // ref is a reference to x. int& ref = x; // printing v
5 min read
Can References Refer to Invalid Location in C++?Reference Variables: You can create a second name for a variable in C++, which you can use to read or edit the original data contained in that variable. While this may not sound appealing at first, declaring a reference and assigning it a variable allows you to treat the reference as if it were the
2 min read
Pointers vs References in C++Prerequisite: Pointers, References C and C++ support pointers, which is different from most other programming languages such as Java, Python, Ruby, Perl and PHP as they only support references. But interestingly, C++, along with pointers, also supports references. On the surface, both references and
5 min read
Passing By Pointer vs Passing By Reference in C++In C++, we can pass parameters to a function either by pointers or by reference. In both cases, we get the same result. So, what is the difference between Passing by Pointer and Passing by Reference in C++?Let's first understand what Passing by Pointer and Passing by Reference in C++ mean:Passing by
5 min read
When do we pass arguments by pointer?In C, the pass-by pointer method allows users to pass the address of an argument to the function instead of the actual value. This allows programmers to change the actual data from the function and also improve the performance of the program. In C, variables are passed by pointer in the following ca
5 min read