7

I was trying to create a program that inputs two number and outputs their sum. For this I must have to use two variables. I was just curious whether this can be done by using only one variable.
Note : user has to input two numbers.

#include<stdio.h>
int main()
{
int a, b;
scanf("%d%d",&a,&b);
printf("%d",(a+b));
return 0;
}
9
  • 2
    &a&b -> &a,&b
    – Yunnosch
    Aug 1, 2018 at 17:10
  • You'll need at least one variable to only read the input, so you'd need at least one more to hond the result.
    – ForceBru
    Aug 1, 2018 at 17:11
  • From where did you get this "problem"? Can you either link to it, or quote the text? Aug 1, 2018 at 17:13
  • 2
    Proving that something is impossible is always hard. But I will pay you a nice dinner if anybody has a solution for this. (You need to come here. ;-) )
    – Yunnosch
    Aug 1, 2018 at 17:14
  • I was just thinking that is it possible so I posted this. Like can overwriting will work? Aug 1, 2018 at 17:14

10 Answers 10

11
#include <stdio.h>
int main ( void )
{
   int a[3];

   scanf("%d", &a[0]);   /* first number */
   sscanf("%d", &a[1] );    /* second number */

   a[2] = a[0] + a[1];

   printf("sum is %d\n", a[0] + a[1] );

   printf("sum stored in a[%d] is %d\n", 2, a[2] );

   return 0;
}
6
  • I was thinking of just defining int a; and then using *(a+1) after all no statement was made that good or correct coding practices must be used
    – ron
    Aug 1, 2018 at 17:37
  • now to confuse some people, replace &a[0] with a, and &a[1] with a+1, and *(a+2) = [0]a + [1]a; just to mess with people some more Aug 1, 2018 at 17:38
  • @ron That is dereferencing the value stored in a as an address is completely different. If we go there, why not use all of available RAM as a buffer and forego variables completely. No, your answer is good as-is. Aug 1, 2018 at 17:41
  • Yes. It works but I was thinking about overwrite can overwrite work? Aug 1, 2018 at 18:07
  • 1
    yes, in C there is a += b which is equivalent to a = a + b and that works fine and is perfectly acceptable. Now if is this some kind of school assignment for learning then okay. But trying to do this to save one variable for no other reason is bad programming... use as many variables as necessary for human readability and let the compiler do the work
    – ron
    Aug 1, 2018 at 20:56
5

Technically one variable, a pointer:

#include<stdio.h>

int main() {
    int *nums = malloc(2 * sizeof(int));
    scanf("%d%d",nums, (nums + sizeof(int)));
    printf("%d",(*nums + *(nums + sizeof(int))));
    return 0;
}

But no there isn't really an elegant way to use one variable for two inputs.

7
  • 1
    But no there isn't really an elegant way to use one variable for two inputs. Can you prove it?
    – Winter
    Aug 1, 2018 at 17:20
  • they are two objects refenced by one pointer. This is not the solution - which actually does not exist Aug 1, 2018 at 17:26
  • @Winter I don't know if it's provable... It hinges on the definition of a variable and the entire underlying syntax of C, but I suppose you could do something where you load the first input into the upper 16 bits of the int and load the second into the lower 16 bits, so maybe I was wrong about there being an elegant way to use one variable for two inputs. But do you want to take a stab at it?
    – agillgilla
    Aug 1, 2018 at 17:29
  • 1
    @P__J__ The question said one variable, not one object/memory location. :)
    – agillgilla
    Aug 1, 2018 at 17:32
  • 3
    Code is broke. Certinaly scanf("%d%d",nums, (nums + sizeof(int))); should be scanf("%d%d",nums, nums + 1); (pointer math) Aug 1, 2018 at 18:24
5

Note that I've considered the question like a challenge or a puzzle. Do not consider this answer good C practice. Obviously the cleanest way to make a sum of 2 values from input is to use 2 variables. I still find the challenge interesting though.

#include <stdio.h>
#include <math.h>

int main()
{
    int a;
    printf("%g", fmin((scanf("%d", &a), a), 1.0/0.0 + rand()) + fmin((scanf("%d", &a), a), 1.0/0.0 + rand()));
    return 0;
}

Works with negative values.

I'm using the comma operator which executes both expressions but only return the second one. So (scanf("%d", &a), a) is like calling scanf("%d", &a) and returns a. I pass this result through a function (any function) as I want to prevent updating the value (to sum it with the new a). I have no idea if your compiler will call the left or right part of the big expression first but it doesn't matter as both are doing the same thing. Whichever executes first will be the first value from input.

