How to put different digits in different sides - c

How to write a program in c that gets single integer and another integer that is more than 3 digits at least and after that the single integer goes to the left side of the three digits number and the right side as well.
Note: I need help for the left side right side number
For example:
I mean if I got 5 and 100
it should be 51005

something like this:
int a = 5, b = 100;
int length = 1;
int tmp = b;
while (tmp /= 10)
length++;
int left = 10;
for (int i = 0; i < length; i++)
left *= 10;
int result = (left * a) + (10 * b) + a;
std::cout << result;
Also, you can play here.

there are so many methods :
one is stated in the reply above by #MikeCAT .
int a = 5, b = 100; printf("%d%d%d\n", a, b, a);
you can also try to transfer them to strings , contact them and put it back as an int if you're asked to have a variable named as c using itoa and atoi with a very static manner
char string[100],string1[100],string2[210];
int a,b,c;
scanf("%d %d",&a,&b);
itoa(a,string,10);
itoa(b,string1,10);
string2 = string+string1+string;
c=atoi(string2);
printf("Your number %d",c);
you can also try to think about it mathematically
int a,b;
scanf("%d %d",&a,&b);
int x=b,i=0,c=a;
while (x!=0) { // to get the length of b
i++;
x= x/10; }
int j ;
for (j=1;j<i;j++)
c=c*10;
c=c+b+a;
printf("your number is %d",c);
etc etc

Related

How to return 3 numbers in a function without adding them?

Doing the 7. Reverse Integer leetcode, (intput =321 expected output = 123)
I don't know how to return my numbers from the function. I'm printing them as of right now to see if I'm solving the problem, and my stdout is fine but my output is 3.
Your input:
123
stdout:
312
Output:
3
Expected:
321
int reverse(int x)
{
int a,b,c;
c = x % 10;
b = (x / 10) / 10;
a = (x / 10) % 10 ;
printf("%d%d%d",c,b,a);
return;
}
It might be easier to generalize reverse to handle numbers of any width, not just 3 digits.
Here's some code to do that (you might have to adjust the format for the printf):
#include <stdio.h>
int
reverse(int x)
{
int y = 0;
while (x != 0) {
y *= 10;
y += (x % 10);
x /= 10;
}
return y;
}
int
main(void)
{
const char *fmt = " %3.3d";
for (int x = 0; x <= 999; ++x) {
printf(fmt,x);
printf(fmt,reverse(x));
printf("\n");
}
return 0;
}
Generalizing a bit and handling potential negative values. You have the basic approach, but, in addition, you want to determine the sign of the input and then operate on a positive value and restore the sign at the end of your function. You can do something similar to:
#include <stdio.h>
#include <stdlib.h>
int reverseint (int n)
{
int reverse = 0,
sign = n < 0 ? -1 : 1;
if (n < 0)
n = -n;
while (n) {
reverse *= 10;
reverse = reverse + n % 10;
n /= 10;
}
return sign * reverse;
}
A short example main() to demonstrate that takes the number to reverse as the first argument to the program (or uses 54321 if no argument is given) could be:
int main (int argc, char **argv) {
int n = (argc > 1) ? (int)strtol(argv[1], NULL, 0) : 54321;
printf ("n : %d\nreverse : %d\n", n, reverseint(n));
}
(note: you should validate the input to the program and the reverseint function are valid integers is in the range of int -- that is left to you)
Example Use/Output
$ ./bin/reverseint
n : 54321
reverse : 12345
$ ./bin/reverseint 0
n : 0
reverse : 0
$ ./bin/reverseint -12345
n : -12345
reverse : -54321
Alternative Using div()
The div() function also provides a nice variant that will replace both your division and modulo operations. See man 3 div. The following is equivalent to the function above but using div() instead of / and %:
int reverseint (int n)
{
/* initialize div_t with positive .quot */
div_t d = { .quot = n < 0 ? -n : n };
int reverse = 0,
sign = n < 0 ? -1 : 1;
do {
d = div (d.quot, 10); /* call div with base 10, to update quotient */
reverse *= 10; /* multiply reverse by 10 */
reverse += d.rem; /* add remainder of division */
} while (d.quot);
return sign * reverse;
}
Look things over and let me know if you have further questions.
As already said you mixed up a and b.
You can't return multiple values.
What you can do is create one number, pack the numbers in an array, pass the pointers to function, place in a struct. You could write something like this:
#include <stdio.h>
int reverse(int x)
{
int a,b,c;
int num;
c = x % 10;
b = (x / 10) % 10;
a = (x / 10) / 10 ;
num = c*100 + b*10 + a;
return num;
}
int main()
{
int x;
scanf("%d", &x);
int num = reverse(x);
printf("%d", num);
}
If you want to return all the values separately you can write something like this for example:
#include <stdio.h>
void reverse(int x , int *a, int *b, int *c)
{
*c = x % 10;
*b = (x / 10) % 10;
*a = (x / 10) / 10 ;
}
int main()
{
int x,a,b,c;
scanf("%d", &x);
reverse(x,&a,&b,&c);
printf("%d%d%d",c,b,a);
}
since you don't want to "return" a single number without the addition operation and display the reversed digits as a whole number there is a way of solving this via the usage of pointers. The code goes like this;
#include <stdio.h>
int* reverse(int);
int main() {
int inputnum;
int *p;
printf("Enter input number: ");
scanf("%d", &inputnum);
p=reverse(inputnum);
printf("\n Output number: ");
for(int i=0;i<3;i++){
printf("%d", *p );
p++;
}
return 0;
}
int* reverse(int x)
{
static int arr [3];
arr[0] = x % 10;
arr[1] = (x / 10) / 10;
arr[2] = (x / 10) % 10 ;
return arr;
}
As you can see, you don't need to use additional integer variables such as a,b,c since we will be storing the data of each operation you have done in a array and treat it as your new number as a whole in the output part. We do this since this is what you specifically asked in your question but there are so much more simpler ways on digit reversing etc. After returning the array that represents the new output number, we can ask our pointer to start from the first index of the array (which is the last digit of the input number in this case) untill the end. By increasing the pointer by 1 we display other digits of our input number as reversed. I hope this will be helpful

