Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

C

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 86

C++ Program

Before starting the abcd of C++ language, you need to learn how to write, compile and run
the first C++ program.

To write the first C++ program, open the C++ console and write the following code:

1. #include <iostream.h>
2. #include<conio.h>
3. void main() {
4. clrscr();
5. cout << "Welcome to C++ Programming.";
6. getch();
7. }

#include<iostream.h> includes the standard input output library functions. It


provides cin and cout methods for reading from input and writing to output respectively.

#include <conio.h> includes the console input output library functions. The getch()
function is defined in conio.h file.

void main() The main() function is the entry point of every program in C++
language. The void keyword specifies that it returns no value.

cout << "Welcome to C++ Programming." is used to print the data "Welcome to
C++ Programming." on the console.

getch() The getch() function asks for a single character. Until you press any key, it
blocks the screen.
How to compile and run the C++ program
There are 2 ways to compile and run the C++ program, by menu and by shortcut.

By menu

Now click on the compile menu then compile sub menu to compile the c++ program.

Then click on the run menu then run sub menu to run the c++ program.

By shortcut

Or, press ctrl+f9 keys compile and run the program directly.

You will see the following output on user screen.

You can view the user screen any time by pressing the alt+f5 keys.

Now press Esc to return to the turbo c++ console.

C++ Basic Input/Output


C++ I/O operation is using the stream concept. Stream is the sequence of bytes or flow of
data. It makes the performance fast.

If bytes flow from main memory to device like printer, display screen, or a network
connection, etc, this is called as output operation.

If bytes flow from device like printer, display screen, or a network connection, etc to main
memory, this is called as input operation.
I/O Library Header Files
Let us see the common header files used in C++ programming are:

Header File Function and Description

<iostream> It is used to define the cout, cin and cerr objects, which correspond to standard outpu
standard input stream and standard error stream, respectively.

<iomanip> It is used to declare services useful for performing formatted I/O, such as setprecision

<fstream> It is used to declare services for user-controlled file processing.

Standard output stream (cout)


The cout is a predefined object of ostream class. It is connected with the standard output
device, which is usually a display screen. The cout is used in conjunction with stream
insertion operator (<<) to display the output on a console

Let's see the simple example of standard output stream (cout):

1. #include <iostream>
2. using namespace std;
3. int main( ) {
4. char ary[] ="Welcome to C++ tutorial";
5. cout << "Value of ary is: " << ary << endl;
6. }

Output:

Value of ary is: Welcome to C++ tutorial

Standard input stream (cin)


The cin is a predefined object of istream class. It is connected with the standard input
device, which is usually a keyboard. The cin is used in conjunction with stream extraction
operator (>>) to read the input from a console.

Let's see the simple example of standard input stream (cin):

1. #include <iostream>
2. using namespace std;
3. int main( ) {
4. int age;
5. cout << "Enter your age: ";
6. cin >> age;
7. cout << "Your age is: " << age << endl;
8. }

Output:

Enter your age: 22


Your age is: 22

Standard end line (endl)


The endl is a predefined object of ostream class. It is used to insert a new line characters
and flushes the stream.

Let's see the simple example of standard end line (endl):

1. #include <iostream>
2. using namespace std;
3. int main( ) {
4. cout << "C++ Tutorial";
5. cout << " Javatpoint"<<endl;
6. cout << "End of line"<<endl;
7. }

Output:

C++ Tutorial Javatpoint


End of line

C++ Variable
A variable is a name of memory location. It is used to store data. Its value can be changed
and it can be reused many times.

It is a way to represent memory location through symbol so that it can be easily identified.

Let's see the syntax to declare a variable:

1. type variable_list;
The example of declaring variable is given below:

1. int x;
2. float y;
3. char z;

Here, x, y, z are variables and int, float, char are data types.

We can also provide values while declaring the variables as given below:

1. int x=5,b=10; //declaring 2 variable of integer type


2. float f=30.8;
3. char c='A';

Rules for defining variables


A variable can have alphabets, digits and underscore.

A variable name can start with alphabet and underscore only. It can't start with digit.

No white space is allowed within variable name.

A variable name must not be any reserved word or keyword e.g. char, float etc.

Valid variable names:

1. int a;
2. int _ab;
3. int a30;

Invalid variable names:

1. int 4;
2. int x y;
3. int double;

C++ Data Types


A data type specifies the type of data that a variable can store such as integer, floating,
character etc.
There are 4 types of data types in C++ language.

Types Data Types

Basic Data Type int, char, float, double, etc

Derived Data Type array, pointer, etc

Enumeration Data Type enum

User Defined Data Type structure

Basic Data Types


The basic data types are integer-based and floating-point based. C++ language supports
both signed and unsigned literals.

The memory size of basic data types may change according to 32 or 64 bit operating
system.
Let's see the basic data types. It size is given according to 32 bit OS.

Data Types Memory Size Range

char 1 byte -128 to 127

signed char 1 byte -128 to 127

unsigned char 1 byte 0 to 127

short 2 byte -32,768 to 32,767

signed short 2 byte -32,768 to 32,767

unsigned short 2 byte 0 to 32,767

int 2 byte -32,768 to 32,767

signed int 2 byte -32,768 to 32,767

unsigned int 2 byte 0 to 32,767

short int 2 byte -32,768 to 32,767

signed short int 2 byte -32,768 to 32,767

unsigned short int 2 byte 0 to 32,767

long int 4 byte

signed long int 4 byte


unsigned long int 4 byte

float 4 byte

double 8 byte

long double 10 byte

C++ Keywords
A keyword is a reserved word. You cannot use it as a variable name, constant name etc. A
list of 32 Keywords in C++ Language which are also available in C language are
given below.

auto break case char const continue defau

double else enum extern float for goto

int long register return short signed sizeo

struct switch typedef union unsigned void volati

A list of 30 Keywords in C++ Language which are not available in C language are
given below.

asm dynamic_cast namespace reinterpret_cast

explicit new static_cast false

operator template friend private


this inline public throw

delete mutable protected true

typeid typename using virtual

C++ Operators
An operator is simply a symbol that is used to perform operations. There can be many types
of operations like arithmetic, logical, bitwise etc.

There are following types of operators to perform different types of operations in C


language.

o Arithmetic Operators
o Relational Operators
o Logical Operators
o Bitwise Operators
o Assignment Operator
o Unary operator
o Ternary or Conditional Operator
o Misc Operator
Precedence of Operators in C++
The precedence of operator species that which operator will be evaluated first and next. The
associativity specifies the operators direction to be evaluated, it may be left to right or right
to left.

Let's understand the precedence by the example given below:

1. int data=5+10*10;

The "data" variable will contain 105 because * (multiplicative operator) is evaluated before
+ (additive operator).

The precedence and associativity of C++ operators is given below:

Category Operator Assoc

Postfix () [] -> . ++ - - Lef

Unary + - ! ~ ++ - - (type)* & sizeof Rig


Multiplicative */% Lef

Additive +- Rig

Shift << >> Lef

Relational < <= > >= Lef

Equality == !=/td> Rig

Bitwise AND & Lef

Bitwise XOR ^ Lef

Bitwise OR | Rig

Logical AND && Lef

Logical OR || Lef

Conditional ?: Rig

Assignment = += -= *= /= %=>>= <<= &= ^= |= Rig

Comma , Lef

C++ if-else
In C++ programming, if statement is used to test the condition. There are various types of
if statements in C++.

o if statement
o if-else statement
o nested if statement
o if-else-if ladder

C++ IF Statement
The C++ if statement tests the condition. It is executed if condition is true.

1. if(condition){
2. //code to be executed
3. }