fmin(x, 1.0/0.0 + rand()) makes sure nothing is inlined by the compiler. 1.0/0.0 is Infinity and would never be returned in fmin() in our case. Compiler would inline this to x normally but adding + rand() to Infinity (which is still Infinity) seems to prevent it.

You can even do it by declaring "0" variable by using argc:

#include <stdio.h>
#include <math.h>

int main(int a)
{
    printf("%g", fmin((scanf("%d", &a), a), 1.0/0.0 + rand()) + fmin((scanf("%d", &a), a), 1.0/0.0 + rand()));
    return 0;
}

I've used this to test: https://www.onlinegdb.com/online_c_compiler

24
  • Hmmmm... Technically you used three variables, the one in the stack in the main() call and the two that are allocated on the stack for the two same calls. Just because you named the variable int a in the same() function doesn't make it the same variable...
    – agillgilla
    Aug 1, 2018 at 17:31
  • 1
    the comma is pretty good here, I wonder if you can do it without same Aug 1, 2018 at 17:32
  • @agillgilla I'm trying to find a function to replace my "same". Floor doesn't seem to work. I'm not responsible for the variables in the function I call right? Otherwise variables in printf and scanf would count
    – Winter
    Aug 1, 2018 at 17:32
  • 1
    I agree with Winter; he declared a single variable. Aug 1, 2018 at 17:33
  • 1
    nice use of sequence points, although the code looks like it's capable of making people incredibly angry Aug 1, 2018 at 17:40
5

Adding Two numbers with using only one variable in C

Create a helper function with the 1 variable.

#include <stdio.h>

int scan_int(void) {
  int a;
  if (scanf("%d", &a) == 1) {
    return a;
  }
  return 0;
}

int main(void) {
  printf("Sum %d\n", scan_int() + scan_int());
  return 0;
}

Note that scan_int() + scan_int(), code could call either the left or the right scan_int() first (or in parallel). Fortunately + is commutative, so it makes no difference here.

The "trick" here is that there exist in sequence or in parallel, a 1st_call_scan_int::a and 2nd_call_scan_int::a. Still only one variable in code.

2

OK, there's been quite a few interesting answers, but weirdly nobody has thought of the obvious way to store 2 ints in a single variable - structs:

#include<stdio.h>

typedef _in struct {
    a int
    b int
} inp;

int main(void)
{
    inp input;
    scanf("%d%d",&input.a,&input.b);
    printf("%d",input.a+input.b);
    return 0;
}
1
  • I like the struct idea. Standard C library does have a standard paired int structure: div_t from #include <stdlib.h>. Aug 1, 2018 at 19:32
1
int main(void) {
    int *num = malloc(sizeof(int)*2);
    scanf("%d %d", num, num+1);
    printf("%d\n", num[0] + (num[1]));
}
  • int *num = malloc(sizeof(int)*2); //two int space
  • scanf("%d %d", num, num+1); // num (pos 0), num+1 (pos1)
  • printf("%d\n", num[0] + (num[1])); //the sum of the positions
1
  • nah - too late. We already have an array answer that doesn't need to be dynamic :) Aug 1, 2018 at 17:42
1

Only one variable - no tricks. As many numbers can be added as you want :)

#include <stdio.h>

int ScanAndAdd(void)
{
    int a;
    if(scanf("%d", &a) != 1) return 0;
    return a + ScanAndAdd();
}

int main()
{
    printf("%d\n", ScanAndAdd());

    return 0;  /**/
}
4
  • why DV? Any explanation Aug 1, 2018 at 18:06
  • 2
    NMDV, yet this obliges special input passed the 2 numbers like "123 456 x" or "123 456" Signal EOF. With input "123 456\n", code does not return. Aug 1, 2018 at 18:13
  • Only one variable, but multiple instances of the variable! Still, way more fun than an array. Aug 3, 2018 at 18:09
  • of course - but array is another abstraction of multiple instance or temp storage on the stack when calling multiple time the same functions insidde onathe one - no miracles, intermediate results have to be store somewhere Aug 3, 2018 at 19:53
1

One way to do it is.

#include <stdio.h>
int x;

int enter(){
scanf("%d",&x);
return x;
}     

int main()
{
    x=enter()+enter();
    print("sum of two number is %d",x);
    return 0;
}

