Ask Question
3 March, 20:00

There are two String variables, s1 and s2, that have already been declared and initialized. Write some code that exchanges their values. Declare any other variables as necessary.

+3
Answers (1)
  1. 3 March, 22:23
    0
    The following are the code

    string s1="san";

    string s2="ran";

    string temp; / / other variable

    temp=s1; / / statement 1

    s1=s2; / / statement 2

    s2=temp; //statement 3

    Explanation:

    In this code we declared two string s1, s2 and initialized them after that we declared an extra variable temp.

    The statement 1 temp=s1 means that temp will store the value of s1 i. e "san". so temp="san";

    The second statement 2 s1=s2 means that s1 will store the value of s2

    i. e s1="ran";

    The third statement 3 s2=temp means that s2 will store the value of temp.

    i. e s2="san"

    we see that s1 and s2 will exchange their value

    Following are the code in c++

    #include / / header file

    #include

    using namespace std;

    int main () / / main function

    {

    string s1="san";

    string s2="ran";

    string temp;

    cout<<"before exchange:"<
    temp=s1;

    s1=s2;

    s2=temp;

    cout<<"after exchange:"<
    return 0;

    }

    Output:

    before exchange:sanran

    after exchange:ransan
Know the Answer?
Not Sure About the Answer?
Find an answer to your question ✅ “There are two String variables, s1 and s2, that have already been declared and initialized. Write some code that exchanges their values. ...” in 📘 Computers and Technology if you're in doubt about the correctness of the answers or there's no answer, then try to use the smart search and find answers to the similar questions.
Search for Other Answers