100% found this document useful (1 vote)
2K views

OOP Through C++ Notes - UNIT1

The document provides an introduction to differences between C and C++ programming languages. It discusses the evolution of C++ from C and the disadvantages of conventional programming. The key concepts of object-oriented programming such as class, object, encapsulation, inheritance, and polymorphism are explained. Differences between C and C++ regarding input/output functions, keywords, memory allocation, and support for OOP concepts are outlined in a table.

Uploaded by

Revanth Reddy
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
2K views

OOP Through C++ Notes - UNIT1

The document provides an introduction to differences between C and C++ programming languages. It discusses the evolution of C++ from C and the disadvantages of conventional programming. The key concepts of object-oriented programming such as class, object, encapsulation, inheritance, and polymorphism are explained. Differences between C and C++ regarding input/output functions, keywords, memory allocation, and support for OOP concepts are outlined in a table.

Uploaded by

Revanth Reddy
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 32

UNIT I

INTRODUCTION: Differences between C and C++, Evolution of C++, Disadvantage of


Conventional Programming, The Object-Oriented Technology, Key Concept of Object-
Oriented Programming, Advantages of OOP, Structure of C++ Program, C++ header Files,
Basic input and output in C++, Illustrating simple C++ programs without classes .Streams in
C++ and Stream Classes, Pre-defined Streams, Buffering, Stream Classes, Formatted and,
Unformatted Data, Unformatted Console I/O Operations, Type Casting with the cout
Statement, Member Functions of the Istream Class, Formatted Console I/O Operations, Bit
Fields, Flags without Bit Field, Manipulators.
Introduction to C++ / Evolution of C++:
C++ is an object-oriented programming language. C++ is an extension of C. It was developed
by Bjarne Stroustrup at AT&T Bell Laboratories in Murray Hill, New Jersey, USA, in the
early 1980’s. C++ runs on various platforms, such as Windows, Mac OS and the various
version of UNIX. Stroustrup combines the features of both C and Simula 67 and developed a
powerful language which supports OOP with features of C. Various features were derived from
SIMULA67 and ALGOL68. Stroustrup called the new language "C with Classes".
In 1983, "C with Classes" was renamed to "C++”. The thought of C++ came from the C
increment operator ++. C++ is superset of C. All the concepts of C are applicable to C++ also.
For developing complicated applications, Object Oriented language such as C++is the most
convenient and easy.
C++ is a middle-level programming language. C++ is a compiled, general purpose, case -
sensitive, free-form programming language that supports procedural, object-oriented, and
generic programming.

Difference between C and C++:


Following are the differences Between C and C++:

1
S.No. C C++
1 C is Procedure Oriented Programming C++ is Procedure Oriented
language Programming language and Object
Oriented Programming language.

2 C was developed by Dennis Ritchie. C++ was developed by Bjarne


Stroustrup.

3 C is a subset of C++. C++ is a superset of C. C++ can run


most of C code while C cannot run C++
code.

4 Top-down approach is used in Program Bottom-up approach adopted in


Design. Program Design.

5 No namespace Feature is present in C Namespace Feature is present in C++


Language. for avoiding Name collision.

6 In C In C++

• scanf() Function used for Input. • Cin>> Function used for Input.

• printf() Function used for output. • Cout<< Function used for output.

7 In C format specifiers are required to read In C++ format specifiers are not
and print the data. required to print or read the data.

8 C uses “stdio.h” header file for input and C++ uses “iostream” for the same
output oprations. purpose.
9 In C all variables are declared at the starting In C++ all variables are declared
of the scope. anywhere in the scope.
i.e.at the time of first use.

10 C is a function-driven language. C++ is an object-driven language

11 Instead of focusing on data, C focuses on C++ focuses on data instead of


method or process. focusing on method or procedure.

12 In C, malloc() and calloc() Functions are In C++, new and delete operators are
used for Memory Allocation and free() used for Memory Allocating and
function for memory Deallocating. Deallocating.

13 Reference variables are not supported by C Reference variables are supported by


C++.

14 C contains 32 keywords. C++ contains 63 keywords.

15 C does not support object-oriented concepts. C++ supports object-oriented concepts


like

