Converting array to number in (Mikro) C - c

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;
}

Related

How to convert each number in a num String to an int in C

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;
};

Counting and deleting repeated digits of array elements

I need to write a program that allows user to enter an array of integers, finds the digit that appears most often in all entered numbers, and removes it from the elements of the array. If several digits appear the same number of times, the smallest of them should be deleted. If all digits of the element of the array are deleted, that element should become zero. In the end, such a modified array is printed.
Example of input and output:
Enter number of elements of the array: 5
Enter the array: 3833 8818 23 33 1288
After deleting, the array is: 8 8818 2 0 1288
Explanation: The numbers 3 and 8 appear the same number of times (6 times each), but 3 is less, so it was removed it from all members of the array. Element 33 consists exclusively of the digits 3, so that it becomes 0.
#include <stdio.h>
int main() {
int i,n,arr[100]; n;
printf("Enter number of elements of the array: ");
scanf("%d", &n);
printf("Enter the array: ");
for(i=0;i<n;i++) {
scanf("%d", &arr[i]);
}
return 0;
}
EDIT: I'm beginner to programming, and this task should be done using only knowledge learned so far in my course which is conditionals, loops, and arrays. This shouldn't be done with strings.
Divide the problem into separate tasks.
Write the code
In the code below I do not treat 0 as having digit 0. It is because it is not possible to remove 0 from 0. You can easily change this behaviour by changing while(){} loop to do{}while()
int removeDigit(int val, int digit)
{
int result = 0;
unsigned mul = 1;
int sign = val < 0 ? -1 : 1;
digit %= 10;
while(val)
{
int dg = abs(val % 10);
if(dg != digit)
{
result += dg * mul;
mul *= 10;
}
val /= 10;
}
return sign * result;
}
void countDigits(int val, size_t *freq)
{
while(val)
{
freq[abs(val % 10)]++;
val /= 10;
}
}
int findMostFrequent(const size_t *freq)
{
size_t max = 0;
for(size_t i = 1; i < 10; i++)
{
if(freq[i] > freq[max]) max = i;
}
return (int)max;
}
int main(void)
{
int table[20];
size_t freq[10] = {0,};
int mostfreq = 0;
srand(time(NULL));
for(size_t i = 0; i < 20; i++)
{
table[i] = rand();
printf("Table[%zu] = %d\n", i, table[i]);
countDigits(table[i], freq);
}
mostfreq = findMostFrequent(freq);
printf("Most frequent digit: %d\n", mostfreq);
for(size_t i = 0; i < 20; i++)
{
table[i] = removeDigit(table[i], mostfreq);
printf("Table[%zu] = %d\n", i, table[i]);
}
}
https://godbolt.org/z/PPj9s341b

Euler Project 4: Finding the largest palindrome product

So, I've wrote several function prototypes for finding the largest palindrome products. The idea is that put the original number into an array in reverse order then convert the array into a number as reverse number. Then compare the reverse number with original number to see if these two numbers are equal or not. However, I am stuck at implementing these functions prototypes in main method. If yes, then it is a palindrome product/ Any suggestions? Please, have mercy I am new to C
#include <stdlib.h>
#include <stdbool.h>
#include <stdio.h>
#include <math.h>
#include <string.h>
// Taking a number and reverse it. Put it in reverse order into an array. Then, convert all elements in the array into an array again
//Ex: Original number = 6542
//Input: "6542" -> arr[4] = {2,4,5,6} -> Output: "2456"
//Original Number = 6542; Reverse Number = 2456
//Original Number != Reverse Number -> The number is not palindrome. Palindrome Number Example: 456654, 1, 2332.
int convert_reverse_num (int original_num, int digits_count){
int arr_size = digits_count;
int x = original_num;
int final_reverse_num = 0;
int *arr;
arr = (int*)malloc (arr_size * sizeof(int));
//convert the number into arr array by placing the first index with the last trailing digit on the right
for (int i = 0; i < arr_size; i++){
arr[i] = x % 10;
x /= 10;
}
//Adding all values in the array into a number
//starting from the first index of the array which has the value of the last digit of the number
for (int i = 0; i < arr_size; i++){
final_reverse_num *= 10;
final_reverse_num += arr[i];
}
free(arr);
return final_reverse_num;
}
//Check the number is palindrome or not by comparing the original num and reverse num
bool is_palindrome(int original_num, int reverse_num){
int x = original_num;
int y = reverse_num;
if(x == y)
return 1;
else
return 0;
}
//Count number of digits in a number in order to declare the buffer size
int count_digit_num(int product_digits){
int y = product_digits;
int digits_count = 0;
while(y!=0){
y /= 10;
++digits_count;
}return digits_count;
}
//Find all possible products from two ndigits(2 digits, 3 digits, 4 digits) number
// Examples: 1 digits: 1*2. 2 digits: 12*13. 3 digits: 100 * 999
int find_largest_palindrome(int ndigits){
int min = 1;
int max;
int smallest_num;
int largest_num = 0;
int product = 0;
//Finding the minima. 1 digit = 1; 2 digits = 10; 3 digits = 100
smallest_num = min * pow(10, ndigits-1);
//Finding the maxima. 1 digits = 9; 2 digits = 99; 3 digits = 999
for (int i = 0; i < ndigits; i++){
max = 9 * pow(10, i);
largest_num += max;
}
//All possible products from minima and maxima
for (int x = largest_num; x >= smallest_num; x--){
for (int y = largest_num; y >= smallest_num; y--){
product = x * y;
}
}
return product;
}
int main(){
return 0;
}

