0% found this document useful (0 votes)
9 views52 pages

21CSC101T: Object Oriented Design and Programming

The document covers fundamental concepts of Object Oriented Design and Programming in C++, focusing on I/O operations, data types, variables, constants, pointers, and type conversions. It explains the structure of a C++ program, the use of namespaces, and various I/O operations including formatted and unformatted input/output. Additionally, it discusses variable types, constants, special operators, and type casting in C++.

Uploaded by

bt0652
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views52 pages

21CSC101T: Object Oriented Design and Programming

The document covers fundamental concepts of Object Oriented Design and Programming in C++, focusing on I/O operations, data types, variables, constants, pointers, and type conversions. It explains the structure of a C++ program, the use of namespaces, and various I/O operations including formatted and unformatted input/output. Additionally, it discusses variable types, constants, special operators, and type casting in C++.

Uploaded by

bt0652
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 52

21CSC101T

Object Oriented Design and Programming

I/O Operations, Data Types, Variables-Static,


Constants-Pointers-Type Conversions
Topics covered

• I/O Operation
• Data types
• Variable
• Static
• Constant
• Pointer
• Type conversion
I/O Operation
• C++ I/O operation occurs in streams, which involve transfer of information into byte

• It’s a sequences of bytes


Stream in C
• It is the source as well as the destination of data
Text Stream Binary Stream
• C++ programs input data and output data from a stream.

• Streams are related with a physical device such as the monitor or with a file stored on the secondary memory.

• It provides a way for the program to interact with various data sources and destinations like the console, files, or
even memory.

• In a text stream, the sequence of characters is divided into lines, with each line being terminated with a new-line
character (\n) .

• On the other hand, a binary stream contains data values using their memory representation.
The Structure of a C++ Program
#include <iostream> // Preprocessor Directive
using namespace std;
/* This program is to demonstrate the structure of a C++ program */
int main()
{
cout << “Welcome to C++\n”;
return 0;
}
Preprocessor Directive
• # include<iostream.h>

• It tells the compiler to add the header file iostream.h

• Iostream.h is concerned with basic input output operations


The using Directive
• A C++ program can be divided into different namespaces

• A namespace is a part of the program in which certain names are


recognized. Outside the namespace they are unknown

• using namespace std says that all the program statements that follow
are within the std namespace
The std namespace is the standard namespace in C++ where most of the standard
library features (like input/output operations, etc.) are defined.
Example Without using namespace std
#include <iostream>
int main() {
std::cout << "Hello, World!" << std::endl; // Using std:: explicitly
return 0;
}
Example With using namespace std
#include <iostream>
using namespace std;
int main() {
cout << "Hello, World!" << endl; // No need for std:: prefix
return 0;
}
I/O Operations
• Input Statement
eg: cin>>a;
>> is known as extraction operator or get from operator
• Output Statement
eg: cout<<a;
<< is known as insertion operator or put to operator
• Cascading I/O Operators
cout<<“Sum = “<<sum<<“\n”;
cin >>a >>b >>c;
Reading and Writing Characters and Strings
• char marks;
• cin.get(marks); //The value for marks is read
OR
• marks=cin.get(); //A character is read and assigned to marks

• string name;
• cin>>name;

• string empname;
• cin.getline(empname,20);
• cout<<“\n Welcome ,”<<empname;
Unformatted Input and Output Operations
#include <iostream>
using namespace std;

cin.get() reads a single character.


int main() {
char marks;

cout << "Enter a single character for marks: ";


cin.get(marks); // Reads a single character including whitespace

cout << "You entered: " << marks << endl;

return 0;
}
#include <iostream>
using namespace std;
cin.getline() reads a string
int main() {
char name[20];

cout << "Enter your name: ";


cin.getline(name, 20); // Reads a full line (max 20 characters)

cout << "Hello, " << name << "!" << endl;

return 0;
}
Formatted Input and Output Operations

#include <iostream>
#define PI 3.14159
using namespace std;
int main()
{
cout.precision(3);
cout.width(10);
cout.fill('*');
cout<<PI;
return 0;
}

Output
******3.14
Formatting with flags
• The setf() is a member function of the ios class that is used to set flags for formatting
output.

• syntax - cout.setf(flag, bit-field)

• Here, flag defined in the ios class specifies how the output should be formatted and
bit-field is a constant (defined in ios ) that identifies the group to which the formatting flag
belongs to.

• There are two types of setf()—one that takes both flag and bit-fields and the other that
takes only the flag.
#include <iostream>
using namespace std;