2
Class, Object, Encapsulation and Data
hiding, Inheritance, Polymorphism,
Abstraction and Message passing.

16 C++ does not support friend function and C++ supports friend function and virtual
virtual function. function.

17 C structures don’t have access modifiers. C ++ structures have access modifiers.

18 C++ does not support constructors and C++ supports Constructors and
destructors. Destructors.

19 C++ does not Exception handling and C++ supports Exception handling and
Templates. Templates.

20 The extension of C program is “.c” The extension of C++ program is “.cpp”

Disadvantage of Conventional Programming:


• Traditional programming languages such as COBOL, FORTRAN, C etc. are commonly
known as procedure-oriented languages and also called as Conventional Languages.
• The program written in these languages consists of a sequence of instructions that tells the
compiler or interpreter to perform a given task.
• When a program code is large, it becomes inconvenient to manage and debug. To
overcome this problem, it is divided into smaller functions the carryout some specific task.
• Each function can call another function during the execution.
• As the functions are executing, they may access same data, and modify the data which in
turn effects the entire task.
• Most of the functions are allowed to access the global data.

3
Disadvantages:
1. Large programs are divided into smaller programs known as functions. These functions can
call one another. Hence security is not provided.
2. No importance is given to security of data and importance is given to doing things.
3. Data move openly around the system from function to function.
4. Most functions accesses global data, what happens to the data is not known.
The Object-Oriented Technology/ Programming:
➢ The major motivating factor in the invention of object oriented approach is to remove
drawbacks of procedural oriented approach.
➢ OOP treats data as critical element in the program development and does not allow it
freely to flow around the system or application or program.
➢ OOP combines the data and functions into a single unit this process is called
encapsulation.
➢ The organisation of data and functions in object oriented programming is shown in the
following diagram.

➢ OOP allows divide a problem into a no of entities called as objects and then build data
and functions around these objects.
➢ The data of an object can be accessed only by the function associated with that object.
➢ In OOP, function of one object can access the function of other objects.
Basic Concepts (Key Concepts) of Object-Oriented Programming:
Object-Oriented Programming is a methodology or paradigm to design a program using
classes and objects.
It simplifies the software development and maintenance by providing some concepts:
➢ Class
➢ Object
➢ Encapsulation & Data hiding
➢ Inheritance
➢ Polymorphism
➢ Abstraction
➢ Message passing

4
Class:
Class is an abstract data type (user defined data type) that contains member variables (Data
members) and member functions that operate on data. It starts with the keyword class. A class
denotes a group of similar objects.
(Or)
Class is a blueprint or template for creating an object.

e.g.: class employee


{
int empno;
char name[25], desg[25];
float sal;
public:
void getdata ();
void putdata ();
};
Object:
An object is an instance of a class. It is a variable that represents data members as well as
member functions required for operating on the data. They interact with private data and
functions through public functions.
(Or)

An object is an entity that exists physically in the real world which requires some memory is
called as an object.
e.g.: employee e1, e2;
In the above example employee is the class name and e1 and e2 are objects of that class.
e.g.: Class Object

Fruit Apple, Banana, Grape


Animal Lion, Tiger, Elephant
Mobile Apple, Samsung, Redmi, Realme
Laptop Dell, HP, Lenovo, Mi
Student s1, s2, s3;

Encapsulation & Data hiding:


Encapsulation:
Encapsulation is the process of combining data members and member functions into a single
unit is called as encapsulation.
Data Hiding:
All the data in a class can be restricted from using it by giving some access levels (visibility
modes). The three access levels are private, public, protected.

5
Private data and functions are available to the public functions only. They cannot be accessed
by the other part of the program. This process of hiding private data and functions from the
other part of the program is called as data hiding
Example: capsule, it is wrapped with different medicines.

Inheritance:
➢ It is a process of using the properties (data members and member functions) of one class
inside other class.
➢ The main aim of Inheritance is Reusability of the data members and member functions i.e
data members and member functions declared in one class can be accessed by other class.
➢ In Inheritance, two classes are involved (super class/base class/parent class and sub
class/derived class/child class).
➢ The class which gives properties is called as super class / base class / parent class.
➢ The class which takes the properties is called as sub-class/derived class /child class.

Base Class

Derived Class

