#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.
Related
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.
I tried to build a heap and finally print the elements in the form of an array.
Here it is the code (I know this doesn't really make sense but I just wanted to test my knowlwdge of heap and dynamic arrays):
#include <stdio.h>
#include <stdlib.h>
void heapiify(int *arr,int n, int i)
{
int largest=i;
int l=2*i+1; // left node
int r= 2*i+2; // right node
if(l<=n && *arr[l]>=*arr[i])
largest=l;
if (r <=n && *arr[r]<=*arr[i])
largest= r;
if(largest !=i)
{
int temp=*arr[i];
*arr[i]=*arr[largest];
*arr[largest]=temp;
}
heapify(*arr,n,largest);
}
void buildh(int *arr,int n,int r,int c)
{
int i;
for(i=n/2-1;i>=0;i--)
heapify(*arr,n,i);
output(*arr,r,c);
}
void output(int *arr,int r,int c)
{
int i,j;
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
printf("%d",*arr[i*c+j]);
}
printf("\n");
}
}
int main()
{
int i,j,r,c;
printf("enter the number of rows");
scanf("%d",&r);
printf("enter the number of columns");
scanf("%d",&c);
int n=r*c;
int *arr=malloc(n*sizeof(int));
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
scanf("%d",&arr[i*c+j]);
}
buildh(*arr,n,r,c);
}
I'm getting 9 errors which are all the same
invalid argument type of unary '*'( have int)
Your arr variable is of type pointer to int:
int *arr=malloc(n*sizeof(int));
So when you call buildh, which takes the same type, you have to pass it as-is:
buildh(arr,n,r,c);
Same for the other cases.
The problem is the dereference of arr, across your funtions in multiple places, and the passing of dereferenced *arr in your functions to int * parameters, you should pass arr, try:
//...
void heapify(int *arr, int n, int i)
{
int largest = i;
int l = 2 * i + 1; // left node
int r = 2 * i + 2; // right node
if (l <= n && arr[l] >= arr[i]) //here
largest = l;
if (r <= n && arr[r] <= arr[i]) //here
largest = r;
if (largest != i)
{
int temp = arr[i]; //here
arr[i] = arr[largest]; //here
arr[largest] = temp; //here
}
heapify(arr, n, largest); //here
}
void buildh(int *arr, int n, int r, int c)
{
int i;
for (i = n / 2 - 1; i >= 0; i--)
heapify(arr, n, i); //here
output(arr, r, c); //here
}
void output(int *arr, int r, int c)
{
int i, j;
for (i = 0; i < r; i++)
{
for (j = 0; j < c; j++)
{
printf("%d", arr[i * c + j]); //here
}
printf("\n");
}
}
int main()
{
//...
buildh(arr, n, r, c); //here
}
Hi i wanted to tranform this code into a recursive function:
int a3(int* a, int length) {
if(a == 0 || length <= 0) return 0;
int sum = 0;
for(int i = 0; i < length; i++) {
for(int j = i; j < length; j++) {
sum += a[j];
}
}
return sum;
}
My approach is :
int rec_help(int*a, int length);
int a3(int* a, int length) {
if(a == 0 || length <= 0) return 0;
else{
return rec_help(a,length) + rec_help(a+1,length-1) ;
}
}
int rec_help(int*a, int length){
if(a == 0 || length <= 0) return 0;
else{
int tmp = a[0];
return tmp + a3(a+1,length-1);
}
}
But i'm not getting it right.
With a3() i wanted to simulate the first for loop, and i think there is my problem :D
And with rec_help() the second loop and the body, but im mixing things here.
I would appreciate any kind of help :)
Because you have 2 loop, if you want your function to be recursive, you will need 2 recursive functions, one which will do the job of the first loop and a second to do the job of your second loop...
Something like that should work :
int a3_rec(int *a, int length)
{
if (length == 0)
return (0);
return (*a + a3_rec(a + 1, length - 1));
}
int a3_rec_hat(int *a, int length)
{
if (a == 0 || length == 0)
return (0);
return (a3_rec(a, length) + a3_rec_hat(a + 1, length - 1));
}
I hope I've helped you :)
As a general rule, when you transform loops into recursion, every loop becomes a function and any non-local variables it uses become arguments.
Your original code is
int a3(int* a, int length) {
if(a == 0 || length <= 0) return 0;
int sum = 0;
for(int i = 0; i < length; i++) {
for(int j = i; j < length; j++) {
sum += a[j];
}
}
return sum;
}
Let's start with the innermost loop. It uses j, i, length, sum, and a from the surrounding scope.
void a3_loop0(int *pj, int length, int *psum, int *a) {
if (*pj < length) {
*psum += a[*pjj];
(*pj)++;
a3_loop0(pj, length, psum, a);
}
}
int a3(int* a, int length) {
if(a == 0 || length <= 0) return 0;
int sum = 0;
for(int i = 0; i < length; i++) {
int j = i;
a3_loop0(&j, length, &sum, a);
}
return sum;
}
This is a very literal and mechanical translation. Every mutable variable has become a pointer (in C++ you'd use references for this), which leads to somewhat ugly and non-functional code (well, code that doesn't use idiomatic functional style). But it works, and we can proceed to the next loop in the same way:
void a3_loop0(int *pj, int length, int *psum, int *a) {
if (*pj < length) {
*psum += a[*pj];
(*pj)++;
a3_loop0(pj, length, psum, a);
}
}
void a3_loop1(int *pi, int length, int *psum, int *a) {
if (*pi < length) {
int j = *pi;
a3_loop0(&j, length, psum, a);
(*pi)++;
a3_loop1(pi, length, psum, a);
}
}
int a3(int* a, int length) {
if(a == 0 || length <= 0) return 0;
int sum = 0;
int i = 0;
a3_loop1(&i, length, &sum, a);
return sum;
}
Technically we're done now, but there's a number of things we can clean up.
The first thing I'd do is to change the type of a to const int * because a3 never modifies any of its elements.
The second thing I'd do is to hoist the loop variables *pi / *pj into their functions; they don't really need to be pointers to mutable objects elsewhere.
void a3_loop0(int j, int length, int *psum, const int *a) {
if (j < length) {
*psum += a[j];
a3_loop0(j + 1, length, psum, a);
}
}
void a3_loop1(int i, int length, int *psum, const int *a) {
if (i < length) {
a3_loop0(i, length, psum, a);
a3_loop1(i + 1, length, psum, a);
}
}
int a3(const int *a, int length) {
if (a == 0 || length <= 0) return 0;
int sum = 0;
a3_loop1(0, length, &sum, a);
return sum;
}
This already simplifies and shortens the code a bit.
The next step is to actually return something from these helper functions. Currently they use *psum as an accumulator and return void. We can keep the use of an accumulator but return the result directly (instead of through an output parameter) as follows:
void a3_loop0(int j, int length, int sum, const int *a) {
if (j < length) {
return a3_loop0(j + 1, length, sum + a[j], a);
}
return sum; // this was implicit before; "return sum unchanged"
}
void a3_loop1(int i, int length, int sum, const int *a) {
if (i < length) {
return a3_loop1(i + 1, length, a3_loop0(i, length, sum, a), a);
}
return sum; // ditto
}
int a3(const int *a, int length) {
if (a == 0 || length <= 0) return 0;
return a3_loop1(0, length, 0, a);
}
This version of the code is "purely functional" in that it never modifies any variables; it only passes and returns values to and from functions, respectively.
If we wanted to, we could get rid of all if statements and write everything as expressions:
void a3_loop0(int j, int length, int sum, const int *a) {
return j < length
? a3_loop0(j + 1, length, sum + a[j], a)
: sum;
}
void a3_loop1(int i, int length, int sum, const int *a) {
return i < length
? a3_loop1(i + 1, length, a3_loop0(i, length, sum, a), a)
: sum;
}
int a3(const int *a, int length) {
return a == 0 || length <= 0
? 0
: a3_loop1(0, length, 0, a);
}
I'll post this because I see the other answers use 1 function per loop which isn't necessary.
You can have just 1 recursive function:
int a3_impl(int* a, int length, int i, int j)
{
if (i >= length)
return 0;
if (j >= length)
return a3_impl(a, length, i + 1, i + 1);
return a[j] + a3_impl(a, length, i, j + 1);
}
int a3(int* a, int length)
{
if(a == 0 || length <= 0)
return 0;
return a3_impl(a, length, 0, 0);
}
I have no idea what's wrong with the function goes by the name "int Count_largest_even". It's supposed to take the largest digit found in the given array (by the function "int find") and find how many times the digit appears in the array.
#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int Count_largest_even(int size, int *array, int large);
void ArrayPrint(int a[], int size);
int find(int array[], int size);
int arr1[16] = { 2, 22, 1, 3, 24, 94, 93, 12, 12, 66666, 21, 24, 8888, 21, 2, 33 };
int main() {
int mount;
int even;
ArrayPrint(arr1,16);
even = find(arr1, 16);
mount = Count_largest_even(16, arr1, even);
printf("\n The biggest even digit is : %d\n %d", even,mount);
system("pause");
return 0;
}
int find(int array[], int size){
int i = 0, digit, edigit = 0;
for (i = 0; i<size; i++){
while (array[i]!=0)
{
digit = abs(array[i] % 10);
if (digit > edigit)//checking condition for large
{
if (digit % 2 == 0)
{
edigit = digit;
}
}
array[i] = array[i] / 10;
}
}
return edigit;
}
void ArrayPrint(int a[], int size)
{
int i;
for (i = 0; i<size; i++){
printf("%d\n", a[i]);
}
}
int Count_largest_even(int size, int *array, int large)
{
int i;
int count = 0, digit;
for (i = 0; i < size; i++){
while ((array[i]!=0))
{
digit = abs(array[i] % 10);
if (digit == large)
{
count++;
}
array[i] = array[i] / 10;
}
}
return count;
}
As Ian Abbott said, you should not modify the array inside your loop.
But you can also do this in a single pass - some pseudo code:
int count = 0;
int largest_digit = 0;
for each digit:
if(digit > largest_digit) {
largest_digit = digit;
count = 1;
}
else if(digit == largest_digit)
count++;
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
}
}