Buscar

Declare two integer variables n1 and n2. After that, calculate the sum of the values of the variables only by using pointers, store the result of t...

Declare two integer variables n1 and n2. After that, calculate the sum of the values of the variables only by using pointers, store the result of the sum in the variable result and show it on the screen.


Essa pergunta também está no material:

Programa em C/C++ para somar valores usando ponteiros
1 pág.

Estrutura de Dados I ExatasExatas

💡 1 Resposta

User badge image

Gustavo Pereira

#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++.







0
Dislike0

Faça como milhares de estudantes: teste grátis o Passei Direto

Esse e outros conteúdos desbloqueados

16 milhões de materiais de várias disciplinas

Impressão de materiais

Agora você pode testar o

Passei Direto grátis

Você também pode ser Premium ajudando estudantes

✏️ Responder

SetasNegritoItálicoSublinhadoTachadoCitaçãoCódigoLista numeradaLista com marcadoresSubscritoSobrescritoDiminuir recuoAumentar recuoCor da fonteCor de fundoAlinhamentoLimparInserir linkImagemFórmula

Para escrever sua resposta aqui, entre ou crie uma conta

User badge image

Outros materiais