Чтобы найти сумму двух чисел без использования оператора

Опубликовано: 21 Января, 2022

Напишите программу для нахождения суммы положительных целых чисел без использования оператора. Разрешено только использование printf (). Никакие другие библиотечные функции использовать нельзя.

Solution 
It’s a trick question. We can use printf() to find sum of two numbers as printf() returns the number of characters printed. The width field in printf() can be used to find the sum of two numbers. We can use ‘*’ which indicates the minimum width of output. For example, in the statement “printf(“%*d”, width, num);”, the specified ‘width’ is substituted in place of *, and ‘num’ is printed within the minimum width specified. If number of digits in ‘num’ is smaller than the specified ‘width’, the output is padded with blank spaces. If number of digits are more, the output is printed as it is (not truncated). In the following program, add() returns sum of x and y. It prints 2 spaces within the width specified using x and y. So total characters printed is equal to sum of x and y. That is why add() returns x+y.

C++

#include <iostream>
using namespace std;
  
int add(int x, int y)
{
    return printf("%*c%*c", x, " ", y, " ");
}
 
// Driver code
int main()
{
    printf("Sum = %d", add(3, 4));
    return 0;
}
 
// This code is contributed by shubhamsingh10

C

#include <stdio.h>
 
int add(int x, int y)
{
    return printf("%*c%*c", x, " ", y, " ");
}
 
// Driver code
int main()
{
    printf("Sum = %d", add(3, 4));
    return 0;
}

Выход:

 Сумма = 7

The output is seven spaces followed by “Sum = 7”. We can avoid the leading spaces by using carriage return. Thanks to krazyCoder and Sandeep for suggesting this. The following program prints output without any leading spaces.

C++

#include <iostream>
using namespace std;
 
int add(int x, int y)
{
    return printf("%*c%*c", x, " ", y, " ");
}
 
// Driver code
int main()
{
    printf("Sum = %d", add(3, 4));
    return 0;
}
 
// This code is contributed by shubhamsingh10

C

#include <stdio.h>
 
int add(int x, int y)
{
    return printf("%*c%*c", x, " ", y, " ");
}
 
// Driver code
int main()
{
    printf("Sum = %d", add(3, 4));
    return 0;
}

Выход:

      Sum = 7

Another Method : 

C++

#include <iostream>
using namespace std;
 
int main()
{
    int a = 10, b = 5;
    if (b > 0) {
        while (b > 0) {
            a++;
            b--;
        }
    }
    if (b < 0) { // when "b" is negative
        while (b < 0) {
            a--;
            b++;
        }
    }
    cout << "Sum = " << a;
    return 0;
}
 
// This code is contributed by SHUBHAMSINGH10
// This code is improved & fixed by Abhijeet Soni.

C

#include <stdio.h>
 
int main()
{
    int a = 10, b = 5;
    if (b > 0) {
        while (b > 0) {
            a++;
            b--;
        }
    }
    if (b < 0) { // when "b" is negative
        while (b < 0) {
            a--;
            b++;
        }
    }
    printf("Sum = %d", a);
    return 0;
}
 
// This code is contributed by Abhijeet Soni

Java

// Java code
class GfG {
 
    public static void main(String[] args)
    {
        int a = 10, b = 5;
        if (b > 0) {
            while (b > 0) {
                a++;
                b--;
            }
        }
        if (b < 0) { // when "b" is negative
            while (b < 0) {
                a--;
                b++;
            }
        }
        System.out.println("Sum is: " + a);
    }
}
 
// This code is contributed by Abhijeet Soni

Python3

# Python 3 Code
 
if __name__ == "__main__":
     
    a = 10
    b = 5
 
    if b > 0:
        while b > 0:
            a = a + 1
            b = b - 1
    if b < 0:
        while b < 0:
            a = a - 1
            b = b + 1
     
    print("Sum is: ", a)
 
# This code is contributed by Akanksha Rai
# This code is improved & fixed by Abhijeet Soni

C#

// C# code
using System;
 
class GFG {
    static public void Main()
    {
        int a = 10, b = 5;
        if (b > 0) {
            while (b > 0) {
                a++;
                b--;
            }
        }
        if (b < 0) { // when "b" is negative
            while (b < 0) {
                a--;
                b++;
            }
        }
        Console.Write("Sum is: " + a);
    }
}
 
// This code is contributed by Tushil
// This code is improved & fixed by Abhijeet Soni.

PHP

<?php
// PHP Code
$a = 10;
$b = 5;
 
if ($b > 0) {
while($b > 0)
{
    $a++;
    $b--;
}
}
 
if ($b < 0) {
while($b < 0)
{
    $a--;
    $b++;
}
}
 
 
echo "Sum is: ", $a;
 
// This code is contributed by Dinesh
// This code is improved & fixed by Abhijeet Soni.
?>

Javascript

<script>
 
// Javascript program for the above approach
 
// Driver Code
 
    let a = 10, b = 5;
    if (b > 0) {
        while (b > 0) {
            a++;
            b--;
        }
    }
    if (b < 0) { // when "b" is negative
        while (b < 0) {
            a--;
            b++;
        }
    }
    document.write("Sum = " + a);
 
</script>

Выход:

 сумма = 15

Пожалуйста, напишите комментарии, если вы обнаружите что-то неправильное, или вы хотите поделиться дополнительной информацией по теме, обсужденной выше

Хотите узнать о лучших видео и практических задачах, ознакомьтесь с Базовым курсом C для базового и продвинутого C.

РЕКОМЕНДУЕМЫЕ СТАТЬИ