Array to int and Sum of them in C - arrays

im learning C and i am a bit confused with array handling.
I have a task that asks me to sum up 2 arrays of non negative integers.
example array 1 = {1,2,3} , array 2 = {4,5,6} -> 123+456 = 579
I searched a bit for a solution on how to convert those arrays of integers to an integer, but didnt really get helpful information.
I ended up with a code:
#include <stdio.h>
int sum(int A[],int B[], int n){
int i,j,t,k;
for(i=0;i<n;i++){
t= t+A[i];
}
for(j=0;j<n;j++){
k= k+B[j];
}
return t+k;
}
int main()
{
int n = 3;
int a[n] = {1,2,3};
int b[n] = {4,5,6};
printf("%d",sum(a,b,n));
return 0;
}
But my result is 1225283 which of course is wrong.
I found a solution where people write something like "t= 10* t+A[i]" , i dont get where that "10* " comes from, but i tested it and then "t" gets "123" but if i try the same for "k" it doesnt work, returning "k" doesnt give me "456". I am a bit confused, whats the proper way of handling this problem?
Thanks for any help.

You're basically adding digits 1+2+3 instead of creating the number 123. Your code also has various other flaws, like uninitialized variables. Here is a working example:
int array2int(int A[], int n) {
int ret = 0;
for(int i=0, k=1; i<n; i++){
ret = ret + k * A[i];
k *= 10;
}
return ret;
}
int sum(int A[],int B[], int n){
return array2int(A, n) + array2int(B, n);
}

First of all, in sum function, you haven't initialized neighter t nor k but you keep summing them and use later, so every time your code is executed, you chould get different result.
On the other hand, in something like "t= 10 t+A[i]", 10 comes from basic math, where a number could be resolved as a10^0 + b10^1 +c*10^2 + .... + m * 10^n. As a result, starting from least significant digit, everytime you try to add new digit (from least to most significant), you need your multipliciant to be 10 times greater.
int sum(int A[],int B[], int n){
int i,j,t=0,k=0,ten=1;
for(i=n-1;i>=0;i--){
t += ten*A[i];
ten *= 10;
}
ten = 1; /* initialize again*/
for(j=n-1;j>=0;j--){
k += ten*B[j];
ten *= 10;
}
return t+k;
}
Something like that should work.

Related

swap pair to make sum equal

Question: Given two arrays of integers A[] and B[] of size N and M, the task is to check if a pair of values (one value from each array) exists such that swapping the elements of the pair will make the sum of two arrays equal.
My approach:
find sum of both arrays.
Identify array with larger sum(denote with A[]).
Sort A.
For all values in B binary search (sum(A)-sum(B)/2 + B[i]) in A, if found return true.
Return false.
code:
int sum(int a[], int n){
int s=0;
for(int i=0; i<n; i++){
s+= a[i];
}
return s;
}
int findSwapValues(int A[], int n, int B[], int m)
{
// Your code goes here
int a = sum(A, n);
int b = sum(B,m);
int t;
int *temp;
if(a<b){
temp = A;
A = B;
B = temp;
t = n;
n = m;
m = t;
t = a;
a = b;
b = t;
}
sort(A, A+n);
for(int i=0; i<m; i++){
if(binary_search(A,A+n,(a-b)/2+B[i])){
return 1;
}
}
return -1;
}
Doubt: My algorithm is failing for some test cases(not TLE). As the test cases are very large, it's difficult to reason out the problem in the algorithm. I searched online and understood other approaches. My only curiosity is why its incorrect?
I think the error in your code is that you find B[i] + (a-b)/2.
The problem with this is that if (a-b) is an odd value, division by 2 will round it down to the nearest integer and you end up finding the wrong value.
What you can instead do is check if the difference is odd before even swapping the arrays, and if it is true, straight-away return -1 because if the difference is odd, no such pair can ever exist.
I hope I cleared your doubt :).

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

algorithm-coin changing code mistake

Given a value N, if we want to make change for N cents, and we have infinite supply of each of S = { S1, S2, .. , Sm} valued coins, how many ways can we make the change? The order of coins doesn’t matter.
I have written below code but it is always returning one less than the actual answer. I want to know if this is the right way of coding up the solution?
#include <stdio.h>
int ways=0;
int remember[100] = {0};
void foo(int coin_denomination[], int size, int sum)
{
int i;
printf("%d\n", sum);
if (sum==0) {
ways++;
return;
}
if (remember[sum]==1)
return;
remember[sum] = 1;
if (sum < 0)
return;
for(i=0;i<size;i++)
foo(coin_denomination, size, sum-coin_denomination[i]);
}
int main()
{
int coin_denomination[] = {1, 2, 3};
int sum = 5;
foo(coin_denomination, sizeof(coin_denomination)/sizeof(coin_denomination[0]), sum);
printf("%d\n", ways);
return 0;
}
You need some change to foo method. Your problem is that with the variable remember you are not counting some solutions. The goal of variable remember is not correct, you are using for not processing the same coin collection multiple times but you are saving only the sum of the coin collection and the sum could be obtained with multiple coin collections (ex: 1 1 1 have same sum that 1 2 when you select the second, remember[3] would be 1 and not be passing this point, missing solution 1 2 2)
Other way of not repeating coin collection is needed, in this case, adding a parameter that represent the index of coin_denomination that is processing and only allow processing of coin after, the problem is solve.
Code (Tested with GCC 4.9.0):
#include <stdio.h>
int ways=0;
void foo(int coin_denomination[], int size, int sum, int coin_idx = 0)
{
if (sum < 0)
return;
int i;
printf("%d\n", sum);
if (sum==0) {
ways++;
return;
}
for(i=coin_idx;i<size;i++)
foo(coin_denomination, size, sum-coin_denomination[i], i);
}
int main()
{
int coin_denomination[] = {1, 2, 3};
int sum = 5;
foo(coin_denomination, sizeof(coin_denomination)/sizeof(coin_denomination[0]), sum);
printf("%d\n", ways);
return 0;
}

