TCS Coding Practice Question | Swap two Numbers

Given two numbers, the task is to swap the two numbers using Command Line Arguments. Examples:

```Input: n1 = 10, n2 = 20
Output: 20 10

Input: n1 = 100, n2 = 101
Output: 101 100```

Approach:

• Since the numbers are entered as Command line Arguments, there is no need for a dedicated input line
• Extract the input numbers from the command line argument
• This extracted numbers will be in string type.
• Convert these numbers into integer type and store it in variables, say num1 and num2
• Get the sum in one of the two given numbers.
• The numbers can then be swapped using the sum and subtraction from the sum.

Program:

C

 `// C program to swap the two numbers ``// using command line arguments `` ` `#include ``#include /* atoi */ `` ` `// Function to swap the two numbers ``void` `swap(``int` `x, ``int` `y) ``{ ``    ``// Code to swap â€˜xâ€™ and â€˜yâ€™ `` ` `    ``// x now becomes x+y ``    ``x = x + y; `` ` `    ``// y becomes x ``    ``y = x - y; `` ` `    ``// x becomes y ``    ``x = x - y; `` ` `    ``printf``(``"%d %d\n"``, x, y); ``} `` ` `// Driver code ``int` `main(``int` `argc, ``char``* argv[]) ``{ `` ` `    ``int` `num1, num2; `` ` `    ``// Check if the length of args array is 1 ``    ``if` `(argc == 1) ``        ``printf``(``"No command line arguments found.\n"``); `` ` `    ``else` `{ `` ` `        ``// Get the command line argument and ``        ``// Convert it from string type to integer type ``        ``// using function "atoi( argument)" ``        ``num1 = ``atoi``(argv[1]); ``        ``num2 = ``atoi``(argv[2]); `` ` `        ``// Swap the numbers and print it ``        ``swap(num1, num2); ``    ``} ``    ``return` `0; ``} `

Java

 `// Java program to swap the two numbers ``// using command line arguments `` ` `class` `GFG { `` ` `    ``// Function to swap the two numbers ``    ``static` `void` `swap(``int` `x, ``int` `y) ``    ``{ ``        ``// Code to swap â€˜xâ€™ and â€˜yâ€™ `` ` `        ``// x now becomes x+y ``        ``x = x + y; `` ` `        ``// y becomes x ``        ``y = x - y; `` ` `        ``// x becomes y ``        ``x = x - y; `` ` `        ``System.out.println(x + ``" "` `+ y); ``    ``} `` ` `    ``// Driver code ``    ``public` `static` `void` `main(String[] args) ``    ``{ `` ` `        ``// Check if length of args array is ``        ``// greater than 0 ``        ``if` `(args.length > ``0``) { `` ` `            ``// Get the command line argument and ``            ``// Convert it from string type to integer type ``            ``int` `num1 = Integer.parseInt(args[``0``]); ``            ``int` `num2 = Integer.parseInt(args[``1``]); `` ` `            ``// Swap the numbers ``            ``swap(num1, num2); ``        ``} ``        ``else``            ``System.out.println(``"No command line "``                               ``+ ``"arguments found."``); ``    ``} ``} `

Output:

• In C:
• In Java:

Time Complexity: O(1)
Auxiliary Space: O(1)

Previous
Next