Completing my addarray () formula - c

I apologize for my vagueness in advance-this is my first post and I can really use some help.
The assignment is as follows:
/* Write a function named addarray() that returns the sum of the
elements of an array of int values. Your functions should take two
parameters, the array and the number of elements in the array. Make
your function work with the following program; */
/* arraysum.c
*
* Synopsis - displays the value returned by the function addarray()
* with 2 different sets of parameters.
*
* Objective - To provide a test program for the addarray() function.
* Your answers should be 55 and 0.
*
*/
#include <stdio.h>
int addarray(int [], int, int);
void main() {
int array1[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int array2[4] = {0, 0, 0, 0};
printf("The sum of array1 = %d\n", addarray(array1, 0, 10));
printf("The sum of array2 = %d\n", addarray(array2, 0, 4));
}
This is my solution aid:
int addarray(int s[], int i, int n) {
int sum = 0;
for (i = 0; i < n; i++) {
sum += s[i];
}
return sum;
}
I cant seem to figure out how to get the proper result. Any help would be appreciated.
This is what I have completed so far:
#include <stdio.h>
int addarray(int array1[], int num_elements);
void print_array(int array1[], int num_elements);
void main(void)
{
int array1[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int sum;
printf("\nArray:\n");
print_array(array1, 10);
sum = addarray(array1, 10);
printf("The sum is %d\n .", sum);
}
int addarray(int array1[], int num_elements)
{
int i, sum=0;
for (i=0; i<num_elements; i++)
{
sum = sum + array1[i];
}
return(sum);
}
void print_array(int array1[], int num_elements)
{
int i;
for(i=0; i<num_elements; i++)
{
printf("%d ", array1[i]);
}
printf("\n");
}
I cant figure out how to get a second array to be summed up.
Such as Array2.

int is a reserved word.you can't give a variable the name int.besides,the assignment says the function should take two parameters,not 3.check this :
#include <stdio.h>
int addarray(int arr[],int size);
void main() {
int array1[10] = {1,2,3,4,5,6,7,8,9,10};
int array2[4] = {0,0,0,0};
printf("The sum of array1 = %d\n", addarray(array1,10));
printf("The sum of array2 = %d\n", addarray(array2,4));
}
int addarray(int arr[],int size)
{
int sum = 0 , n ;
for( n = 0 ; n < size ; n++ )
{
sum += arr[n];
}
return sum;
}

Related

Find max, min and sum of an array using function

I want to create a programm to find maximum, minimum and summation for a given array, but when I take my code to compiler, it returned expressed expression before 'int' and too few arguments to all the functions.
And here is my code, please tell me why it doesn't work.
#include <stdio.h>
#include <stdlib.h>
void print_array(int array[], int len) {
// print array on screen
int b;
printf("Array: ");
for (b = 0; b < len - 1; b++) {
printf("%d, ", array[b]);
}
if (b >= len - 1) {
printf("%d\n", array[b]);
}
}
// function
int min(int *x, int len) {
int mintemp = x[0], i;
for (i = 1;i < len;i++) {
if(x[i] < mintemp) {
mintemp = x[i];
}
}
return mintemp;
}
int max(int *y, int len) {
int maxtemp = y[0], j;
for (j = 1;j < len;j++) {
if(y[j] > maxtemp) {
maxtemp = y[j];
}
}
return maxtemp;
}
int sum(int *z, int len) {
int sumtemp = 0, k;
for (k = 0;k < len;k++) {
sumtemp = sumtemp + z[k];
}
return sumtemp;
}
int main() {
int array[] = {3, 9, 1, 2, 5, 8, 7, 6, 4, 10, 11};
int len = 11;
print_array(array, len);
// print other elements on screen
printf("Maximum: %d\n", max(int *x, int len));
printf("Minimum: %d\n", min(int *y, int len));
printf("Summation: %d\n", sum(int *z, int len));
return 0;
}
The problem was with calling the functions. Function call in C is like this
function_name(argument 1, argument 2, argument 3, ......, argument n);
There is no need to specifying the data type along the parameters in the call like you were doing in your code.
Also you were passing pointers x, y and z that do not point to your array.
I have corrected the code as shown below.
int main() {
int array[] = {3, 9, 1, 2, 5, 8, 7, 6, 4, 10, 11};
int len = 11;
print_array(array, len);
// print other elements on screen
printf("Maximum: %d\n", max(array, len)); // pass array and len
printf("Minimum: %d\n", min(array, len));
printf("Summation: %d\n", sum(array, len));
return 0;
}
If you want to pass the array to functions via pointers you can do it like this.
int main() {
int array[] = {3, 9, 1, 2, 5, 8, 7, 6, 4, 10, 11};
int len = 11;
int *x = array;
int *y = array;
int *z = array;
print_array(array, len);
// print other elements on screen
printf("Maximum: %d\n", max(x, len));
printf("Minimum: %d\n", min(y, len));
printf("Summation: %d\n", sum(z, len));
return 0;
}
Also there is no need to declare 3 different pointers and pass it to the functions, you can declare just one and reuse it with subsequent calls.
Hope this helps.!!

How to merge array elements with token merging ## operator???

I want to merge 3, 7, 1 to get 371. I want to know how to merge it???
#include <stdio.h>
int main(void)
{
int a[] ={3, 7, 1};
return(0);
}
I think rather than "merge", you want to convert array into an integer value, just like join operation that we see in Java variants. You can easily achieve this by iterating over the array :
#include <stdio.h>
int joinArray(int a[], int N) {
int i, res = 0;
for(i = 0; i < N; i++)
res = res*10 + a[i];
return res;
}
int main() {
int a[] = {3, 7, 1};
printf("merged res : %d\n", joinArray(a, 3));
return 0;
}
You could try something like this;
#include <stdio.h>
int main(void)
{
int a[] ={3, 7, 1};
int i, result = 0;
for(i=0;i<sizeof(a)/sizeof(a[0]);i++)
result += a[i] * pow(10, sizeof(a)/sizeof(a[0])-i-1);
printf("result %d\n", result);
return(0);
}

largest sum contiguous sub array using recursion to directly output result

Is is possible to find the largest sum contiguous sub array using recursion such that the function would directly return the output.
Below is my solution where I store the max subarray ending at each index and then find the largest among those in the print() function. However, I want the following
Use recursion
Use the recursive function to directly output the final result.
My code which uses a recursive function and a helper print() function to find the largest among those numbers
#include <stdio.h>
//int a[] = {-6,60,-10,20};
int a[] = {-2, -3, 4, -1, -2, 1, 5, -3};
int len = sizeof(a)/sizeof(*a);
int maxherearray[10];
int main(void)
{
fun(len-1);
printf("max sub array == %d\n",print(maxherearray));
printf("\n");
return 0;
}
int fun(int n)
{
if(n==0)
return a[n];
maxherearray[n] = max(a[n], a[n]+fun(n-1));
return maxherearray[n];
}
int max(int a, int b)
{
return (a > b)? a : b;
}
EDIT : Posting the print() function which I somehow missed out
//Please make sure that #include <limits.h> is added
int print(int a[])
{
int i = 0;
int largest = INT_MIN;
printf("largest == %d\n",largest);
for(i=0;i<len;i++)
{
if(a[i] > largest)
largest = a[i];
}
return largest;
}
Generally, your algorithm logic is OK. It's like,
f(0) = a(i);
f(i) = max(f(i-1) + a(i), a(i));, get the middle result array
max(0, f(1), f(2), ... , f(n-1)), get the final max_sub result
And you designed a function namedfun for #2, and a helper print() for #3.
Now, (I guess ) what you'd like is to combine #2 and #3 together, i.e., to utilise the middle results of #2 to avoid extra computing/memory space. In terms of your original algorithm logic, here are some possible ways, such as
Add a parameter in your fun to keep max_sub result
int fun(int n, int *result)// add int *result to return max_sub
{
int max_here = 0;
if(n==0){
return a[n];
}
max_here = max(a[n],a[n]+fun(n-1, result));
*result = max(*result, max_here);
return max_here;
}
//...
int main(void)
{
int result = 0;
fun(len-1, &result);
printf("max sub : %d\n", result);
}
Use a global variable (Oh!) to get max_sub in time
int g_maxhere = 0;
int fun2(int n)
{
if(n==0){
return a[n];
}
g_maxhere = max(g_maxhere, max(a[n],a[n]+fun2(n-1)));
return max(a[n], a[n]+fun2(n-1));
}
//...
int main(void)
{
fun2(len-1);
printf("max sub:%d\n",g_maxhere)
}
In fact, your original solution of using a helper function can make your algorithm more clear.
Introduce two global variables, start_idx and end_idx to track the start and end indices of the largest contiguous subarray. Update these variables accordingly in the recursive function.
#include <stdio.h>
/* int a[] = {-6,60,-10,20}; */
int a[] = {-2, -3, 4, -1, -2, 1, 5, -3};
int len = sizeof(a)/sizeof(*a);
int maxherearray[10];
int fun(int n);
int max(int a, int b);
int find_max(int a[], int len);
void print_array(int a[], int start_idx, int end_idx);
int start_idx = 0; // Start of contiguous subarray giving max sum
int end_idx = 0; // End of contiguous subarray giving max sum
#define NEG_INF (-100000)
int max_sum = NEG_INF; // The max cont sum seen so far.
int main(void)
{
start_idx = 0;
end_idx = len - 1;
maxherearray[0] = a[0];
printf("Array a[]: ");
print_array(a, 0, len-1);
printf("\n");
// Compute the necessary information to get max contiguous subarray
fun(len - 1);
printf("Max subarray value == %d\n", find_max(maxherearray, len));
printf("\n");
printf("Contiguous sums: ");
print_array(maxherearray, 0, len - 1);
printf("\n");
printf("Contiguous subarray giving max sum: ");
print_array(a, start_idx, end_idx);
printf("\n\n");
return 0;
}
int fun(int n)
{
if(n==0)
return a[0];
int max_till_j = fun(n - 1);
// Start of new contiguous sum
if (a[n] > a[n] + max_till_j)
{
maxherearray[n] = a[n];
if (maxherearray[n] > max_sum)
{
start_idx = end_idx = n;
max_sum = maxherearray[n];
}
}
// Add to current contiguous sum
else
{
maxherearray[n] = a[n] + max_till_j;
if (maxherearray[n] > max_sum)
{
end_idx = n;
max_sum = maxherearray[n];
}
}
return maxherearray[n];
}
int max(int a, int b)
{
return (a > b)? a : b;
}
// Print subarray a[i] to a[j], inclusive of end points.
void print_array(int a[], int i, int j)
{
for (; i <= j; ++i) {
printf("%d ", a[i]);
}
}
int find_max(int a[], int len)
{
int i;
int max_val = NEG_INF;
for (i = 0; i < len; ++i)
{
if (a[i] > max_val)
{
max_val = a[i];
}
}
return max_val;
}

Count the number of times a number appears in an array

I'm working on a small program that counts the number of times an integer appears in an array.
I managed to do this but there is one thing I can't overcome.
My code is:
#include <stdio.h>
int count_occur(int a[], int num_elements, int value);
void print_array(int a[], int num_elements);
void main(void)
{
int a[20] = {2, 5, 0, 5, 5, 66, 3, 78, -4, -56, 2, 66, -4, -4, 2, 0, 66, 17, 17, -4};
int num_occ, i;
printf("\nArray:\n");
print_array(a, 20);
for (i = 0; i<20; i++)
{
num_occ = count_occur(a, 20, a[i]);
printf("The value %d was found %d times.\n", a[i], num_occ);
}
}
int count_occur(int a[], int num_elements, int value)
/* checks array a for number of occurrances of value */
{
int i, count = 0;
for (i = 0; i<num_elements; i++)
{
if (a[i] == value)
{
++count; /* it was found */
}
}
return(count);
}
void print_array(int a[], int num_elements)
{
int i;
for (i = 0; i<num_elements; i++)
{
printf("%d ", a[i]);
}
printf("\n");
}
My output is :
Array:
2 5 0 5 5 66 3 78 -4 -56 2 66 -4 -4 2 0 66 17 17 -4
The value 2 was found 3 times.
The value 5 was found 3 times.
The value 0 was found 2 times.
The value 5 was found 3 times.
The value 5 was found 3 times.
The value 66 was found 3 times.
The value 3 was found 1 times.
The value 78 was found 1 times.
The value -4 was found 4 times.
The value -56 was found 1 times.
The value 2 was found 3 times.
The value 66 was found 3 times.
The value -4 was found 4 times.
The value -4 was found 4 times.
The value 2 was found 3 times.
The value 0 was found 2 times.
The value 66 was found 3 times.
The value 17 was found 2 times.
The value 17 was found 2 times.
The value -4 was found 4 times.
How can I avoid double lines in the output?
You can use a parallel array, this example uses char[20] in order to save some space:
#include <stdio.h>
int count_occur(int a[], char exists[], int num_elements, int value);
void print_array(int a[], int num_elements);
int main(void) /* int main(void), please */
{
int a[20] = {2, 5, 0, 5, 5, 66, 3, 78, -4, -56, 2, 66, -4, -4, 2, 0, 66, 17, 17, -4};
char exists[20] = {0}; /* initialize all elements to 0 */
int num_occ, i;
printf("\nArray:\n");
print_array(a, 20);
for (i = 0; i < 20; i++)
{
num_occ = count_occur(a, exists, 20, a[i]);
if (num_occ) {
exists[i] = 1; /* first time, set to 1 */
printf("The value %d was found %d times.\n", a[i], num_occ);
}
}
}
int count_occur(int a[], char exists[], int num_elements, int value)
/* checks array a for number of occurrances of value */
{
int i, count = 0;
for (i = 0; i < num_elements; i++)
{
if (a[i] == value)
{
if (exists[i] != 0) return 0;
++count; /* it was found */
}
}
return (count);
}
void print_array(int a[], int num_elements)
{
int i;
for (i = 0; i<num_elements; i++)
{
printf("%d ", a[i]);
}
printf("\n");
}
This method is faster, as it skips values already readed and starts iterating from i in count_ocurr:
#include <stdio.h>
int count_occur(int a[], char map[], int num_elements, int start);
void print_array(int a[], int num_elements);
int main(void)
{
int a[20] = {2, 5, 0, 5, 5, 66, 3, 78, -4, -56, 2, 66, -4, -4, 2, 0, 66, 17, 17, -4};
char map[20] = {0};
int num_occ, i;
printf("\nArray:\n");
print_array(a, 20);
for (i = 0; i < 20; i++)
{
if (map[i] == 0) {
num_occ = count_occur(a, map, 20, i);
printf("The value %d was found %d times.\n", a[i], num_occ);
}
}
}
int count_occur(int a[], char map[], int num_elements, int start)
/* checks array a for number of occurrances of value */
{
int i, count = 0, value = a[start];
for (i = start; i < num_elements; i++)
{
if (a[i] == value)
{
map[i] = 1;
++count; /* it was found */
}
}
return (count);
}
void print_array(int a[], int num_elements)
{
int i;
for (i = 0; i< num_elements; i++)
{
printf("%d ", a[i]);
}
printf("\n");
}
I would suggest only printing the statement if the current index is also the index of the first occurrence of the number in question.
Inside count_occur, you have the index of each match in i. If you pass in the i from main to count_occur, you can do something such as returning -1 if that value is greater than the i in count_occur. Then if you get that -1 in main, don't print.
In addition, your algorithm could be made faster. Instead of searching the array linearly every time, you can sort a copy of the array so that the search can be done efficiently. (Even if you use one array to index and the other to search, it'll be faster - and still return values in the same order.)
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
int count_occur(int a[], int num_elements, int value, bool selected[]);
void print_array(int a[], int num_elements);
int main(void){
int a[] = {2, 5, 0, 5, 5, 66, 3, 78, -4, -56, 2, 66, -4, -4, 2, 0, 66, 17, 17, -4};
int size = sizeof(a)/sizeof(*a);
bool ba[size];
memset(ba, 0, sizeof ba);
int num_occ, i;
printf("\nArray:\n");
print_array(a, size);
for (i = 0; i<size; i++){
if(ba[i] == true) continue;//skip already count
num_occ = count_occur(a, 20, a[i], ba);
printf("The value %d was found %d times.\n", a[i], num_occ);
}
}
int count_occur(int a[], int num_elements, int value, bool ba[]){
int i, count = 0;
for (i = 0; i<num_elements; i++){
if (a[i] == value){
ba[i] = true;
++count;
}
}
return count;
}
void print_array(int a[], int num_elements){
int i;
for (i = 0; i<num_elements; i++){
printf("%d ", a[i]);
}
printf("\n");
}
Little improvement
int count_occur(int a[], int num_elements, int index, bool selected[]);
num_occ = count_occur(a, 20, i, ba);
int count_occur(int a[], int num_elements, int index, bool ba[]){
int i, count = 0;
for (i = index; i<num_elements; i++){
if (a[i] == a[index]){
ba[i] = true;
++count;
}
}
return count;
}
#include<stdio.h>
#include<string.h>
int main()
{
int arr[] = {2, 5, 0, 5, 5, 66, 3, 78, -4, -56, 2, 66, -4, -4, 2, 0, 66, 17, 17, -4};
int arrSize = sizeof(arr)/sizeof(arr[0]);
int tracker[20];
int i,j,k=0,l=0,count,exists=0;
for (i=0;i<arrSize;i++)
printf("%d\t", arr[i]);
printf("\n");
memset(tracker, '$', 20);
for (i=0, j=i+1, count=1, l=0; i<arrSize; i++)
{
j=i+1;
count=1;
l=0;
while (l < arrSize)
{
if (arr[i] == tracker[l])
{
exists = 1;
break;
}
l++;
}
if (1 == exists)
{
exists = 0;
continue;
}
while (j < arrSize)
{
if (arr[i] == arr[j])
count++;
j++;
}
tracker[k] = arr[i];
k++;
printf("count of element %d is %d\n", arr[i], count);
}
}
very simple logic to count how many time a digit apper
#include<stdio.h>
int main()
{
int a,b,c,k[10];
int p[10]={0};
int bb[10]={0};
scanf("%d\n",&a);
for(b=0;b<a;b++)
{
scanf("%d",&k[b]);
}
for(b=a-1;b>0;b--)
{
for(c=b-1;c>=0;c--)
{
if((k[b]==k[c])&&(bb[c]==0))
{
p[b]=p[b]+1;
bb[c]=1;
}
}
}
for(c=0;c<a;c++)
{
if(p[c]!=0)
{
printf("%d is coming %d times\n",k[c],p[c]+1);
}
}
return 0;
}
In your function :
int count_occur(int a[], int num_elements, int value)
/* checks array a for number of occurrances of value */
{
int i, count = 0;
for (i = 0; i<num_elements; i++)
{
if (a[i] == value)
{
++count; /* it was found */
a[i] = INFINITY; // you can typedef INFINITY with some big number out of your bound
}
}
return(count);
}
And in main() you can edit for loop:
for (i = 0; i<20; i++)
{
if(a[i] != INFINITY)
{
num_occ = count_occur(a, 20, a[i]);
printf("The value %d was found %d times.\n", a[i], num_occ);
}
}
It is possible to solve with two arrays
#include <stdio.h>
int main() {
int array[12] = {1,2,2,5,2,5,7,6,2,4,2,4};
int array2[100] = {0};
int indicator = 1;
int i = 0,j;
int index = 0;
int number_count;
for(int i = 0; i<12;i++) {
indicator = 1;
for(j = i+1;j<12;j++) {
if(array[i] == array[j]){
indicator = -1;
break;
}
}
if(indicator == 1){
array2[index] = array[i];
index++;
}
}
for(int k = 0; array2[k]; k++) {
number_count = 0;
for(int m = 0; m<12;m++){
if(array2[k] == array[m]){
number_count++;
}
}
printf("%d was found %d times...\n",array2[k],number_count);
}
return 0;
}

C recursive permutations

i have been trying to complete figure out this part of my assignment to no avail for the past day, and require some help or guidance to help understand the problem.
so far i have this:
swap(int A, int B){
int temp;
temp = A;
A = B;
B = temp;
}
int max_array(int array[], int arraySize)
{
int i, max=-32000;
for (i=0; i<arraySize; i++)
{
if (array[i]>max)
{
max=array[i];
}
}
printf("%d \n Max array: ", max)
return(max);
}
int nextPermutation(int array[], int arraySize){
int i;
n = max_array(array, arraySize);
if (int i; n == array[i] && i > 1; i++){
swap(array[i], array[i-1]);
}
else if(int i; n == array[i]; i++){
}
}
void main(){
int intArray[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
//int intArray[10] = {1, 10, 3, 9, 8, 6, 7, 2, 4, 5};
nextPermutation(intArray, 10);
int i = 0;
for(i = 0; i < 10; i++){
printf("%d ",intArray[i]);
}
}
But the question that i'm struggling to understand is
"If a1,...,an is an arbitrary permutation (where a1,...,an are the numbers 1, 2, …, n in a probably different order) then the “next” permutation is produced by the
following procedure:
(i) If the maximal element of the array (which is n) is not the first element of the
array, say n=ai , where i>1 , then to produce the "next" permutation you
need to swap ai and ai−1 .
(ii) If the maximal element of the array is in the first position, i.e. n=a1 , then to
produce the “next” permutation to the permutation (a1,...,an)
, first find the “next” permutation to the (n-1)-element permutation (a2,...,an
), and then append a1 to the end of thus obtained array of (n-1) elements."
so it needs to permutate every single possible combination with the array of 1,2,3,4,5,6,7,8,9,10 and then finish when it reaches this point "(n, …, 2, 1). And this is
the only permutation that does not have the "next" permutation to it."
And the function int 'nextPermutation(int array[], int arraySize){' needs to stay the same.
Any help or tips will be excellent!
There are some errors in your program,
swap() function will not affect the program as it doesn't use pass by reference.
max_array() should find the index of the maximum value, not the maximum value itself.
There is no recursion in your program as far as I can see.
main() should return int.
The program fragement given below might give you an idea,
int ct=-1,n=10,temp[10]={0,0,0,0,0,0,0,0,0,0};
int intArray[10]={1,2,3,4,5,6,7,8,9,10};
permute(int k)
{
int i;
temp[k]=++ct;
if(ct==n-1)
{
for(i=0;i<n;i++)
{
printf("%d",intArray[temp[i]]);
}
printf("\n");
}
for(i=0;i<n;i++)
{
if(temp[i]==0)
{
permute(i);
}
}
ct--;
temp[k]=0;
}
int main()
{
permute(0);
}
for swap sample
#include <stdio.h>
void swap(int* A, int* B){
int wk;
wk = *A;
*A = *B;
*B = wk;
}
int main(void){
int array[] = { 1,2,3 };
swap(&array[0], &array[2]);
printf("array[0]=%d, array[2]=%d\n", array[0], array[2]);
return 0;
}

Resources