C++ If Example
1. #include <iostream>
2. using namespace std;
3.
4. int main () {
5. int num = 10;
6. if (num % 2 == 0)
7. {
8. cout<<"It is even number";
9. }
10. return 0;
11. }

Output:/p>

It is even number

C++ IF-else Statement


The C++ if-else statement also tests the condition. It executes if block if condition is true
otherwise else block is executed.

1. if(condition){
2. //code if condition is true
3. }else{
4. //code if condition is false
5. }
C++ If-else Example
1. #include <iostream>
2. using namespace std;
3. int main () {
4. int num = 11;
5. if (num % 2 == 0)
6. {
7. cout<<"It is even number";
8. }
9. else
10. {
11. cout<<"It is odd number";
12. }
13. return 0;
14. }

Output:

It is odd number

C++ If-else Example: with input from user


1. #include <iostream>
2. using namespace std;
3. int main () {
4. int num;
5. cout<<"Enter a Number: ";
6. cin>>num;
7. if (num % 2 == 0)
8. {
9. cout<<"It is even number"<<endl;
10. }
11. else
12. {
13. cout<<"It is odd number"<<endl;
14. }
15. return 0;
16. }

Output:

Enter a number:11
It is odd number

Output:

Enter a number:12
It is even number

C++ IF-else-if ladder Statement


The C++ if-else-if ladder statement executes one condition from multiple statements.

1. if(condition1){
2. //code to be executed if condition1 is true
3. }else if(condition2){
4. //code to be executed if condition2 is true
5. }
6. else if(condition3){
7. //code to be executed if condition3 is true
8. }
9. ...
10. else{
11. //code to be executed if all the conditions are false
12. }

C++ If else-if Example


1. #include <iostream>
2. using namespace std;
3. int main () {
4. int num;
5. cout<<"Enter a number to check grade:";
6. cin>>num;
7. if (num <0 || num >100)
8. {
9. cout<<"wrong number";
10. }
11. else if(num >= 0 && num < 50){
12. cout<<"Fail";
13. }
14. else if (num >= 50 && num < 60)
15. {
16. cout<<"D Grade";
17. }
18. else if (num >= 60 && num < 70)
19. {
20. cout<<"C Grade";
21. }
22. else if (num >= 70 && num < 80)
23. {
24. cout<<"B Grade";
25. }
26. else if (num >= 80 && num < 90)
27. {
28. cout<<"A Grade";
29. }
30. else if (num >= 90 && num <= 100)
31. {
32. cout<<"A+ Grade";
33. }
34. }

Output:

Enter a number to check grade:66


C Grade

Output:

Enter a number to check grade:-2


wrong number
C++ switch
The C++ switch statement executes one statement from multiple conditions. It is like if-
else-if ladder statement in C++.

1. switch(expression){
2. case value1:
3. //code to be executed;
4. break;
5. case value2:
6. //code to be executed;
7. break;
8. ......
9.
10. default:
11. //code to be executed if all cases are not matched;
12. break;
13. }
C++ Switch Example
1. #include <iostream>
2. using namespace std;
3. int main () {
4. int num;
5. cout<<"Enter a number to check grade:";
6. cin>>num;
7. switch (num)
8. {
9. case 10: cout<<"It is 10"; break;
10. case 20: cout<<"It is 20"; break;
11. case 30: cout<<"It is 30"; break;
12. default: cout<<"Not 10, 20 or 30"; break;
13. }
14. }

Output:

Enter a number:
10
It is 10

Output:

Enter a number:
55
Not 10, 20 or 30

C++ For Loop


The C++ for loop is used to iterate a part of the program several times. If the number of
iteration is fixed, it is recommended to use for loop than while or do-while loops.

The C++ for loop is same as C/C#. We can initialize variable, check condition and
increment/decrement value.

1. for(initialization; condition; incr/decr){


2. //code to be executed
3. }

Flowchart:
C++ For Loop Example
1. #include <iostream>
2. using namespace std;
3. int main() {
4. for(int i=1;i<=10;i++){
5. cout<<i <<"\n";
6. }
7. }

Output:

1
2
3
4
5
6
7
8
9
10

C++ Nested For Loop


In C++, we can use for loop inside another for loop, it is known as nested for loop. The
inner loop is executed fully when outer loop is executed one time. So if outer loop and inner
loop are executed 4 times, inner loop will be executed 4 times for each outer loop i.e. total
16 times.

C++ Nested For Loop Example


Let's see a simple example of nested for loop in C++.

1. #include <iostream>
2. using namespace std;
3.
4. int main () {
5. for(int i=1;i<=3;i++){
6. for(int j=1;j<=3;j++){
7. cout<<i<<" "<<j<<"\n";
8. }
9. }
10. }

Output:

1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3

C++ Infinite For Loop


If we use double semicolon in for loop, it will be executed infinite times. Let's see a simple
example of infinite for loop in C++.
1. #include <iostream>
2. using namespace std;
3.
4. int main () {
5. for (; ;)
6. {
7. cout<<"Infinitive For Loop";
8. }
9. }

Output:

Infinitive For Loop


Infinitive For Loop
Infinitive For Loop
Infinitive For Loop
Infinitive For Loop
ctrl+c

C++ While loop


In C++, while loop is used to iterate a part of the program several times. If the number of
iteration is not fixed, it is recommended to use while loop than for loop.

1. while(condition){
2. //code to be executed
3. }

Flowchart:
C++ While Loop Example
Let's see a simple example of while loop to print table of 1.

1. #include <iostream>
2. using namespace std;
3. int main() {
4. int i=1;
5. while(i<=10)
6. {
7. cout<<i <<"\n";
8. i++;
9. }
10. }

Output:

1
2
3
4
5
6
7
8
9
10

C++ Nested While Loop Example


In C++, we can use while loop inside another while loop, it is known as nested while loop.
The nested while loop is executed fully when outer loop is executed once.

Let's see a simple example of nested while loop in C++ programming language.

1. #include <iostream>
2. using namespace std;
3. int main () {
4. int i=1;
5. while(i<=3)
6. {
7. int j = 1;
8. while (j <= 3)
9. {
10. cout<<i<<" "<<j<<"\n";
11. j++;
12. }
13. i++;
14. }
15. }

Output:

1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3

C++ Infinitive While Loop Example:


We can also create infinite while loop by passing true as the test condition.

1. #include <iostream>
2. using namespace std;
3. int main () {
4. while(true)
5. {
6. cout<<"Infinitive While Loop";
7. }
8. }

Output:

Infinitive While Loop


Infinitive While Loop
Infinitive While Loop
Infinitive While Loop
Infinitive While Loop
ctrl+c

C++ Do-While Loop


The C++ do-while loop is used to iterate a part of the program several times. If the number
of iteration is not fixed and you must have to execute the loop at least once, it is
recommended to use do-while loop.

The C++ do-while loop is executed at least once because condition is checked after loop
body.

1. do{
2. //code to be executed
3. }while(condition);

Flowchart:
C++ do-while Loop Example
Let's see a simple example of C++ do-while loop to print the table of 1.

1. #include <iostream>
2. using namespace std;
3. int main() {
4. int i = 1;
5. do{
6. cout<<i<<"\n";
7. i++;
8. } while (i <= 10) ;
9. }

Output:

1
2
3
4
5
6
7
8
9
10
C++ Nested do-while Loop
In C++, if you use do-while loop inside another do-while loop, it is known as nested do-
while loop. The nested do-while loop is executed fully for each outer do-while loop.

Let's see a simple example of nested do-while loop in C++.

1. #include <iostream>
2. using namespace std;
3. int main() {
4. int i = 1;
5. do{
6. int j = 1;
7. do{
8. cout<<i<<"\n";
9. j++;
10. } while (j <= 3) ;
11. i++;
12. } while (i <= 3) ;
13. }

Output:

