Turn a List of digits into an Intenger in C - c

Given a list of digits, for example: <1 6 3 2 5>
How can you turn it into an integer?
In this case, 16325.
I was able do the reverse operation, turning an integer into a list of digits, but im stuck with this one...

Here is a short program that takes an integer array and multiplies it out into an integer:
#include <stdio.h>
#include <math.h>
int main()
{
int output = 0;
int numbers[5] = {1,2,3,4,5};
int size = sizeof numbers / sizeof numbers[0];
for(int i = size; i > 0; i--)
{
output = output + numbers[size-i] * pow(10,i-1);
printf("%d\n",output);
}
return 0;
}
First, it finds the length of the array. Then it needs take each element and multiply it by a power of ten depending upon its location in the array, adding to output to get the total sum.

Related

C program to adjust the carry in an integer array

I want to write a C program to adjust the carry in an integer array (i.e. convert the 2 digit number into a single-digit and add the carry to the next number).
For example -
Array - 6 12 3 15 7
Answer: 7 2 4 5 7
Here's my code:
#include<stdio.h>
int main(){
int array[6]={6,22,3,15,7};
int array2[2];
int i;
printf("%d\n",array[1]);
for(i=0;i<6;i++){
if(array[i]>10){
array2[i]=array[i];
printf("Value at %d element of array is: %d \n",i,array2[i]);
}
}
return 0;
}
So far I have been able to write a program that just finds out double-digit numbers in the array.
I'm relatively new to C and don't know much about how to perform arithmetic operations in arrays.
Help me please!!
since we are adding the carry to previous element, we should start in reverse order.
#include <stdio.h>
int main()
{
int i;
int a[5] = {6,22,3,15,7};
for(i=4;i>0;i--)
{
if(a[i]>9)
{
int rem = a[i]%10;
int carry = a[i]/10;
a[i] = rem;
a[i-1] = a[i-1] + carry;
}
}
if(a[0]>9)
a[0] = a[0]%10;
for(i=0;i<5;i++)
{
printf("%d ",a[i]);
}
return 0;
}

How can you convert a long into an array in c?

