Open In App

C++ Basics

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++ Basic Program




// C++ Hello World Program
#include <iostream>
using namespace std;
int main()
{
  cout << "Hello World!\n";
  return 0;
}

Output

Hello World!

Components of a C++ Code:

  1. 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.
  2. #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++.
  3. Using namespace std: All elements of the standard C++ library are declared within a namespace.  Here we are using the std namespace.
  4. 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).
  5. {}: The curly brackets are used to indicate the starting and ending point of any function. Every opening bracket should have a corresponding closing bracket.
  6. 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 (;).
  7. 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)  



Below is the C++ program to illustrate standard output:




// C++ program to implement
// standard output
#include <iostream>
using namespace std;
int main()
{
  cout << "Geeks For Geeks";
  return 0;
}

Output
Geeks For Geeks

Standard input (cin)  

Below is the C++ program to illustrate standard input:




// 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;
}

Output
Enter a number
User entered number 0

Data Types in C++  

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 

2. float and double

3. char 

4. bool 

C++ Type Modifiers  

Type modifiers are used to modify the fundamental data types.

Data Type    Size (in Bytes) Meaning 
signed int  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++ 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;
}

Output
Size 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

Derived Data Types

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++ 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;
}

Output
Array 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

User-Defined Data Types

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++ 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;
}

Output
String is: GeeksForGeeks is the best Technical Website

Below is the C++ program to implement structure user-defined data type:




// 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;
}

Output
30, 40

Below is the C++ program to implement union user-defined data type:




// 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;
}

Output
After 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++ 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;
}

Output
3

Operators in C++

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.

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++ 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;
}

Output
Sum 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
  1. Pre-incrementer: It increments the value of the operand instantly.
  2. 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.
  3. Pre-decrementer: It decrements the value of the operand instantly.
  4. 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++ 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;
}

Output
11 10
10 11

Below is the C++ program to implement Pre-incrementer and Pre-decrementer:




// 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;
}

Output
11 11
10 10

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++ 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;
}

Output
a != 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++ 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;
}

Output
a || b is true
!a is true

Example:

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,

Below is the C++ program to implement bitwise operators:




// 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;
}

Output
4
7
3
10
2

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++ 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;
}

Output
5
7
5
10
5

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++ 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;
}

Output
4
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

Decision Making  

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++ 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;
}

Output
Not 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++ 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;
}

Output
Y 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++ 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;
}

Output
Y 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
} 

Basic Calculator Using Switch Statement:




// 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;
}

Output
Enter 2 numbers: Enter operand: Operator not found!

Loops in C++

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++ 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;
}

Output
1 2 3 4 5 

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++ 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;
}

Output
1 2 3 4 5 

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++ 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;
}

Output
1 2 3 4 5 

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++ 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;
  }
}

Output
1
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++ 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;
  }
}

Output
1
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.


Article Tags :