Convert int to bytes array in c

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);

Printing Integer array in reverse

This is fairly simple problem to print the integer array in reverse order. Although whenever i try printing, it ends up displaying garbage value. Below is my program.
#include <stdio.h>
#include <conio.h>
int main()
{
int temp = { '\0' };
int num[9];
int i;
int j = 8;
printf("Enter 8 numbers\n");
for (i = 0; i < 8; i++)
{
scanf_s("%d", &num[i], 1);
}
for (i = 0; i <= j; i++, j--)
{
temp = num[i];
num[i] = num[j];
num[j] = temp;
}
printf("\nThe numbers in reverse are\n");
for (i = 0; i <=8; i++)
{
printf("%d\n", num[i]);
}
_getch();
return 0;
}
Let just say i input numbers from 1 to 8, it does print the number in reverse but the first value it prints is a garbage value. I know i can use and If statement to counter the situation but is there a way to counter this problem without using if?
You've made two mistakes here:
With 8 numbers, the index of the highest item is 7, not 8. Set j to 7 on initialization to fix this.
When you iterate 8 numbers from index zero, use operator < or !=, not <= to avoid an off-by-one error. Your first loop does it right, but the last loop is broken.
In addition, you may want to reduce the size of the array to 8, because the ninth element is unused.
If you want to print the integers in your array in reverse, simply start at the last index, then work up to the top.
The third loop should look more like this:
int j = 7; // an array of size 8 starts at the 0th and ends at the 7th index.
while(j >= 0)
{
printf("%d", num[j]);
j--;
}
There are several logical inconsistences in your program,
You defined the array as having 9 elements
int num[9];
but enter only 8 elements
for (i = 0; i < 8; i++)
{
scanf_s("%d", &num[i], 1);
}
Thus the last element of the array with insex 8 is not initialized. Nevertheless in the loop that swaps elements of the array you access this uninitialized element
int j = 8;
//...
for (i = 0; i <= j; i++, j--)
{
temp = num[i];
num[i] = num[j];
num[j] = temp;
}
There is also no need to use function scanf_s instead of scanf
Take into account that to output an array in the reverse order you need not to swap its elements.
The program that outputs an array in the reverse order without swapping its elements can look the following way
#include <stdio.h>
#include <conio.h>
#define N 9
int main( void )
{
int num[N];
int i;
printf( "Enter %d numbers\n", N );
i = 0;
while ( i < N && scanf( "%d", &num[i] ) == 1 ) i++;
printf( "\nThe numbers in reverse are\n" );
while ( i-- ) printf( "%d ", num[i] );
printf( "\n" );
_getch();
return 0;
}
If to enter a sequence of numbers
1 2 3 4 5 6 7 8 9
then the output will look like
9 8 7 6 5 4 3 2 1
If you want to swap elements of the array then the program can look like
#include <stdio.h>
#include <conio.h>
#define N 9
int main( void )
{
int num[N];
int n;
int i;
printf( "Enter %d numbers\n", N );
n = 0;
while ( n < N && scanf( "%d", &num[n] ) == 1 ) n++;
for ( i = 0; i < n / 2; i++ )
{
int tmp = num[i];
num[i] = num[n - i - 1];
num[n - i - 1] = tmp;
}
printf( "\nThe numbers in reverse are\n" );
for ( i = 0; i < n; i++ ) printf( "%d ", num[i] );
printf( "\n" );
_getch();
return 0;
}
If the input is the same as above then output will be
9 8 7 6 5 4 3 2 1
You can also keep the for loop the same and change the indexing
#define ARRAY_SIZE 8
// print in reverse order
for (i = 0; i < ARRAY_SIZE; i++)
{
printf("%d\n", num[ARRAY_SIZE - i - 1]);
}
I used a #define to make it easier to change the program when you need a different array size: just change at one place rather than the 5 you currently need.

Resources