CPP All
CPP All
In this tutorial, we are going to learn about the basic structure of a C++
program. Let's first write a simple C++ program to print "Hello World" string on
screen. This program is very useful to learn the basic syntax and semantics of
the C++ language. It become the traditional first program that many people
write while learning a new programming language.
2. Compile
o Open command prompt and go to your current working
directory where you saved your HelloWorld.cpp file.
o Compile your code by typing "g++ HelloWorld.cpp" in
command prompt. Your program will compile successfully, If your
program doesn't contain any syntax error.
o It will generate an a.out file.
3. Execute
o Now run your program by typing "a.out" in command
prompt.
4. Output
o You will see "Hello World" printed on your console.
C++ First Program Hello World
In this tutorial, we are going to learn about the basic structure of a C++
program. Let's first write a simple C++ program to print "Hello World" string on
screen. This program is very useful to learn the basic syntax and semantics of
the C++ language. It become the traditional first program that many people
write while learning a new programming language.
2. Compile
o Open command prompt and go to your current working
directory where you saved your HelloWorld.cpp file.
o Compile your code by typing "g++ HelloWorld.cpp" in
command prompt. Your program will compile successfully, If your
program doesn't contain any syntax error.
o It will generate an a.out file.
3. Execute
o Now run your program by typing "a.out" in command
prompt.
4. Output
o You will see "Hello World" printed on your console.
C++ Comments
Comments are added in C++ program for documentation purpose. Comments
are explanatory statements that we can in our code to make it easy to
understand for anyone reading this source code. We can add comments
anywhere and any number of times in our programs. Adding comments in
your code is highly recommended and is considered as a good programming
practice. Comment are ignored by C++ compilers.
C++ programming language supports two types of comments
• Single line comments.
• Multi line comments(inherited from C).
• Single line comment starts with “//” symbol and till end of the line.
• Everything on the line after // is ignored by compiler.
For Example:
// My first C++ Program
cout << "Hello_World";
cout << "Hello_World"; // My first C++ Program
• Multi line comments in C++ start with /* and end with */.
Everything between /* and */ is ignored by compiler.
• Nesting of multi-line comments is not allowed.
• Inside multi line comment // characters have no special meaning.
For Example:
/* This is my first C++ program
to print Hello World string on screen
*/
cout << "Hello World";
cout << "Hello World"; /* My first C++ Program */
Summary
Based on the data type of the variable after extraction operator(>>) cin
determine how it interprets the characters read from the input. If the variable is
of integer data type than it will expect integer input from user.
We can also take string input from user using cin and extraction operator. For
string input, it reads characters till first white space character(space, tab,
newline etc). With cin we can only read one word at a time, it does not support
reading an entire line having space characters. To read an entire space
seperated sentence we should use "getline" function.
Output :
20
Hello
World
C++ Program for Basic Input Output using cin and cout
#include <iostream>
using namespace std;
int main( ) {
char name[50];
int age, salary, account_number;
cout << name << endl << age << endl <<
salary << endl << account_number;
return 0;
}
Output
Enter your name
Adam
Enter your age
22
Enter your salary and account number
2345 87654
Adam
22
2345
87654
In above program, we are taking input from user using cin and printing it on
screen using cout as explained above. We are taking input of different data
types like integer and string. We are also taking multiple inputs in a single cin
statement by using multiple extraction operator.
C++ Keywords and Identifiers
C++ Keywords
C++ keywords are the reserved words which are pre-defined in C++
programming language. We cannot use keywords as an identifier. Each
keyword has a pre-defined meaning for C++ compiler.
• Trying to use a keyword as an identifier will generate a
compilation error.
• All keywords are in lower case letters.
Here is the list of reserved keywords in C++.
asm else new thi
C++ Identifiers
In C++ programming language, the name of variables, functions, labels,
classes and user-defined entities are called Identifiers. Each element of a C++
program are given an identifier. A C++ identifier can be of any length, there is
no limit on the length of the identifiers in C++.
For Example:
int Interest;
int getSimpleInterest(int amount);
hello 1hello
Hello Hel/lo
_hello hel lo
hello_world hello,,,world
C++ Data Types
In C++ programming language, data type specifies the type of data a variable
can store and how much memory is required to store this data. The data type
of a variable also defines the format in which a data of particular type should
be stored.
Above statement declares a variable 'c' of character data type and stores
character 'A' in it's memory location.
Above statement declares a variable 'fl' of float data type and stores
11.243567f in it's memory location.
double data type
Floating point data type similar to float data type except it provides up-to ten
digit of precision and occupies eight bytes of memory.
For Example:
double d = 11676.2435676542;
Above statement declares a variable 'd' of double data type and stores
11676.2435676542 in it's memory location.
Output
Size for char : 1
Size for int : 4
Size for float : 4
Size for double : 8
You can also specify the type of integer constant by using a suffix character. It
can be lowercase or uppercase and can be in any order.
• L, l : Long
• U, u : Unsigned
Examples of Integer Constants
• Unsigned Integer Constant : 100U, 565U
• Long Constant : 67L, -2398876L
• Unsigned Long Constant : 55UL, 77652UL
• Decimal Constants : 85, -54
• Octal Constants : 0213, 045
• Hexadecimal Constants : 0x4b, 0x2A
\” Double quote(")
\\ Backslash Character(\)
Escape Sequence Description
\b Backspace
\f Form feed
\n New line
\r Carriage return
\t Horizontal tab
\v Vertical tab
\a Alert or bell
\? Question mark
\0 Null character
int main() {
char c1 = 'E';
wchar_t wc = L'E';
return(0);
}
Output
E
69
Tech
Crash
Course
int main() {
float radius;
return 0;
}
Output
Enter Radius of Circle
5.0
Circumference of Circle : 31.41
C++ Operators
In C++, an operator is a symbol used to perform logical and mathematical
operations in a C++ program. An expression ia a statement containing
operators and variables. C++ operators connects constants and variables to
form expressions.
For Example:
3.141 x radius x radius;
• x is operator
• 3.141 is a constant
• radius is a variables
• "3.141 x radius x radius;" is an expression, performing one logical
task.
C++ programming language is rich in built in operators.
<<= A <<= B; A = A<<b;< td="" It does bitwise left shift, then assign resu
style="box-sizing:
border-box;"></b;<>
== A == B Checks if A is equal to B
14 }
Output
Enter your score : 45
Your score : 45
Enter your score : 25
You Failed :(
Your score : 25
int main() {
int score;
cout << "Enter your score : ";
cin >> score;
/* Using if else statement to decide whether
a student passed or failed in examination */
if(score < 35){
// if condition is true then print the following
cout << "You Failed :(\n";
} else {
// if condition is false then print the following
cout << "Congrats You Passed :)\n";
}
// This line always gets printed
cout << "Your score : " << score;
return 0;
}
Output
Enter your score : 25
You Failed :(
Your score : 25
Enter your score : 60
Congrats You Passed :)
Your score : 60
int main(){
int score;
return 0;
}
Output
Enter your score between 0-100
72
YOUR GRADE : B
Enter your score between 0-100
10
YOUR GRADE : Failed
• The default code block gets executed when none of the case
matches with expression. default case is optional and doesn't require a
break statement.
29 break;
30 default :
31 /* following code will execute when n < 1 or n > 6 */
32 cout << "INVALID INPUT\n";
33 }
34
35 cout << "Always gets printed\n";
36
37 return 0;
}
Output
For Example:
for(i = 1; i <= 10; i++){
cout << i;
}
int main(){
int N, i, sum=0;
return 0;
}
Output
Enter a positive number
6
Sum of all numbers from 1 to 6 = 21
In above program, we first take a number N as input from user. Now, we have
to find sum of all numbers from 1 to N. We are using a for loop to iterate from
1 to N and add each number to variable sum.
• Opening and Closing braces are not required for single statement
inside for loop code block.
For Example:
for(i = 0; i < 100; i++)
sum+= i;
• We can also use infinite for loops like for(;;), which will never
terminate. You should add terminating condition using break statement
in order to terminate infinite for loop.
For Example:
for(;;){
if(.....){
break;
}
}
C++ While Loop
The while loop in C++ used for repetitive execution of the statements until the
given condition is true. Unlike for loop in C++, there is no initialization and
update statements in while loop.
int main(){
int N, i, sum=0;
cout << "Enter a positive number\n";
cin >> N;
/*
* Initializing loop control variable before while loop
*/
i = 1;
while(i <= N){
// Below statements will only execute if while loop
// condition evaluates to true
sum+= i;
//Incrementing loop control variable
i++;
}
cout << "Sum of Integers from 1 to %d = %d", N, sum;
return 0;
}
Output
Enter a positive number
5
Sum of Integers from 1 to 5 = 15
Enter a positive number
7
Sum of Integers from 1 to 7 = 28
• Unlike do..while loop, the body of while might not executes even
once.
• Opening and Closing braces are not required for single statement
inside while loop code block.
For Example:
while(i < 100)
sum+= i;
• We can also use infinite while loops like while(1), which will never
terminate. You should add terminating condition using break statement
in order to terminate infinite while loop.
For Example:
while(1) {
if(.....){
break;
}
}
C++ do while Loop
The do while loop in C++ is similar to while loop with one important difference,
the code block of do..while loop is executed once before the condition is
checked. It checks its condition at the bottom of the loop, before allowing the
execution of loop body for second time. The block of code is before the
condition, so code will be executed at lease once.
int main(){
int N, i, sum=0;
cout << "Enter a positive number\n";
cin >> N;
i = 1;
do {
// Below statements will execute atleast once
sum+= i;
//Incrementing loop control variable
i++;
} while(i <= N);
cout <<"Sum of Integers from 1 to " << N << " = " << sum;
return 0;
}
Output
Enter a positive number
5
Sum of Integers from 1 to 5 = 15
Enter a positive number
7
Sum of Integers from 1 to 7 = 28
• Opening and Closing braces are not required for single statement
inside do while loop code block.
For Example:
do
statement;
while(condition);
• We can also use infinite do while loops which will never terminate.
You should add terminating condition using break statement in order to
terminate infinite do while loop.
For Example:
do {
if(....){
break;
}
} while(1);
C++ goto Statement
The goto statement in C++ is used to transfer the control of program to some
other part of the program. A goto statement used as unconditional jump to
alter the normal sequence of execution of a program.
int main(){
return 0;
}
Output
Enter a positive number
25
Sum is > 50, terminating loop
Enter a positive number
8
Sum of Integers from 1 to 8 = 36
In above program, we first take an integer N as input from user using cin. We
wan to find the sum of all numbers from 1 to N. We are using a for loop to
iterate from i to N and adding the value of each number to variable sum. If
becomes greater than 50 then we break for loop using a goto statement,
which transfers control to the next statement after for loop body.
• goto statement ignores nesting levels, and does not cause any
automatic stack unwinding.
• goto statement jumps must be limited to within same function.
Cross function jumps are not allowed.
• goto statement makes difficult to trace the control flow of program
and reduces the readability of the program.
• Use of goto statement is highly discouraged in modern
programming languages.
In above example we cannot exit all three for loops at a time using break
statement because break only terminate the inner loop from where break is
executed.
Any program written in C++ language using goto statement can be re-written
using break and continue statements.
C++ break Statement
The break statement in C++ is used to terminate loops and switch statement
immediately when it appears. We sometimes want to terminate the loop
immediately without checking the condition expression of loop. Most of the
time, break statement is used with conditional statement inside body of the
loop.
Use of break statement, change the normal sequence of execution of
statements inside loop.
int main(){
return 0;
}
Output
Enter a positive number
20
Sum is > 50, terminating loop
Enter a positive number
7
Sum of Integers from 1 to 7 = 28
Above program find sum of all integers from 1 to N, using for loop. It sum is
greater than 50, break statement will terminate for loop.
C++ break Statement
The break statement in C++ is used to terminate loops and switch statement
immediately when it appears. We sometimes want to terminate the loop
immediately without checking the condition expression of loop. Most of the
time, break statement is used with conditional statement inside body of the
loop.
Use of break statement, change the normal sequence of execution of
statements inside loop.
int main(){
return 0;
}
Output
Enter a positive number
20
Sum is > 50, terminating loop
Enter a positive number
7
Sum of Integers from 1 to 7 = 28
Above program find sum of all integers from 1 to N, using for loop. It sum is
greater than 50, break statement will terminate for loop.
C++ continue Statement
The continue statement in C++ is used to skip some statements inside the
body of the loop and forces the next iteration of the loop. The continue
statement skips the rest of the statements of loop body in the current iteration.
Most of the time, continue statement is used with conditional statement inside
body of the loop. Use of continue statement, change the normal sequence of
execution of statements inside loop.
• Inside while and do..while loop, continue statement will take
control to the condition statement.
• Inside for loop, continue statement will take control to the update
statement(increment/decrement of loop control variable) then condition
will be checked.
int main(){
int N, counter, sum=0;
cout << "Enter a positive number\n";
cin >> N;
return 0;
}
Output
Enter a positive number
6
Sum of all even numbers from 1 to 6 = 12
For Example
• Declaration of a function with no input parameters
void printName();
// Function Declaration
int getSum(int a, int b);
int main(){
int a, b, sum;
cout << "Enter two numbers\n";
cin >> a >> b;
// Calling getSum function
sum = getSum(a, b);
cout << "SUM = " <<sum;
return 0;
}
// Function Defination
int getSum(int a, int b) {
return a+b;
}
Output
Enter two numbers
3 6
SUM = 9
Points To Remember
• First line is called as Function Header and it should be identical to
function Declaration/Prototype except semicolon.
• Function's definition contains code to be executed when this
function is called.
• Name of arguments are compulsory here unlike function
declaration.
// Function Defination
int getAreaOfSquare(int side){
// local variable declaration
int area;
area = side*side;
// Return statement
return area;
}
int main(){
int side, area;
return 0;
}
Output
Enter side of square
5
Area of Square = 25
C++ Calling a Function and Return Statement
Calling a function in C++ programming language
After writing a function in C++, we should call this function to perform the task
defined inside function body. We cannot execute the code defined inside
function's body unless we call it from another function.
When a function X calls another function Y, program control is transferred to
function Y. Function Y performs specific task defined in function's body and
when function Y terminates either by return statement or when the last
statement of function body executes, program control returns back to the
calling function X.
Above statement will call a function named findSum and pass 2 and 3 as a
parameter. It also stores the return value of findSum function in variable sum.
// Function Defination
int getAreaOfSquare(int side){
// local variable declaration
int area;
area = side*side;
// Return statement
return area;
}
int main(){
int side, area;
return 0;
}
Output
Enter radius of circle
4
Area of Circle = 50.256
Call by value
In call by value method a copy of actual arguments is passed into formal
arguments in the function definition. Any change in the formal parameters of
the function have no effect on the value of actual argument. Call by value is
the default method of passing parameters in C++. Different memories are
allocated for the formal and actual parameters.
C++ Program to Pass Arguments to Function as Call by Value
#include <iostream>
using namespace std;
int main(){
int A;
cout << "Enter a number\n";
cin >> A;
// Calling function using call by value
getDoubleValue(A);
/* Any change in the value of formal parameter(F)
will not effect the value of actual parameter(A) */
cout << "\nA(Actual Parameter) = " << A;
return 0;
}
Output
Enter a number
5
F(Formal Parameter) = 10
A(Actual Parameter) = 5
Call by reference
In call by reference method the address of the variable is passed to the formal
arguments of a function. Any change in the formal parameters of the function
will effect the value of actual argument. Same memory location is accessed by
the formal and actual parameters.
C++ Program to Pass Arguments to Function as Call by Reference
#include <iostream>
using namespace std;
void getIncrementValue(int *ptr){
*ptr = *ptr + 1;
cout << "F(Formal Parameter) = " << *ptr;
}
int main(){
int A;
cout << "Enter a number\n";
cin >> A;
// Calling function using call by reference
// by passing address of A
getIncrementValue(&A);
/* Any change in the value of formal parameter(F)
will effect the value of actual parameter(A) */
cout << "\nA(Actual Parameter) = " << A;
return 0;
}
Output
Enter a number
5
F(Formal Parameter) = 6
A(Actual Parameter) = 6
Calling function can call getSum function by either passing one or two
parameters.
Here, calling function is only passing value for formal parameter A(which is 5)
and parameter B will take default value which is 10. Hence, the value of sum
will be 15.
Here, calling function is passing value for both parameters A and B. Both A
and B will contain the actual parameters passed by the calling. In this case
function will not use the default value for argument B. Hence, the value of sum
will be 11.
int main () {
int sum;
return 0;
}
Output
Sum = 11
Sum = 15
Both count and size are automatic variable. C++ Local Variable(auto)
Example Program
#include <iostream>
using namespace std;
int main(){
// Automatic variable by default
int a = 5;
// Declaration of automatic variables using auto keyword
auto int b = 10;
return 0;
}
Output
Sum = 15
static Storage Class
A local static variable is visible only inside their own function but unlike local
variables, they retain their values between function calls. We can declare
static variable by adding static keyword before data type in variable
declaration statement.
static data_type variable_name;
For Example :
static int count;
int printVal(){
// Declaring a loval static variable
static int sVariable = 0;
// Declaring a local variable
int lVariable = 0;
int main(){
printVal();
printVal();
printVal();
printVal();
return 0;
}
Output
StaticVariable = 1 LocalVariable = 1
StaticVariable = 2 LocalVariable = 1
StaticVariable = 3 LocalVariable = 1
StaticVariable = 4 LocalVariable = 1
int main(){
// Declaration of a variables using register keyword
register int counter;
int sum=0;
// Variable counter is used frequently within for loop
for(counter = 1; counter <= 500; counter++){
sum+= counter;
}
cout << "Sum = " << sum;
return 0;
}
Output
Sum = 125250
This is a simple function which takes two integer arguments and returns the
sum of two integers. We can use this function to add two integers only. To add
two floating point numbers we can overload getSum function ad follows:
Now, both above functions have same name "getSum" but their parameters
are of a different data type. We can further overload getSum function to add
three integers as follows :
All of the three overloaded functions are different from each other either in
their number of parameters or data types of parameters. We now have three
version of getSum function:
• int getSum(int a, int b); // To add two integers.
• float getSum(float a, float b); // To add two floating point numbers.
• int getSum(int a, int b, int c); // To add three integers.
int main(){
// calling getSum function with different arguments
getSum(3,5);
getSum((float)3.2, (float)5.7);
getSum(4, 7, 9);
return 0;
}
Output
Inside getSum 3 5
Inside getSum 3.2 5.7
Inside getSum 4 7 9
C++ Arrays
Array in C++ is a collection of fixed size data belongings to the same data
type. An array is a data structure provided in C++ which can store a number of
variables of same data type in sequence. These similar elements could be of
type int, float, double, char etc. All array elements are stored in the contiguous
memory locations.
For Example :
int score[100]; /* Integer array of size 100 */
char name[10]; /* character array of size 10 */
Suppose, you want to store marks of 100 students. You can store marks of all
students by creating 100 variable of int data type individually like
studentMarks1, studentMarks2, studentMarks3 .... studentMarks100. This is
very tedious, time consuming and difficult to maintain method of storing 100
marks.
C++ programming language provides support for array data structure, which
solves the problem of storing N similar data. We can declare an integer array
of length 100 to store marks of 100 students.
int studentMarks[100];
Now we can access elements of array marks using subscript followed by array
name.
• age[0] = First element of array age = 8
• age[1] = Second element of array age = 5
• age[2] = Third element of array age = 2
• age[3] = Fourth element of array age = 3
• age[4] = Last element of array age = 7
Point To Remember
Remember array indexing starts from 0. Nth element in array is at index N-1.
int main(){
int age[7] = {8,5,2,3,7,6,7};
int i;
// Printing array elements using loop
for(i = 0; i < 7; i++){
// Accessing array elements using i as index
cout << "Element at index " << i <<" is " << age[i];
cout << endl;
}
return 0;
}
Output
Element at index 0 is 8
Element at index 1 is 5
Element at index 2 is 2
Element at index 3 is 3
Element at index 4 is 7
Element at index 5 is 6
Element at index 6 is 7
int matrix[3][4];
int matrix[4][3] = {
{1, 2, 3}, /* Initialization of first row */
{4, 5, 6}, /* Initialization of second row */
{7, 8, 9}, /* Initialization of third row */
{10, 11, 12}, /* Initialization of fourth row */
};
In above declaration, compiler will assign first four values(1, 2, 3 and 4) to first
row of matrix and within a row it will populate elements from left to right. Then
next four elements to second row and so on.
Initialization of Three Dimensional Array
Similarly, we can initialize any multi dimensional array.
Similar to two dimensional array, we can also initialize 3 dimensional array as
follows :
data_type array_name[R][C];
For Example :
A two dimensional integer matrix of 3 rows and 3 columns can be declared as
int score[3][3];
int main(){
// Two dimentional array declaration
int matrix[20][20];
int rowCounter, colCounter, rows, cols, sum=0;
return 0;
}
Output
Enter size of a matrix
3 3
Enter elements of a matrix
1 2 3
3 4 5
6 7 8
Sum of all elements = 39
In above program, we first take number of rows and columns as input from
user. Then using two for loops we take matrix elements input from user and
store it in 2D array named matrix. To find the sum of each element of matrix
we traverse the matrix row wise using two for loop.
C++ Passing Array to a Function
In C++ programming, an array can be passed to a function as an argument.
We can pass an array of any dimension to a function as argument.
• Passing an array to a function uses pass by reference, which
means any change in array data inside function's body will reflect
globally.
• When an array is passed as an argument to a function, only the
name of an array is passed. Name of the array represent the address of
the first element of array.
For Example :
• int arrayName[10];
int main(){
int array[5]={1, 2, 3, 4, 5};
int counter;
for(counter = 0; counter < 5; counter++){
// Passing individual array elements to function
cout << "Square of " << array[counter] << " is " << getSquare(array[counter]);
cout << endl;
}
return 0;
}
Output
Square of 1 is 1
Square of 2 is 4
Square of 3 is 9
Square of 4 is 16
Square of 5 is 25
• }
• /* Function body */
• }
• }
int main(){
int score[5]={1, 2, 3, 4, 5};
// Passing name of array
printArrayOne(score, 5);
printArrayTwo(score, 5);
// passing address of first array element
printArrayThree(&score[0], 5);
return 0;
}
Output
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
int main(){
int matrix[3][3]={{1, 2, 3},{4, 5, 6},{7, 8, 9}};
// Passing name of array
printArray(matrix, 3, 3);
return 0;
}
Output
1 2 3
4 5 6
7 8 9
C++ Returning Array from a Function
In C++, we can return a pointer to the base address(address of first element
of array) of array from a function like any basic data type. However, C++
programming language does not allow to return whole array from a function.
We should not return base pointer of a local array declared inside a function
because as soon as control returns from a function all local variables gets
destroyed. If we want to return a local array then we should declare it as a
static variable so that it retains it's value after function call.
Declaration of a Function Returning Integer Array
int* getScoreList();
int main(){
int *array, counter;
array = getEvenNumbers(10);
cout << "Even Numbers\n";
for(counter=0; counter<10; counter++){
cout << array[counter] << " ";
}
return 0;
}
Output
2 4 6 8 10 12 14 16 18 20
C Strings
String in C programming language is a one-dimensional array of characters
which is terminated by a null character('\0'). A character array which is not null
terminated is not a valid C string. In a C string, each character occupies one
byte of memory including null character.
Null character marks the end of the string, it is the only way for the compiler to
know where this string is ending.
Examples of C Strings
• "A"
• "TechCrashCourse"
• "Tech Crash Course"
• ""
Memory representation of C string
Declaration of C Strings
Syntax of String Declaration
char string_name[SIZE_OF_STRING];
Initialization of C Strings
Initialization of string using a character array
char name[16] = {'T','e','c','h','C','r','a','s','h','C','o','u','r','s','e','\0'};
or
char name[] = {'T','e','c','h','C','r','a','s','h','C','o','u','r','s','e','\0'};
or
char name[] = "TechCrashCourse";
int main(){
char nameOne[16] = {'T','e','c','h','C','r','a','s','h','C','o','u','r','s','e','\0'};
char nameTwo[] = {'T','e','c','h','C','r','a','s','h','C','o','u','r','s','e','\0'};
char nameThree[16] = "TechCrashCourse";
char nameFour[] = "TechCrashCourse";
char *nameFive = "TechCrashCourse";
char nameSix[16];
return 0;
}
Output
TechCrashCourse
TechCrashCourse
TechCrashCourse
TechCrashCourse
TechCrashCourse
Enter a string
C++
You Entered : C++
String Handling Standard Library Functions in C++
cstring header file contains a wide range of functions to manipulate null-
terminated C strings. Below are some commonly used string handling
functions of cstring header file.
Function Description
#include <iostream>
#include <cstring>
using namespace std;
int main(){
char input[50];
char copyString[60];
return 0;
}
Output
Enter a string: TechCrashCourse
Length of TechCrashCourse : 15
Copied String : TechCrashCourse
Both Strings are Equal
Points To Remember
• Null character marks the end of the C strings.
• C Strings are single dimensional array of characters ending with a
null character(‘\0’).
• The ASCII value of null character('\0') is 0.
• Each character of string is stored in consecutive memory location
and occupy 1 byte of memory.
• Strings constants are enclosed by double quotes and character
are enclosed by single quotes.
• If the size of a C string is N, it means this string contains N-1
characters from index 0 to N-2 and last character at index N-1 is a null
character.
int main () {
// Declaring objects of string class
string strOne = "C++";
string strTwo = "Programming";
string strThree;
int length;
// Printing String
cout << strThree<< endl;;
// concatenating strOne and strTwo
strOne = strOne + strTwo;
cout << "Combined String : " << strOne << endl;
return 0;
}
Output
Enter a string
TechCrashCourse
TechCrashCourse
Combined String : C++Programming
Length of Combined String : 14
C++ Pointers
A pointer in C++ allows us to directly access data stored at a particular
memory location. Pointers are one of the most powerful feature of C++
programming language. Once you master the use of pointers, you will use
them everywhere to make the code more efficient and faster. In C++, some
operations can be performed more efficiently using pointers like dynamic data
structures like linked list and trees,dynamic memory allocation, pass
arguments to a function as Call by Reference, access array elements etc.
What is a Pointer
A pointer in C++ is a variable which is used to store the address of another
variable.
Advantages of Pointers
The * is a unary operator which returns the value stored at a memory location
which is pointed by a pointer variable. It is known as "value of" operator. It is
also used for declaring pointer variable.
For Example :
int A = 100;
int *ptr = &A;
cout << *ptr;
In the first statement, we first declare an integer variable and initialize it with
value 100. In second statement, we are declaring a pointer to a variable of
type int and initializing it with address of A. The third statement prints the
value stored at the memory location pointed by ptr, which is 100.
Pointer Declaration
A pointer is a derived data type that is created from fundamental data types.
We use (*) for defining pointer variables. Here is the syntax of declaring a
pointer variable.
<data_type> *<identifier>;
For Example :
int *ptr;
Above pointer declaration specifies that, ptr is a pointer variable that will store
the memory address of an integer. We can also initialize a pointer as follows:
int main () {
int age = 10;
int *ptr = &age;
cout << "Value of count variable is " << age << endl;
cout << "Address of count variable: " << ptr << endl;
cout << "Value retrieved through pointer : " << *ptr;
return 0;
}
Output
Value of count variable is 10
Address of count variable: 0x22fe34
Value retrieved through pointer : 10
int main() {
int count = 10;
float sum = 20.5;
int *null_ptr = NULL;
int *int_ptr = &count;
float *float_ptr = ∑
cout << "Size of NULL Pointer : " << sizeof(null_ptr) << " Bytes\n";
cout << "Size of Integer Variable : " << sizeof(count) << " Bytes\n";
cout << "Size of Integer Pointer : " << sizeof(int_ptr) << " Bytes\n";
cout << "Size of Float Variable : " << sizeof(sum) << " Bytes\n";
cout << "Size of Float Pointer : " << sizeof(float_ptr) << " Bytes\n";
return 0;
}
Output
Size of NULL Pointer : 8
Size of Integer Variable : 4
Size of Integer Pointer : 8
Size of Float Variable : 4
Size of Float Pointer : 8
C++ Pointer Arithmetic
In C++, arithmetic operations on pointer variable is similar to a numeric value.
As we know that, a pointer in C++ is a variable used to store the memory
address which is a numeric value. The arithmetic operations on pointer
variable changes the memory address pointed by pointer. Not all arithmetic
operations are valid for pointer variable, like multiplication and division. Here
is the list of valid pointer arithmetic operations.
• Incrementing a pointer.
• Decrementing a pointer.
• Adding a number to pointer.
• Subtracting a number form a pointer.
• Comparison on two pointers.
• Subtracting two pointers.
And, here is the list of invalid pointer arithmetic operations.
• Addition of two pointers.
• Division of two pointers.
• Multiplication of two pointers.
For example, Let ptr be an integer pointer, initially pointing to location 1000.
The size of integer data type is 4 bytes. Then ptr + 5 = 1000 + 4*5 = 1020.
Pointer ptr will now point at memory address 1020.
For example, Let ptr be a double pointer, initially pointing to location 1000.
The size of double data type is 6 bytes. Then ptr - 3 = 1000 - 6*3 = 982.
Pointer ptr will now point at memory address 982.
ptr++;
it will point to memory location 5004 because it will jump to the next integer
location which is 4 bytes next to the current location. Incrementing a pointer is
not same as incrementing an integer value. On incrementing, a pointer will
point to the memory location after skipping N bytes, where N is the size of the
data type(in this case it is 4).
ptr--;
int score[100];
• int score[100];
• int *ptr = score;
• int score[100];
• int score[100];
ptr = ptr + 1;
int main () {
int score[6] = {1, 2, 3, 4, 5, 6};
int i, *ptr;
// Initializing pointer
ptr = score;
// printing array elements using pointer
for(i = 0; i < 6; i++){
cout << *(ptr) << " ";
// Incrementing pointer
ptr++;
}
return 0;
}
Output
1 2 3 4 5 6
1 2 3 4 5 6