TutorialStudyMite

Program to Add two numbers using pointers in C++

JJuhi Kamdar2 min read
Beginner friendly

Track completion, mastery, and revision.

C++ Program to Add Two Numbers Using Pointers

Understanding Pointers in C++

Pointers are fundamental elements in C++ programming that store memory addresses rather than direct values. This program demonstrates how to use pointers to access and manipulate data by adding two numbers through their memory addresses.

Program Logic

The program follows these logical steps:

1. Declare two integer variables to store user input

2. Create two integer pointers to hold memory addresses

3. Assign the addresses of the integer variables to the pointers

4. Dereference the pointers to access the actual values

5. Perform addition using the dereferenced values

6. Display the result

Complete C++ Implementation

#include <iostream>
#include <memory>  // For smart pointers

int main() {
    auto num1 = std::make_unique<int>();
    auto num2 = std::make_unique<int>();
    
    std::cout << "Enter first number: ";
    std::cin >> *num1;
    std::cout << "Enter second number: ";
    std::cin >> *num2;
    
    int sum = *num1 + *num2;
    std::cout << "Sum: " << sum << std::endl;
    
    return 0;
}

Sample Output


Enter first number: 3

Enter second number: 4

First number: 3 (stored at address: 0x7ffd5a2b5a68)

Second number: 4 (stored at address: 0x7ffd5a2b5a6c)

Sum calculated using pointers: 7

Key Concepts Explained

Pointer Operations

  • Declaration: int *ptr; declares an integer pointer

  • Address Assignment: ptr = &num; assigns the address of num to ptr

  • Dereferencing: *ptr accesses the value stored at the pointer's address

Memory Management

  • Pointers provide direct access to memory locations

  • The & operator returns the address of a variable

  • The * operator accesses the value at a stored address

Benefits of Using Pointers

1. Memory Efficiency: Direct memory access reduces overhead

2. Flexibility: Enables dynamic memory allocation

3. Functionality: Essential for advanced operations like dynamic arrays and data structures

4. Performance: Can optimize certain operations by reducing copying

Finished reading?

Was this helpful?

Your feedback shapes better tutorials for everyone.