int main() {
cout.setf(ios::left); // Left-align output
cout.width(10);
cout.fill('*');
cout << 123 << endl; // Output: "123*******"

cout.setf(ios::right);
cout.width(10);
cout << 456 << endl; // Output: "*******456"

cout.precision(4);
cout.setf(ios::fixed);
cout << "PI: " << 3.14159265 << endl; // Output: "PI: 3.1416"

return 0;
}
cout.precision(4);
• This sets the precision of floating-point numbers to 4 significant digits by
default.
• However, since we are using ios::fixed, it will affect the number of digits after
the decimal point.
cout.setf(ios::fixed);
• This forces the output to use fixed-point notation, meaning the precision(4)
will apply only to the digits after the decimal point, not to total significant
digits.
cout << "PI: " << 3.14159265 << endl;
• The value 3.14159265 is a floating-point number.
• Since ios::fixed is set, the precision(4) applies only to the decimal places.
• The original number 3.14159265 is rounded to 4 decimal places, resulting in
3.1416.
Formatting Output Using Manipulators
• C++ has a header file iomanip.h that contains certain manipulators to format the output
#include <iostream>
#include <iomanip> // For manipulators
using namespace std;

int main() {
double pi = 3.14159265;

cout << "Using setw(10):" << endl;


cout << setw(10) << 1239 << endl; // Sets field width to 10

cout << "\nUsing setprecision(3) without fixed:" << endl;


cout << setprecision(3) << pi << endl; // 3 significant digits

cout << "\nUsing setprecision(3) with fixed:" << endl;


cout << fixed << setprecision(3) << pi << endl; // 3 decimal places

cout << "\nUsing setfill('#') with setw(10):" << endl;


cout << setfill('#') << setw(10) << 1239 << endl; // Fills empty spaces with #

return 0;
}
Data Types in C++
Variables

A variable is the content of a memory location that stores a certain value. A variable is identified or denoted by a variable
name. The variable name is a sequence of one or more letters, digits or underscore, for example: character_
Rules for defining variable name:
❖ A variable name can have one or more letters or digits or underscore for example character_.
❖ White space, punctuation symbols or other characters are not permitted to denote variable name.
❖ A variable name must begin with a letter.
❖ Variable names cannot be keywords or any reserved words of the C++ programming language.
❖ Data C++ is a case-sensitive language. Variable names written in capital letters differ from variable names with the same
name but written in small letters.

01 Local Variables 03 Instance variables

02 Static Variables 04 Final Variables


Variables

Local Variables Instance Variables Static Variables Constant Variables

Local variable: These are the Instance variable: These are