Reusability: Using the already existing code is called as reusability. This is mostly used in
inheritance. The already existing code is inherited to the new class. It saves a lot of time and
effort. It also reduces the size of the program.

Polymorphism:
The word polymorphism is derived from two latin words poly(many) and morph (forms).
Polymorphism means the ability to take many forms. Polymorphism allows to take different
implementations for same name.
Poly -> many
Morph -> forms
ism -> behaviours
There are two types of polymorphism, Compile time polymorphism and Run time
polymorphism.
In Compile time polymorphism binding is done at compile time and in runtime polymorphism
binding is done at runtime.
e.g.: Function overloading, operator overloading

6
Function Overloading:
Function overloading is a part of polymorphism. Same function name having different
implementations with different number and type of arguments.
Operator Overloading:
Operator overloading is a part of polymorphism. Same operator can have different
implementations with different data types.
e.g.: MouseClick()
Close button -> Window gets closed
Max button -> window gets maximised
Min button -> window gets minimized
Abstraction:
It is a process of Hiding internal details and showing functionality is known as abstraction.
They are divided into two types:
1.Functional Abstraction
2.Data Abstraction
Functional Abstraction:
Just making a call to a function not bothering how it has been implemented is call as Functional
Abstraction.
Data Abstraction:
Using a class without the knowledge of its implementation is called as Data Abstraction.
For example: phone call, we don't know the internal processing.
Message Passing:
An object-oriented program contains a set of objects that communicate with one another. The
process of object oriented programming contains the basic steps:
1. Creating classes
2. Creating objects
3. Establishing communication among objects

This communication is done with the help of functions (i.e., passing objects to functions)
Objects communicate with one another by sending and receiving information much the same
way as people pass messages to one another.
Message passing involves specifying the name of object, the name of the function (message)
and the information to be sent.

Example:

7
Advantages of OOP:
Object oriented technology provides many advantages to the programmer and the user. This
technology solves many problems related to software development, provides improved quality
and low cost software.
1. Object oriented programs can be comfortably upgraded.
2. Using inheritance, we can eliminate redundant program code and reuse already existing
code.
3. Data hiding facilitates the programmer to design and develop safe programs.
4. Through polymorphism, it provides the extensibility of the code.
5. With OOP, programs are easy to understand.
6. With OOP, programs are easier to test, manage and maintain.
7. Objects can communicate with each other by message passing mechanism.
Applications of OOP:
The promising areas for application of OOP includes:
1. Real-time systems
2. Simulation and modeling
3. Object-oriented databases
4. Hypertext, hypermedia and experttext
5. AI and expertsystems
6. Neural networks and parallel programming
7. Decision support and Automation system
8. CIM/CAM/CAD systems

Structure of a C++ Program:


The structure of C++ program is divided into different sections:

Documentation Section
Linking Section
Definition Section
Global Declaration Section
Class Declaration Section
Class Member Functions Definitions Section
Main Function Section
Fig. Structure of a C++ program
Documentation Section:
1. This section comes first and it is also called as comments sections.
2. Comments are non-executable statements in any programming language.
3. Comments are used to write the program statement / program name.
e.g. /* Write a C++ program illustrating Checking whether the number is even or odd
using Ternary operator. */