Multiplying and increasing pows

Idea is this: http://prntscr.com/m0xopk , It works perfectly except 5, when i give 5 it calculates wrong.I can't understand why?
int i,a,n;
int sum = 1;
scanf("%d",&a);
scanf("%d",&n);
for(i = 1;i <= n;i++){
sum *=pow(a,i);
}
printf("%d",sum);
It works perfectly except 5, when i give 5 it calculates wrong
No, it works perfectly for values less than 5. When you give input 5 for both a and n, the summation resultant number will be 30517578125 which is big for 32 bit int type variable to hold. Instead, you should use uint64_t type variable.
Also, you should not use pow() function for integer type. Check this.
You can do:
#include <stdio.h>
#include <inttypes.h>
int main()
{
int i, a, n;
uint64_t num = 1, result = 1;;
printf ("Enter a: \n");
scanf("%d",&a);
printf ("Enter n: \n");
scanf("%d",&n);
for(i = 0;i < n;i++){
num = num * a;
result = num * result;
}
printf("result: %"PRId64"\n", result);
return 0;
}
Note that this 64 bit solution is also having a limit and will work for input 5 but may not be for a number little bigger than 5. If you want arbitrarily large number, check this.
Integers cant accommodate so large numbers. You need to use float numbers instead.
double calc(double a, int i)
{
double sum = 1;
for(int p = 1; p <= i; p++)
{
sum *= pow(a,i);
}
return sum;
}

Write a program in C that takes a natural number n and base b and outputs digits of n in b

I need to write a program in C language that will take a natural number n and base b(assuming b is in the interval [2,10]) and will output the digits of the number n in base b, from left to right. For example, if n=38 and b=3, the output should be 1102. This is what I have tried:
#include<stdio.h>
int main(void) {
int n,b,number=0,digit=0;
scanf("%d", &n);
scanf("%d", &b);
while(n>0) {
digit=n%b;
number=number*10+digit;
n=n/b;
}
while(number>0) {
printf("%d", number%10);
number=number/10;
}
return 0;
}
This works for n=38 and b=3, but if I take for example n=8 and b=2, the output is 1, when it should be 1000. How do I fix this?
That is a better idea to use a buffer to write your solution:
void print_base(int n, int b)
{
static char const digits[] = "0123456789ABCDEF";
char buffer[16] = { '\0' };
char * buff = buffer + 15;
if ((b >= sizeof digits) || (b <= 1))
return; // error
for (; n > 0; n /= b)
*--buff = digits[n % b]; // move the char pointer backward then write the next digit
printf("%s\n", buff);
}
You must write backward in your buffer (or write forward, then reverse the string) because with your method, you have the smallest digit first.

How I can Gave The Variable To The Array in c [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am trying to solve a problem, I have one integer variable such as
unsigned int x = 456;
Now I want to decompose my integer to an array of its digits, like so:
unsigned int i[] = {4,5,6};
Then I want to convert each element of the array to a string or char.
Any ideas?
I use Avr studio
#include <stdio.h>
int main(){
unsigned int x = 456;
int len = snprintf(NULL, 0, "%u", x);
unsigned int i[len];
unsigned int wk = x;
for(int k=len-1;k>=0;--k, wk/=10)
i[k]=wk % 10;
for(int k=0;k<len;++k)
printf("%u", i[k]);
char string[len+1];
for(int k=0;k<len;++k)
sprintf(string+k, "%u", i[k]);
printf("\n%s\n", string);
return 0;
}
The easiest way to convert an integer to a string is to use a library function such as snprintf().
If you don't have the standard C library, you can use the classic remainder/division trick:
void uint_to_string(char *buf, unsigned int x, unsigned int digits)
{
buf[digits] = '\0';
while(digits > 0)
{
buf[--digits] = '0' + (x % 10);
x /= 10;
}
}
Note that the above builds the string "backwards" (right to left) since that's easiest. It will generate a 0-padded result, you can fix that by adding code to break out of the loop (after the digit is generated on the first line of the loop's body) if x == 0.
main()
{
unsigned int x = 456;
char i[3];
int j,k;
for (j=0; x!=0; j++){
i[j] = x%10 + '0';
x /= 10;
}
for (k=0; k<j; k++)
printf("%c ", i[k]);
return 0;
}
The answer to this is slightly dependent on your actual problem. Do you need the array of digits, or is this merely the intermediate step you yourself came up with to convert an unsigned integer to a string?
If all you need is the string, it would be much simpler to use a function such as sprintf or snprintf.
#include <stdio.h>
//...
unsigned int x = 456;
char digits[50]; // 50 is chosen arbitrarily
snprintf(digits, 50, "%u", x);
//...
Will yield a null-terminated string in digits that looks exactly like the string representation of x, with the caveat that if x is more than 50 digits it will just do as much as it can. (Though I'm not sure an unsigned int can even have more than 50 decimal digits off the top of my head)
If you want the char* to be exactly the correct size to hold the number, it's only a little more difficult.
#include <stdio.h>
// ...
unsigned int x = 456;
int numDigits = snprintf(NULL, 0, "%u", x); // snprintf returns the number of characters that could potentially be written.
char digits[numDigits];
sprintf(digits, "%u", x);
// ...
Without the standard library available, it gets a bit more hairy, but not unmanageably so. Unfortunately, you're going to need two passes that do almost exactly the same things: one to count the digits and one to actually assign them to your array.
int main( void ) {
// ...
unsigned int x = 456;
int numDigits = countDigits(x);
char digits[numDigits+1]; // The +1 is for null-termination
fillDigitArray(digits, x, numDigits);
// ...
}
int fillDigitArray(char *digits, int x, int numDigits) {
int i;
// This requires perhaps a little explaining
// By far the easiest way to get individual digits of a number is with
// x % 10, but this gives us the righthand-most digits
// Thus by counting DOWN, we're filling our buffer from the RIGHT
// making up for the "backwards" nature.
digits[numDigits] = 0;
for (i = numDigits-1; i >= 0; i--) {
digits[i] = '0' + (x%10);
x /= 10;
}
}
int countDigits(int x) {
// Special case
if( x == 0 ) {
return 1;
}
int numDigits;
while(x > 0) {
x /= 10;
numDigits++;
}
return numDigits;
}
Extracting it into an array of unsigned ints is similar, just make digits an unsigned int * rather than a char *, and instead of making digits[i] = '0' + x%10 make it digits[i] = x%10.
Edit: In the interest of fully explaining the example, x%10 is "x mod 10", which can roughly be stated as "give me the rightmost digit of x". x /= 10, while dividing x by 10 and overwriting x with the new value, is essentially just our way of saying "make the right-most digit of x what is currently in the 10's place".
The '0'+ x%10 part is admittedly a bit of magic. The actual ASCII character value for the number "0" isn't actually 0, but the digits 0-9 are laid out in order. So if the rightmost digits of x is 0, we get '0'+0, which is '0', and if we get the rightmost digit as 9 '0'+9' becomes '9'. Using this allows us to bypass an ugly if or switch statement to map the number to the right character.
Getting each digit is a math/logic problem. You need to use the modulus operator which gives you the remainder of the division of the operands.
#include <stdio.h>
static char digits[10];
int main(void) {
int number = 4056;
int remainder = 0;
int i = 0;
while(number > 0 && digits[i] >= 0) {
remainder = number % 10;
number /= 10;
digits[i] = 48 + remainder;
i++;
}
for(i--; i >= 0; i--) {
printf("%c", digits[i]);
}
printf("\n");
}

Counting the number of digits before and after the decimal point in C

I need to write a C program that will compare the number of digits before decimal point and after the decimal point and make sure they are equal.
How can I count how many powers of ten we have before and after the decimal point?
Here is what I have so far:
void main()
{
is_equal(6757.658);
}
INT is_equal(double x)
{
int digits = 0;
while (x) {
x /= 10;
digits++;
}
printf("%d ",digits);
}
Is there a better way to do this?
You do not seem to know binary representation of double/float variables as #AProgrammer suggests.
Your job is impossible if you use float/double. You may use string for the job.
something like below.NOTE: it's just a hint and not a good style.
EDIT: disable cout since this is C
bool checkFloat(string); //the function checks whether the string have a float number format
void twoPart(string num)
{
if (!checkFloat(num))
return;
int i = 0;
int a = 0;//integer part
int b = 0;//fractional part
for(;i<num.length() && num[i]!='.'; i ++);
a = i;
b = num.length() - a - 1;
if(i == num.length())
b = 0;
// print the result here
//cout << a << " " << b << endl;
}
The above piece of code accepts number like 123, 123.456, .123
That's a bit tricky. IEEE floats can't represent most decimal fractions exactly. The number 6757.658 is represented as a binary decimal: 0x1a65a872b020c5×2-40, which is exactly 6757.6580000000003565219230949878692626953125 (I think). I.e., your number actually has 40 decimal places.
This simplest work-around is to format it using something like sprintf(buf, "%.10g", x);, then read the parts back using int a, b; sscanf(buf, "%d.%d", &a, &b);. Alternatively, you could start with int b = 1e10*(x - floor(x)) and keep dividing b by 10 until it isn't a multiple of 10 (while (b%10 == 0) b /= 10;).
3rd try:
Count the number of "digits" before and after a "."
Null is considered not equal to anything
I did not test this code it might contain typos.
int is_equal(char *buffer)
{
char *temp;
int leftLen,rightLen;
temp = strtok(buffer,".");
if (temp == null) return false;
leftLen = strlen(temp);
temp = strtok(buffer,".");
if (temp == null) return false;
rightLen = strlen(temp);
return (leftLen == rightLen);
}
Old stuff...
There are going to be lots of problems here, a floating point (double) in C is not always accurate to 100%; If you perform multiplication or division. If you multiply the digits will change.
The best way to solve this problem is to render the double to a string and then parse that string.
You can use sprintf to write the formatted double to a buffer.
OR
You can skip using a double all together and use a string to start with.
Thus building on Marcelo's answer:
Read the string from the user into a buffer called buff
Then parse it with a statement like sscanf(buf, "%d.%d", &a, &b);
buff is a char * or a char [], a and b are int. You test by saying a == b
void main()
{
is_equal("6757.658");
}
int is_equal(char *x)
{
int left,right;
sscanf(x, "%d.%d", &left, &right);
printf("Left digits: %d\n\r",left);
printf("Right digits: %d\n\r",right);
return (left == right);
}
#include <stdio.h>
#include <assert.h>
float main(void)
{
int siz;
assert (sizeof siz == sizeof (float));
siz = is_equal(6757.658);
printf( "Size=%d\n", siz);
return 0.0;
}
int is_equal(double x)
{
int digits;
for (digits=0; x >= 1.0; digits++) {
x /= 10;
}
return digits;
}

Resources