#include int main() { int n1, n2, result; int *ptr1, *ptr2; std::cout << "Enter the first number: "; std::cin >> n1; std::cout << "Enter the second number: "; std::cin >> n2; ptr1 = &n1; // ptr1 points to n1 ptr2 = &n2; // ptr2 points to n2 result = *ptr1 + *ptr2; // sum of the values pointed by ptr1 and ptr2 std::cout << "The sum of " << *ptr1 << " and " << *ptr2 << " is " << result << std::endl; return 0; }
In this program, we declare four variables: n1, n2, result, ptr1, and ptr2. We also use pointers to store the memory addresses of n1 and n2 in ptr1 and ptr2, respectively.
Then, we ask the user to enter two numbers, which are stored in n1 and n2 using the standard input function std::cin
.
After that, we make ptr1 point to the memory address of n1 using the address-of operator &
, and we make ptr2 point to the memory address of n2 in the same way.
Next, we calculate the sum of the values pointed by ptr1 and ptr2 by using the dereference operator *
to access the values stored in n1 and n2.
Finally, we store the result of the sum in the variable result and print it on the screen using the standard output function std::cout
. Note that we also use the dereference operator to show the values of n1 and n2 in the output.
Overall, this program demonstrates how to use pointers to perform arithmetic operations on variables in C/C++.
Para escrever sua resposta aqui, entre ou crie uma conta
Compartilhar