8
4. Comments are used to write the program log.
e.g. /* Program Description : To check the no is even or odd
Created Date : 28/10/2021
Created Time : 10.00 am
Created by : ABC
*/
5. Comments are used to write the remarks for each line in the program.
6. Comments are two types
1.Single line Comments:
Single-line comments start with two forward slashes (//).
Example: // This is a comment
2. Multi line Comments:
Multi-line comments start with /* and ends with */.
Example: /* Write a C++ program illustrating Checking
whether the number is even or odd
using Ternary operator. */
7. Whatever written in the documentation section is the comment and is not compiled by
the compiler.
8. Documentation Section is optional since the program can execute without them.
Linking Section:
The linking section contains two parts:
1. Header Files
2. Namespaces
Header Files:
1. Generally, a program includes various programming elements like built-in functions,
classes, objects, keywords, constants, operators, etc. that are already defined in the
standard C++ library.
2. In order to use such pre-defined elements in a program, an appropriate header must be
included in the program.
3. Standard headers are specified in a program through the pre-processor
directive #include.
Example: #include<iostream>
4. When the compiler processes the instruction #include<iostream>, it includes the
objects (cout, cin, cerr & clog) of the stream in the program.
Namespaces:
1. A namespace permits grouping of various entities like classes, objects, functions, and
various C++ tokens, etc. under a single name.
2. Any user can create separate namespaces of its own and can use them in any other
program.
3. In the below snippets, namespace std contains declarations for cout, cin, endl, etc.
statements.
Example: using namespace std;

9
4. Namespaces can be accessed in multiple ways:
using namespace std;
using std :: cout;
Definition Section:
1. It is used to declare some constants and assign them some value.
Example: #define PI 3.14
In #define is a pre-processor directive which tells the compiler whenever the PI is found
replace it with 3.14.
2. It is used to define your own datatype using primitive data types.
Example: typedef int K;
This statement telling the compiler that whenever you will encounter K replace it by int
and as you have declared k as datatype you cannot use it as an identifier.
Global Declaration Section:
1. Here the variables, functions and the class definitions which are going to be used in the
program are declared to make them global.
2. The scope of the variable / function declared in this section continues until the entire
program terminates.
Example:
int a, b; // Global Delaration
int main ()
{
Statements;
}
Class Declaration Section:
This section contains declaration section of Class. You can declare a class and then declare
data members and member functions inside that class. You can also inherit one class from
another existing class in this section.
Example:
class Demo
{
int a, b;
public:
void input();
void output();
};

Class Member Functions Definitions Section:


1. This section is optional in the structure of C++ program.
2. Because you can define member functions inside the class or outside the class. If all the
member functions are defined inside the class then there is no need of this section.
3. This section is used only when you want to define member function outside the class.

10
4. This section contains definition of the member functions that are declared inside the
class.
Example:
void Demo::input( )
{
cout <<” Enter value of a : “<<endl;
cin >> a;
cout <<” Enter value of b : “<<endl;
cin >> b;
}

Main Function Section:


The main function tells the compiler where to start the execution of the program. The execution
of the program starts with the main function.
In this section you can create an object of the class and then using this object you can call
various functions defined inside the class as per your requirement.
Example:
int main ()
{
Demo d1;
d1.input();
d1.output();
return 0;
}

C++ header Files:


1. Generally, a program includes various programming elements like built-in functions,
classes, objects, keywords, constants, operators, etc. that are already defined in the
standard C++ library.
2. In order to use such pre-defined elements in a program, an appropriate header must be
included in the program.
3. Standard headers are specified in a program through the pre-processor
directive #include.
Example: #include<iostream>
4. When the compiler processes the instruction #include<iostream>, it includes the
objects (cout, cin, cerr & clog) of the stream in the program.
There are of 2 types of header file:
1. Pre-existing header files: Files which are already available in C/C++ compiler we just
need to import them.
2. User-defined header files: These files are defined by the user and can be imported
using “#include”.

11
Syntax:
#include <filename.h>
or
#include "filename.h"

1. Pre-existing header files:


Example:
#include<iostream>
using namespace std;
int main()
{
cout<<”Welcome to C++”<<endl;
return 0;
}
2. User-defined header files:
Create your own header file:
Instead of writing a large and complex code, we can create your own header files and
include them in our program to use it whenever we want. It enhances code functionality
and readability.
Below are the steps to create our own header file:
1.Write your own C++ code and save that file with “.h” extension. Below is the
illustration of header file:

// Function to find the sum of two


// numbers passed
int sumOfTwoNumbers(int a, int b)
{
return (a + b);
}
2. Include your header file with “#include” in your C++ program as shown below:

// C++ program to find the sum of two numbers using function declared in header file

#include "iostream"
#include "sum.h" // Including header file
using namespace std;
int main()
{
int a = 13, b = 22; // Given two numbers
// Function declared in header file to find the sum
cout << "Sum is: "<< sumOfTwoNumbers(a, b)<< endl;
}

12
Basic input and output in C++:
• 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 keyboard, 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:

13
Header File Function and Description

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

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

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

Illustrating simple C++ programs without classes:

Example 1: String Output


#include <iostream>
using namespace std;
int main()
{
// prints the string enclosed in double quotes
cout << "Welcome to C++ Programming";
return 0;
}

(Or)
#include <iostream>
int main()
{
// prints the string enclosed in double quotes
std::cout << " Welcome to C++ Programming";
return 0;
}
Output:
Welcome to C++ Programming

Example 2: Numbers and Characters Output:

#include <iostream>
using namespace std;
int main()
{
int num1 = 70;
double num2 = 256.783;
char ch = 'A';
cout << num1 << endl; // print integer
cout << num2 << endl; // print double

14
cout << "character: " << ch << endl; // print char
return 0;
}
Output:
70
256.783
character: A

Example 3: Integer Input/Output


#include <iostream>
using namespace std;

int main()
{
int num;
cout << “Enter an integer: “;
cin >> num; // Taking input
cout << “The number is: “ << num;
return 0;
}
Output:
Enter an integer: 70
The number is: 70

Example 4: C++ Taking Multiple Inputs

#include <iostream>
using namespace std;

int main()
{
char a;
int num;
cout << "Enter a character and an integer: ";
cin >> a >> num;
cout << "Character: " << a << endl;
cout << "Number: " << num;
return 0;
}
Output:
Enter a character and an integer: F
23
Character: F
Number: 23

15
Example: How gets() and puts() function works
#include <iostream>
using namespace std;
int main()
{
char str[100];
cout << "Enter a string: ";
gets(str);
cout << "You entered: " ;
puts(str);
return 0;
}
Output:
Enter a string: Have a great day!
You entered: Have a great day!
Example: How write() function works
#include <iostream>
using namespace std;
int main()
{
// this function display
// ncount character from array
cout.write("Hello World!", 5);
}
Output:
Hello
Example: Writing to a file
#include <iostream>
#include <fstream>
using namespace std;
int main ()
{
ofstream of("testout1.txt");
if (of.is_open())
{
of << "Welcome to ";
of << "C++ Tutorial.\n";
of.close();
}
else
cout <<"File opening is fail.";
return 0;
}

16
Example: Reading from a file
#include <iostream>
#include <fstream>
using namespace std;
int main ()
{
string srg;
ifstream ifs("testout1.txt");
if (ifs.is_open())
{
while ( getline (ifs,srg) )
{
cout << srg <<endl;
}
ifs.close();
}
else
cout << "File opening is fail."<<endl;
return 0;
}

Streams in C++ and Pre-defined Streams:

Fig. Streams and I/O Devices

17
S.No Stream Description
1 cin Standard input stream, usually the keyboard
2 cout Standard input stream, usually the monitor
3 cerr Un-buffered standard error stream, usually the monitor
4 clog Buffered standard error stream, usually the monitor
Cin:
It 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.
Cout:
It is used to display the output on a standard output device which is usually the monitor. The
insertion operator (<<) is used along with the object cout for displaying outputs.
Cerr:
The cerr is the standard error stream that is used to output the errors. This is also an instance
of the ostream 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.
Clog:
The clog is the Buffered standard error stream. 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 then The error
message will be displayed on the screen.
Write an example program to display a message using predefined objects.
#include <iostream>
using namespace std;
int main()
{
int n;
cout <<"Enter an integer: ";
cin>>n;
cout<<"The entered no is:"<<n<<endl;
cout<<"Hello World displayed on monitor"<<endl;
cerr<<"Un-buffered standard error"<<endl;
clog<<"Buffered standard error"<<endl;
return 0;
}
Output:
Enter an integer: 11
The entered no is:11
Hello World displayed on monitor
Un-buffered standard error
Buffered standard error

18
Buffering:
A temporary storage area is called a buffer. All standard input and output devices contain an
input and output buffer. In standard C/C++, streams are buffered.
For example, in the case of standard input, when we press the key on the keyboard, it isn’t
sent to your program, rather it is buffered by the operating system till the time is allotted to that
program.
Example-1:
#include<iostream>
using namespace std;
int main()
{
int a;
char ch[10];
cout<<"Enter an integer:";
cin>>a;
cout<<"Enter any name up to 10 charactes:"<<endl;
cin.getline(ch,10);
cout << a << endl;
cout << ch << endl;
return 0;
}
Output:
Enter an integer:10
Enter any name up to 10 charactes:
10
Example-2: Example-3:
#include<iostream> #include<iostream>
using namespace std; using namespace std;
int main() int main()
{ {
int a; int a;
char ch[10]; char ch[10];
cout<<"Enter an integer:"; cout<<"Enter any string: ";
cin>>a; cin.getline(ch,10);
cin >> ws; cout<<"Enter an integer:";
cin.getline(ch,10); cin>>a;
cout << a << endl; cout << a << endl;
cout << ch << endl; cout << ch << endl;
return 0; return 0;
} }
Output: Output:
Enter an integer:10 Enter any string:Hello
hello Enter an integer:10
10 10
hello Hello

19
Stream Classes:

Fig. Stream Class Hierarchy


1. ios class is topmost class in the stream classes hierarchy. It is the base class for istream,
ostream, and streambuf class.
2. istream and ostream serves the base classes for iostream class. The class istream is used
for input and ostream for the output.
3. Class ios is indirectly inherited to iostream class using istream and ostream. To avoid the
duplicity of data and member functions of ios class.
Facilities provided by these stream classes.
4. The ios class: The ios class is responsible for providing all input and output facilities to
all other stream classes.
5. The istream class: This class is responsible for handling input stream. It provides number
of function for handling chars, strings and objects such as get, getline, gcount,peek,
ignore, putback etc.
6. The ostream class: This class is responsible for handling output stream. It provides
number of function for handling chars, strings and objects such as write, put etc.
7. The iostream class: This class is responsible for handling both input and output stream as
both istream class and ostream class is inherited into it. It provides function of both istream
class and ostream class for handling chars, strings and objects such as get, getline,
gcount,peek, ignore, putback, put, write etc.
8. The istream_withassign class: This class is responsible for handling standard input object
(cin).
9. The ostream_withassign class: This class is responsible for handling standard output
object (cout).
10. The iostream_withassign class: This class is responsible for handling both cin and cout.
11. The ifstream class: This class is responsible for reading the data from a disk file.
12. The ofstream class: This class is responsible for writing the data into a disk file.
13. The fstream class: This class is responsible for both reading the data from a disk file and
writing the data into a disk file.
14. The Streambuf class: This class is responsible for implementing the buffer between the
input and output system.

20
Fig. Working of cin and cout statements

21
22
Type Casting with cout statement:
A type cast is basically a conversion from one type (data type) to another (data type). There
are two types of type conversion:
1. Implicit Type Conversion / Casting
2. Explicit Type Conversion / Casting
Implicit Type Conversion / Casting:
1. It is also called as ‘automatic type conversion’.
2. Done by the compiler on its own, without any external trigger from the user.
Example:
// An example of implicit conversion

#include <iostream>
using namespace std;
int main()
{
int x = 10; // integer x
char y = 'a'; // character c
// y implicitly converted to int. ASCII
// value of 'a' is 97
x = x + y;
// x is implicitly converted to float
float z = x + 1.5;

cout << "x = " << x << endl


<< "y = " << y << endl
<< "z = " << z << endl;

return 0;
}
Output:

23
x = 107
y=a
z = 108.5
Explicit Type Conversion / Casting:

Examples:

24
Example Programs:
1. Write a c++ program to demonstrate the use of get(), peek() , ignore() and putback()
functions.
#include <iostream>
using namespace std;
int main()
{
char ch;
cout << "Enter a phrase: ";
while ( cin.get(ch) )
{
if (ch == '!')
cin.putback('$');
else
cout << ch;
while (cin.peek() == '#')
cin.ignore(1,'#');
}
return 0;
}
Output:
Now!is#the!time#for!fun#!
Now$isthe$timefor$fun$

25
2. Write a c++ program to demonstrate the use of getline() and gcount() functions.
#include <iostream>
using namespace std;
int main()
{
char name[20];
int len;
cout<<"Enter text:"<<endl;
cin.getline(name,20);
len=cin.gcount();
cout<<"The number of chars is:"<<len<<endl;
return 0;
}
Output:
Enter text:
Welcome to C++
The number of chars is:15

26
Example: Write a program to display the formatted output using IOS Functions and
flags.
#include <iostream>
using namespace std;
int main()
{
cout.width(6); // sets the width with given integer
int x=cout.width(); // returns current width
cout<<"The current width is:"<<x<<endl;

cout.width(10); // sets the width 10


cout<<"A"<<endl;

cout.precision(2); // keeps only decimal points


cout.setf(ios::fixed,ios::floatfield);
cout<<3.1472<<endl;

cout.fill('*'); // used to set the blank spaces with *


cout.width(15);
cout<<123<<endl;

cout.width(20);
cout.setf(ios::left,ios::adjustfield); // sets the justification left
cout<<"C++"<<endl;

cout.setf(ios::hex,ios::basefield); // sets input number to hexadecimal


cout<<27<<endl;

return 0;
}

Output:
The current width is:6
A
3.15
************123
C++*****************
1b

27
Example: Write a program to display the formatted output using manipulator.
#include <iostream>
#include <iomanip>
using namespace std;

int main()
{
// setting the width and precision at a time
cout<<setw(10)<<fixed<<setprecision(2)<<3.14567;
cout<<endl; // splits the new line
cout<<hex<<setiosflags(ios::showbase | ios::uppercase)<<15<<endl;
cout<<"The octal value of 23 is:"<<oct<<23<<endl; // Convert hex into oct
int x;
cout<<"Enter a number:"<<endl;
cin>>hex>>x; // reading a number into hexa decimal format
cout<<hex<<x<<endl;
}

Output:

28
Example:
#include <iostream>
#include <iomanip>
using namespace std;

ostream &tab(ostream &o)


{
//here tab is the name of the manipulator
//when it is used it returns the o which contains the tab
o<<"\t";
return o;
}
int main()
{
cout<<1<<tab<<2<<tab<<3<<endl;
}

Output:
1 2 3

Bit Fields:
1. Bit Fields are used to save memory or to restrict memory of members of structure.
2. Using bitfield we can specify the memory to be allocated for individual members of a
structure.
3. When we use structures in the c programming language, the memory required by
structure variable is the sum of memory required by all individual members of that
structure.
To understand the bitfields, let us consider the following example code.

#include <iostream>
using namespace std;
struct Date
{
unsigned int day;
unsigned int month;
unsigned int year;
};

29
int main()
{
cout << sizeof(Date) << endl; // usually prints 12
}

Here, the Date structure allocates 12 bytes of memory.

In the above example structure the members day and month both does not requires 2 bytes
of memory for each. Because member day stores values from 1 to 31 only which requires 5
bits of memory, and the member month stores values from 1 to 12 only which required 4 bits
of memory. So, to save the memory we use the bitfields.

Consider the following structure with bitfields.

#include <iostream>
using namespace std;
struct Date
{
unsigned int day : 5;
unsigned int month : 4;
unsigned int year;
};
int main()
{
cout << sizeof(Date) << endl;
}

Here, the Date structure allocates 8 bytes of memory.

30
Example:
Write a C++ program that uses various Flags of ios?
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
cout << hex;
cout << setiosflags (ios::showbase | ios::uppercase);
cout << 100 << endl;
cout << setiosflags(ios::showpos) << setiosflags(ios::scientific) << 123 << 123.23<<endl;
int num = 50;
cout << "Before reset: \n"
<< hex
<< setiosflags(ios::showbase)
<< num << endl;
// Using resetiosflags()
cout << "Resetting showbase flag"
<< " using resetiosflags: \n"
<< resetiosflags(ios::showbase)
<< num << endl;
}

Output:

31
Assignment Questions:
1.a) Briefly write about the evolution of C++.
b) What are the differences between C and C++?
2.a) State the important features/ key concepts/ principles of object-oriented programming. List
the advantages of OOP?
b) List the drawbacks of conventional programming. Explain how object oriented
programming overcome them.
3.a) Present the structure of C++ program. Explain different elements in it. Give example.
b) Discuss about the Bit Fields. Give example
4. a) What is stream and stream classes? How streams are represented in C++?
b) Discuss about the member functions of iostream class.
5. a) Discuss about Formatted and Unformatted data.
b) Explain formatted and unformatted console I/O operations with examples.

32

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy