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]);
}
}
Related
I am writing a code to find the factor of the user given number. And then I want to store all the factors in an array. I created two functions, factors and insert_element. factors will find the factor and insert_element will store the factor in array as loop continues. When i call insert_element function form factors it shows me an error like warning: passing argument 1 of ‘insert_element’ from incompatible pointer type [-Wincompatible-pointer-types]. I have no idea what this means and how it occurred as I am new at C language. I would like to know how a bit about how compiler works with array along with how this error occurred
I am extremely SORRY if the question title and the question body seems to be misleading..
Here's my code below:
// PROGRAME TO FIND FACTORS OF GIVEN NUMBER"
#include <stdio.h>
void insert_element(int *factor_array[], int *base_divisor, int *index_of_array_elements)
//I heve used * because i want to ruturn more then one thing
{
*factor_array[*index_of_array_elements] = *base_divisor;
*index_of_array_elements++;
}
void factors(int number)
// I dont know if I want to return something or not so i kept it of type void
{
int base_divisor = 2, factor_array[50], index_of_array_elements = 0;
// base_divisor starts dividing given number from 2
while (number != 1)
{
if (number % base_divisor==0) //If remainder is zero then only devide number by base_divisor
{
number = number / base_divisor;
}
else //If remainder is not zero then base_divisor will be increase by 1.
{
base_divisor++;
}
// calling the function to insert element in array
insert_element(&factor_array[50], &base_divisor, &index_of_array_elements);
}
//i dont know why i did this but error is not caused by this.
printf("%ls", factor_array);
}
int main()
{
int number;
printf("\nPROGRAME TO FIND FACTORS OF GIVEN NUMBER\n\n");
printf("Enter the number to find factor: ");
scanf("%d", &number);
factors(number);
}
As written, the code in your post is outputting values that are not always factors. Only during the final iteration of the loop is the value for factor_array (if stored correctly) a quotient and a factor, which of course should also mean it is prime.
The following example, for simplification removes one function, and modifies the prototype of the remaining function to take a struct array argument. The struct itself contains values for quotient, factor, base. The code is also commented to explain some of the modification. In particular I hope this will help you to understand how to pass an array as a function argument, and how to use a loop to output the values in an array.
typedef struct {
long long factor;
long long quotient;
long long base;
}elements_s;
elements_s factor_array[50] = {{0}};
//REMOVED as all the work done here is moved to it's calling function
// void insert_element(size_t arr_size int *factor_array[], int *base_divisor, int *index_of_array_elements)
////I heve used * because i want to ruturn more then one thing
//{
//
// *factor_array[*index_of_array_elements] = *base_divisor;
// *index_of_array_elements++;
//
//
//}
void factors(long long number, size_t size, elements_s arr[size])//changed to pass container for results.
// I dont know if I want to return something or not so i kept it of type void
{
long long base_divisor = 2, /**factor_array[50],*/ index_of_array_elements = 0;//factor_array replaced by struct array
arr[index_of_array_elements].factor = 1;//fill array here, no need to send via function
arr[index_of_array_elements].quotient = number;
arr[index_of_array_elements].base = base_divisor;
int i=0;
// base_divisor starts dividing given number from 2
while (number != 1 && base_divisor < LLONG_MAX )
{
if (number % base_divisor==0) //If remainder is zero then only devide number by base_divisor
{
index_of_array_elements++;//index array index
number = number / base_divisor;
arr[index_of_array_elements].factor = base_divisor;//fill array here, no need to send via function
arr[index_of_array_elements].quotient = number;//fill array here, no need to send via function
arr[index_of_array_elements].base = base_divisor;//fill array here, no need to send via function
}
else //If remainder is not zero then base_divisor will be increase by 1.
{
base_divisor++;
}
//REMOVED for simplification of example (Not needed)
// calling the function to insert element in array
//insert_element(&factor_array[50], &base_divisor, &index_of_array_elements);
//insert_element(&factor_array, &base_divisor, &index_of_array_elements);
}
//i dont know why i did this but error is not caused by this.
for(i = 0;i < index_of_array_elements-1; i++)//putting into loop so all populated element of array are output
{
printf("quotient:%lld\nfactor:%lld\n", factor_array[i].quotient,factor_array[i].factor);//using %d for int
}
printf("base divisor:%lld\nfactor and quotient:%lld\nfactor:%lld\n", factor_array[i].base, factor_array[i].quotient,factor_array[i].factor);//using %d for int
}
int main(void)//this is a minumum signature for main. Anything less is not portable.
{
long long number = 0; //allows larger values up to 9223372036854775807 (LLONG_MAX)
//int factor_array[50] = {0};
size_t size = sizeof factor_array/sizeof *factor_array;
printf("\nPROGRAME TO FIND [prime] FACTORS OF GIVEN NUMBER\n\n");
printf("Enter the number to find factor...\n");
scanf("%lld", &number);//format specifier changed to accomodate larger type
factors(number, size, factor_array);//factor_array contains all the results here,
// so prinf could be used here if index were
// also passed as argument
return 0;//int main(void) requires this statement
}
Example run for value: 1234567890: (multiply all factors to test for input)
I am essentially attempting to print out how many values are entered for the array in this code (If they enter 10 numbers, I would want to print for index: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 as well as taking user inputs for the array values and printing those in a table-like fashion beside of their index). How would I go about doing this, and is there anything wrong with this code?
#include <stdio.h>
#include <stdlib.h>
int arr_1 (int ar[], int size);
int main()
{
double sentinel[20];
printf("Hello User!\n\nEnter up to 20 values, and type -1 when you are finished: ");
for (int i = 0; i < 20; ++i) {
scanf("%lf", &sentinel[i]);
}
for (int i = 0; i < 20; ++i) {
printf("%f\n", sentinel[i]);
}
printf("\n%lu\n", sizeof(sentinel[20]));
}
int arr_1 (int ar[], int size)
{
return 0;
}
First, you will need to check whether the user actually inputs as many values as you expect to get (20 in your case). The scanf() function tells you, in its return value, whether it actually managed to parse another number from the input.
Then, you'll need to exit your loop when no more numbers are available on the input.
Finally, you'll need to keep track of how far you got in the loop. One way to do this is to define the loop index (i) in the scope outside the loop. That way it's not lost to you when the loop is eventually cleared.
Once you have the last i value (suppose you assign it to a new variable like so, int num_input_elements = i + 1) then you know your indices are 0, 1,... num_input_elements - 1. And you can easily loop through those, printing, in fact, your loop index.
Additional notes:
Don't use the "magic number" 20 all over. Use a preprocessor definition before you first use it, e.g. something like #define MAX_NUM_ELEMENTS 20.
sentinel is a confusing name for your array, because a sentinel typically means something else in programming.
sizeof(sentinel[20]) is always sizeof(double)... not the number of elements you got on the input.
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));
}
I wrote two functions and call the functions in main.
Function 1 – I wrote a function that returns void and takes an int * (pointer to integer array) or int[], and int (for the size). The function needs to initialize all the elements of the array to non-zero values.
Function 2 – I wrote another function that returns int and takes an const int * (pointer to integer array) or int[], and int (for the size). The function should sum all the elements of the array and return the sum.
In main I defined an integer array of size 5. Called function 1 in main to initialize the values of the array. Called function 2 in main to get the sum and print the value of the sum to the console.
My problem is the program runs but the print out for sum we are getting is a large (in the millions), random, number and is not the expected answer of 15. Anyone who can help us get the correct answer would be greatly appreciated
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#pragma warning(disable: 4996)
void func1(int* ptr, int size);
int func2(const int* ptr, int size);
int main()
{
int grid[5];
func1(grid, 5);
func2(grid, 5);
}
void func1(int* ptr, int size)
{
*ptr = 1, 2, 3, 4, 5;
}
int func2(const int* ptr, int size)
{
int sum;
sum = ptr[0] + ptr[1] + ptr[2] + ptr[3] + ptr[4]; // *(ptr + 0); putting an asterisk makes it so that it changes the entire "ptr" value and the "[0]" value
printf("\n\nThe sum of the integers in the array is %d.\n\n", &sum);
}
*ptr = 1, 2, 3, 4, 5;
does not do what you think it does. It actually evaluates all the integer constants but sets ptr[0] to be 1 (see comma operator for more detail), leaving all the others at some arbitrary value.
Note that it is not evaluating *ptr = (1, 2, 3, 4, 5) (which would set *ptr to 5) but is actually evaluating (*ptr = 1), 2, 3, 4, 5 - this works because something like 42 is actually a valid C statement, albeit not very useful.
If you're trying to set the array to increasing values, just use something like:
for (int i = 0; i < size; i++)
ptr[i] = i + 1;
You probably also want to do that when summing the values since it should depend on the passed-in size rather than just summing five values:
int sum = 0;
for (int i = 0; i < size; i++)
sum += ptr[i];
Additionally, the value you are printing out is not the sum, it's the address of the variable containing the sum (a decent compiler will warn you about this). You should be using sum in your printf rather than &sum.
And, as a final note, the signature for func2 indicates that you should actually be returning the sum rather than just printing it. So I would suggest removing the printf from that function and simply doing:
return sum;
Then you can put the printf into the caller (main) as follows:
int main(void)
{
int grid[5];
func1(grid, sizeof(grid) / sizeof(*grid));
int sum = func2(grid, sizeof(grid) / sizeof(*grid));
printf("The sum of the integers in the array is %d.\n\n", sum);
return 0;
}
Note the use of sizeof(grid) / sizeof(*grid), which is basically the number of array elements in grid - this will allow you to resize grid by simply changing it in one place to something like int grid[42] and still have all the code work with the updated size.
Not actually necessary for your code but it's best to get into good programming habits early (more descriptive names for your functions may also be a good idea).
Line *ptr = 1, 2, 3, 4, 5; assigns ptr[0] value and leaves other spots unitilized so when you sum it, it will be random memory.
You should use for like this to initialize
for(int i=0;i<size;i++)
{
ptr[i] = i+1;
}
and similiar aproach to sum it.
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.