38.4k views
10 votes
In Cloud9, create a new file called function.cpp. If you aren't sure how to create a new .cpp file in the Cloud9 environment, refer Slide 24 of the Cloud9SetUpSlides (Links to an external site.). In this new file write a function called swapInts that swaps (interchanges) the values of two integers that it is given access to via pointer parameters. Write a main function that asks the user for two integer values, stores them in variables num1 and num2, calls the swap function to swap the values of num1

1 Answer

10 votes

Answer:

#include <iostream>

using namespace std;

void swapInts(int* x, int* y) {

*x = *x + *y;

*y= *x - *y;

*x = *x - *y;

}

int main(){

int num1, num2;

cout << "Before swap:";

cin>>num1; cin>>num2;

swapInts(&num1, &num2);

cout<<"After swap:"<<num1<<" "<<num2;

}

Step-by-step explanation:

The function begins here:

This line defines the function

void swapInts(int* x, int* y) {

The next three line swap the integer values

*x = *x + *y;

*y= *x - *y;

*x = *x - *y;

}

The main begins here:

int main(){

This line declares two integer variables

int num1, num2;

This line prompts the user for inputs before swap

cout << "Before swap:";

This line gets user inputs for both integers

cin>>num1; cin>>num2;

This line calls the function

swapInts(&num1, &num2);

This prints the numbers after swap

cout<<"After swap:"<<num1<<" "<<num2;

}

User Aosmith
by
4.6k points