Static variables: Static Constant is something that
variables which are declared the variables which
variables are also called as doesn't change. In C
within the method of a class. are declared in a class but
class variables. These language and C++ we use
outside a method,
variables have only one copy the keyword const to
Example: constructor or any block.
that is shared by all the make program elements
public class Car { Example:
different objects in a class. constant.
public: public class Car {
Example: Example:
void display(int m){ // private: String color;
public class Car { const int i = 10;
Method // Created an instance
public static int tyres; void f(const int i)
int model=m; variable color
// Created a class variable class Test
// Created a local variable Car(String c)
void init(){ {
model {
tyres=4; const int i;
cout<<model; color=c;
}} };
} }}
CONSTANTS
• Constants are identifiers whose value does not change. While variables can change their value at any
time, constants can never change their value.
• Constants are used to define fixed values such as Pi or the charge on an electron so that their value does
not get changed in the program even by mistake.
• A constant is an explicit data value specified by the programmer.
• The value of the constant is known to the compiler at the compile time.
Declaring Constants
• Rule 1 Constant names are usually written in capital letters to visually distinguish them from other variable
names which are normally written in lower case characters.

• Rule 2 No blank spaces are permitted in between the # symbol and define keyword.

• Rule 3 Blank space must be used between #define and constant name and between constant name and
constant value.

• Rule 4 #define is a preprocessor compiler directive and not a statement. Therefore, it does not end with a
semi-colon.
Special Operators

Scope resolution operator

In C, the global version of a variable cannot be accessed from within the inner block. C++ resolves this
1
problem by using scope resolution operator (::), because this operator allows access to the
global version of a variable. New Operator

The new operator denotes a request for memory allocation on the Heap. If sufficient memory is available, new
2
operator initializes the memory and returns the address of the newly allocated and initialized memory to the
Delete Operator
pointer variable.
3 Since it is programmer’s responsibility to deallocate dynamically allocated memory, programmers are provided
.
delete operator by C++ language
Member Operator

4 C++ permits us to define a class containing various types of data & functions as members. To access a
member using a pointer in the object & a pointer to the member.
#include <iostream>
using namespace std;

int main() {
cout << "Hello, World!" << endl;
return 0;
}

#include <iostream>
using namespace std;

int main() {
int num1, num2, sum;
cout << "Enter two numbers: ";
cin >> num1 >> num2;
sum = num1 + num2;
cout << "Sum = " << sum << endl;
return 0;
}
#include <iostream>
using namespace std;

int add(int a, int b) {


return a + b;
}

int main() {
int x, y;
cout << "Enter two numbers: ";
cin >> x >> y;
cout << "Sum = " << add(x, y) << endl;
return 0;
}
#include <iostream>
using namespace std;

int main() {
int num;
cout << "Enter a number: ";
cin >> num;

if (num % 2 == 0) {
cout << "The number is even." << endl;
} else {
cout << "The number is odd." << endl;
}

return 0;
}
#include <iostream>
using namespace std;

int main() {
int n;
cout << "Enter a number: ";
cin >> n;

for (int i = 1; i <= n; i++) {


cout << i << " ";
}
return 0;
}
#include <iostream>
using namespace std;

int main() {
int num1, num2, choice;
cout << "Enter two numbers: ";
cin >> num1 >> num2;

cout << "Choose an operation: \n";


cout << "1. Add\n2. Subtract\n3. Multiply\n4. Divide\n";
cin >> choice;

switch(choice) {
case 1:
cout << "Result: " << num1 + num2 << endl;
break;
case 2:
cout << "Result: " << num1 - num2 << endl;
break;
case 3:
cout << "Result: " << num1 * num2 << endl;
break;
case 4:
if (num2 != 0) {
cout << "Result: " << num1 / num2 << endl;
} else {
cout << "Cannot divide by zero!" << endl;
}
break;
default:
cout << "Invalid choice!" << endl;
}

return 0;
}
Pointers
• Pointer is variable in C++
• It holds the address of another variable
• Syntax : data_type *pointer_variable;
• Example int *p, sum;

Assignment
• integer type pointer can hold the address of another int variable
• To assign the address of variable to pointer - ampersand symbol (&)
• p=&sum;
• A pointer is a variable that stores the address of another variable.
Pointer Declaration and Initialization
How to use it
• P=&sum; //assign address of another variable
• cout<<&sum; //to print the address of variable
• cout<<*p; //print the value of variable

Example of pointer
Output:
#include<iostream> Address of sum:0x7ffce7507964
using namespace std; Address of sum:0x7ffce7507964
int main() Address of p:0x7ffce7507968
{ Value of Sum=10
int *p, sum=10;
p=&sum;
cout<<"Address of sum:"<<&sum<<endl;
cout<<"Address of sum:"<<p<<endl;
cout<<"Address of p:"<<&p<<endl;
cout<<"Value of Sum="<<*p;
}
Pointers and Arrays
• assigning the address of array to pointer don’t use ampersand sign(&)
• ptr = arr ; // ptr is the pointer variable and arr is the array variable.

int *ptr;
int arr[5];
ptr = arr;
ptr + 1 is equivalent to &arr[1];
ptr + 2 is equivalent to &arr[2];
ptr + 3 is equivalent to &arr[3];
ptr + 4 is equivalent to &arr[4];

ptr = arr; and ptr = &arr[0]; are equivalent.


Pointers and Arrays
• Assigning the address of array to pointer don’t use ampersand sign(&)
#include <iostream>
using namespace std;
int main(){
//Pointer declaration
int *p;
//Array declaration OUTPUT:
int arr[]={1, 2, 3, 4, 5, 6};
//Assignment 1
p = arr; 2
3
for(int i=0; i<6;i++)
4
{ 5
cout<<*p<<endl; 6
//++ moves the pointer to next int position
p++;
}
return 0;
}
This Pointers
• this pointer hold the address of current object
• int num;
• This->num=num;

Number: 10
• Inside the class, num is a private data member (by default, members
of a class are private).
• Example(int num) { // Constructor with an integer parameter
• The constructor is a special function that gets called automatically
when an object of the class is created.
• Using this-> ensures the class variable num gets assigned the correct
value.
Main function:
Example obj(10); // Creating object with value 10
The constructor is called automatically with the value 10.
Inside the constructor, this->num = 10; is executed.
It then prints "Number: 10".
This : A special pointer that holds the address of the current object.
Type conversion and type casting
• Type conversion or typecasting of variables refers to changing a variable of one data type into
another. While type conversion is done implicitly, casting has to be done explicitly by the
programmer.
Implicit Type conversion
#include <iostream>
using namespace std;
int main()
{
int x = 10; // integer x
char y = 'a'; // character y

// y implicitly converted to int. ASCII


// value of 'a' is 97
x = x + y;

// x is implicitly converted to float


float z = x + 1.0;

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


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

return 0;
}
Type Casting
• Type casting an arithmetic expression tells the compiler to represent the value of the expression in
a certain format.

• It is done when the value of a higher data type has to be converted into the value of a lower data
type.

• However, this cast is under the programmer’s control and not under the compiler’s control.

• The general syntax for type casting is

• destination_variable_name=destination_data_type(source_variable_name);

float sal=10000.00;
int income;
Income=int(sal);
Example for Explicit Type Conversion
#include <iostream>
Output:
using namespace std; Sum = 2
int main()
{
double x = 1.2;
// Explicit conversion from double to int
int sum = (int)x + 1;
cout << "Sum = " << sum;
return 0;
}

8/24/2022 52

You might also like