I would like to convert an int to a char[4] where each byte in the char[4] contains a decimal value of 2. So in the following example:
int p = 2999999;
Convert p to the array that is identical to k where k is constructed via:
char k[4];
k[0] = 2;
k[1] = 99;
k[2] = 99;
k[3] = 99;
How can I do this in C?
Thanks in advance!
It's strange problem for me but OK. here's what I would have done:
Copy value of p so that it can be used later (I assume that this conversion doesn't intend to change its value).
Use modulo operation to get 2 last digits
cut down the copy of p to be able to read next two digits.
So complete answer is:
#include <stdio.h>
int main()
{
int p = 2999999;
char k[4];
int p_copy = p;
int i;
for(i = 3; i >=0; i--)
{
k[i] = p_copy % 100;
p_copy /= 100;
}
for(i = 0; i < 4; i++)
printf("k[%d]: %d\n",i, k[i]);
return 0;
}
And for sanity the output:
gonczor#wiktor-papu:~/tmp$ gcc test.c -o test
gonczor#wiktor-papu:~/tmp$ ./test
k[0]: 2
k[1]: 99
k[2]: 99
k[3]: 99
for (i =4; i--; k[i] = p % 100, p /= 100);
Related
My printf() function is continuously printing nothing to the terminal instead of the characters in the array that it is supposed to.
#include <stdio.h>
#include <cs50.h>
int main(void)
{
char s[4];
s[0] = '0';
s[1] = '0';
s[2] = '0';
s[3] = '\0';
int nums[3] = {0, 0, 0};
for (int i = 92; i < 110; i++)
{
// Number maxes at three digits
for (int j = 0; j < 3; j++)
{
nums[2 - j] = i % 10;
i /= 10;
}
for (int k = 0; k < 3; k++)
{
s[k] = (char) nums[k];
}
printf("%s\n", s);
}
}
I am trying to get the program to print out 3 number increasing every time the loop is completed. If the number is not 3 digits all of the not occupied spots should be 0's.
I was testing out your code as others were commenting on your code. As I found testing, the program did not print out anything and can running in an endless loop as a result of the issues noted in the comments. With those comments in mind, following is a refactored version of your program.
#include <stdio.h>
int main(void)
{
char s[4];
s[0] = '0';
s[1] = '0';
s[2] = '0';
s[3] = '\0';
int nums[3] = {0, 0, 0};
int x;
for (int i = 92; i < 110; i++)
{
x = i; /* Need to use a work variable - shouldn't be modifying the loop counter */
// Number maxes at three digits
for (int j = 0; j < 3; j++)
{
nums[2 - j] = x % 10;
x /= 10;
}
for (int k = 0; k < 3; k++)
{
s[k] = (char) nums[k] + '0'; /* As noted in the comments */
}
printf("%s\n", s);
}
}
Things to point out.
As noted, it is not a good idea to be modifying a variable used as a loop counter within a loop as noted in the endless loop behavior experienced, so the loop counter is placed into a work variable for use on the needed calculations.
As also noted in the comments, since an ASCII character value is wanted in the character array, the value of character "0" (zero) would need to be added to the integer value derived for each position in order to attain the equivalent character in the character array.
With those bits refactored, following is the terminal output from a test run.
#Vera:~/C_Programs/Console/PrintChars/bin/Release$ ./PrintChars
092
093
094
095
096
097
098
099
100
101
102
103
104
105
106
107
108
109
Give those tweaks a try and see if it meets the spirit of your project.
I've been trying to do this problem on Project Euler
This is what I've done so far -
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main(){
char nums[] = "7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450"
int64_t sum = 1, new_sum = 0;
int num;
for(int i = 0; i < 988; i+= 13){
sum = 1
for(int j = 0; j < 13; ++j){
//Converting nums[i] to int and storing it to num here
sum *= num;
}
if(sum > new_sum){
new_sum = sum;
}
}
printf("%lld", new_sum);
}
I don't know how to convert each charNum in the String to an integer, I've tried atoi and sscanf and both of them ask for a char pointer.
I get these errors respectively
passing argument to parameter here
int atoi(const char *); //sum *= atoi(nums[i])
format specifies type 'int *' but the argument has type 'int' [-Wformat]
sscanf(nums[i], "%d", num);
Any help is appreciated.
Just converting a character representing a digit to the digit itself is simply done by
int digit = nums[position] - '0';
C language guarantees for any character set that the digits 0-9 are succeeding one another in exactly that order (which is not necessarily the case for alphabetic characters, see e.g. (in-?) famous EBCDIC).
As I read the problem the maximum can be at any location, not only multiples of 13. For this speaks as well that the maximum of four subsequent digits is found at a location where the number of digits preceding is not a multiple of four.
Apart from, unless the number if digits is a multiple of 13, your loops would exceed array bounds of nums, so undefined behaviour (if not a multiple of 13, then for last iteration of i there are less than 13 digits left, but j still tries to iterate over all 13 digits).
Fixing both:
size_t sequenceLength = 13; // could be a function parameter
size_t len = strlen(nums); // sizeof would include the terminating 0 character!
if(len < sequenceLength)
{
return 0; // if within a function, else whatever appropriate error handling
}
uint64_t max = 1; // can't have negative values anyway...
for(size_t i = 0; i < sequenceLength; ++i)
{
max *= nums[i] - '0'; // see above
}
// now we found first possible maximum: the product of first 13 digits
uint64_t num = max;
for(size_t i = sequenceLength; i < len; ++i)
{
// for next product, we have already included the first 12 digits
// within the previous product!
// but there is one surplus digit contained we need to eliminate:
num /= nums[i - sequenceLength] - '0';
// now we can include the yet missing one:
num *= nums[i] - '0';
// or as a one-liner:
num = num / (nums[i - sequenceLength] - '0') * (nums[i] - '0');
// TODO: update maximum, if need be, just as in your code
}
Would you please try the following:
#include <stdio.h>
#include <stdlib.h>
#define N 13
int main() {
char nums[] = "7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450";
int64_t prod = 1, max_prod = 0;
int num;
int pos;
for (int i = 0; i < sizeof nums; i += N) {
prod = 1;
for (int j = 0; j < N; j++){
// Converting nums[i] to int and storing it to num here
num = nums[i + j] - '0';
prod *= num;
}
if (prod > max_prod) {
max_prod = prod;
pos = i;
}
}
printf("max product = %ld at %.*s\n", max_prod, N, nums + pos);
}
Output:
max product = 6270566400 at 4355766896648
BTW as the variable name sum is misleading, I've changed it to prod for product.
I assume that you want a nuber for each digit (i.e., range 0 to 9)
If yes, the below code should be not too far from what you need:
char nums[] = "73167176531330624919225119674426574742355349194934969835203... (so long)...";
char *p;
long lTheTotalCount, lTheNumber;
lTheTotalCount = 0;
for (p=nums ; *p ; p++) {
lTheNumber = (long)(*p - '0');
lTheTotalCount += lTheNumber;
};
I'm trying to make a code which converts some decimal numbers to bits.
There are more simple ways to reach this result but I'm poking around and joking with memory in C.
int ** decimalToBits(int *number,int size){
int **bits = (int **)malloc(sizeof(*bits)*size), i = 0;
for (int j = 0; j < size; j++) {
int * temp = (int *)malloc(sizeof(int));
while (number[j] >= 1) {
temp[i++] = number[j] % 2;
number[j] /= 2;
realloc(temp, sizeof(int));
}
printf("\n");
bits[j] = (int *) malloc(sizeof(int)*i);
for (int k = i-1; k >= 0; k--){
bits[j][k] = temp[k];
printf("%d" ,bits[j][k]);
}
i = 0;
}
return bits;
}
I'm having some allocation problems, first of all I'm going to explain the idea:
I pass to the function multiple numbers, so for example:
int numbers[2] = {23,73};
decimalToBits(numbers,2);
Each converted number will be stored in **bits double pointer, so bits[0] will contain the number 23 converted, and bits[1] will contain 73 converted as well.
The problem shows up when I do bits[j] = (int *) malloc(sizeof(int)*i); call,
because this seems to let the temp pointer to be overwritten with some random numbers. In fact if I remove the bits[j] = (int *) malloc(sizeof(int)*i); and bits[j][k] = temp[k]; lines and I replace printf("%d" ,bits[j][k]); with printf("%d" ,temp[k]);
the code seems to have a good behavior, and it gives me the correct output:
10111
1001001
I also noticed that allocating the bits[j] = (int *) malloc(sizeof(int)*8); externally from the for (int j = 0; j < size; j++) loop let the code works. So why this allocation problem occurs when declared just like the above code and what's the best way to solve it?
I'm running into some coding troubles.
I am reading serial input into my program, and it saves the numbers into an array.
Now I want to convert this array into an integer to do calculations, where Array index 0 represents the one digits, index 1 the ten digits etc.
Array[0] represents 1 digit
Array[1] represents 10 digit
Array[2] represents 100 digit
Array[3] represents 1000 digit
Array[4] represents 10000 digit
Array[5] represents 100000 digit
The array is dynamic, so could have only 2 indexes.
Use a loop. You must know the length of the number, or the length of the array. Unused positions in the array should be 0.
int i;
long result = 0; // Choose a suitable integer type.
for (i = length; i <= 0; --i) {
result = result * 10 + Array[i];
}
Given if all the array entries are 0-9, and given they are in a data type that can be converted to int without a cast, this could work for you:
#include <stdio.h>
int main (void) {
int lenght = 6;
int Array[lenght];
Array[0] = 9;
Array[1] = 4;
Array[2] = 5;
Array[3] = 8;
Array[4] = 1;
Array[5] = 0;
int pow = 1;
int val = 0;
for (int i = 0; i < lenght; i++) {
val += Array[lenght-i-1] * pow;
pow *= 10;
}
printf("Val is %d", val);
return 0;
}
Note: This is a primitive, non error handled approach. It may not work in all cases.
Reason for not using pow:
pow does not return a integer, leading to inaccuracies with implicit integer casts. E.G 100 could be 99.9999 instead and then get truncated to 99.
I'm not 100% sure what you are trying to do, but is this what you want to do:
#include <stdio.h>
int main ( void )
{
int numbers[] = { 1, 2, 3, 4, 5, 6 };
int multiplier = 1;
printf ( "First printout\n" );
for ( int i = 0; i < 5; ++i )
printf ( "Numbers[%i] = %i\n", i, numbers[i] );
//this is where the numbers in the array are made into the 1, 10s, 100s etc
for ( int i = 0; i < 5; ++i )
{
numbers[i] *= multiplier;
multiplier *= 10;
}
printf ( "Second printout\n" );
for ( int i = 0; i < 5; ++i )
printf ( "Numbers[%i] = %i\n", i, numbers[i] );
return 0;
}
I just started learning C a couple of months ago. I'm sure there are better ways to do this, but this is a solution that seems to solve your problem. I hope this helps!
The digits represent the value in the tens place.
Array[0]*1 + Array[1]*10 + Array[2]*100 ... etc.
You could make a loop to do it.
int value = 0;
int pow = 1;
for(int i = 0; i<length; i++){
value += Array[i]*pow;
pow *=10;
}
The thing I am trying to achieve is given by the following code:
int a = 2, b = 7, c = 5, d = 0, e = 9;
int x = 27509; /* aka a + b + c + d + e */
What would be a way to do this?
You can try this:
int nums[5] = {2,7,5,0,9};
long long sum = 0;
for (int i=0; i<5; ++i)
sum = sum * 10 + nums[i];
// print: sum
for(int x = 10; x < 1000000000; x++){
if(b < x){
c = a*x + b;
break;
}
}
Here
int a = 2;
int b = 3;
char str[80];
char stringNum[20];
char *success;
success = malloc(20 * sizeof(*success));
sprintf(stringNum, "%d", a); // converts int a into a string
strcpy(str, stringNum); // initializes str
sprintf(stringNum, "%d", b);
strcat(str, stringNum);
printf("%ul", strtol(str, &success, 10)); // you'll get an int 23
free(success);
Just modify the values of the int variables to suit your needs and concatenate them to str.