factorial giving wrong answer

#include<stdio.h>
int max = 100;
int main()
{
int a,j;
int * arr = (int*)malloc(sizeof(int)*max);
arr[max-1] = 1;
scanf("%d",&a);
factor( arr, a);
display(arr);
}
int factor( int arr[],int a)
{
if (!a) return;
int i,carry;
for(i=max-1;i>=0;i--)
{
arr[i] = (arr[i]*a) + carry;
carry = arr[i]/10;
arr[i] = arr[i]%10;
}
factor( arr, a-1);
}
int display(int arr[])
{
int i;
for ( i=0; i<max; i++)
{
printf("%d",arr[i]);
}
}
HI this is my program to find the factorial of numbers but its giving wrong answer i dont know why ...???
like when i give input as 13
then according to myprogram 13 is to be treated in array as 1 and 3 but its giving random numbers -1216731443 -121673144 . i think malloc is having problem , but i can't identify it .
thank you
I think the reason why you are getting "random" numbers is because you haven't initialized the carry variable. In the for loop, you are adding the un-initialized value of carry to the array which will cause undefined results.

Unable to get a factorial function to work in C

I cannot get the following code to work.
#include <stdio.h>
// I am not sure whethere I should void here or not.
int main() {
// when the first bug is solved, I put here arg[0]. It should be
// similar command line parameter as args[0] in Java.
int a=3;
int b;
b = factorial(a);
// bug seems to be here, since the %1i seems to work only in fprintf
printf("%1i", b);
return 0;
}
int factorial(int x) {
int i;
for(i=1; i<x; i++)
x *= i;
return x;
}
How can you get the code to work?
You're modifying your loop terminating variable (x) inside the loop. Currently your code blows up after a few iterations, when x overflows the range of a 32 bit integer and then becomes negative and very large, hence terminating the loop.
It should be:
int factorial(int n) {
int i, x = 1;
for (i = 2; i <= n; ++i) {
x *= i;
}
return x;
}
Better yet, you should use long instead of int for the variable x and the return value, because n! gets very large very quickly.
AInitak gave the right answer, but I want to add that one way you can find the bug in your code is to print out the values of i and x in the factorial loop.
int factorial(int x) {
int i;
for(i=1; i<x; i++)
{
x *= i;
printf("%d, %d\n", i, x);
}
return x;
}
This gives you the output
1, 3
2, 6
3, 18
4, 72
5, 360
6, 2160
7, 15120
8, 120960
9, 1088640
10, 10886400
11, 119750400
12, 1437004800
13, 1501193216
14, -458131456
-458131456
This makes it easier to see what's going wrong. The loop doesn't stop where you expect it to for the reasons AInitak explained.
It's bad style in C to leave out void when defining or declaring a function. So put it in
int main(void)
While it doesn't change anything about the number of parameters the function has (the function has zero parameters without that void either), it will declare the function as one that accepts only zero arguments, while it won't tell anything about the amount and types of accepted arguments when you omit the void. However, both versions with and without void are correct.
Read this answer about that matter too.
#include<stdio.h>
#include<stdlib.h>
int main(int c,char *v[])
{
int x,y;
int *num;
if(c==1)
{
printf("Usage : programName : number");
return 0;
}
num=(int *)malloc(sizeof(int));
*num=atoi(v[1]);
x=1;y=1;
while(x<=*num)
{
y=y*x;
x++;
}
printf("Factorial of %d is %d ",*num,y);
free(num);
return 0;
}
What error message do you get?
First off, declare your function factorial before main. Also, pay attention to correct indentation. Your declaration of function main is correct, by the way.
I would suggest to use also double or unsigned long for factorial computation in order to be able to compute the greater value of the factorial function.
double fact( double n)
{
if ( n == 1)
return 1;
return n*(fact(n-1));
}
A more elegant non-recursive function.
#include<stdio.h>
long long int fact(long long int);
long long int fact(long long int n){
long long int num = 1;
long long int fi = 0;
for(long long int i=2;i<=n;i++){
for(long long int j=1;j<=i;j++){
fi += num;
}
num = fi;
fi = 0;
}
return num;
}
int main(){
long long int n;
scanf("%lld",&n);
printf("%lld\n",fact(n));
return 0;
}

Resources