Putting number inside int but not summing it - c

I want to put some numbers in my integer but I don't want to sum them, for example:
I have int car = 500; and I want to add a digit 5 at end of it, but I don't want to sum 500 and 5, I want it to look like 5005. How I can do that?

// Only works for digits <10
int new_digit = 5;
// "Shift" the current value 1 digit left.
car *= 10;
// Append the new digit
car += new_digit;
The other thing to consider: If you need to manipulate numbers like that, is int the correct data type? perhaps you would be better off with a string?

doesn't it will be as simple as follows?
int car = 500;
car *= 10; //adding another digit -> 5000
car += 5; // add that 5 -> 5005

Other answers have shown you how to do this by doing math, by multiplying by 10. Depending on your needs, you could also do it using strings, like this:
int car = 500;
int newdigit = 5;
char carstr[10], suffix[10], newstr[20];
snprintf(carstr, 10, "%d", car);
snprintf(suffix, 10, "%d", newdigit);
strcpy(newstr, carstr);
strcat(newstr, suffix);
printf("%s\n", newstr);
/* or you can convert new digit string back to int */
int newnum = atoi(newstr);
printf("%d\n", newnum);
If you go this road, of course, you have to always be careful to make the character arrays big enough to hold the strings you're storing in them. For production code, many people recommend not using functions like strcpy and strcat at all, because it's simply too easy to end up overflowing the underlying character arrays.

Related

Performing a sum between two arrays of digis

Had an interview today and I was asked the following question - given two arrays arr1 and arr2 of chars where they contain only numbers and one dot and also given a value m, sum them into one array of chars where they contain m digits after the dot. The program should be written in C. The algorithm was not important for them, they just gave me a compiler and 20 minutes to pass their tests.
First of all I though to find the maximum length and iterate through the array from the end and sum the values while keeping the carry:
int length = (firstLength < secondLength) ? secondLength : firstLength;
char[length] result;
for (int i = length - 1; i >= 0; i--) {
// TODO: add code
}
The problem is that for some reason I'm not sure what is the right way to perform that sum while keeping with the dot. This loop should just perform the look and not counter to k. I mean that at this point I thought just adding the values and at the end i'll insert another loop which will print k values after the dot.
My question is how should look the first loop I mentioned (the one that actually sums), I'm really got stuck on it.
The algorithm was not important
Ok, I'll let libc do it for me in that case (obviously error handling is missing):
void sum(char *as, char *bs, char *out, int precision)
{
float a, b;
sscanf(as, "%f", &a);
sscanf(bs, "%f", &b);
a += b;
sprintf(out, "%.*f", precision, a);
}
It actually took me a lot longer than 20 mins to do this. The code is fairly long too so I don't plan on posting it here. In a nutshell, the code does:
normalize the 2 numbers into 2 new strings so they have the same number of decimal digits
allocate a new string with length of longer of the 2 strings above + 1
add the 2 strings together, 2 digits at a time, with carrier
it is not clear if the final answer needs to be rounded. If not, just expand/truncate the decimals to m digits. Remove any leading zero if needed.
I am not sure whether this is the best solution or not but here's a solution and I hope it helps.
#include<stdio.h>
#include<math.h>
double convertNumber(char *arr){
int i;
int flag_d=0; //To check whether we are reading digits before or after decimal
double a=0;
int j=1;
for(i=0;i<arr[i]!='\0';i++){
if(arr[i] !='.'){
if(flag_d==0)
a = a*10 + arr[i]-48;
else{
a = a + (arr[i]-48.0)/pow(10, j);
j++;
}
}else{
flag_d=1;
}
}
return a;
}
int main() {
char num1[] = "23.20";
char num2[] = "20.2";
printf("%.6lf", convertNumber(num1) + convertNumber(num2));
}

How to store 100 digit number in C using strings

My problem is that i dont know what this functions do, thats program
from my teacher(not whole program just functions). Just wanna ask you what this functions do, mainly why
i store my number from right to left at string? thanks
#include<stdio.h>
#include<string.h>
#define MAX 1000
void str_to_num(char *str, char *number, int *dlzka)
{
int i;
for(i=0; i < MAX; i++)
number[i] = 0;
*dlzka = strlen(str);
for(i = 0; i < *dlzka; i++)
cis[(*dlzka) - 1 - i] = str[i] - '0';
}
void plus(char *cislo, int *d1, char *cis2, int d2)
{
int i; prenos = 0;
if(*d1 < d2)
*d1 = d2;
for(i = 0; i < *d1; i++)
{
pom = number[i] + number[i];
pom += prenos;
number[i] = pom % 10;
prenos = pom / 10;
}
}
Here is the lesson your teacher should be teaching:
There is a difference between the numerical value of 1, and the computer code (ASCII for example) that is used to represent character 1 displayed on the screen or typed on the keyboard.
Every time you see 1 on the screen, your computer sees 49 in memory.
0 is 48, 2 is 50 and so on.
Conveniently, all digit characters are arranged in a sequence from 0 to 9, so to convert their character codes to their numeric values all you have to do is subtract the character code of zero to get the digit position in the sequence.
For example: 49 - 48 = 1 --> '1' - '0' = 1
And this is how the first function, str_to_num works.
C language does not provide a variable large enough to work with 100 digit numbers, so you need to sum them up one digit at a time.
The second function has completely wrong variable names, but it is still pretty obvious what it is trying to do:
It sums up two single digit numbers, then stores the ones part of the result in an array and the tenth (if sum is > 9) in a helper variable.
As already suggested in the comments, this is how you sum up numbers manually on a page one digit at a time.
I don't know what prenos means in your language, but in English this variable should be called carry and it keeps the overflowing tens digit for the next round.
There is however something missing from the sum function: if the sum of the last (leftmost) two digits is more than 9, the extra 1 will be lost, and the result will be wrong.
Check the original code your teacher gave you - either you copied it wrong, or he is giving a bad example.

How to extract last 3 digit of an array of a string and store it to different int array in C

I want to extract last 3 digit of a string suppose like :
char a[100][100] = ["17BIT0111" , "17BIT0222", ... n];
and I want to take last three digits and store in different array like
int b[100] =[111 , 222 , ... n];
I took reference from this but I wan't it without using pointer or a linked list. As I am gonna use it for comparing stack.
C program to extract different substrings from array of strings
Something like this:
for (int i = 0; i < 100; ++i)
{
unsigned int value = 0;
sscanf(a[i], "17BIT%u", &value);
b[i] = (int) (value % 1000);
}
This doesn't check the return value of sscanf(), instead defaulting the value to 0 in case conversion fails.
This will convert a larger integer, so the % 1000 was added to make sure only the last three digits really matter in the conversion. The unsigned is simply to disallow embedded dashes in the string, which makes sense to me in cases like these.

How can I convert a long long into an array in C?

I would like to convert an integer into an array. My goal is to be able to take a long long, for example 123456789..., and make an array in which each digit holds one spot, like this {1, 2, 3, 4, 5, 6, 7, 8, 9, ...}.
I can't use iota() because I am not allowed to, and I don't want to use snprintf because I don't want to print the array. I just want to make it.
After thinking about it for awhile, the only solution I thought of was to
Create a loop to divide the number by ten for each digit, leaving the quotient as an int
Let the decimals of the quotient go away via the restrictions of the int data type
Make a for loop to decrement the number until it becomes divisible by ten, all while incrementing a counter i
Let the i effectively become the digit and pass it into the array
But I feel like I am making this extremely overcomplicated, and there must be a simpler way to do this. So, have I answered my own question or is there and easier way?
This is an iterative approach for your problem which I guess works perfectly
The code below is commented ! Hope it helps
#include <stdio.h>
int main()
{
// a will hold the number
int a=548763,i=0;
// str will hold the result which is the array
char str[20]= "";
// first we need to see the length of the number a
int b=a;
while(b>=10)
{
b=b/10;
i++;
}
// the length of the number a will be stored in variable i
// we set the end of the string str as we know the length needed
str[i+1]='\0';
// the while loop below will store the digit from the end of str to the
// the beginning
while(i>=0)
{
str[i]=a%10+48;
a=a/10;
i--;
}
// only for test
printf("the value of str is \"%s\"",str);
return 0;
}
if you want the array to store only ints you need only to change the type of the array str and change
str[i]=a%10+48;
to
str[i]=a%10;
You can use only 1 loop :
#include <math.h>
int main() {
int number = 123456789;
int digit = floor(log10(number)) + 1;
printf("%d\n", digit);
int arr[digit];
int i;
for (i = digit; i > 0; i--) {
arr[digit-i] = (int)(number/pow(10,i-1)) % 10;
printf("%d : %d\n", digit-i, arr[digit-i]);
}
}

How to add numbers between two string array in c

Sometimes we need to calculate very long number which couldn't hold any numerical data type of C. As we know all common numerical data type has limitation.
I'm beginner and I think... it is possible by string. My question is:
How can I add two strings?
Sample Input:
String 1: 1234
String 2: 1234
Output
Result : 2468
[Note: Numbers can be very very long in Strings. Unlimited]
Do not convert to a number. Instead, add as you (must) have learned in basic eductation: one pair of digits at a time, starting from the lowest (rightmost) and remember to carry the tens forwards (to the left).
The length of the source strings does not matter, but you must be sure the result char array is large enough for the longest input value plus one (optional) digit.
The algorithm is so simple that I will not "type the code" (which is off-topic for Stack Overflow). It boils down to
carryOver = 0
loop:
result0 = inputA0 + inputB0 + carryOver
if result0 > '9'
carryOver = 1
result0 -= 10
else
carryOver = 0
go to loop while there is still input left ...
where the 0 in the variable names indicate the index of the current digits under consideration.
Edit This Answer does not allow carry overs but infinity long add operations. It does not solve the problem of the user. But it is an implementation example and the user asked for one. This is why I will let the answer stay here and not delete it.
You can use atoi (ascii to int)
Do you realy mean C or C++?
This code can't calculate 8+3 = 11 but 5+3 = 8. There is no carry over.
int temp;
const inst size_of_array;
char one[size_of_array];
char two[size_of_array];
char result[size_of_array];
for(int i = 0; i < size_of_array; i++)
{
temp = atoi(one[i]) +atoi(two[i]);
results[i] = numberToCharacter(temp);
}
char numberToCharacter((int temp)
{
if(temp == 1)
{
return('1'):
} ///..
}
Parse the string variables to integer variables. Calculate sum of them, then parse the result to string.
Here is a fiddler.
Here is the code:
#include <stdio.h>
int main(void) {
//Declaring string variables
char string1[10] = "1234";
char string2[10] = "1234";
//Converting them to integer
int int1 = atoi(string1);
int int2 = atoi(string2);
//Summing them
int intResult = int1 + int2;
//Printing the result
printf("%d", intResult);
return 0;
}

Resources