Question:

Write the statement that swaps the first element and the second element using the third variable. Fill in the blanks.

Show Hint

While swapping two variables, always use a temporary variable if you want to avoid losing one of the values during assignment.
Hide Solution
collegedunia
Verified By Collegedunia

Solution and Explanation

Step 1: Understand the concept of swapping.
To swap two values, we use a third temporary variable to store one value so that it is not lost during assignment.
Step 2: Store the first element in the third variable.
First, store the value of the first element in the temporary variable:
\[ \texttt{temp = first;} \] Step 3: Copy the second element into the first.
Now assign the value of the second element to the first element:
\[ \texttt{first = second;} \] Step 4: Copy the temporary value into the second.
Finally, assign the stored value from the temporary variable to the second element:
\[ \texttt{second = temp;} \] Step 5: Write the final statements.
Therefore, the required swapping statements are:
\texttt{temp = first;}
\texttt{first = second;}
\texttt{second = temp;}
Was this answer helpful?
0
0

Questions Asked in ICSE Class X board exam

View More Questions