1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3

C++ Infinitive do-while Loop


In C++, if you pass true in the do-while loop, it will be infinitive do-while loop.

1. do{
2. //code to be executed
3. }while(true);

C++ Infinitive do-while Loop Example


1. #include <iostream>
2. using namespace std;
3. int main() {
4. do{
5. cout<<"Infinitive do-while Loop";
6. } while(true);
7. }

Output:

Infinitive do-while Loop


Infinitive do-while Loop
Infinitive do-while Loop
Infinitive do-while Loop
Infinitive do-while Loop
ctrl+c

C++ Break Statement


The C++ break is used to break loop or switch statement. It breaks the current flow of the
program at the given condition. In case of inner loop, it breaks only inner loop.

1. jump-statement;
2. break;

Flowchart:
C++ Break Statement Example
Let's see a simple example of C++ break statement which is used inside the loop.

1. #include <iostream>
2. using namespace std;
3. int main() {
4. for (int i = 1; i <= 10; i++)
5. {
6. if (i == 5)
7. {
8. break;
9. }
10. cout<<i<<"\n";
11. }
12. }

Output:

1
2
3
4

C++ Break Statement with Inner Loop


The C++ break statement breaks inner loop only if you use break statement inside the inner
loop.

Let's see the example code:

1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. for(int i=1;i<=3;i++){
6. for(int j=1;j<=3;j++){
7. if(i==2&&j==2){
8. break;
9. }
10. cout<<i<<" "<<j<<"\n";
11. }
12. }
13. }

Output:

1 1
1 2
1 3
2 1
3 1
3 2
3 3

C++ Continue Statement


The C++ continue statement is used to continue loop. It continues the current flow of the
program and skips the remaining code at specified condition. In case of inner loop, it
continues only inner loop.

1. jump-statement;
2. continue;

C++ Continue Statement Example


1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. for(int i=1;i<=10;i++){
6. if(i==5){
7. continue;
8. }
9. cout<<i<<"\n";
10. }
11. }

Output:

1
2
3
4
6
7
8
9
10

C++ Continue Statement with Inner Loop


C++ Continue Statement continues inner loop only if you use continue statement inside the
inner loop.

1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. for(int i=1;i<=3;i++){
6. for(int j=1;j<=3;j++){
7. if(i==2&&j==2){
8. continue;
9. }
10. cout<<i<<" "<<j<<"\n";
11. }
12. }
13. }

Output:

1 1
1 2
1 3
2 1
2 3
3 1
3 2
3 3

C++ Functions
The function in C++ language is also known as procedure or subroutine in other
programming languages.

To perform any task, we can create function. A function can be called many times. It
provides modularity and code reusability.
Advantage of functions in C
There are many advantages of functions.

1) Code Reusability

By creating functions in C++, you can call it many times. So we don't need to write the
same code again and again.

2) Code optimization

It makes the code optimized, we don't need to write much code.

Suppose, you have to check 3 numbers (531, 883 and 781) whether it is prime number or
not. Without using function, you need to write the prime number logic 3 times. So, there is
repetition of code.

But if you use functions, you need to write the logic only once and you can reuse it several
times.

Types of Functions
There are two types of functions in C programming:

1. Library Functions: are the functions which are declared in the C++ header files such as
ceil(x), cos(x), exp(x), etc.

2. User-defined functions: are the functions which are created by the C++ programmer,
so that he/she can use it many times. It reduces complexity of a big program and optimizes
the code.
Declaration of a function
The syntax of creating function in C++ language is given below:

1. return_type function_name(data_type parameter...)


2. {
3. //code to be executed
4. }

C++ Function Example


Let's see the simple example of C++ function.

1. #include <iostream>
2. using namespace std;
3. void func() {
4. static int i=0; //static variable
5. int j=0; //local variable
6. i++;
7. j++;
8. cout<<"i=" << i<<" and j=" <<j<<endl;
9. }
10. int main()
11. {
12. func();
13. func();
14. func();
15. }

Output:

i= 1 and j= 1
i= 2 and j= 1
i= 3 and j= 1

C++ Math Functions


C++ offers some basic math functions and the required header file to use these functions is
<math.h>

Trignometric functions

Method Description

cos(x) It computes the cosine of x.

sin(x) It computes the sine of x.

tan(x) It computes the tangent of x.

acos(x) It finds the inverse cosine of x.

asin(x) It finds the inverse sine of x.

atan(x) It finds the inverse tangent of x.

atan2(x,y) It finds the inverse tangent of a coordinate x and y.


Hyperbolic functions

Method Description

cosh(x) It computes the hyperbolic cosine of x.

sinh(x) It computes the hyperbolic sine of x.

tanh(x) It computes the hyperbolic tangent of x.

acosh(x) It finds the arc hyperbolic cosine of x.

asinh(x) It finds the arc hyperbolic sine of x.

atanh(x) It finds the arc hyperbolic tangent of x.

Exponential functions

Method Description

exp(x) It computes the exponential e raised to the power x.

frexp(value_type x,int* exp) It breaks a number into significand and 2 raised to the power exp

Idexp(float x, int e) It computes the product of x and 2 raised to the power e.

log(x) It computes the natural logarithm of x.

log10(x) It computes the common logarithm of x.


modf() It breaks a number into an integer and fractional part.

exp2(x) It computes the base 2 exponential of x.

expm1(x) It computes the exponential raised to the power x minus one.

log1p(x) It computes the natural logarithm of x plus one.

log2(x) It computes the base 2 logarithm of x.

logb(x) It computes the logarithm of x.

scalbn( x, n) It computes the product of x and FLT_RADX raised to the power n

scalbln( x, n) It computes the product of x and FLT_RADX raised to the power n

ilogb(x) It returns the exponent part of x.

Floating point manipulation functions

Method Description

copysign(x,y) It returns the magnitude of x with the sign of y.

nextafter(x,y) It represents the next representable value of x in the direction of y.

nexttoward(x,y) It represents the next representable value of x in the direction of y.

Maximum,Minimum and Difference functions


Method Description

fdim(x,y) It calculates the positive difference between x and y.

fmax(x,y) It returns the larger number among two numbers x and y.

fmin() It returns the smaller number among two numbers x and y .

Power functions

Method Description

pow(x,y) It computes x raised to the power y.

sqrt(x) It computes the square root of x.

cbrt(x) It computes the cube root of x.

hypot(x,y) It finds the hypotenuse of a right angled triangle.

Nearest integer operations

Method Description

ceil(x) It rounds up the value of x.

floor(x) It rounds down the value of x.

round(x) It rounds off the value of x.


lround(x) It rounds off the value of x and cast to long integer.

llround(x) It rounds off the value of x and cast to long long integer.

fmod(n,d) It computes the remainder of division n/d.

trunc(x) It rounds off the value x towards zero.

rint(x) It rounds off the value of x using rounding mode.

lrint(x) It rounds off the value of x using rounding mode and cast to long integer.

llrint(x) It rounds off the value x and cast to long long integer.

nearbyint(x) It rounds off the value x to a nearby integral value.

remainder(n,d) It computes the remainder of n/d.

remquo() It computes remainder and quotient both.

Other functions

Method Description

fabs(x) It computes the absolute value of x.

abs(x) It computes the absolute value of x.

fma(x,y,z) It computes the expression x*y+z.


Macro functions

Method Description

fpclassify(x) It returns the value of type that matches one of the macro constants.

isfinite(x) It checks whether x is finite or not.

isinf() It checks whether x is infinite or not.

isnan() It checks whether x is nan or not.

isnormal(x) It checks whether x is normal or not.

signbit(x) It checks whether the sign of x is negative or not.

Comparison macro functions

Method Description

isgreater(x,y) It determines whether x is greater than y or not.

isgreaterequal(x,y) It determines whether x is greater than or equal to y or not.

less(x,y) It determines whether x is less than y or not.

islessequal(x,y) It determines whether x is less than or equal to y.

islessgreater(x,y) It determines whether x is less or greater than y or not.


isunordered(x,y) It checks whether x can be meaningfully compared or not.

Error and gamma functions

Method Description

erf(x) It computes the error function value of x.

erfc(x) It computes the complementary error function value of x.

tgamma(x) It computes the gamma function value of x.

lgamma(x) It computes the logarithm of a gamma function of x

C++ Iterators
Iterators are just like pointers used to access the container elements.

Important Points:
o Iterators are used to traverse from one element to another element, a process is
known as iterating through the container.
o The main advantage of an iterator is to provide a common interface for all the
containers type.
o Iterators make the algorithm independent of the type of the container used.
o Iterators provide a generic approach to navigate through the elements of a
container.

Syntax
1. <ContainerType> :: iterator;
2. <ContainerType> :: const_iterator;
Operations Performed on the Iterators:
o Operator (*) : The '*' operator returns the element of the current position pointed
by the iterator.
o Operator (++) : The '++' operator increments the iterator by one. Therefore, an
iterator points to the next element of the container.
o Operator (==) and Operator (!=) : Both these operators determine whether the
two iterators point to the same position or not.
o Operator (=) : The '=' operator assigns the iterator.

Difference b/w Iterators & Pointers


Iterators can be smart pointers which allow to iterate over the complex data structures. A
Container provides its iterator type. Therefore, we can say that the iterators have the
common interface with different container type.

The container classes provide two basic member functions that allow to iterate or move
through the elements of a container:

o begin(): The begin() function returns an iterator pointing to the first element of the
container.
o end(): The end() function returns an iterator pointing to the past-the-last element
of the container.

Let's see a simple example:

1. #include <iostream>
2. #include<iterator>
3. #include<vector>
4. using namespace std;
5. int main()
6. {
7. std::vector<int> v{1,2,3,4,5};
8. vector<int>::iterator itr;
9. for(itr=v.begin();itr!=v.end();itr++)
10. {
11. std::cout << *itr <<" ";
12. }
13. return 0;
14. }

Output:

1 2 3 4 5

Iterator Categories
An iterator can be categorized in the following ways:

o Input Iterator
o Output Iterator
o Forward Iterator
o Bidirectional Iterator
o Random Access Iterator

Input Iterator: An input iterator is an iterator used to access the elements from the
container, but it does not modify the value of a container.

Operators used for an input iterator are:

o Increment operator(++)
o Equal operator(==)
o Not equal operator(!=)
o Dereference operator(*)

Output Iterator: An output iterator is an iterator used to modify the value of a container,
but it does not read the value from a container. Therefore, we can say that an output
iterator is a write-only iterator.

Operators used for an output iterator are:

o Increment operator(++)
o Assignment operator(=)

Forward Iterator: A forward iterator is an iterator used to read and write to a container. It
is a multi-pass iterator.

Operators used for a Forward iterator are:

o Increment operator(++)
o Assignment operator(=)
o Equal operator(=)
o Not equal operator(!=)

Bidirectional iterator: A bidirectional iterator is an iterator supports all the features of a


forward iterator plus it adds one more feature, i.e., decrement operator(--). We can move
backward by decrementing an iterator.

Operators used for a Bidirectional iterator are:

o Increment operator(++)
o Assignment operator(=)
o Equal operator(=)
o Not equal operator(!=)
o Decrement operator(--)

Random Access Iterator: A Random Access iterator is an iterator provides random access
of an element at an arbitrary location. It has all the features of a bidirectional iterator plus it
adds one more feature, i.e., pointer addition and pointer subtraction to provide random
access to an element.

Providers Of Iterators

Iterator categories Provider


Input iterator istream

Output iterator ostream

Forward iterator

Bidirectional iterator List, set, multiset, map, multimap

Random access iterator Vector, deque, array

Iterators and their Characteristics

Iterator Access method Direction of movement I/O ca

Input Linear Forward only Read

Output Linear Forward only Writ

Forward Linear Forward only Read

Bidirectional Linear Forward & backward Read

Random Random Forward & backward Read

Disadvantages of iterator
o If we want to move from one data structure to another at the same time, iterators
won't work.
o If we want to update the structure which is being iterated, an iterator won?t allow us
to do because of the way it stores the position.
o If we want to backtrack while processing through a list, the iterator will not work in
this case.

Advantages of iterator
Following are the advantages of an iterator:

o Ease in programming: It is convenient to use iterators rather than using a


subscript operator[] to access the elements of a container. If we use subscript
operator[] to access the elements, then we need to keep the track of the number of
elements added at the runtime, but this would not happen in the case of an iterator.

Let's see a simple example:

1. #include <iostream>
2. #include<vector>
3. #include<iterator>
4. using namespace std;
5. int main()
6. {
7. vector<int> v{1,2,3,4,5};
8. vector<int>::iterator itr;
9. for(int i=0;i<5;i++) // Traversal without using an iterator.
10. {
11. cout<<v[i]<<" ";
12. }
13. cout<<'\n';
14. for(itr=v.begin();itr!=v.end();itr++) // Traversal by using an iterator.
15. {
16. cout<<*itr<<" ";
17. }
18. v.push_back(10);
19. cout<<'\n';
20. for(int i=0;i<6;i++)
21. {
22. cout<<v[i]<<" ";
23. }
24. cout<<'\n';
25. for(itr=v.begin();itr!=v.end();itr++)
26. {
27. cout<<*itr<<" ";
28. }
29. return 0;
30. }

Output:

1 2 3 4 5
1 2 3 4 5
1 2 3 4 5 10
1 2 3 4 5 10
In the above example, we observe that if we traverse the elements of a vector without
using an iterator, then we need to keep track of the number of elements added in the
container.

o Code Reusability: A code can be reused if we use iterators. In the above example,
if we replace vector with the list, and then the subscript operator[] would not work to
access the elements as the list does not support the random access. However, we
use iterators to access the elements, then we can also access the list elements.
o Dynamic Processing: C++ iterators provide the facility to add or delete the data
dynamically.

Let's see a simple example:

1. #include <iostream>
2. #include<vector>
3. #include<iterator>
4. using namespace std;
5. int main()
6. {
7. vector<int> v{1,2,3,4,5}; // vector declaration
8. vector<int>::iterator itr;
9. v.insert(v.begin()+1,10);
10. for(itr=v.begin();itr!=v.end();itr++)
11. {
12. cout<<*itr<<" ";
13. }
14. return 0;
15. }

Output:

1 10 2 3 4 5

In the above example, we insert a new element at the second position by using insert()
function and all other elements are shifted by one.

Difference b/w Random Access Iterator and Other


Iterators
The most important difference between the Random access iterator and other iterators is
that random access iterator requires '1' step to access an element while other
iterators require 'n' steps.
Next Topic C++ Tutorial

C++ Namespaces
Namespaces in C++ are used to organize too many classes so that it can be easy to handle
the application.

For accessing the class of a namespace, we need to use namespacename::classname. We


can use using keyword so that we don't have to use complete name all the time.

In C++, global namespace is the root namespace. The global::std will always refer to the
namespace "std" of C++ Framework.
C++ namespace Example
Let's see the simple example of namespace which include variable and functions.

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

C++ namespace example: by using keyword


Let's see another example of namespace where we are using "using" keyword so that we
don't have to use complete name for accessing a namespace program.

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

C++ Vector
A vector is a sequence container class that implements dynamic array, means size
automatically changes when appending elements. A vector stores the elements in
contiguous memory locations and allocates the memory as needed at run time.

Difference between vector and array


An array follows static approach, means its size cannot be changed during run time while
vector implements dynamic array means it automatically resizes itself when appending
elements.

Syntax
Consider a vector 'v1'. Syntax would be:

1. vector<object_type> v1;

Example
Let's see a simple example.

1. #include<iostream>
2. #include<vector>
3. using namespace std;
4. int main()
5. {
6. vector<string> v1;
7. v1.push_back("javaTpoint ");
8. v1.push_back("tutorial");
9. for(vector<string>::iterator itr=v1.begin();itr!=v1.end();++itr)
10. cout<<*itr;
11. return 0;
12. }

Output:

javaTpoint tutorial

In this example, vector class has been used to display the string.

C++ Vector Functions

Function Description

at() It provides a reference to an element.

back() It gives a reference to the last element.

front() It gives a reference to the first element.

swap() It exchanges the elements between two vectors.

push_back() It adds a new element at the end.

pop_back() It removes a last element from the vector.

empty() It determines whether the vector is empty or not.

insert() It inserts new element at the specified position.

erase() It deletes the specified element.

resize() It modifies the size of the vector.

clear() It removes all the elements from the vector.

size() It determines a number of elements in the vector.


capacity() It determines the current capacity of the vector.

assign() It assigns new values to the vector.

operator=() It assigns new values to the vector container.

operator[]() It access a specified element.

end() It refers to the past-lats-element in the vector.

emplace() It inserts a new element just before the position pos.

emplace_back() It inserts a new element at the end.

rend() It points the element preceding the first element of the vector.

rbegin() It points the last element of the vector.

begin() It points the first element of the vector.

max_size() It determines the maximum size that vector can hold.

cend() It refers to the past-last-element in the vector.

cbegin() It refers to the first element of the vector.

crbegin() It refers to the last character of the vector.

crend() It refers to the element preceding the first element of the vector.

data() It writes the data of the vector into an array.

shrink_to_fit() It reduces the capacity and makes it equal to the size of the vector.

C++ Programs
C++ programs are frequently asked in the interview. These programs can be asked from
basics, array, string, pointer, linked list, file handling etc. Let's see the list of top c++
programs.
1) Fibonacci Series

Write a c++ program to print fibonacci series without using recursion and using recursion.

Input: 10

Output: 0 1 1 2 3 5 8 13 21 34

2) Prime number

Write a c++ program to check prime number.

Input: 17

Output: not prime number

Input: 57

Output: prime number

3) Palindrome number

Write a c++ program to check palindrome number.

Input: 121

Output: not palindrome number

Input: 113

Output: palindrome number

4) Factorial

Write a c++ program to print factorial of a number.

Input: 5

Output: 120
Input: 6

Output: 720

5) Armstrong number

Write a c++ program to check armstrong number.

Input: 371

Output: armstrong

Input: 342

Output: not armstrong

6) Sum of Digits

Write a c++ program to print sum of digits.

Input: 23

Output: 5

Input: 624

Output: 12

7) Reverse Number

Write a c++ program to reverse given number.

Input: 234

Output: 432

8) Swap two numbers without using third variable

Write a c++ program to swap two numbers without using third variable.
Input: a=5 b=10

Output: a=10 b=5

9) Matrix Multiplication

Write a c++ program to print multiplication of 2 matrices.

Input:

first matrix elements:


1 2 3
1 2 3
1 2 3
second matrix elements
1 1 1
2 1 2
3 2 1

Output:

multiplication of the matrix:


14 9 8
14 9 8
14 9 8

10) Decimal to Binary

Write a c++ program to convert decimal number to binary.

Input: 9

Output: 1001

Input: 20

Output: 10100

11) Alphabet Triangle

Write a c++ program to print alphabet triangle.

Output:

A
ABA
ABCBA
ABCDCBA
ABCDEDCBA

12) Number Triangle

Write a c++ program to print number triangle.

Input: 7

Output:

enter the range= 6


1
121
12321
1234321
123454321
12345654321

13) Fibonacci Triangle

Write a c++ program to generate fibonacci triangle.

Input: 5

Output:

1
1 1
1 1 2
1 1 2 3
1 1 2 3 5

14) Number in Characters

Write a c++ program to convert number in characters.

Input: 74254

Output:Seven Four Two Five Four

Input: 203

Output: two zero three

Fibonacci Series in C++


Fibonacci Series in C++: In case of fibonacci series, next number is the sum of previous
two numbers for example 0, 1, 1, 2, 3, 5, 8, 13, 21 etc. The first two numbers of fibonacci
series are 0 and 1.

There are two ways to write the fibonacci series program:

o Fibonacci Series without recursion


o Fibonacci Series using recursion

Fibonaccci Series in C++ without Recursion


Let's see the fibonacci series program in C++ without recursion.

1. #include <iostream>
2. using namespace std;
3. int main() {
4. int n1=0,n2=1,n3,i,number;
5. cout<<"Enter the number of elements: ";
6. cin>>number;
7. cout<<n1<<" "<<n2<<" ";//printing 0 and 1
8. for(i=2;i<number;++i) //loop starts from 2 because 0 and 1 are already printe
d
9. {
10. n3=n1+n2;
11. cout<<n3<<" ";
12. n1=n2;
13. n2=n3;
14. }
15. return 0;
16. }

Output:

Enter the number of elements: 10


0 1 1 2 3 5 8 13 21 34

Fibonnaci series using recursion in C++


Let's see the fibonacci series program in C++ using recursion.

1. #include<iostream>
2. using namespace std;
3. void printFibonacci(int n){
4. static int n1=0, n2=1, n3;
5. if(n>0){
6. n3 = n1 + n2;
7. n1 = n2;
8. n2 = n3;
9. cout<<n3<<" ";
10. printFibonacci(n-1);
11. }
12. }
13. int main(){
14. int n;
15. cout<<"Enter the number of elements: ";
16. cin>>n;
17. cout<<"Fibonacci Series: ";
18. cout<<"0 "<<"1 ";
19. printFibonacci(n-2); //n-2 because 2 numbers are already printed
20. return 0;
21. }

Output:

Enter the number of elements: 15


Fibonacci Series: 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377

Prime Number Program in C++


Prime number is a number that is greater than 1 and divided by 1 or itself. In other words,
prime numbers can't be divided by other numbers than itself or 1. For example 2, 3, 5, 7,
11, 13, 17, 19, 23.... are the prime numbers.

Let's see the prime number program in C++. In this C++ program, we will take an input
from the user and check whether the number is prime or not.

1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int n, i, m=0, flag=0;
6. cout << "Enter the Number to check Prime: ";
7. cin >> n;
8. m=n/2;
9. for(i = 2; i <= m; i++)
10. {
11. if(n % i == 0)
12. {
13. cout<<"Number is not Prime."<<endl;
14. flag=1;
15. break;
16. }
17. }
18. if (flag==0)
19. cout << "Number is Prime."<<endl;
20. return 0;
21. }

Output:

Enter the Number to check Prime: 17


Number is Prime.
Enter the Number to check Prime: 57
Number is not Prime.

Palindrome program in C++


A palindrome number is a number that is same after reverse. For example 121, 34543,
343, 131, 48984 are the palindrome numbers.

Palindrome number algorithm


o Get the number from user
o Hold the number in temporary variable
o Reverse the number
o Compare the temporary number with reversed number
o If both numbers are same, print palindrome number
o Else print not palindrome number

Let's see the palindrome program in C++. In this program, we will get an input from the
user and check whether number is palindrome or not.

1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int n,r,sum=0,temp;
6. cout<<"Enter the Number=";
7. cin>>n;
8. temp=n;
9. while(n>0)
10. {
11. r=n%10;
12. sum=(sum*10)+r;
13. n=n/10;
14. }
15. if(temp==sum)
16. cout<<"Number is Palindrome.";
17. else
18. cout<<"Number is not Palindrome.";
19. return 0;
20. }

Output:

Enter the Number=121


Number is Palindrome.
Enter the number=113
Number is not Palindrome.

Factorial program in C++


Factorial Program in C++: Factorial of n is the product of all positive descending integers.
Factorial of n is denoted by n!. For example:

1. 4! = 4*3*2*1 = 24
2. 6! = 6*5*4*3*2*1 = 720

Here, 4! is pronounced as "4 factorial", it is also called "4 bang" or "4 shriek".

The factorial is normally used in Combinations and Permutations (mathematics).

There are many ways to write the factorial program in C++ language. Let's see the 2 ways
to write the factorial program.

o Factorial Program using loop


o Factorial Program using recursion
Factorial Program using Loop
Let's see the factorial Program in C++ using loop.

1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int i,fact=1,number;
6. cout<<"Enter any Number: ";
7. cin>>number;
8. for(i=1;i<=number;i++){
9. fact=fact*i;
10. }
11. cout<<"Factorial of " <<number<<" is: "<<fact<<endl;
12. return 0;
13. }

Output:

Enter any Number: 5


Factorial of 5 is: 120

Factorial Program using Recursion


Let's see the factorial program in C++ using recursion.

1. #include<iostream>
2. using namespace std;
3. int main()
4. {
5. int factorial(int);
6. int fact,value;
7. cout<<"Enter any number: ";
8. cin>>value;
9. fact=factorial(value);
10. cout<<"Factorial of a number is: "<<fact<<endl;
11. return 0;
12. }
13. int factorial(int n)
14. {
15. if(n<0)
16. return(-1); /*Wrong value*/
17. if(n==0)
18. return(1); /*Terminating condition*/
19. else
20. {
21. return(n*factorial(n-1));
22. }
23. }

Output:

Enter any number: 6


Factorial of a number is: 720

Armstrong Number in C++


Before going to write the C++ program to check whether the number is Armstrong or not,
let's understand what is Armstrong number.

Armstrong number is a number that is equal to the sum of cubes of its digits. For example
0, 1, 153, 370, 371 and 407 are the Armstrong numbers.

Let's try to understand why 371 is an Armstrong number.

1. 371 = (3*3*3)+(7*7*7)+(1*1*1)
2. where:
3. (3*3*3)=27
4. (7*7*7)=343
5. (1*1*1)=1
6. So:
7. 27+343+1=371

Let's see the C++ program to check Armstrong Number.

1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int n,r,sum=0,temp;
6. cout<<"Enter the Number= ";
7. cin>>n;
8. temp=n;
9. while(n>0)
10. {
11. r=n%10;
12. sum=sum+(r*r*r);
13. n=n/10;
14. }
15. if(temp==sum)
16. cout<<"Armstrong Number."<<endl;
17. else
18. cout<<"Not Armstrong Number."<<endl;
19. return 0;
20. }

Output:

Enter the Number= 371


Armstrong Number.
Enter the Number= 342
Not Armstrong Number.

Sum of digits program in C++


We can write the sum of digits program in C++ language by the help of loop and
mathematical operation only.

Sum of digits algorithm


To get sum of each digit by C++ program, use the following algorithm:

o Step 1: Get number by user


o Step 2: Get the modulus/remainder of the number
o Step 3: sum the remainder of the number
o Step 4: Divide the number by 10
o Step 5: Repeat the step 2 while number is greater than 0.

Let's see the sum of digits program in C++.

1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int n,sum=0,m;
6. cout<<"Enter a number: ";
7. cin>>n;
8. while(n>0)
9. {
10. m=n%10;
11. sum=sum+m;
12. n=n/10;
13. }
14. cout<<"Sum is= "<<sum<<endl;
15. return 0;
16. }

Output:

Enter a number: 23
Sum is= 5
Enter a number: 624
Sum is= 12

C++ Program to reverse number


We can reverse a number in C++ using loop and arithmetic operators. In this program, we
are getting number as input from the user and reversing that number.

Let's see a simple C++ example to reverse a given number.

1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int n, reverse=0, rem;
6. cout<<"Enter a number: ";
7. cin>>n;
8. while(n!=0)
9. {
10. rem=n%10;
11. reverse=reverse*10+rem;
12. n/=10;
13. }
14. cout<<"Reversed Number: "<<reverse<<endl;
15. return 0;
16. }

Output:

Enter a number: 234


Reversed Number: 432

C++ Program to swap two numbers without


third variable
We can swap two numbers without using third variable. There are two common ways to
swap two numbers without using third variable:

1. By + and -
2. By * and /

Program 1: Using * and /


Let's see a simple C++ example to swap two numbers without using third variable.

1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int a=5, b=10;
6. cout<<"Before swap a= "<<a<<" b= "<<b<<endl;
7. a=a*b; //a=50 (5*10)
8. b=a/b; //b=5 (50/10)
9. a=a/b; //a=10 (50/5)
10. cout<<"After swap a= "<<a<<" b= "<<b<<endl;
11. return 0;
12. }

Output:

Before swap a= 5 b= 10
After swap a= 10 b= 5
Program 2: Using + and -
Let's see another example to swap two numbers using + and -.

1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int a=5, b=10;
6. cout<<"Before swap a= "<<a<<" b= "<<b<<endl;
7. a=a+b; //a=15 (5+10)
8. b=a-b; //b=5 (15-10)
9. a=a-b; //a=10 (15-5)
10. cout<<"After swap a= "<<a<<" b= "<<b<<endl;
11. return 0;
12. }

Output:

Before swap a= 5 b= 10
After swap a= 10 b= 5

Matrix multiplication in C++


We can add, subtract, multiply and divide 2 matrices. To do so, we are taking input from
the user for row number, column number, first matrix elements and second matrix
elements. Then we are performing multiplication on the matrices entered by the user.

In matrix multiplication first matrix one row element is multiplied by second matrix all
column elements.

Let's try to understand the matrix multiplication of 3*3 and 3*3 matrices by the figure
given below:
Let's see the program of matrix multiplication in C++.

1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int a[10][10],b[10][10],mul[10][10],r,c,i,j,k;
6. cout<<"enter the number of row=";
7. cin>>r;
8. cout<<"enter the number of column=";
9. cin>>c;
10. cout<<"enter the first matrix element=\n";
11. for(i=0;i<r;i++)
12. {
13. for(j=0;j<c;j++)
14. {
15. cin>>a[i][j];
16. }
17. }
18. cout<<"enter the second matrix element=\n";
19. for(i=0;i<r;i++)
20. {
21. for(j=0;j<c;j++)
22. {
23. cin>>b[i][j];
24. }
25. }
26. cout<<"multiply of the matrix=\n";
27. for(i=0;i<r;i++)
28. {
29. for(j=0;j<c;j++)
30. {
31. mul[i][j]=0;
32. for(k=0;k<c;k++)
33. {
34. mul[i][j]+=a[i][k]*b[k][j];
35. }
36. }
37. }
38. //for printing result
39. for(i=0;i<r;i++)
40. {
41. for(j=0;j<c;j++)
42. {
43. cout<<mul[i][j]<<" ";
44. }
45. cout<<"\n";
46. }
47. return 0;
48. }

Output:

enter the number of row=3


enter the number of column=3
enter the first matrix element=
1 2 3
1 2 3
1 2 3
enter the second matrix element=
1 1 1
2 1 2
3 2 1
multiply of the matrix=
14 9 8
14 9 8
14 9 8
C++ Program to convert Decimal to Binary
We can convert any decimal number (base-10 (0 to 9)) into binary number (base-2 (0 or
1)) by C++ program.