Another way to do it..

#include <stdio.h>
int main()
{ 
int x;
scanf("%d",&x);
printf("next no. ");
 x= x*(scanf("%d",&x))+x;
printf("%d",x);
return 0;
}

Although the second one is not consistent, in some compiler it works perfectly and in some, it doesn't

7
  • Another way to do it is just create x as global variable, now create funtion to input the value and return the assigned value, then make x= function + function Will solve it Aug 1, 2018 at 18:11
  • 2
    As there is no sequence point between x*(scanf("%d",&x)) and x in the addition, code does not insure the + x happens with the first or second value of x. Thus not certain to properly generate the sum. Aug 1, 2018 at 18:21
  • 2
    Doesn't work for me, it gives me the double of the second input using this online compiler onlinegdb.com/online_c_compiler
    – Winter
    Aug 1, 2018 at 18:35
  • 2
    @AnkushRawat "C compiler executes from right to left" may be so with the compiler and options you use, yet that is not required by the C spec. There are various things that determine what must evaluate first (sequence points) and what may evaluate first. With x*(scanf("%d",&x))+x, a compliant C compilation may access the 3 x's in an order that fails to provide the desired functionality. Aug 2, 2018 at 3:30
  • 2
    @chux is correct: the result of this code is undefined by the C standard. Therefore, it could crash, print the complete works of Shakespeare, or fail to terminate, and be compliant with the standard. Avoid code like this in real work. Avoid it like the plague. Google "C sequence points" and learn something very valuable! Aug 3, 2018 at 18:13
0
#include <stdio.h>
int main()
{
    long long int buffer=0;
    scanf("%d",(int*)&buffer);
    scanf("%d",(int *)&buffer+1);
    printf("\nsum is %d\n",*((int*)&buffer)+*((int*)&buffer+1));
    return 0;
}
1
  • According to the standard, 2 * sizeof (int) could be greater than sizeof (double). Never in practice though. Aug 2, 2018 at 2:49
0

Try this on for size. It uses fixed width C99 types to guarantee that memory alignment works as intended. It even does the 32-bit arithmetic in a uint64_t type to prevent overflow issues. This will work with any of the other fixed-width integer types, signed or unsigned, with trivial modification.

#include <stdio.h>
#include <stdint.h>
#include <inttypes.h>

int main (void)
{
    uint64_t a;

    scanf ("%" SCNu32 "%" SCNu32, (uint32_t*)&a, (uint32_t*)&a + 1);

    printf ("%" PRIu64 "\n", (uint64_t)((uint32_t*)&a)[0] +
        ((uint32_t*)&a)[1]);
}

The above code was modified from my original answer, seen below. I removed the void* cast in (uint32_t*)(void*)&a because it was unnecessary. I also cleaned up the scanf arguments to increase readability, and added a new line to the end of the printf format argument.

#include <stdio.h>
#include <stdint.h>
#include <inttypes.h>

int main (void)
{
    uint64_t a;

    scanf ("%" SCNu32 "%" SCNu32,
        &((uint32_t*)(void*)&a)[0], &((uint32_t*)(void*)&a)[1]);

    printf ("%" PRIu64, (uint64_t)((uint32_t*)(void*)&a)[0] +
        ((uint32_t*)(void*)&a)[1]);
}
4
  • The 4 void* casts are not necessary here. (uint32_t*)(void*)&a can use (uint32_t*)&a. Aug 3, 2018 at 4:04
  • The void* casts are not necessary, but it fixes a warning certain compilers and linters give when casting between different types of pointers. I don't like warnings. I will edit my answer to make my reasoning clear. Aug 3, 2018 at 16:29
  • Hmmm, Do you have an example of your code the causes that warning posted? I would not expect a linter to warn here with uint64_t a; ... (uint32_t*)&a. Aug 3, 2018 at 16:32
  • It seems I was mistaken. I couldn't find a compiler or linter which complained about uint64_t a; ... (uint32_t*)&a. The reason I thought they were necessary to silence a warning is that GCC warns about possible alignment issues when -Wcast-align is enabled and the casted-to type has a larger memory alignment requirement than the casted-from type. For example, uint32_t foo; ... (uint64_t*)&foo causes GCC to complain about alignment (if -Wcast-align is on), but uint64_t foo; ... (uint32_t*)&foo does not. I have added to my answer the code with this and other minor adjustments. Aug 3, 2018 at 23:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.