Professional Documents
Culture Documents
Unit 1 Lecture Material
Unit 1 Lecture Material
General Introduction:
C++ is portable and can be used to develop applications that can be adapted
to multiple platforms.
Overall, C++ is a powerful and versatile programming language that is widely used
for a range of applications and is well-suited for both low-level system
programming and high-level application development.
#include <iostream>
int main() {
std::cout << "Hello, World!" << std::endl;
return 0;
}
Output:
Hello, World!
Functions in C are not defined inside Functions can be used inside a structure
structures. in C++.
Namespace features are not present Namespace is used by C++, which avoid
C C++
Virtual and friend functions are not Virtual and friend functions are
supported by C. supported by C++.
C
C++ provides new operator for memory
provides malloc() and calloc() functions
allocation and delete operator for
for dynamic memory allocation ,
memory de-allocation.
and free() for memory de-allocation.
scanf() and printf() functions are used for cin and cout are used for input/output in
input/output in C. C++.
Feature of C++
Object-Oriented Programming
Machine Independent and Platform-Dependent
Simple
High-Level Language
Popular
Case-sensitive
Compiler Based
Dynamic Memory Allocation
Memory Management
Multi-threading
Rich Library
1. Object-Oriented Programming
C++ is an Object-Oriented Programming Language, unlike C which is
a procedural programming language. This is the most important feature of C++. It
can create/destroy objects while programming. Also, it can create blueprints with
which objects can be created.
3. Simple
It is a simple language in the sense that programs can be broken down into
logical units and parts, has rich library support and has a variety of data types. Also,
the Auto Keyword of C++ makes life easier.
4. High-Level Language
C++ is a High-Level Language, unlike C which is a Mid-Level Programming
Language. It makes life easier to work in C++ as it is a high-level language it is closely
associated with the human-comprehensible English language.
5. Popular
With its support for object-oriented programming, C++ can be a good basis for a
number of other programming languages. C++ is a favorite today for game
development and complex business applications because of its incredibly fast speed
and precise memory management. The language is applied to a variety of different
fields requiring high-performance applications. Adobe products, Unreal Engine, and
popular browsers such as Chrome and Firefox are all built using C++.
6. Case-sensitive
It is clear that C++ is a case-sensitive programming language. For
example, cin is used to take input from the input stream. But if the “Cin” won’t work.
Other languages like HTML and MySQL are not case-sensitive languages.
7. Compiler Based
C++ is a compiler-based language, unlike Python. That is C++ programs used to
be compiled and their executable file is used to run them. C++ is a relatively faster
language than Java and Python.
9. Memory Management
C++ allows us to allocate the memory of a variable or an array in run time. This is
known as Dynamic Memory Allocation.
In other programming languages such as Java and Python, the compiler
automatically manages the memories allocated to variables. But this is not the case
in C++.
In C++, the memory must be de-allocated dynamically allocated memory
manually after it is of no use.
The allocation and deallocation of the memory can be done using the new and
delete operators respectively.
10. Multi-threading
Multithreading is a specialized form of multitasking and multitasking is a feature
that allows your system to execute two or more programs concurrently. In
general, there are two sorts of multitasking: process-based and thread-based.
Process-based multitasking handles the concurrent execution of programs. Thread-
based multitasking deals with the multiprogramming of pieces of an equivalent
program.
A multithreaded program contains two or more parts that will run concurrently.
Each part of such a program is named a thread, and every thread defines a separate
path of execution.
C++ doesn’t contain any built-in support for multithreaded applications. Instead, it
relies entirely upon the OS to supply this feature.
11) Rich Library
C++ provides a lot of inbuilt functions that make the development fast. Following are the
sample libraries used in C++ programming:
<iostream>
<cmath>
<cstdlib>
<fstream>
Identifiers:
In C++ programming language, identifiers are the unique names assigned to variables,
functions, classes, structs, or other entities within the program. For example, in the below
statement,
Ex:
int minutesPerHour = 60;
1. An identifier can consist of letters (A-Z or a-z), digits (0-9), and underscores (_).
Special characters and spaces are not allowed.
2. An identifier can only begin with a letter or an underscore only.
3. C++ has reserved keywords that cannot be used as identifiers since they have
predefined meanings in the language. For example, int cannot be used as an
identifier as it has already some predefined meaning in C++. Attempting to use these
as identifiers will result in a compilation error.
4. Identifier must be unique in its namespace.
5. Identifier cannot contain whitespaces or special characters like !, #, %, etc.
6. C++ is a case-sensitive language so the identifier such as Num and num are treated
as different.
int main()
{
// identifiers used as variable names
int studentAge = 20;
double accountBalance = 1000.50;
string student_Name = "Karan";
calculateSum(2, 10);
return 0;
}
Output
The sum is: 12
Data Types:
All variables use data type during declaration to restrict the type of data to be stored.
Therefore, we can say that data types are used to tell the variables the type of data they
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. Every data type requires
a different amount of memory.
C++ supports a wide variety of data types and the programmer can select the data type
appropriate to the needs of the application. Data types specify the size and types of values
to be stored.
1. Primitive Data Types: These data types are built-in or predefined data types and can
be used directly by the user to declare variables. example: int, char, float, bool, etc.
Primitive data types available in C++ are:
Integer
Character
Boolean
Floating Point
Double Floating Point
Valueless or Void
Wide Character
2. Derived Data Types: Derived data types that are derived from the primitive or built-
in datatypes are referred to as Derived Data Types. These can be of four types namely:
Function
Array
Pointer
Reference
float 4 byte
double 8 byte
As the name suggests, datatype modifiers are used with built-in data types to modify
the length of data that a particular data type can hold.
cout << "char minimum value: " << CHAR_MIN << endl;
cout << "char maximum value: " << CHAR_MAX << endl;
cout << "Size of int : " << sizeof(int) << " bytes"
<< endl;
cout << "Size of float : " << sizeof(float) << " bytes"
<< endl;
Output:
Size of char : 1 byte
char minimum value: -128
char maximum value: 127
Size of int : 4 bytes
Size of short int : 2 bytes
Size of long int : 8 bytes
Size of signed long int : 8 bytes
Size of unsigned long int : 8 bytes
Size of float : 4 bytes
Size of double : 8 bytes
Size of wchar_t : 4 bytes
Namespace in C++
Namespace provide the space where we can define or declare identifier i.e. variable,
method, classes.
Using namespace, you can define the space or context in which identifiers are
defined i.e. variable, method, classes. In essence, a namespace defines a scope.
Example, you might be writing some code that has a function called xyz() and
there is another library available which is also having same function xyz(). Now
the compiler has no way of knowing which version of xyz() function you are
referring to within your code.
A namespace is designed to overcome this difficulty and is used as additional
information to differentiate similar functions, classes, variables etc. with the same
name available in different libraries.
The best example of namespace scope is the C++ standard library (std) where all the
classes, methods and templates are declared. Hence while writing a C++ program we
usually include the directive using namespace std;
Defining a Namespace:
namespace namespace_name
{
// code declarations i.e. variable (int a;)
method (void add();)
classes ( class student{};)
}
Namespaces in C++ are used to organize too many classes so that it can be easy to handle
the application.
In C++, global namespace is the root namespace. The global::std will always refer to the
namespace "std" of C++ Framework.
1. #include <iostream>
2. using namespace std;
3. namespace First {
4. void sayHello() {
5. cout<<"Hello First Namespace"<<endl;
6. }
7. }
8. namespace Second {
9. void sayHello() {
10. cout<<"Hello Second Namespace"<<endl;
11. }
12. }
13. int main()
14. {
15. First::sayHello();
16. Second::sayHello();
17. return 0;
18. }
Output:
Hello First Namespace
Hello Second Namespace
1. #include <iostream>
2. using namespace std;
3. namespace First{
4. void sayHello(){
5. cout << "Hello First Namespace" << endl;
6. }
7. }
8. namespace Second{
9. void sayHello(){
10. cout << "Hello Second Namespace" << endl;
11. }
12. }
13. using namespace First;
14. int main () {
15. sayHello();
16. return 0;
17. }
Output:
Hello First Namespace
Keywords
Keywords(also known as reserved words) have special meanings to the C++
compiler and are always written or typed in short(lower) cases. Keywords are words
that the language uses for a special purpose, such as void, int, public, etc. It can’t be
used for a variable name or function name or any other identifiers. The total count of
reserved keywords is 95. Below is the table for some commonly used C++ keywords.
C++ Keyword
For example,
int c = a + b;
Here, ‘+’ is the addition operator. ‘a’ and ‘b’ are the operands that are being ‘added’.
Operators in C++ can be classified into 6 types:
1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Bitwise Operators
5. Assignment Operators
6. Ternary or Conditional Operators
1) Arithmetic Operators
A) Unary Operators: These operators operate or work with a single operand. For
example: Increment(++) and Decrement(–) Operators.
Name Symbol Description Example
int a = 5;
Increment Increases the integer value of the
++ a++; // returns
Operator variable by one
6
int a = 3, b = 6;
Addition + Adds two operands int c = a+b; // c =
9
int a = 9, b = 6;
Subtracts second operand from the
Subtraction – int c = a-b; // c =
first
3
int a = 3, b = 6;
Multiplication * Multiplies two operands int c = a*b; // c =
18
int a = 12, b = 6;
Divides first operand by the second
Division / int c = a/b; // c =
operand
2
int a = 8, b = 6;
Modulo Returns the remainder an integer
% int c = a%b; // c
Operation division
=2
Example-1
// Working of increment and decrement operators
#include <iostream>
using namespace std;
int main() {
int a = 10, b = 100, result_a, result_b;
return 0;
}
Output
result_a = 11
result_b = 99
Example-2
// CPP Program to demonstrate the Binary Operators
#include <iostream>
using namespace std;
int main()
{
int a = 8, b = 3;
// Addition operator
cout << "a + b = " << (a + b) << endl;
// Subtraction operator
cout << "a - b = " << (a - b) << endl;
// Multiplication operator
cout << "a * b = " << (a * b) << endl;
// Division operator
cout << "a / b = " << (a / b) << endl;
// Modulo operator
cout << "a % b = " << (a % b) << endl;
return 0;
}
Output
a + b = 11
a-b=5
a * b = 24
a/b=2
a%b=2
2) Relational Operators
These operators are used for the comparison of the values of two operands. For
example, ‘>’ checks if one operand is greater than the other operand or not, etc. The
result returns a Boolean value, i.e., true or false.
Name Symbol Description Example
int a = 3, b =
6;
int a = 3, b =
6;
Checks if first operand is greater than the a>b;
Greater Than >
second operand
// returns
false
int a = 3, b =
6;
Greater Than or Checks if first operand is greater than or a>=b;
>=
Equal To equal to the second operand
// returns
false
Less Than < Checks if first operand is lesser than the int a = 3, b =
second operand
Name Symbol Description Example
6;
a<b;
// returns
true
int a = 3, b =
6;
Less Than or Checks if first operand is lesser than or a<=b;
<=
Equal To equal to the second operand
// returns
true
int a = 3, b =
6;
Example:
// CPP Program to demonstrate the Relational Operators
#include <iostream>
using namespace std;
int main()
{
int a = 6, b = 4;
// Equal to operator
cout << "a == b is " << (a == b) << endl;
// true
cout << "a != b is " << (a != b) << endl;
return 0;
}
Output
a == b is 0
a > b is 1
a >= b is 1
a < b is 0
a <= b is 0
a != b is 1
3) Logical Operators
int a = 3, b =
Logical Returns true only if all the operands are true 6;
&&
AND or non-zero a&&b;
// returns true
int a = 3, b =
Returns true if either of the operands is true 6;
Logical OR ||
or non-zero a||b;
// returns true
Name Symbol Description Example
int a = 3;
Logical !a;
! Returns true if the operand is false or zero
NOT
// returns
false
Example-1:
#include <iostream>
using namespace std;
int main() {
bool result;
return 0;
}
Output:
(3 != 5) && (3 < 5) is 1
(3 == 5) && (3 < 5) is 0
(3 == 5) && (3 > 5) is 0
(3 != 5) || (3 < 5) is 1
(3 != 5) || (3 > 5) is 1
(3 == 5) || (3 > 5) is 0
!(5 == 2) is 1
!(5 == 5) is 0
Example:
int main()
{
int a = 6, b = 4;
// Logical OR operator
cout << "a ! b is " << (a > b) << endl;
return 0;
}
Output
a && b is 1
a ! b is 1
!b is 0
4) Bitwise Operators
These operators are used to perform bit-level operations on the operands. The operators
are first converted to bit-level and then the calculation is performed on the operands.
Mathematical operations such as addition, subtraction, multiplication, etc. can be
performed at the bit level for faster processing.
Bitwise operator works on bits and perform bit-by-bit operation. The truth tables for
&, |, and ^ are as follows −
0 0 0 0 0
0 1 0 1 1
1 1 1 1 0
1 0 0 1 1
Assume if A = 60; and B = 13; now in binary format they will be as follows −
A = 0011 1100
B = 0000 1101
-----------------
~A = 1100 0011
(a & b);
//returns 2
int a = 2, b =
Copies a bit to the evaluated result if it 3;
Binary OR |
exists in any of the operand (a | b);
//returns 3
int a = 2, b =
Copies the bit to the evaluated result if it 3;
Binary XOR ^ is present in either of the operands but not
both (a ^ b);
//returns 1
int a = 2, b =
Shifts the value to left by the number of 3;
Left Shift <<
bits specified by the right operand. (a << 1);
//returns 4
int a = 2, b =
Shifts the value to right by the number of 3;
Right Shift >>
bits specified by the right operand. (a >> 1);
//returns 1
int b = 3;
One’s
~ Changes binary digits 1 to 0 and 0 to 1 (~b); //returns
Complement
-4
Note: Only char and int data types can be used with Bitwise Operators.
Example:
// CPP Program to demonstrate the Bitwise Operators
#include <iostream>
using namespace std;
int main()
{
int a = 6, b = 4;
// Binary OR operator
cout << "a | b is " << (a | b) << endl;
return 0;
}
Output:
a & b is 4
a | b is 6
a ^ b is 2
a<<1 is 12
a>>1 is 3
~(a) is -7
5) Assignment Operators
These operators are used to assign value to a variable. The left side operand of the
assignment operator is a variable and the right side operand of the assignment operator
is a value. The value on the right side must be of the same data type as the variable on
the left side otherwise the compiler will raise an error.
Namemultiply Symbol Description Example
Example:
// CPP Program to demonstrate the Assignment Operators
#include <iostream>
using namespace std;
int main()
{
int a = 6, b = 4;
// Assignment Operator
cout << "a = " << a << endl;
// Add and Assignment Operator
cout << "a += b is " << (a += b) << endl;
return 0;
}
Output
a=6
a += b is 10
a -= b is 6
a *= b is 24
a /= b is 6
int main()
{
int a = 3, b = 4;
// Conditional Operator
int result = (a < b) ? b : a;
cout << "The greatest number is " << result << endl;
return 0;
}
Output
The greatest number is 4
7) There are some other common operators available in C++ besides the operators
discussed above. Following is a list of these operators discussed in detail:
A) sizeof Operator: This unary operator is used to compute the size of its operand or
variable.
sizeof(char); // returns 1
B) Comma Operator(,): This binary operator (represented by the token) is used to
evaluate its first operand and discards the result, it then evaluates the second operand
and returns this value (and type). It is used to combine various expressions together.
int a = 6;
int b = (a+1, a-2, a+5); // b = 11
C) -> Operator: This operator is used to access the variables of classes or structures.
cout<<emp->first_name;
D) Cast Operator: This unary operator is used to convert one data type into another.
float a = 11.567;
int c = (int) a; // returns 11
E) Dot Operator(.): This operator is used to access members of structure variables or
class objects in C++.
cout<<emp.first_name;
F) & Operator: This is a pointer operator and is used to represent the memory address
of an operand.
G) * Operator: This is an Indirection Operator
H) << Operator: It is called the insertion operator. It is used with cout to print the
output.
I) >> Operator: It is called the extraction operator. It is used with cin to get the input.
Operator Precedence Chart
Precedenc
e Operator Description Associativity
* Dereference
6.
Relational greater than/greater than or equal
> , >= left-to-right
to
= Assignment right-to-left
+= , -= Addition/subtraction assignment
*= , /= Multiplication/division assignment
14.
%= , &= Modulus/bitwise AND assignment
Input Stream: If the direction of flow of bytes is from the device (for example,
Keyboard) to the main memory then this process is called input.
Output Stream: If the direction of flow of bytes is opposite, i.e. from main memory
to device (display screen) then this process is called output.
In C++ after the header files, we often use ‘using namespace std;‘. The reason behind it
is that all of the standard library definitions are inside the namespace std. As the library
functions are not defined at global scope, so in order to use them we use namespace std.
So, that we don’t need to write STD:: at every line (eg. STD::cout etc.).
The two instances cout in C++ and cin in C++ of iostream class are used very often
for printing outputs and taking inputs respectively.
Standard output stream (cout): Usually the standard output device is the display
screen. The C++ cout statement is the instance of the ostream class. It is used to
produce output on the standard output device which is usually the display screen. The
data needed to be displayed on the screen is inserted in the standard output stream
(cout) using the insertion operator(<<).
Standard input stream (cin): Usually the input device in a computer is the keyboard.
C++ cin statement is the instance of the class istream and is used to read input from the
standard input device which is usually a keyboard.
The extraction operator(>>) is used along with the object cin for reading inputs. The
extraction operator extracts the data from the object cin which is entered using the
keyboard.
Example:
#include <iostream>
using namespace std;
int main()
{ int age;
cout << "Enter your age:";
cin >> age;
cout << "\nYour age is: " << age;
return 0;
}
Output:
Enter your age: 18
Your age is: 18
Un-buffered standard error stream (cerr): The C++ cerr is the standard error stream
that is used to output the errors. This is also an instance of the iostream class. As cerr in
C++ is un-buffered so it is used when one needs to display the error message
immediately. It does not have any buffer to store the error message and display it later.
Buffered standard error stream (clog): This is also an instance of ostream class and
used to display errors but unlike cerr the error is first inserted into a buffer and is stored
in the buffer until it is not fully filled. or the buffer is not explicitly flushed (using
flush()). The error message will be displayed on the screen too.
Example:
#include <iostream>
using namespace std;
int main() {
int first_number, second_number, sum;
cout << "Enter two integers: ";
cin >> first_number >> second_number;
sum = first_number + second_number;
cout << first_number << " + " << second_number << " = " << sum;
return 0;
}
Output:
Enter two integers: 4
5
4+5=9
Control statements
1. Conditional Control Structures (Decision making statements)
if
if – else Statements
Swtich Case Statments
2. Looping / Iterative Control Structures
For Loop
While Loop
Do…..While Loop
3. Functions
Apart from these we have certain Jump Statements in C++ which assist in manipulating
the flow of the program execution. Following are those statements –
Conditional Statements:
Conditional Statements are used in C++ to run a certain piece of program only if a
specific condition is met. There are generally three types of conditional statements
in C++: if, if-else, and switch.
if Statement:
The if statement is the simplest of the three and is used to run a certain piece of
code only if a certain condition is true. For example:
Example:
#include <iostream>
using namespace std;
int main () {
int number = 10;
if (number % 2 == 0)
{
cout << "The Number you have Enter it is Even";
}
return 0;
}
Output:
The Number you have Enter it is Even
If…else statement
The statement C++ if-else also checks the condition. The declaration executes if
the condition is true otherwise the block is carried out.
if(condition)
{
//code should be executed;
}else
{
//code should be executed;
}
Example of if-else Statement
#include<iostream>
using namespace std;
int main () {
int number = 15;
if (number % 2 == 0)
{
cout << "The Number you have Enter it is Even";
}
else
{
cout << "The Number you have Enter it is Odd";
}
return 0;
}
Output:
The Number you have Enter it is Odd
If(condition1)
{
// code should be executed if condition1 is true
}
else if(condition2)
{
// code should be executed if condition2 is true
}
else if(condition3)
{
// code should be executed if condition3 is true
}
...
else{
// code should be executed if all condition is false
}
Example:
#include <iostream>
using namespace std;
int main () {
int number;
cout << "To Check Grade Enter a Number:";
cin >> number;
if (number < 0 || number > 100)
{
cout << "wrong No";
}
else if(number >= 0 && number < 40){
cout << "Fail";
}
else if (number >= 40 && number < 59)
{
cout << "D Grade";
}
else if (number >= 60 && number < 70)
{
cout <<" C Grade";
}
else if (number >= 71 && number < 79)
{
cout << "B Grade";
}
else if (number >= 80 && number < 89)
{
cout << "A Grade";
}
else if (number >= 90 && number <= 100)
{
cout << "A+ Grade";
} }
Output:
To Check Grade Enter a Number: 75
B Grade
Switch(expression)
{
case value1:
//code should be executed;
break;
case value2:
//code should be executed;
break;
…
Default:
//Code to execute if not all cases matched
break;
}
1. Entry Controlled loops: In this type of loop, the test condition is tested before
entering the loop body. For Loop and While Loop is entry-controlled loops.
2. Exit Controlled Loops: In this type of loop the test condition is tested or evaluated
at the end of the loop body. Therefore, the loop body will execute at least once,
irrespective of whether the test condition is true or false. the do-while loop is exit
controlled loop.
For Loop:
A For loop is a repetition control structure that allows us to write a loop that is
executed a specific number of times. The loop enables us to perform n number of
steps together in one line.
Syntax:
for (initialization expr; test expr; update expr)
{
// body of the loop
// statements we want to execute
}
Example:
using namespace std;
int main()
{
int i = 99;
for (int i = 0; i < 5; i++) {
cout << i << "\t";
}
cout << "\n" << i;
return 0;
}
Output:
0 1 2 3 4
99
While Loop:
In for loop the number of iterations is known beforehand, i.e. the number of
times the loop body is needed to be executed is known to us.
while loops are used in situations where we do not know the exact number of
iterations of the loop beforehand.
The loop execution is terminated on the basis of the test conditions.
Syntax:
initialization expression;
while (test_expression)
{
// statements
update_expression;
}
Example:
// C++ program to Demonstrate while loop
#include <iostream>
using namespace std;
int main()
{
// initialization expression
int i = 1;
// test expression
while (i < 6) {
cout << "Hello World\n";
// update expression
i++;
}
return 0;
}
Output:
Hello World
Hello World
Hello World
Hello World
Hello World
Do-while loop
In Do-while loops also the loop execution is terminated on the basis of test conditions.
The main difference between a do-while loop and the while loop is in the do-while loop
the condition is tested at the end of the loop body, i.e do-while loop is exit controlled
whereas the other two loops are entry-controlled loops.
Note: In a do-while loop, the loop body will execute at least once irrespective of the
test condition.
Syntax:
initialization expression;
do
{
// statements
update_expression;
} while (test_expression);
Example:
int main()
{
int i = 2; // Initialization expression
do {
// loop body
cout << "Hello World\n";
// update expression
i++;
return 0;
}
Output:
Hello World
Jump Statement:
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.
This statement can be used inside for loop or while or do-while loop.
Syntax:
continue;
Example:
// Driver code
int main()
{
for (int i = 1; i < 10; i++) {
if (i == 5)
continue;
cout << i << " ";
}
return 0;
}
Output
12346789
break in C++
The C++ break statement is used to terminate the whole loop if the condition is met.
Unlike the continue statement after the condition is met, it breaks the loop and the
remaining part of the loop is not executed.
Break statement forces the loop to stop the execution of the further
iteration.
Syntax:
break;
Example:
// C++ program to demonstrate the
// break statement
#include <iostream>
using namespace std;
// Driver Code
int main()
{
for (int i = 1; i < 10; i++) {
// Breaking Condition
if (i == 5)
break;
cout << i << " ";
}
return 0;
}
Output:
1234
return in C++
The return statement takes control out of the function itself. It is stronger than a break.
It is used to terminate the entire function after the execution of the function or after
some condition.
Syntax
return expression;
Example:
// Termination condition
if (i == 5)
return 0;
cout << i << " ";
}
cout << "end";
return 0;
}
Output:
Begin 0 1 2 3 4
Explanation:
The above program starts execution by printing “Begin” and then the for loop starts to
print the value of, it will print the value of i from 0 to 4 but as soon as i becomes equal
to 5 it will terminate the whole function i.e., it will never go to print the “end” statement
of the program.
Syntax
goto label_name;
.
.
.
label_name:
Example:
// C++ program to demonstrate the
// goto statement
#include <iostream>
using namespace std;
// Driver Code
int main()
{
int n = 4;
if (n % 2 == 0)
goto label1;
else
goto label2;
label1:
cout << "Even" << endl;
return 0;
label2:
cout << "Odd" << endl;
}
Output
Even
Arrays
Array is a group of similar types of elements that have contiguous or adjacent
memory location.
A collection of related data items stored in adjacent memory places is referred to as
an array. Elements of an array can be accessed arbitrarily using its indices. They
can be used to store a collection of any type of primitive data type, including int,
float, double, char, etc. An array in C/C++ can also store derived data types like
structures, pointers, and other data types, which is an addition.
Array Types
There are 2 types of arrays in C++ programming:
int main()
{
int arr[3];
return 0;
}
Output
arr[0]: 10
arr[1]: 20
arr[2]: 30
Example-2
1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int arr[5]={10, 0, 20, 0, 30}; //creating and initializing array
6. //traversing array
7. for (int i = 0; i < 5; i++)
8. {
9. cout<<arr[i]<<"\n";
10. }
11. }
Output:
10
0
20
0
30
1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int arr[5]={10, 0, 20, 0, 30}; //creating and initializing array
6. //traversing array
7. for (int i: arr)
8. {
9. cout<<i<<"\n";
10. }
11. }
Output:
10
20
30
40
50
So, as you can see, we initialize a 2D array arr, with 4 rows and 2 columns as an
array of arrays. Each element of the array is yet again an array of integers.
int arr[4][2] = {1234, 56, 1212, 33, 1434, 80, 1312, 78};
Example-1:
#include<iostream>
using namespace std;
main( )
{
int arr[4][2] = {
{ 10, 11 },
{ 20, 21 },
{ 30, 31 },
{ 40, 41 }
};
int i,j;
cout<<"Printing a 2D Array:\n";
for(i=0;i<4;i++)
{
for(j=0;j<2;j++)
{
cout<<"\t"<<arr[i][j];
}
cout<<endl;
}
}
Output:
Taking 2D Array Elements As User Input
#include<iostream>
using namespace std;
main( )
{
int s[2][2];
int i, j;
cout<<"\n2D Array Input:\n";
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
cout<<"\ns["<<i<<"]["<<j<<"]= ";
cin>>s[i][j];
}
}
Output:
Example: Matrix Addition using Two Dimensional
Arrays in C++
#include<iostream>
using namespace std;
main()
{
int m1[5][5], m2[5][5], m3[5][5];
int i, j, r, c;
cout<<"\nAdding Matrices...\n";
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
m3[i][j]=m1[i][j]+m2[i][j];
}
}
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
cout<<"\t"<<m3[i][j];
}
cout<<endl;
}
Output:
Strings
C++ strings are sequences of characters stored in a char array. Strings are used to store
words and text. They are also used to store data, such as numbers and other types of
information. Strings in C++ can be defined either using the std::string class or the
C-style character arrays.
1. C Style Strings
These strings are stored as the plain old array of characters terminated by a null
character ‘\0’. They are the type of strings that C++ inherited from C language.
Syntax:
char str[] = "GeeksforGeeks";
Example 1:
// C++ Program to demonstrate strings
#include <iostream>
using namespace std;
int main()
{
2. std::string Class
These are the new types of strings that are introduced in C++ as std::string class defined
inside <string> header file. This provides many advantages over conventional C-style
strings such as dynamic size, member functions, etc.
Syntax:
std::string str("GeeksforGeeks");
Example:
// C++ program to create std::string objects
#include <iostream>
using namespace std;
int main()
{
string str("GeeksforGeeks");
cout << str;
return 0;
}
Output:
GeeksforGeeks
How to Take String Input in C++
String input means accepting a string from a user. In C++. We have different types of
taking input from the user which depend on the string. The most common way is to take
input with cin keyword with the extraction operator (>>) in C++. Methods to take a
string as input are:
cin
getline
stringstream
1. Using Cin
Example:
// C++ Program to demonstrate string input using cin
#include <iostream>
using namespace std;
int main() {
string s;
cout<<"Enter String"<<endl;
cin>>s;
Output:
Enter String
GeeksforGeeks
String is: GeeksforGeeks
2. Using getline
The getline() function in C++ is used to read a string from an input stream. It is
declared in the <string> header file.
Syntax:
getline(cin,s);
Example:
// C++ Program to demonstrate use of getline function
#include <iostream>
using namespace std;
int main()
{
string s;
cout << "Enter String" << endl;
getline(cin, s);
cout << "String is: " << s << endl;
return 0;
}
Output:
Enter String
GeeksforGeeks
String is: GeeksforGeeks
3. Using stringstream
The stringstream class in C++ is used to take multiple strings as input at once.
Syntax:
stringstream stringstream_object(string_name);
Example:
int main()
{
string s = " GeeksforGeeks to the Moon ";
stringstream obj(s);
// string to store words individually
string temp;
// >> operator will read from the stringstream object
while (obj >> temp) {
cout << temp << endl;
}
return 0;
}
Output:
GeeksforGeeks
to
the
Moon
S. Functions and
No. Category Operators Functionality
To access individual
Indexing (using
characters using array
array[index])
indexing.
10 strcat(Str1, Str2);
String Concat
Output:
What is my favourite fruit? apple
What is my favourite fruit? banana
What is my favourite fruit? mango
Answer is correct!!
Output:
Enter the key string: Welcome to
Enter the buffer string: C++ Programming.
Key = Welcome to C++ Programming.
Buffer = C++ Programming.
Output:
Enter the key string: C++ Tutorial
Key = C++ Tutorial
Buffer = C++ Tutorial
Output:
Length of String = 26