📜  TCS编码实践问题|交换两个数字

📅  最后修改于: 2021-05-31 22:25:59             🧑  作者: Mango

给定两个数字,任务是使用命令行参数交换两个数字。

例子:

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

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

方法:

  • 由于数字是作为命令行参数输入的,因此不需要专用的输入行
  • 从命令行参数中提取输入数字
  • 提取的数字将为String类型。
  • 将这些数字转换为整数类型并将其存储在变量中,例如num1和num2
  • 获取两个给定数字之一的总和。
  • 然后可以使用总和与总和相减来交换数字。

程序:

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.");
    }
}


输出:

  • 在C中:

  • 在Java:

想要从精选的最佳视频中学习并解决问题,请查看有关从基础到高级C++的C++基础课程以及有关语言和STL的C++ STL课程。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”