I am writing a program to add two large numbers in C.
My integer array result holds the sum of the two numbers (which were also stored in arrays).
For example, if the result array is [0,0,3,2] (actual array size is 20)
If 32 is my actual result, how can I display the contents of the result array without the leading zeros ?
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define BASE 10
void align(int A[],int n);
void add(int A[],int B[], int C[]);
void Invert(int* a, int n);
int main(int argc, char** argv){
char input1[20];
char input2[20];
int size = 20;
int a;
int b;
int num1[20];
int num2[20];
int result[20];
int length1 = strlen(argv[1]);
int length2 = strlen(argv[2]);
int i = 0;
for (i=0;i<length1;i++){
input1[i] = argv[1][i];
}
for (i=0;i<length2;i++){
input2[i] = argv[2][i];
}
a=atoi(input1);
b=atoi(input2);
align(num1,a);
align(num2,b);
add(num1,num2,result);
Invert(result,size);
for (i=0;i<20;i++){
printf("%d",result[i]);
}
return 0;
}
void align (int A[], int n){
int i = 0;
while (n) {
A[i++] = n % BASE;
n /= BASE;
}
while (i < 20) A[i++] = 0;
}
void add (int A[], int B[], int C[]) {
int i, carry, sum;
carry = 0;
for (i=0; i<20; i++) {
sum = A[i] + B[i] + carry;
if (sum >= BASE) {
carry = 1;
sum -= BASE;
} else
carry = 0;
C[i] = sum;
}
if (carry) printf ("overflow in addition!\n");
}
void Invert(int* a, int n)
{
int i;
int b;
for(i=0; i<n/2; i++){
b = a[i];
a[i] = a[n-i-1];
a[n-i-1] = b;
}
}
`
To get the actual digits (I assume that each digit is stored as a byte in an array of 20 bytes, lowest digit at highest index), you do something like this:
int i;
int size = sizeof(thearray) / sizeof(thearray[0]);
/* find first non-0 byte, starting at the highest "digit" */
for (i = 0; i < size - 1; ++i)
if (thearray[i] != 0)
break;
/* output every byte as character */
for (; i < size; i++)
printf("%c", thearray[i] + '0'); /* 0 --> '0', 1 --> '1', etc. */
printf("\n");
You can do this by below code:-
int flag=1;
for(i=0;i<20;i++)
{
if(flag==1&&array[i]!=0)
flag=0;
if(flag!=1)
{
printf("%d",array[i]);
}
}
This will remove all leading zeros.
I propose a solution by using the pointer. The situation where only zero is stored in the array is also handled. I'm more comfortable with the pointer.
int test[20] = {0,0,0,0,1,2,3,4,5,6,7,8,9,0,0,1,2,3,4,5};
int test_bis[20] = {0};
int * ptr_test = test_bis;
int ii = 0;
while( *(ptr_test)== 0 && ii < 20 ) {
ptr_test++;
ii++;
}
if( ii < 20)
do {
printf("%d",*(ptr_test));
ptr_test++;
} while (++ii < 20);
else
printf("0");
Thats for integer array you can modify it accordingly.
for(i=0;i<20;i++){
if(flag==1&&array[i]==0)
{
// just skips until first nonzero
}
else if(flag==1&&array[i]!=0){
flag=0; // when first nonzero comes set flag to 0 and print it
printf("%d",array[i]);
}
else {
printf("%d",array[i]); // after first nonzero simply print it
}
}
Related
#include<stdio.h>
#include<assert.h>
const char *authour ="Alexandre Santos";
int ints_get(int *a)
{
int result = 0;
int x;
while (scanf("%d", &x) !=EOF)
{
a[result++] = x;
}
return result;
}
int sum_odd(const int *a, int n)
{
int sum = 0;
for(int i = 0; i < n; i++)
if(i%2 != 0)
sum += a[i];
return sum;
}
int sum_all(const int *a, int n)
{
int sum = 0;
for(int i = 0; i < n; i++)
sum = sum + a[i];
return sum;
}
int final(const int *a, int n)
{
return sum_all(a,n) - sum_odd(a,n);
}
void unit_test_even_values_minus_odd_values(void){
int a1[8] = {1,2,3,4,5,6,7,8};
assert(final(a1, 8) == 4);
assert(final(a1, 6) == 3);
assert(final(a1, 4) == 2);
assert(final(a1, 2) == 1);
}
void unit_tests(void){
unit_test_even_values_minus_odd_values();
}
void test_sum(void)
{
int a[100];
int n = ints_get(a);
int total = final(a,n);
printf("%d\n", total);
}
int main()
{
test_sum();
return 0;
}
I have this program but I don't understand how the assertions work here, my main question is what the second number represents. For example I understand that assert(final(a1, 8) == 4) I understand that a1 is the array determined in the line above but I can't understand the second number (8).... Can anyone explain to me how this works? I tried to search a little bit but I still don't understand...
The second argument to final is the number of values to work on from that array, starting from the beginning.
final(a1, 8) sums all eight values. final(a1, 6) only sums the first six values.
So I want to split each digit of a decimal number into an array. I have the following code:
#include <stdio.h>
int * splitNumberIntoArr(int num) {
int i = num;
int modulus,newNum;
static int arr[5];
int j = 0;
while (i > 0) {
modulus = i % 10;
newNum = i / 10;
arr[j] = modulus;
j++;
i = newNum;
};
return arr;
};
int main() {
int num;
printf("Provide a number:\t");
scanf("%d", &num);
int *arr;
arr = splitNumberIntoArr(num);
int k;
for(k = 0; k <= sizeof(arr) / sizeof(arr[0]); k++) {
printf("%d\n",arr[k]);
return 0;
};
When num is an integer consising of 3 digits, the code works how it is supposed to.
However, when the input consists of more than 3 digits, the array that is returned by the splitNumberIntoArr()
function only returns an array of length 2.
for example,
Since I am new to C, I struggle to understand why this problem even exists, taking into consideration the fact that the declared array is of length 5: static int arr[5];
Your help would be greatly appreciated.
Try something like this:
#include <stdio.h>
#include <string.h> // for memset
void splitNumberIntoArr(int num, int *arr) {
int i = num;
int modulus, newNum;
int j = 0;
while (i > 0) {
modulus = i % 10;
newNum = i / 10;
arr[j] = modulus;
j++;
i = newNum;
};
}
int main() {
int num;
scanf("%d", &num);
int arr[32];
memset(arr, -1, sizeof(arr));
splitNumberIntoArr(num, arr);
for (int k = 0; k < sizeof(arr) / sizeof(arr[0]) && arr[k] != -1; k++) {
printf("%d\n",arr[k]);
}
}
In main(), the sizeof(arr) is known, because it lies on the stack.
So the problem here was to write a program that uses pointers to point to functions and write it in such a way that it collects 10 doubles, gives feedback to the user of the program, sorts them and print the sorted results as proof. The problem is, the program either prints the printf statement in the beginning infinitely, or collects numbers infinitely.
Here is some code
#include <stdio.h>
void func1(double x);
void below_five(void);
void above_five(void);
void other(void);
void sort(double *p[], int n);
void print_doubles(double *p[], int n);
int main(void){
double *numbers[9];
int nbr;
printf("\nEnter 10 doubles that are less than 5 or greater than 5, type 0 to exit");
for(int i = 0; i < 10 ; i++)
{
scanf("%d", &nbr);
func1(nbr);
numbers[i] = nbr;
if(nbr == 0)
break;
}
sort(numbers, 10);
print_doubles(numbers, 10);
return 0;
}
void func1(double val)
{
double (*ptr)(void);
if(val <= 5.00){
ptr = below_five;
}else if((val > 5.00) && (val <= 10.00)){
ptr = above_five;
}else
ptr = other;
}
void below_five(void){
puts("You entered a number below or equal to five");
}
void above_five(void){
puts("You entered a number above five");
}
void other(void){
puts("You entered a number well above five.");
}
void sort(double *p[], int n)
{
double *tmp;
for(int i = 0; i < n; i++)
{
if(p[i] > p[i+1]){
tmp = p[i];
p[i] = p[i+1];
p[i + 1] = tmp;
}
}
}
void print_doubles(double *p[], int n)
{
int count;
for(count = 0; count < n; count++)
printf("%d\n", p[count]);
}
Like I said, what I expect it to be able to do is collect doubles into the scanf method and then print the numbers after sorting them, but it seems the for loop collects doubles forever without end in this case.
What have I done wrong, exactly?
See my comments in your updated code.
There are other modifications required, but the minimum updates needed to work your code is below
#include <stdio.h>
void func1(double x);
void below_five(void);
void above_five(void);
void other(void);
void sort(double p[], int n); /* Simply use a array notation,
arrays passed to functions decays to pointer */
void print_doubles(double p[], int n); /* Simply use a array notation,
arrays passed to functions decays to pointer */
int main(void){
double numbers[10];
double nbr; // Change type to double, as you're reading doubles
printf("\nEnter 10 doubles that are less than
5 or greater than 5, type 0 to exit\n");
for(int i = 0; i < 10 ; i++)
{
scanf("%lf", &nbr); // Use correct format specifier to read doubles
func1(nbr);
numbers[i] = nbr;
if(nbr == 0)
break;
}
sort(numbers, 10);
print_doubles(numbers, 10);
return 0;
}
void func1(double val)
{
double (*ptr)(void);
if(val <= 5.00){
ptr = below_five;
}else if((val > 5.00) && (val <= 10.00)){
ptr = above_five;
}else
ptr = other;
/* Why you set the pointer to function if you don't call it,
so call it here*/
(*ptr)();
}
void below_five(void){
puts("You entered a number below or equal to five");
}
void above_five(void){
puts("You entered a number above five");
}
void other(void){
puts("You entered a number well above five.");
}
void sort(double p[], int n) /* Your sorting routine is wrong ,
see the modified code */
{
double tmp;
for(int j = 0; j < n-1; j++)
for(int i = 0; i < n-j-1; i++)
{
if(p[i] > p[i+1]){
tmp = p[i];
p[i] = p[i+1];
p[i + 1] = tmp;
}
}
}
void print_doubles(double p[], int n)
{
int count;
for(count = 0; count < n; count++)
printf("%lf\n", p[count]); // Use correct format specifier
}
Demo Here
The rest of my functions work fabulously, however the last function has my goat. The goal of this function is to use pointers to obtain the values of two different arrays and add those values to a third array. However, when I run the main method to make the function run, it pauses for a second and provides a wedge exit code that does not work.
I've tried removing the if((sizeof(*ptr1)) == (sizeof(*ptr2)){
---insert code here---
}
from the for loop, however, the problem seems to be just the for loop itself.
//===================================Broken Code========================================
#include <stdio.h>
#define MAXIMUM 1000
int sumArrays(int arr1[], int arr2[]);
int addArrays(int arr1[], int arr2[]);
int main()
{
int arrayOne[MAXIMUM];
int arrayTwo[MAXIMUM];
for(int i = 0; i <= MAXIMUM; i++)
arrayOne[i] = i;
printf("Arrayone %d\n", arrayOne);
for(int j = 0; j <= MAXIMUM; j++)
arrayTwo[j] = j;
printf("ArrayTwo %d\n", arrayTwo);
printf(" The sum of the arrays is : %d\n",sumArrays(arrayOne, arrayTwo));
printf("%d", addArrays(arrayOne, arrayTwo));
return 0;
}
int sumArrays(int arr1[],int arr2[]){
int *ptr_1;
int *ptr_2;
ptr_1 = &arr1[0];
ptr_2 = &arr2[0];
int sum;
for(int i = 0; i < MAXIMUM; i++){
sum += *ptr_1 + i;
sum += *ptr_2 + i;
}
return sum;
}
int addArrays(int arr1[],int arr2[]){
int *ptr1 = &arr1[0];
int *ptr2 = &arr2[0];
int sum = 0;
int i = 0;
int arr3[0];
if(sizeof(*ptr1) == sizeof(*ptr2)){
for(int i = 0; i < MAXIMUM; i++){
sum += *ptr1 +i;
sum += *ptr2 +i;
arr3[i] = sum;
}
}
printf("The value of array3 is %d", arr3);
}
The other function works perfectly, but the addArrays function does a wedge exit and doesn't cooperate.
I expect the addArrays function to take the elements from each array, add them together and assign them to the third array.
Thank you for your time.
UPDATE: WORKING CODE
#include <stdio.h>
#define MAXIMUM 1000
#define ARRAY_SZ(x) (sizeof(x) / sizeof((x)[0]))
int sumArrays(int arr1[], int arr2[], size_t len);
int addArrays(int arr1[], int arr2[], int arr3[], size_t len);
int main()
{
int arrayOne[MAXIMUM];
int arrayTwo[MAXIMUM];
int arrayThree[MAXIMUM];
for(int i = 0; i <= MAXIMUM; i++)
arrayOne[i] = i;
printf("Array One %d\n", ARRAY_SZ(arrayOne));
for(int j = 0; j <= MAXIMUM; j++)
arrayTwo[j] = j;
printf("Array Two %d\n", ARRAY_SZ(arrayTwo));
printf(" The sum of the arrays is : %d\n",sumArrays(arrayOne, arrayTwo, ARRAY_SZ(arrayOne)));
printf("%d", addArrays(arrayOne, arrayTwo, arrayThree, MAXIMUM));
return 0;
}
int sumArrays(int arr1[],int arr2[], size_t len){
int *ptr_1;
int *ptr_2;
ptr_1 = &arr1[0];
ptr_2 = &arr2[0];
int sum = 0 ;
for(int i = 0; i < len; i++){
sum += *ptr_1++;
sum += *ptr_2++;
}
return sum;
}
int addArrays(int arr1[],int arr2[], int result[], size_t len){
int *ptr1 = &arr1[0];
int *ptr2 = &arr2[0];
int *ptr3 = &result[0];
int sum = 0;
int sum2 = 0;
int i = 0;
for(int i = 0; i < MAXIMUM; i++){
sum = *ptr1 ++;
sum += *ptr2 ++;
result[i] = sum;
printf("The result of array 3 is %d\n", *ptr3++);
}
}
Here are some notes:
When you assign/pass/print the and array using the name of the array, you are actually passing the memory location of the first element in the array (a pointer).So when you write:
printf("Arrayone %d\n", arrayOne);
You will see the memory address of the first element of the array being printed. If you would like to print the entire array you will need to loop through it. In this case you would be printing 1000 integers which might be undesirable.
void printArray(int * array, size_t len)
{
while(len--)
{
printf("%d ", *array++);
}
}
To get the number of elements in an array you can do something like this:
sizeof(arrayOne) / sizeof(arrayOne[0])
and you can put it in a macro like this:
#define ARRAY_SZ(x) (sizeof(x) / sizeof((x)[0]))
and call it like this:
ARRAY_SZ(arrayOne);
You cannot get the array size if you are receiving an array in a function (it has decayed to a pointer), instead you should pass the array size to the function too. Here because you initialize the arrays with the size MAXIMUM we don't actually need to calculate the array size, but we can just to show it works.
If you want to return an array (like in addArrays()) you should create an empty array and pass it to the function, then the function can update the array with the result.
When looping through an array you never want to do array[maximum] because the array indices range from 0 to maximum - 1
#include <stdio.h>
#define MAXIMUM 1000
#define ARRAY_SZ(x) (sizeof(x) / sizeof((x)[0]))
int sumArrays(int arr1[], int arr2[]);
int addArrays(int arr1[], int arr2[]);
int main()
{
int arrayOne[MAXIMUM];
int arrayTwo[MAXIMUM];
int arrayThree[MAXIMUM];
for(int i = 0; i < MAXIMUM; i++)
arrayOne[i] = i;
printf("Array one size %d\n", ARRAY_SZ(arrayOne));
for(int j = 0; j < MAXIMUM; j++)
arrayTwo[j] = j;
printf("Array Two size %d\n", ARRAY_SZ(arrayTwo));
printf(" The sum of the arrays is : %d\n",sumArrays(arrayOne, arrayTwo, ARRAY_SZ(arrayOne)));
addArrays(arrayOne, arrayTwo, arrayThree, MAXIMUM);
return 0;
}
int sumArrays(int arr1[],int arr2[], size_t len)
{
int *ptr_1;
int *ptr_2;
ptr_1 = &arr1[0];
ptr_2 = &arr2[0];
int sum;
for(int i = 0; i < len; i++){
sum += *ptr_1 + i;
sum += *ptr_2 + i;
}
return sum;
}
void addArrays(int arr1[], int arr2[], int result[], size_t len){
int *ptr1 = arr1;
int *ptr2 = arr2;
int sum = 0;
int i = 0;
for(int i = 0; i < len; i++){
sum = *ptr1 +i;
sum += *ptr2 +i;
result[i] = sum;
}
}
can you help me with code which returns partial sum of 'X' numbers in array in c?
Complete :
int arr_sum( int arr[], int n )//Recursive sum of array
{
if (n < 0) //base case:
{
return arr[0];
}
else
{
return arr[n] + arr_sum(arr, n-1);
}
}
void sum_till_last (int *ar,int si )
{
**int sum,i;// the problem some where here
ar=(int*) malloc(si*sizeof(int));
for (i=0; i<si;i++)
{
sum=arr_sum(ar,i);
ar [i]=sum;
}
free (ar);**
}
void main ()
{
int i;
int a [5];
for (i = 0; i < 5; i++)
scanf_s("%d", &a[i]);
sum_till_last(a,5);
printf("%d\n",a[5]);
}
\i want to create new array with this this legality:
My input :
4
13
23
21
11
The output should be (without brackets or commas):
4
17
40
61
72
Now when we can see the full code, it's quite obvious that the problem is in the sum_till_last function where you overwrite the pointer you pass to the function with some new and uninitialized memory you allocate.
Drop the allocation (and the call to free of course). And fix the logical bug in arr_sum that causes you to get arr[0] + arr[0] when i is zero.
Here you go:
#include <stdio.h>
int main () {
int in_arr[5] = {4,13,23,21,11};
int out_arr[5];
int p_sum =0;
int i;
for ( i=0;i<5;i++){
out_arr[i] = in_arr[i]+p_sum;
p_sum=p_sum+in_arr[i];
}
for (i=0;i<5;i++){
printf("%d", out_arr[i] );
}
}
Fix according to your policy
#include <stdio.h>
#include <stdlib.h>
int arr_sum(int arr[], int n){
if (n == 0){//Change to this
return arr[0];
} else {
return arr[n] + arr_sum(arr, n-1);
}
}
void sum_till_last(int *ar, int si){
int sum,i;
int *temp = malloc(si * sizeof(int));//variable name ar is shadowing parameter name ar.
for(i = 0; i < si; i++){
temp[i] = arr_sum(ar, i);
if(i)
putchar(' ');
printf("%d", temp[i]);//need print out :D
}
free(temp);
}
int main(void){
int i, a[5];
for (i = 0; i < 5; i++)
scanf_s("%d", &a[i]);
sum_till_last(a, 5);
//printf("%d\n",a[5]);<-- this print only one element. and It's out of bounds element XD
}
I just made it simple so it´s easy to understand :)
I´m assuming "n" is always equal or less then array element number. Then you just print the SUM.
#include <stdio.h>
int arr_sum( int arr[], int n ){
int i=0,SUM=0;
for(; i < n;i++){
SUM= SUM+ arr[i];
printf("%d ",SUM);
}
}
int main(void) {
int array[] = {4, 13, 23, 21, 11};
arr_sum(array,5);
return 0;
}