Decimal Number
Decimal number is a base 10 number because it ranges from 0 to 9, there are total 10 digits
between 0 to 9. Any combination of digits is decimal number such as 223, 585, 192, 0, 7
etc.

Binary Number
Binary number is a base 2 number because it is either 0 or 1. Any combination of 0 and 1 is
binary number such as 1001, 101, 11111, 101010 etc.

Let's see the some binary numbers for the decimal number.

Decimal Binary

1 0

2 10

3 11

4 100

5 101

6 110

7 111

8 1000

9 1001

10 1010
Decimal to Binary Conversion Algorithm
Step 1: Divide the number by 2 through % (modulus operator) and store the remainder in
array

Step 2: Divide the number by 2 through / (division operator)

Step 3: Repeat the step 2 until the number is greater than zero

Let's see the C++ example to convert decimal to binary.

1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int a[10], n, i;
6. cout<<"Enter the number to convert: ";
7. cin>>n;
8. for(i=0; n>0; i++)
9. {
10. a[i]=n%2;
11. n= n/2;
12. }
13. cout<<"Binary of the given number= ";
14. for(i=i-1 ;i>=0 ;i--)
15. {
16. cout<<a[i];
17. }
18. }

Output:

Enter the number to convert: 9


Binary of the given number= 1001

C++ Program to Convert Number in Characters


In C++ language, we can easily convert number in characters by the help of loop and
switch case. In this program, we are taking input from the user and iterating this number
until it is 0. While iteration, we are dividing it by 10 and the remainder is passed in switch
case to get the word for the number.

Let's see the C++ program to convert number in characters.


1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. long int n,sum=0,r;
6. cout<<"Enter the Number= ";
7. cin>>n;
8. while(n>0)
9. {
10. r=n%10;
11. sum=sum*10+r;
12. n=n/10;
13. }
14. n=sum;
15. while(n>0)
16. {
17. r=n%10;
18. switch(r)
19. {
20. case 1:
21. cout<<"one ";
22. break;
23. case 2:
24. cout<<"two ";
25. break;
26. case 3:
27. cout<<"three ";
28. break;
29. case 4:
30. cout<<"four ";
31. break;
32. case 5:
33. cout<<"five ";
34. break;
35. case 6:
36. cout<<"six ";
37. break;
38. case 7:
39. cout<<"seven ";
40. break;
41. case 8:
42. cout<<"eight ";
43. break;
44. case 9:
45. cout<<"nine ";
46. break;
47. case 0:
48. cout<<"zero ";
49. break;
50. default:
51. cout<<"tttt ";
52. break;
53. }
54. n=n/10;
55. }
56. }

Output:

Enter the Number= 74254


seven four two five four

C++ Program to Print Alphabet Triangle


There are different triangles that can be printed. Triangles can be generated by alphabets or
numbers. In this C++ program, we are going to print alphabet triangles.

Let's see the C++ example to print alphabet triangle.

1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. char ch='A';
6. int i, j, k, m;
7. for(i=1;i<=5;i++)
8. {
9. for(j=5;j>=i;j--)
10. cout<<" ";
11. for(k=1;k<=i;k++)
12. cout<<ch++;
13. ch--;
14. for(m=1;m<i;m++)
15. cout<<--ch;
16. cout<<"\n";
17. ch='A';
18. }
19. return 0;
20. }

Output:

A
ABA
ABCBA
ABCDCBA
ABCDEDCBA

C++ Program to print Number Triangle


Like alphabet triangle, we can write the C++ program to print the number triangle. The
number triangle can be printed in different ways.

Let's see the C++ example to print number triangle.

1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int i,j,k,l,n;
6. cout<<"Enter the Range=";
7. cin>>n;
8. for(i=1;i<=n;i++)
9. {
10. for(j=1;j<=n-i;j++)
11. {
12. cout<<" ";
13. }
14. for(k=1;k<=i;k++)
15. {
16. cout<<k;
17. }
18. for(l=i-1;l>=1;l--)
19. {
20. cout<<l;
21. }
22. cout<<"\n";
23. }
24. return 0;
25. }

Output:

Enter the Range=5


1
121
12321
1234321
123454321
Enter the Range=6
1
121
2321
1234321
123454321
12345654321

Embedded System Project: RFID Based


Attendance System

RFID Based Attendance System Using 8051


Microcontroller
Nowadays, attendance in schools and colleges is based on paper. Sometimes this process
causes errors and takes more time.

This project uses RFID technology for making a note of every student entering in a
classroom and also calculates the time resides in a class.

In this system every student is allotted with an RFID tag. The attendance can be done by
placing card near RFID reader.

What is RFID?
The Radio Frequency Identification (RFID) is an electronic device which includes a small
antenna and a chip. This device is used for transmitting information between reader and
RFID tag using radio frequency electromagnetic fields.

The operating frequency ranges of these devices include low, mid and high ranges. The low
frequency range is from 30 KHz to 500 KHz, middle frequency range is from 500 KHz to 900
KHz and high frequency range is from 2.4 MHz to 2.5 MHz

Block Diagram of RFID Based Attendance system


The attendance system in most of schools and colleges is mostly documented based. For
automatic attendance system a wireless technology based RFID system is proposed. Every
student is provided with an RFID tag, which uses inbuilt IC for storing and processing the
information.

The block diagram of this system includes preset circuit, a microcontroller, an oscillator
circuit, LCD display and an RFID reader.
o Microcontroller-The microcontroller used in a RFID based attendance system is
AT89C52 from the family of 8051. It includes 4-I/O ports and 40-pins.
o Oscillator Circuit-Oscillator circuit is connected in between the pins of 18 and 19 of
a microcontroller. This circuit is built with a combination of oscillator and two 33 pF
capacitors at 11.0592 MHz operational frequency.
o Preset Circuit-The microcontroller AT89C52 9th pin is reset pin. The circuit of the
preset is built with a capacitor, a resistor and a switch. When switch is pressed, the
reset pin is connected with and the microcontroller becomes reset.
o LCD Display-LCD display is consists of 16 pins, where 3 pins are connected with and
remaining all pins are connected with the port-2 of the microcontroller.
o RFID Reader-RFID reader is used for reading the information which is stored in the
RFID tags. It incorporates with any type of hardware design.

Working of Attendance System Circuit


After connecting all the components of attendance system, give the power supply to switch
on the circuit. Then LCD will displays, please swipe the card. The information contain in the
RFID tag is stated as the ID and attendance of the student. When person placed card in
front of RFID reader, it reads the information and start matching with the information stored
in the AT89S52 microcontroller. Before operation microcontroller is preprogrammed with
embedded C language.

If the data of the card matches with RFID reader, then information will display on LCD. By
using this system the operational time can be save as all the information is stored directly
inside the database.

Source Code:

Consider the embedded system program required for operating the microcontroller
system as RFID based attendance system is:-