I'm working on a project that does an algorithm with the given input. I have the input stored in a long. with the given input, I need to convert “number” into an array so I can have access to each digit. for example, if “number = 73757383” I need to convert that into an array: array = [7, 3, 7, 5, 7...] to be able to do the algorithm (multiply every other digit, then add the others together). But I can't seem to figure out how to do this.
Any help is appropriate.
Also just as a note, I'm using the cs50 library.
Thank you!
#include <stdio.h>
#include <cs50.h>
#include <math.h>
int main(){
long credit;
int number;
int arr[digit];
int i;
do
{
credit = get_long("Number: ");
number = floor(log10(credit) + 1);
}
while (number < 13 || number > 16);
You could simply compare the number with 1000000000000 (at least 13 digits) and 9999999999999999 (at most 16 digits), but you probably need the number of digits later in the code:
#include <stdio.h>
#include <cs50.h>
int main() {
long credit;
int arr[16];
int i;
do {
credit = get_long("Number: ");
}
while (credit < 1000000000000 || credit > 9999999999999999);
...
Alternative:
#include <stdio.h>
#include <cs50.h>
int main() {
long credit;
int arr[16];
int number, i;
do {
credit = get_long("Number: ");
number = snprintf(NULL, 0, "%lu", credit);
}
while (number < 13 || number > 16);
for (i = number; i --> 0;) {
arr[i] = credit % 10;
credit /= 10;
}
Also note that type long may be too small to accommodate numbers larger than 231. You should use long long or even unsigned long long for this or better use a string.
The easiest way is to create a string out of the number and then process 1 digit after another:
#include <stdio.h>
#include <string.h>
int main(){
long credit = 4564894564846;
int arr[20];
char buffer[21];
sprintf(buffer, "%ld", credit);
int n = strlen(buffer);
for (int i = 0; i < n; i++)
arr[i] = buffer[i] - '0';
for (int i = 0; i < n; i++)
printf("%d\n", arr[i]);
}
https://godbolt.org/z/YY4znd
Another possibility is to extract the digit from the number with % 10 and divide by 10 afterwards, but then you get the digits in the wrong order.
You may use a long to ascii function:
ltoa()
or the the well known and standard library function:
sprintf()
In the ascii buffer you can access each individual digit as a char digit.
If you need an array of integer instead, just subtract '0' to each char digit:
buffer[k] - '0'
using % operator can be a good solution
while(input != 0) {
digit = input%10; // store this one
input = input/10;
}
alternatively, you can use 'sprintf' for converting the input to a string. Then, you can access every digit using the index of each digit.

Simple C function returns nonsense

I need to make simple function that converts binary number (string) to decimal number (long). When it returns result, it's nonsense. I've tried to return all others variables and it returned correct numbers. There is something wrong with my result variable.
#include "stdio.h"
#include "string.h"
#include "math.h"
long bintodec(const char *bin_num) {
long DIGIT, SUBTOTAL, RESULT = 0, I, LEN;
LEN = strlen(bin_num);
for(I = 0; I != LEN; I++) {
sscanf(&bin_num[I], "%li", &DIGIT);
SUBTOTAL = DIGIT * pow(2, LEN - I - 1);
RESULT = RESULT + SUBTOTAL;
}
return RESULT;
}
main() {
clrscr();
printf("%li", bintodec("101"));
getch();
}
sscanf is expecting a C string:
During the first iteration it receives "101" and 101 * 4 is 404
During the second iteration it receives 01 and 1 * 2 is 2
During the third iteration it receives 1 and 1 * 1 is 1
404 + 2 + 1 is 407 which must be the nonsense you are seeing
What you want is to convert each character:
DIGIT = bin_num[I] - '0';
You can convert string to long in one go, no need to iterate in loop. Changing your code like below can give you desired output
#include <stdio.h>
#include <string.h>
#include <math.h>
long bintodec(const char *bin_num)
{
long DIGIT, SUBTOTAL, RESULT = 0, I, LEN, REM;
LEN = strlen(bin_num);
sscanf(bin_num, "%li", &DIGIT);
printf("DIGIT = %li\n", DIGIT);
for (I = 0; I < LEN; I++)
{
REM = DIGIT%10;
RESULT += REM * pow(2, I);
DIGIT /= 10;
}
return RESULT;
}
int main() {
printf("%li", bintodec("101"));
}
Rather than debug your code, I'll present a more elegant solution. Consider:
long bintodec(const char *bin_num)
{
long sum = 0;
for (; *bin_num != '\0'; bin_num++) /* move pointer through string */
{
sum <<= 1; /* shift bits left (meaningless on first pass) */
sum |= (*bin_num == '1'); /* conditionally tack on new least significant bit */
}
return sum;
}
Some notes:
The key point is that the bits that encode integer type variables are identical to the binary sequence that you pass in as a string. Thus: bitwise operators. The only ones we need here are left bit-shift, which shifts each of the underlying bits one place to the left, and bitwise-or, which logically or's the bits of two numbers against one another. The equivalent representations render valid a pictorial understanding of the problem.
Rather than having to pass through the entire string to determine its length, and using that to inform the pow function, we can slot incoming bits in on the right.
Here's what's going on within the for loop:
1st pass:
sum <<= : 00000 /* more zero's contained in a long */
string: "10101"
ptr: ^
sum |= : 00001
2nd pass:
sum: 00010
string: "10101"
ptr: ^
sum: 00010
3rd pass:
sum: 00100
string: "10101"
ptr: ^
sum: 00101
... and so forth.
In general, rather than invoking
pow(2, arg)
you should leverage the bit-shift operator, which exactly accomplishes multiplication by some power of two. (Appending a zero is multiplication by 10 in base 10).

Finding frequency of an integer in an array and calculating x to the nth power

I am trying to solve two different C problems and would like some help and advice in order to better understand how C works and if I'm on the right track with these.
First problem is: To write a function that counts the number of times the value (x) appears among the first (n) elements of an array and returns that count as the frequency of x in theArray. So, an example would be if the array being passed contained the values {5, 7, 23, 8, 23, 67, 23}. And n was 7 and x was 23, then it would return a value of 3 since 23 occurs 3 times within the first 7 elements of the array.
Here is what I have so far:
#include <stdio.h>
#define SIZE 20 /* just for example - function should work with array of any size */
int frequency (int theArray[], int n, int x)
{
int i;
int count = 0;
for (i = 0; i < n; i++)
{
if (theArray[i] == x)
{
count = count++;
}
}
return (count);
}
int main(void)
{
/* hard code n and x just as examples */
int n = 12; /* look through first 12 items of array */
int x = 5; /* value to find */
int numberFrequency;
long int theArray[SIZE] = {5,2,3,4,5,6,1,2,10,5,10,12,6,8,7};
numberFrequency = frequency (theArray[SIZE], n, x);
printf ("%i", numberFrequency);
return 0;
}
Currently I'm getting a run time error message and believe it has something to do with the for loop function.
Second problem is: Write a function that raises an integer to a positive integer power. Have the function return a long int, which represents the results of calculating x to the nth power. Do not use the C pow library function and do not use recursion!
My code so far:
#include <stdio.h>
int x_to_the_n (int x, int n)
{
int i;
long int result = 1;
if (n == 0)
{
return(result);
}
else
{
for (i = 0; i < n ; ++i)
{
/* equation here - How can I make (x*x*x*x*x*x,etc...? */
result = x*(n*x);
}
}
return (result);
}
int main(void)
{
int x =4;
int n =5;
long int result;
result = x_to_the_n (x, n);
printf ("%i", result);
return 0;
}
I can't use recursion so that is out of the question. So, I thought the next best thing would be a for loop. But I'm a little stuck in how I would go about making a for loop do (xxx*x....) based on value of (n). Any help and advice would be appreciated!
In the first problem you give an element after the array as a parameter to your function.
You define a long int array, and pass it into a function expecting an int array.
long int theArray[SIZE] = {5,2,3,4,5,6,1,2,10,5,10,12,6,8,7};
should be
int theArray[SIZE] = {5,2,3,4,5,6,1,2,10,5,10,12,6,8,7};
Instead of this:
numberFrequency = frequency (theArray[SIZE], n, x);
try this:
numberFrequency = frequency (theArray, n, x);
And replace:
count = count++;
with:
count++;

Problems in Project Euler #8

I have been working on Project Euler lately. I am programming in C and have a query related to Problem 8. The question is:
Find the greatest product of five consecutive digits in the 1000-digit number.
73167176531330624919225119674426574742355349194934
96983520312774506326239578318016984801869478851843
85861560789112949495459501737958331952853208805511
12540698747158523863050715693290963295227443043557
66896648950445244523161731856403098711121722383113
62229893423380308135336276614282806444486645238749
30358907296290491560440772390713810515859307960866
70172427121883998797908792274921901699720888093776
65727333001053367881220235421809751254540594752243
52584907711670556013604839586446706324415722155397
53697817977846174064955149290862569321978468622482
83972241375657056057490261407972968652414535100474
82166370484403199890008895243450658541227588666881
16427171479924442928230863465674813919123162824586
17866458359124566529476545682848912883142607690042
24219022671055626321111109370544217506941658960408
07198403850962455444362981230987879927244284909188
84580156166097919133875499200524063689912560717606
05886116467109405077541002256983155200055935729725
71636269561882670428252483600823257530420752963450
Here is my own done work yet:
#include <stdio.h>
#include <string.h>
int main(void)
{
char *string = "731671765313306249192251196744.............";
char *x;
x = string;
for(int counter = 0;counter < 2;counter++)
{
printf("%s\n", x + strlen(x) - 5);
x = x + strlen(x) - 5;
}
}
SO, the problem is that unable to understand what to do next. I am able to extract the digits, but what would be the algorithm to use these digits and create an algorithm thats fast and efficient. So, any help, please! Another problem is that when I try to convert the char to an int value, it fails and gives the error "error: incompatible pointer to integer conversion initializing 'char' with an expression of type'char[1001]'. I have used the methods to convert values as here:Coversion of char to int, and so thats it. If any more suggestions, please suggest the better things...
You can read the characters in the string, convert them to integers and then find their product to check which group of 5 consecutive integers give the highest product. At the loss of fun and learning that you can have trying to do it yourself, you can try this.
#include <stdio.h>
#include <string.h>
// calculates the product of a group of numeric chars
// after converting them to int type
int gproduct(char *s, int glen) {
int i = 0;
int val = 1;
// convert a numeric char to int value by subtracting '0'
// assuming the chars are encoded in ascii. consider using
// the standard library function atoi for portability.
while(i < glen)
val *= (s[i++] - '0');
return val;
}
int main(void) {
char *numstr = "731671765313306249192251196744.............";
int glen = 5; // group length
int maxcount = strlen(numstr) - glen;
int maxval = gproduct(numstr, glen); // initialize maxval
int tempval;
for(int i = 1; i < maxcount; i++) {
tempval = gproduct(numstr + i, glen);
if(tempval > maxval)
maxval = tempval;
}
printf("%d\n", maxval);
return 0;
}

Resources