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;
}
#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;
}
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.
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
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.
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;
}
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
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; /**/
}
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
#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;
}
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]);
}
Related
#include <stdlib.h>
#include <math.h>
#include <stdio.h>
int rev (int N);
int rev(int N){
return ((N <= 9)) ? N : rev(N / 10) + ((N % 10) * (pow(10, (floor(log10(abs(N))))))) ;
}
int main(void){
int r, n;
scanf("%d", &n);
r = rev(n);
printf("%d %d", r, n);
return EXIT_SUCCESS;
}
A simple code just to find out the reverse of a number. Everything is fine. Until I put a number with more than 2 digits. Things behave weirdly, somehow the last digit is always 0 of the reversed number. I have checked out in online compilers where things behave just fine. However the problem arises when I run the code on my own machine. I am on Windows 10 with MINGw. Could you guys suggest me a solution. I previously had problems where the value stored in an int matrix changes to huge values which is practically impossible to store in int due to it's size.
Using the pow and floor function, working with floats will not always round the way you'd expect.
As already commented, work with integers.
Propose doing this digit-by-digit, and sticking with integers. A proposal for your rev() function:
int rev(unsigned int N)
{
unsigned int res = 0;
while(N>0)
{
// pick off lowest digit
unsigned int digit = N%10;
// put into result, moving up all previous digits by doing *10
res = 10*res+digit;
// remove this digit from input value
N/=10;
}
return res;
}
I am a beginner starting in C and am doing some exercises on codewars. The exercise requires me to take a decimal int, convert it into binary and output the number of 1s in the binary number. Below my incomplete code. I store the binary in int b and I want to output it into an array so that I can run a loop to search for the 1s and output the sum.
Thanks in advance!
#include <stddef.h>
#include <stdio.h>
//size_t countBits(unsigned value);
int countBits(int d);
int main() {
int numD = 1234;
int numB = countBits(numD);
printf("The number %d converted to binary is %d \n", numD, numB);
}
int countBits(int d) {
if (d < 2) {
return d;
} else {
int b = countBits(d / 2) * 10 + d % 2; //convert decimal into binary
int c;
int bArray[c];
}
Your function is almost correct:
you should define the argument type as unsigned to avoid problems with negative numbers
you should just return b in the else branch. Trying to use base 10 as an intermediary representation is useless and would fail for numbers larger than 1023.
Here is a corrected version:
int countBits(unsigned d) {
if (d < 2) {
return d;
} else {
return countBits(d / 2) + d % 2;
}
}
There are many more efficient ways to compute the number of bits in a word.
Check Sean Eron Anderson's Bit Twiddling Hacks for classic and advanced solutions.
You can make an array char as one of the replies said, for example:
#include <stdio.h>
#include <string.h>
int main(){
int count=0;
int n,bit;
char binary[50];
printf("Enter a binary: \n");
scanf("%s",binary);
n=strlen(binary);
for(int i=0;i<n;i++){
bit=binary[i]-'0';
if (bit==1){
count=count+1;
}
}
printf("Number of 1's: %d\n",count);
return 0;
}
This should count the number of 1's of a given binary.
Try something like this!
edit: I know that binary[i]-'0' might be confusing, if you don't understand that..take a look at this:
There are definitely 'smarter'/more compact ways to do this, but here is one way that will allow you to count bits of a bit larger numbers
#include <stdio.h>
int count_bits(int x)
{
char c_bin[33];
int count=0;
int mask=1;
for( int i =0; i < 32; i++){
if (x & mask ){
count=i+1;
c_bin[31-i]='1';
}
else{
c_bin[31-i]='0';
}
mask=mask*2;
}
c_bin[32]='\0';
printf("%d has %d bits\n",x,count);
printf("Binary x:%s\n",c_bin);
return count;
}
int main()
{
int c=count_bits(4);
return 0;
}
When we wanna return one particular type of data, we need to declare a global variable first right? and assign this variable to the value thats being returned by the funtion?
Also for int primitive data type, we cannot use malloc to reserve memory block?
Sincerely,
headful of doubts.
#include <math.h>
#include <stdio.h>
int *sum();
int main()
{
int *num;
num = sum();
printf("\nSum of two given values = %d", *num);
return 0;
}
int *sum()
{
int a = 50, b = 80;
int *sum = NULL;
printf("%d %d",a,b);
*sum = a+b;
return sum;
}
I wanna using pointers to save the data thats being returned by the function. is it possible? I know it's possible for linked list structures. But I'm not sure about integers and other primitive data types.
Starting with your second question, you can use malloc to allocate memory of any size for any type of variable. Yes, you can use malloc to allocate ints and other primitive types on the heap.
int i_am_a_stack_variable = 1;
int * i_am_a_pointer_to_heap_memory = malloc(sizeof(int));
For your first question, I think you are mis-understanding how return variables work. Typically, the use of global variables should be avoided. They certainly aren't needed to return values from functions. The return value of a function is copied from the function's stack frame back to the calling stack frame wherever it is assigned. Note that it is COPIED back. Whether it is a primitive type or a pointer (which is really just another type of primitive). Your code could be written just not using pointers at all. Also, note that your code was not using a global variable at all even though you mentioned global variables.
#include <math.h>
#include <stdio.h>
int sum();
int main()
{
int num;
num = sum();
printf("\nSum of two given values = %d", num);
return 0;
}
int sum()
{
int a = 50, b = 80;
int sum = 0;
printf("%d %d",a,b);
sum = a+b;
return sum;
}
Does this make sense?
This should work
#include <math.h>
#include <stdio.h>
int *sum();
int main()
{
int *num;
num = sum();
printf("\nSum of two given values = %d", *num);
free(num);
return 0;
}
int *sum()
{
int a = 50, b = 80;
int *sum = malloc(sizeof(int));
printf("%d %d",a,b);
*sum = a+b;
return sum;
}
You need to allocate memory for the pointer. In your case you need memory for one Integer. When you say int* sum =NULL your pointer has no Adress. You can't access a null pointer.
I'm learning C function construction and I'm trying to make an exponent function with two arguments: base & exponent.
#include <stdio.h>
#include <stdlib.h>
int power(int a,int b){
int c;
int i;
c=1;
for(i=1;i<=b;++i){
c=c*a;
}
return c;
}
int main(){
int nice=power(5,20);
printf("answer =%d , and size is=%d ", nice, sizeof(nice));
return 0;
}
When I execute the program, it gives me the following output:
answer =1977800241 ,and size is=4
EDIT:
But when I execute power(5,2), it gives a perfect result of 25.
It is having integer overflow. You have to use unsigned long long or long long .
#include <stdio.h>
#include <stdlib.h>
typedef long long ll;
ll power(ll a,ll b){
ll c,i;
c=1;
for(i=1;i<=b;++i){
c=c*a;
}
return c;
}
int main(){
ll nice=power(5,20);
printf("answer =%lld , and size is=%lld ", nice, sizeof(nice));
return 0;
}
NOTE:
You will have a good idea about this -> read this SO question.
QUESTION-2: WHat happens for a=5 b=100
Then you have to write your custom function for manipulating the multiplications. Use int arr[100] to hold the digits of the large number and then multiply it accordingly.C/C++ doesn't provide anything like BIgInt of Java, you have to build it.
im a 1st grader when it comes to c and need help with storing 5 random values in an array and outputting them. Heres where am at.
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
struct score_card {int A_ones; int B_twos; int C_threes; int D_fours; int E_fives; int F_sixes; int G_chance;};
int dice_rolls[5];
int randomize(void);
int value;
int main(void) {
struct score_card test;
randomize;
int i;
for(i = 0; i <= 4; i++){
printf("%d\n", dice_rolls[i]);
}
printf("\n");
return 0;
}
int randomize(void){
int i;
srand(time(0));
for(i = 0; i <= 4; i++){
value = rand() % 6 + 1;
dice_rolls[i] = value;
}
}
The output is :
6294304
6294308
6294312
6294316
6294320
the goal was to use modular division to get values from 1 -->6 and store them in the dicerolls array.
I see two immediate problems.
First. you're not terminating your random numbers with a newline. That's why they're all strung together in a big sequence. Change your output line to:
printf("%d\n", &dice_rolls[i]);
Secondly, you're not actually calling randomize. The correct way to call it is with:
randomize();
The statement randomize; is simply an expression giving you the address of the function. It's as useless in this case as the expression 42; which also does nothing. However it's valid C so the compiler doesn't necessarily complain.