1. #include<reg51.h>
2. #include<string.h>
3.
4. //0000 to 7FFF
5.
6. sbit RS = P0^7;
7. sbit EN = P0^6;
8.
9. sbit SDA = P1^0;
10. sbit SCL = P1^1;
11. sbit RELAY = P1^2;
12.
13. code unsigned char RFID_1[] = "34006C9C04C0"; //34006C9C04+NULL
14. code unsigned char RFID_2[] = "34006C549C90";
15. code unsigned char RFID_3[] = "1300F8FAC1D0";
16. code unsigned char RFID_4[] = "34006CD5AD20";
17. code unsigned char RFID_5[] = "420061231E1E";
18.
19. code unsigned char name_1[] = "SANJAY JAIN";
20. code unsigned char name_2[] = "SHEKHAT HARSH";
21. code unsigned char name_3[] = "DHOLARIYA RAKSHIT";
22. code unsigned char name_4[] = "DIVYANG SINGH ";
23. code unsigned char name_5[] = "NAKUL JAIN";
24.
25. unsigned char rs[15];
26.
27. unsigned int no_of_records;
28.
29. void delay()
30. {
31. int j;
32. for(j=0;j<500;j++);
33. }
34.
35. void long_delay()
36. {
37. unsigned int j;
38. for(j=0;j<65000;j++);
39. }
40.
41. void idelay()
42. {
43. unsigned int j;
44. for(j=0;j<10000;j++);
45. }
46.
47. void lcd_command(char lc)
48. {
49. P2 = lc;
50. RS = 0;
51. EN = 1;
52. delay();
53. EN = 0;
54. }
55.
56. void lcd_data(char ld)
57. {
58. P2 = ld;
59. RS = 1;
60. EN = 1;
61. delay();
62. EN = 0;
63. }
64.
65. void lcd_init()
66. {
67. lcd_command(0x38);
68. lcd_command(0x0E);
69. lcd_command(0x01);
70. }
71.
72. void serial_init()
73. {
74. TMOD = 0x20;
75. SCON = 0x50;
76. TH1 = 0xFD;
77. TR1 = 1;
78. }
79.
80. void transmit(unsigned char tx)
81. {
82. SBUF = tx;
83. while(TI==0);
84. TI = 0;
85. }
86.
87. void send_string(unsigned char *str)
88. {
89. int j;
90. for(j=0;str[j]!='\0';j++)
91. transmit(str[j]);
92. }
93.
94. unsigned char receive()
95. {
96. char rx;
97. while(RI==0);
98. RI = 0;
99. rx = SBUF;
100. return(rx);
101. }
102.
103. void lcd_string(char add,char *str)
104. {
105. int j;
106. lcd_command(add);
107. for(j=0;str[j]!='\0';j++)
108. lcd_data(str[j]);
109. }
110.
111. void start()
112. {
113. SDA = 1;
114. SCL = 1;
115. SDA = 0;
116. }
117.
118. void stop()
119. {
120. SDA = 0;
121. SCL = 1;
122. SDA = 1;
123. }
124.
125. void write(unsigned char w)
126. {
127. int j;
128. SCL = 0;
129. for(j=0;j<8;j++)
130. {
131. if((w & 0x80)==0)
132. SDA = 0;
133. else
134. SDA = 1;
135. SCL = 1;
136. SCL = 0;
137. ww = w << 1;
138. }
139. SCL = 1;
140. SCL = 0;
141. }
142.
143. unsigned char read()
144. {
145. int j;
146. unsigned char r = 0x00;
147. SDA = 1;
148.
149. for(j=0;j<8;j++)
150. {
151. SCL = 1;
152. rr = r << 1;
153. if(SDA == 1)
154. rr = r | 0x01;
155. SCL = 0;
156. }
157. return(r);
158. }
159.
160. void ack()
161. {
162. SDA = 0;
163. SCL = 1;
164. SCL = 0;
165. }
166.
167. void nack()
168. {
169. SDA = 1;
170. SCL = 1;
171. SCL = 0;
172. }
173.
174. void rtc_read()
175. {
176. unsigned char ss,mm,hh,day,mn,date,yr;
177. start();
178. write(0xD0);
179. write(0x00);
180. stop();
181. start();
182. write(0xD1);
183. ss = read();
184. ack();
185. mm = read();
186. ack();
187. hh = read();
188. ack();
189. day = read();
190. ack();
191. date = read();
192. ack();
193. mn = read();
194. ack();
195. yr = read();
196. nack();
197. stop();
198.
199. rs[0] = hh/0x10 + 48;
200. rs[1] = hh%0x10 + 48;
201. rs[2] = ':';
202. rs[3] = mm/0x10 + 48;
203. rs[4] = mm%0x10 + 48;
204. rs[5] = ',';
205. rs[6] = date/0x10 + 48;
206. rs[7] = date%0x10 + 48;
207. rs[8] = '/';
208. rs[9] = mn/0x10 + 48;
209. rs[10] = mn%0x10 + 48;
210. rs[11] = '/';
211. rs[12] = yr/0x10 + 48;
212. rs[13] = yr%0x10 + 48;
213. rs[14] = '\0';
214. }
215.
216. void rtc_init()
217. {
218. start();
219. write(0xD0);
220. write(0x00);
221. write(0x00);
222. write(0x00);
223. write(0x13);
224. write(0x05);
225. write(0x12);
226. write(0x04);
227. write(0x12);
228. stop();
229.
230. }
231.
232. void write_records(unsigned char *str);
233. void read_records();
234.
235. void main()
236. {
237. unsigned char rec_data[13],i,t;
238.
239. RELAY = 0;
240.
241. lcd_init();
242. serial_init();
243. rtc_init();
244. idelay();
245. start();
246. write(0xA0);
247. write(0x7F);
248. write(0xFF);
249. stop();
250. start();
251. write(0xA1);
252. no_of_records = read();
253. nack();
254. stop();
255.
256. // no_of_records = 0;
257.
258. while(1)
259. {
260. start:
261. lcd_command(0x01);
262. lcd_string(0x80,"RFID ATTENDANCE");
263. lcd_string(0xC5,"SYSTEM");
264.
265. j = 0;
266. while(1)
267. {
268. if(RI==1)
269. {
270. RI = 0;
271. t = receive();
272. if(t == '+')
273. {
274. read_records();
275. goto start;
276. }
277. else
278. {
279. rec_data[j] = t;
280. for(j=1;j<12;j++)
281. rec_data[j] = receive();
282. rec_data[j] = '\0';
283. break;
284. }
285. }
286. }
287.
288. j = strcmp(RFID_1,rec_data); //match => j = 0
289.
290. lcd_command(0x01);
291.
292. if(j==0)
293. {
294. RELAY = 1;
295. lcd_string(0x80,name_1);
296. rtc_read();
297. lcd_string(0xC0,rs);
298. long_delay();
299. write_records(name_1);
300. RELAY = 0;
301. goto start;
302. }
303.
304. //
305. j = strcmp(RFID_2,rec_data); //match => j = 0
306.
307. if(j==0)
308. {
309. RELAY = 1;
310. lcd_string(0x80,name_2);
311. rtc_read();
312. lcd_string(0xC0,rs);
313. long_delay();
314. write_records(name_2);
315. RELAY = 0;
316. goto start;
317. }
318.
319. //
320. j = strcmp(RFID_3,rec_data); //match => j = 0
321.
322. if(j==0)
323. {
324. RELAY = 1;
325. lcd_string(0x80,name_3);
326. rtc_read();
327. lcd_string(0xC0,rs);
328. long_delay();
329. write_records(name_3);
330. RELAY = 0;
331. goto start;
332. }
333.
334. j = strcmp(RFID_4,rec_data); //match => j = 0
335.
336. if(j==0)
337. {
338. RELAY = 1;
339. lcd_string(0x80,name_4);
340. rtc_read();
341. lcd_string(0xC0,rs);
342. long_delay();
343. write_records(name_4);
344. RELAY = 0;
345. goto start;
346. }
347.
348. j = strcmp(RFID_5,rec_data); //match => j = 0
349.
350. if(j==0)
351. {
352. RELAY = 1;
353. lcd_string(0x80,name_5);
354. no_of_records = 0;
355. start();
356. write(0xA0);
357. write(0x7F);
358. write(0xFF);
359. write(0x00);
360. stop();
361. lcd_string(0xC0,"MEMORY CLEARED");
362. long_delay();
363. RELAY = 0;
364. goto start;
365. }
366. lcd_string(0x80,"ERROR");
367. lcd_string(0xC0,rec_data);
368. long_delay();
369. }
370. }

You might also like