C++ & Java
C++ & Java
• In C++, the scope resolution operator (::) is used both inside and outside functions.
• A default constructor has (a) Zero arguments.
• Inheritance is in C++ truly used, Single Inheritance, Multipath Inheritance, Multiple
Inheritance.
• The operator >> is primarily known as the extraction operator (or stream extraction
operator) in C++.
• keyword is of Java is Import, Interface,and Implements.
• The double data type in Java is a double-precision 64-bit IEEE 754 floating point. In
memory, it occupies 8 bytes (64 bits).
• C++ provides inline functions to reduce function call overhead mainly for Small
functions.
• Constructors and destructors are special member functions that are automatically
invoked by the compiler
• In C++, the conditional (ternary) operator is one of a few built-in operators that
cannot be overloaded.
• Dynamic binding (also known as late binding or runtime polymorphism) is achieved
in C++ by declaring member functions in the base class using the virtual keyword.
• int []x=new int [6]. In Java, array initialization using the new keyword requires square
brackets [] for the type and dimension.
• In Java, the Scanner class is the most common and user-friendly way to obtain input
from a user.
• In Java, the final keyword can be used with classes, methods, and variables to
enforce restrictions and ensure code stability.
• In Java,this keyword is used to hold the reference of the current object.
Q. Write differences between C and C++.
Basis C C++
Procedural programming Multi-paradigm (Procedural + Object-
Programming Type
language Oriented)
Approach Top-down approach Bottom-up approach
Focuses on functions and
Focus Focuses on objects and data
procedures
More secure (supports encapsulation
Data Security Less secure (no data hiding)
& data hiding)
Object-Oriented Fully supports OOP (class, object,
Not supported
Features inheritance, polymorphism)
Classes and Objects Not available Available
Inheritance Not supported Supported
Polymorphism Not supported Supported
Encapsulation Not available Available
Abstraction Limited Strong support
Function
Not supported Supported
Overloading
Operator
Not supported Supported
Overloading
Exception Handling Not available Available (try, catch)
Standard
Uses printf() and scanf() Uses cin and cout
Input/Output
Memory
Uses malloc() and free() Uses new and delete
Management
Namespace Not available Available (namespace)
File Extension .c .cpp
More powerful (STL – Standard
Standard Library Limited
Template Library)
Reusability Less reusability High reusability due to OOP
Simpler and easier for
Complexity More complex but powerful
beginners
Generally faster (low-level Slightly slower but more efficient in
Speed
control) large programs
System programming, OS, Game development, GUI apps, large-
Use Cases
embedded systems scale applications
1. Class
2. Object
An object is an instance of a class. It is used to access the data and functions of the class.
// Class definition
class Student {
private:
int id;
string name;
public:
// Member function to input data
void getData() {
cout << "Enter ID and Name: ";
cin >> id >> name;
}
int main() {
// Object creation
Student s1;
return 0;
}
Explanation
• class Student → defines a class
• private → data hiding (id, name)
• public → functions accessible outside class
• Student s1; → object creation
• [Link]() and [Link]() → accessing class functions
A friend function in C++ is a function that is not a member of a class but is granted access
to its private and protected members. It is declared inside the class using the friend
keyword, enabling controlled external access to class data.
Core Points
• External to Class
A friend function is defined outside the class scope, unlike member functions.
However, it is declared inside the class using the friend keyword to gain special
access privileges.
• Access to Private and Protected Members
It can directly access private and protected data members of the class. This breaks
strict encapsulation but is useful in specific design situations.
• No Object Association
Friend functions are not called using objects with dot operator like member
functions. They are invoked like normal functions, passing objects as arguments.
• Useful for Multiple Class Interaction
Friend functions are helpful when two or more classes need to share data. They
provide a common function to operate on objects of different classes.
• Declared in Class, Defined Outside
The function must be declared as friend inside the class but is implemented outside
the class definition. This separation maintains clarity in program structure.
Example/Application
#include <iostream>
using namespace std;
class Sample {
private:
int num;
public:
Sample() {
num = 25;
}
void display(Sample s) {
cout << "Value of num = " << [Link];
}
int main() {
Sample obj;
display(obj); // Calling friend function
return 0;
}
In this example, the display() function accesses the private member num of class
Sample, demonstrating how friend functions allow controlled external access.
Conclusion
Friend functions provide a flexible mechanism to access class data from outside, supporting
collaboration between classes while maintaining controlled access.
A virtual function in C++ is a member function of a class that is declared using the keyword
virtual and is overridden in a derived class. It supports runtime polymorphism, allowing
the program to decide which function to call at runtime based on the object type.
Core Points
• Runtime Polymorphism
Virtual functions enable dynamic (late) binding, meaning the function call is
resolved at runtime. This allows different classes to respond differently to the same
function call.
• Use of Base Class Pointer
A virtual function is typically accessed using a base class pointer pointing to a
derived class object. This ensures the correct function of the derived class is executed.
• Function Overriding
Derived classes can override the virtual function of the base class with their own
implementation. This allows customization of behavior in child classes.
• Declared with virtual Keyword
The function is declared in the base class using the virtual keyword. Once declared
virtual, it remains virtual in all derived classes.
• Supports Flexibility and Extensibility
Virtual functions make programs more flexible and extensible by allowing new
classes to be added without modifying existing code.
Example
#include <iostream>
using namespace std;
class Base {
public:
virtual void show() {
cout << "This is Base class function" << endl;
}
};
int main() {
Base* b;
Derived d;
b = &d;
b->show(); // Calls Derived's show()
return 0;
}
Core Features
• Encapsulation
Encapsulation is the process of binding data and methods together into a single unit
called a class. It also provides data hiding by restricting direct access to internal data
using access specifiers.
• Abstraction
Abstraction means hiding implementation details and showing only essential
features to the user. It helps reduce complexity and improves code clarity.
• Inheritance
Inheritance allows one class to acquire properties and methods of another class. It
promotes code reusability and establishes a hierarchical relationship between classes.
• Polymorphism
Polymorphism means one name, many forms. It allows methods to perform different
tasks based on the context (e.g., method overloading and overriding).
• Dynamic Binding
Dynamic binding refers to linking a function call to its definition at runtime. It is
achieved using virtual functions and supports runtime polymorphism.
• Message Passing
Objects communicate with each other by sending messages (method calls). This
enhances interaction and modularity in programs.
Conclusion
OOP features make programs more modular, reusable, and secure, forming the foundation of
modern programming languages like C++ and Java.
Q. Write a program in C++ using a member function passing object of
class to display smallest between two number.
Here is a clear C++ program using a member function and passing objects to find the
smallest of two numbers
C++ Program
#include <iostream>
using namespace std;
class Number {
private:
int num;
public:
// Function to input number
void getData() {
cin >> num;
}
int main() {
Number obj1, obj2, result;
return 0;
}
Short Note
This program demonstrates object passing to member functions, where objects are used as
parameters to perform operations.
Here is a clear Java program using class and object to check whether a number is
Palindrome or not
Java Program
import [Link];
class Palindrome {
int num, reverse = 0, remainder;
while (temp != 0) {
remainder = temp % 10;
reverse = reverse * 10 + remainder;
temp = temp / 10;
}
if (num == reverse)
[Link]("Number is Palindrome");
else
[Link]("Number is Not Palindrome");
}
}
[Link]();
}
}
Input: 121
Output: Number is Palindrome
Input: 123
Output: Number is Not Palindrome
Short Definition
A Palindrome number is a number that remains the same when reversed (e.g., 121, 12121).
Features of Java
1. Simple
Java is easy to learn and use because it has a clean and simple syntax.
2. Object-Oriented
Java follows OOP concepts like class, object, inheritance, polymorphism, etc.
3. Platform Independent
Java follows “Write Once, Run Anywhere” — programs run on any system with
JVM.
4. Secure
Java provides security through features like bytecode verification, no pointers, and
sandboxing.
5. Robust
Java is strong and reliable due to exception handling and memory management.
6. Multithreaded
Java supports multiple threads, allowing programs to perform many tasks
simultaneously.
7. Portable
Java programs can be easily moved from one system to another without modification.
8. High Performance
Java uses Just-In-Time (JIT) compiler to improve execution speed.
9. Distributed
Java supports distributed computing with tools like RMI (Remote Method
Invocation).
10. Dynamic
Java can adapt to changing environments and supports dynamic memory allocation.
Short Trick to Remember
SOPSRMPHDD
(Simple, Object-Oriented, Platform Independent, Secure, Robust, Multithreaded, Portable,
High Performance, Distributed, Dynamic)
Constructor in Java
1. Default Constructor
Example:
class Student {
int id;
String name;
// Default constructor
Student() {
id = 0;
name = "Unknown";
}
void display() {
[Link](id + " " + name);
}
}
class Main {
public static void main(String[] args) {
Student s1 = new Student();
[Link]();
}
}
2. Parameterized Constructor
Example:
class Student {
int id;
String name;
// Parameterized constructor
Student(int i, String n) {
id = i;
name = n;
}
void display() {
[Link](id + " " + name);
}
}
class Main {
public static void main(String[] args) {
Student s1 = new Student(101, "Arvind");
[Link]();
}
}
A copy constructor creates a new object by copying values from another object.
Example:
class Student {
int id;
String name;
// Constructor
Student(int i, String n) {
id = i;
name = n;
}
// Copy constructor
Student(Student s) {
id = [Link];
name = [Link];
}
void display() {
[Link](id + " " + name);
}
}
class Main {
public static void main(String[] args) {
Student s1 = new Student(101, "Arvind");
Student s2 = new Student(s1);
[Link]();
}
}
Program
#include <iostream>
using namespace std;
class Arithmetic {
private:
int a, b;
public:
// Constructor
Arithmetic(int x, int y) {
a = x;
b = y;
int main() {
int num1, num2;
return 0;
}
Explanation
• The constructor Arithmetic(int x, int y) is called when the object is created.
• It initializes the values and performs all arithmetic operations.
• Results are displayed immediately when the object is created.
Conclusion
Constructors provide an efficient way to initialize data and perform operations automatically,
improving code simplicity and execution flow.
A pure virtual function in C++ is a virtual function that is declared in a base class but does
not have any implementation. It is assigned = 0 and makes the class an abstract class,
meaning objects of that class cannot be created directly.
Core Points
• Declared with = 0
A pure virtual function is declared by assigning = 0 in its declaration. This indicates
that the function has no body in the base class.
• Creates Abstract Class
Any class containing at least one pure virtual function becomes an abstract class.
Such classes cannot be instantiated and are used only as base classes.
• Must be Overridden
Derived classes are required to implement the pure virtual function. If not
implemented, the derived class also becomes abstract.
• Supports Runtime Polymorphism
Pure virtual functions enable runtime polymorphism using base class pointers. The
function call is resolved at runtime based on the object type.
• Used for Abstraction
It enforces a common interface for all derived classes while hiding implementation
details. This ensures consistency in program design.
Example
#include <iostream>
using namespace std;
class Shape {
public:
virtual void draw() = 0; // Pure virtual function
};
int main() {
Shape *s;
Circle c;
s = &c;
s->draw(); // Calls Circle's draw()
return 0;
}
Conclusion
Pure virtual functions are essential in C++ for achieving abstraction and enforcing
implementation in derived classes, making programs more structured and flexible.
A Template Class in C++ allows writing generic and reusable code that can work with
different data types such as int, float, and char. It helps in reducing code duplication by
enabling a single class or function to operate on multiple data types.
void showGreater() {
if (a > b)
cout << "Greatest value is: " << a << endl;
else
cout << "Greatest value is: " << b << endl;
}
};
int main() {
Compare<int> obj1;
[Link](10, 20);
[Link]();
Compare<float> obj2;
[Link](5.5, 2.3);
[Link]();
Compare<char> obj3;
[Link]('A', 'Z');
[Link]();
return 0;
}
Explanation
• template <class T> → Defines a generic data type
• Same class works for int, float, and char
• Objects are created for each data type separately
Output
Greatest value is: 20
Greatest value is: 5.5
Greatest value is: Z
Conclusion
Template classes make C++ programs more flexible and reusable by allowing a single
implementation to work with multiple data types efficiently.
Explanation
• The base class contains common properties and methods.
• The derived class reuses these features and can also add new ones.
• It is implemented using the : (colon) symbol in C++.
Example (C++)
#include <iostream>
using namespace std;
class Animal {
public:
void eat() {
cout << "Eating..." << endl;
}
};
int main() {
Dog d;
[Link](); // Inherited function
[Link]();
return 0;
}
Advantages of Inheritance
• Code Reusability
Existing code can be reused, reducing duplication.
• Improved Maintainability
Changes in base class automatically reflect in derived classes.
• Extensibility
New features can be added easily without modifying existing code.
• Hierarchical Classification
Helps in organizing classes in a structured manner.
Types of Inheritance in Java
• Single Inheritance
One class inherits from one base class.
• Multilevel Inheritance
A class inherits from another derived class (chain structure).
• Hierarchical Inheritance
Multiple classes inherit from a single base class.
• Multiple Inheritance (via Interfaces)
Java does not support multiple inheritance with classes, but it is achieved using
interfaces.
• Hybrid Inheritance
Combination of two or more types of inheritance (achieved using interfaces in Java).
Conclusion
Inheritance is a core concept in both C++ and Java that enhances code reuse, modularity, and
scalability in software development.
Loops in Java
Introduction
A loop in Java is a control structure used to execute a block of code repeatedly as long as a
specified condition is true. Loops help reduce code repetition and make programs more
efficient.
2. while Loop
3. do-while Loop
• Executes the loop body at least once, even if the condition is false.
• Condition is checked after execution.
int i = 1;
do {
[Link](i);
i++;
} while(i <= 5);
Conclusion
Loops in Java are essential for performing repetitive tasks efficiently, and choosing the
correct type of loop improves code readability and performance.
Before we jump in—quick check: are you preparing this for an exam (like 5-mark answer), or
do you want a deeper practical understanding too?
An array is a collection of elements of the same data type, stored in continuous memory
locations and accessed using an index.
Question for you: if data is stored in a single row, what type of array is it?
Yes — 1D array.
[Link](arr[0]); // 10
That’s a 2D array.
int arr[][] = {
{1, 2},
{3, 4}
};
[Link](arr[1][0]); // 3
3. Multidimensional Array
Q. What is Applet? Write a program in Applet to Add two number and display values
in Applet on Button Click.
Applet in Java
Introduction
An Applet is a small Java program that runs inside a web browser or applet viewer. It is
used to create interactive applications and works within a restricted environment for security.
/*
<applet code="[Link]" width="300" height="200"></applet>
*/
[Link](this);
}
[Link]([Link](sum));
}
}
Explanation
• Applet class is extended to create the program
• init() → initializes controls (TextField, Button, Label)
• ActionListener → handles button click
• On clicking the button → numbers are added and result displayed
Conclusion
Applets provide a way to create interactive GUI-based Java programs, though they are now
outdated and replaced by modern technologies like web applications.
A reference variable in C++ is an alias (another name) for an existing variable. Once a
reference is created, it refers to the same memory location as the original variable, and any
changes made through the reference affect the original variable.
Example
#include <iostream>
using namespace std;
int main() {
int x = 10;
int &ref = x; // reference variable
return 0;
}
Output:
x = 20
ref = 20
Conclusion
Reference variables in C++ provide a simple and efficient way to work with existing
variables, improving code readability and enabling powerful features like pass-by-reference.
Destructor in C++
Introduction
Features of Destructor
• Same Name as Class with Tilde (~)
A destructor has the same name as the class, preceded by a tilde (~). This naming
convention distinguishes it from constructors and other member functions.
• No Return Type and No Arguments
A destructor does not return any value and does not take parameters. It is
automatically invoked by the compiler, so no explicit call is required.
• Automatically Called
The destructor is automatically executed when an object goes out of scope or when
the program ends. This ensures proper cleanup of resources.
• Only One Destructor per Class
A class can have only one destructor, and it cannot be overloaded. This simplifies
object destruction management.
• Used for Memory Deallocation
It is commonly used to free dynamically allocated memory and perform cleanup
operations. This helps prevent memory leaks in programs.
Example
#include <iostream>
using namespace std;
class Demo {
public:
Demo() {
cout << "Constructor called" << endl;
}
~Demo() {
cout << "Destructor called" << endl;
}
};
int main() {
Demo obj; // Object created
return 0; // Destructor called automatically
}
Output:
Constructor called
Destructor called
Conclusion
Destructors play a crucial role in C++ by ensuring proper cleanup of resources, making
programs more efficient and memory-safe.
Method Overloading and Method Overriding are important concepts in Java that support
polymorphism. Overloading allows multiple methods with the same name but different
parameters, while overriding allows a subclass to provide a specific implementation of a
method already defined in its superclass.
Comparison Table
Basis of
Overloading Overriding
Difference
Same method name and
Same method name with different
Definition parameters in parent and child
parameters in the same class
class
Achieves compile-time
Purpose Achieves runtime polymorphism
polymorphism
Must be different (type, number, or
Parameters Must be same as parent method
order)
Inheritance Not required (can occur in same Required (needs parent-child
Requirement class) relationship)
Can be different (but usually same
Return Type Must be same or covariant
for clarity)
Method Binding Early binding (compile-time) Late binding (runtime)
Example
Overloading Example
class Demo {
void add(int a, int b) {
[Link](a + b);
}
Overriding Example
class Animal {
void sound() {
[Link]("Animal makes sound");
}
}
Conclusion
Overloading improves flexibility within a class, while overriding enables dynamic behavior
through inheritance, making both essential for implementing polymorphism in Java.
Q. Define the features of AI.
Artificial Intelligence (AI) refers to the ability of machines to simulate human intelligence
such as learning, reasoning, and problem-solving. It enables computers to perform tasks that
normally require human intelligence.
Features of AI
• Learning Ability
AI systems can learn from data and past experiences using techniques like machine
learning. This allows them to improve performance over time without explicit
programming.
• Reasoning and Decision Making
AI can analyze information and make logical decisions based on rules or patterns. It
helps in solving complex problems efficiently.
• Problem-Solving Capability
AI can break down complex problems into smaller parts and find optimal solutions.
It is widely used in areas like games, robotics, and optimization tasks.
• Automation
AI enables automation of repetitive and routine tasks. This increases efficiency and
reduces human effort in various industries.
• Natural Language Processing (NLP)
AI can understand and process human language (text or speech). This is used in
chatbots, voice assistants, and translation systems.
• Perception
AI systems can interpret data from the environment using sensors, images, or audio.
For example, image recognition and speech recognition.
• Adaptability
AI systems can adapt to new situations and changes in the environment. This makes
them flexible and capable of handling dynamic conditions.
Conclusion
AI features make machines intelligent and capable of performing complex tasks, playing a
crucial role in modern technology and automation.
Characteristics of ATM
• Fixed Cell Size
ATM uses a fixed cell size of 53 bytes (48 bytes data + 5 bytes header). This ensures
fast and predictable data transmission with minimal delay.
• High-Speed Transmission
ATM supports very high data transfer rates, making it suitable for broadband
networks. It is widely used in backbone networks and telecommunications.
• Connection-Oriented
ATM establishes a virtual connection before data transfer begins. This ensures
reliable and ordered delivery of data.
• Quality of Service (QoS)
ATM provides different levels of Quality of Service, allowing priority to be given to
critical data like voice and video. This helps in reducing latency and maintaining
performance.
• Supports Multiple Services
ATM can carry voice, video, and data simultaneously over the same network. This
makes it a versatile communication technology.
• Low Latency and Delay
Due to fixed cell size and efficient switching, ATM offers low transmission delay,
which is ideal for real-time applications.
• Scalability
ATM networks can be easily expanded to handle more users and higher data loads.
This makes them suitable for large-scale systems.
Conclusion
ATM is a powerful networking technology known for its speed, reliability, and ability to
handle multiple types of data efficiently, making it important in advanced communication
systems.
Primitive data types in Java are the basic built-in data types used to store simple values.
They are not objects and directly hold data in memory, making them fast and efficient.
Types of Primitive Data Types
• Integer Types (byte, short, int, long)
These are used to store whole numbers (without decimals). They differ in size and
range, allowing efficient memory usage depending on the requirement.
• Floating-Point Types (float, double)
These are used to store decimal or real numbers. float is single precision, while
double provides higher precision and is more commonly used.
• Character Type (char)
The char data type is used to store a single character such as letters, digits, or
symbols. It uses Unicode encoding and occupies 2 bytes of memory.
• Boolean Type (boolean)
The boolean type stores only two values: true or false. It is mainly used for
decision-making and conditional statements.
Example
int a = 10;
float b = 5.5f;
char c = 'A';
boolean d = true;
Conclusion
Primitive data types are fundamental in Java programming, providing efficient storage and
forming the building blocks for more complex data structures.
Thread in Java
Introduction
A thread in Java is the smallest unit of execution within a program. It allows multiple tasks
to run concurrently (multithreading), improving performance and efficient CPU utilization.
• A class extends the Thread class and overrides the run() method.
• The thread starts execution when start() is called.
class MyThread extends Thread {
public void run() {
[Link]("Thread is running");
}
}
• A class implements the Runnable interface and defines the run() method.
• A Thread object is created and passed the Runnable object.
Key Points
• run() → contains the code executed by the thread
• start() → starts a new thread
• Multiple threads run simultaneously
Conclusion
Threads in Java enable concurrent execution of tasks, and they can be created either by
extending the Thread class or implementing the Runnable interface, making programs more
efficient and responsive.
Core Points
• new Keyword (Memory Allocation)
The new keyword is used to allocate memory dynamically on the heap. It returns the
address of the allocated memory, which is stored in a pointer variable.
• delete Keyword (Memory Deallocation)
The delete keyword is used to free the memory that was previously allocated using
new. This helps prevent memory leaks and ensures efficient memory usage.
• Use with Pointers
Both new and delete work with pointer variables. The pointer stores the address of
dynamically allocated memory and is used to access it.
• Array Allocation and Deallocation
Memory for arrays can be allocated using new[] and released using delete[]. This is
important to correctly manage memory for multiple elements.
• Improves Flexibility
Dynamic memory allocation allows programs to allocate memory as needed at
runtime, making them more flexible and efficient.
Example
#include <iostream>
using namespace std;
int main() {
int *ptr;
return 0;
}
Array Example
int *arr = new int[5]; // allocate array
// use array
Conclusion
The new and delete keywords are essential in C++ for managing memory dynamically,
enabling efficient use of resources and preventing memory-related issues.
In C++, input and output operations are handled through the I/O stream library, which is
organized in a hierarchical structure of classes. The base class ios provides the foundation
for all input/output stream classes and defines common properties and functions.
Explanation of Classes
• ios (Base Class)
The ios class is the base class for all stream classes. It contains basic features like
formatting, error handling, and stream state.
• istream (Input Stream)
Derived from ios, it is used for input operations like cin. It provides functions such
as >> (extraction operator).
• ostream (Output Stream)
Also derived from ios, it is used for output operations like cout. It supports the <<
(insertion operator).
• iostream (Input + Output)
Derived from both istream and ostream, it supports both input and output
operations.
• ifstream (Input File Stream)
Derived from istream, it is used for reading data from files.
• ofstream (Output File Stream)
Derived from ostream, it is used for writing data to files.
• fstream (File Stream)
Derived from iostream, it supports both reading and writing to files.
Conclusion
The ios class hierarchy provides a structured and flexible way to handle input and output
operations in C++, supporting console and file handling efficiently.
In C++, files are handled using the fstream library, which provides classes like ifstream,
ofstream, and fstream. A file can be opened using two main methods, allowing the
program to read from or write to external files.
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ofstream file("[Link]"); // File opened using constructor
file << "Hello World";
[Link]();
return 0;
}
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ofstream file;
[Link]("[Link]"); // File opened using open() function
file << "Hello World";
[Link]();
return 0;
}
Conclusion
Both methods are useful for file handling in C++, where the constructor method is simpler,
while the open() function provides greater flexibility and control.
Q. Write a program in java to enter a number by user and print the reverse ofthat
number.
Reversing a number means changing the order of its digits. This can be done by extracting
digits one by one and rebuilding the number in reverse order.
Program
import [Link];
while (num != 0) {
int digit = num % 10; // extract last digit
rev = rev * 10 + digit; // build reverse
num = num / 10; // remove last digit
}
Explanation
• % 10 → extracts last digit
• / 10 → removes last digit
• rev = rev * 10 + digit → forms reversed number
Conclusion
This program efficiently reverses a number using a loop, demonstrating basic arithmetic
operations and control structures in Java.
Q. Write a program in C++ to enter a number and check whether the number is
armstrong or not. (Using class and object)
An Armstrong number is a number in which the sum of the cubes of its digits is equal to
the number itself (for 3-digit numbers). Example: 153 = 1³ + 5³ + 3³.
Program
#include <iostream>
using namespace std;
class Armstrong {
private:
int num, sum, temp;
public:
void input() {
cout << "Enter a number: ";
cin >> num;
temp = num;
sum = 0;
}
void check() {
while (temp != 0) {
int digit = temp % 10;
sum += digit * digit * digit;
temp = temp / 10;
}
if (sum == num)
cout << num << " is an Armstrong number";
else
cout << num << " is not an Armstrong number";
}
};
int main() {
Armstrong obj;
[Link]();
[Link]();
return 0;
}
Explanation
• A class Armstrong is created with data members and functions.
• input() → takes number from user
• check() → calculates sum of cubes of digits
• Compares result with original number
Conclusion
This program demonstrates how object-oriented concepts (class & object) can be used to
solve problems like checking Armstrong numbers in C++.