Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
in visuals studio i try to make respectively sum of rows. but first sum multiplied by 4 . i didnt understand this situation
get_sum(int **q, int p, int n);
int main(void)
{
int num[3][5] = { 10,11,12,13,14,15,16,17,18,19,20,21,22,23,24 };
get_sum(&num[0][0], 3, 5);
}
get_sum(int **q, int p, int n)
{
/*for (int i = 0; i < ; i++)
printf("%d\n", *(q + i));*/
for (int k = 0; k < p; k++)
{
int sum = 0;
for (int i = 0; i < n; i++)
{
sum =*(q + n*k + i)+sum;
printf("%d\n", sum);
}
}
}
If I understand you simply want to create a function that sums the elements of the array passed as a parameter, along with the dimensions of the array, then you have the right idea, but woefully wrong syntax.
Rather than verbally discussing each change, the simple example contains all the changes. Look over the changes and why they were made:
#include <stdio.h>
int get_sum (int (*q)[5], int p, int n);
int main (void)
{
int num[3][5] = {{ 10, 11, 12, 13, 14 },
{ 15, 16, 17, 18, 19 },
{ 20, 21, 22, 23, 24 }};
int sum = get_sum (num, 3, 5);
printf (" -----------\n sum : %d\n", sum);
return 0;
}
int get_sum (int (*q)[5], int p, int n)
{
int sum = 0;
for (int k = 0; k < p; k++) {
for (int i = 0; i < n; i++)
sum += q[k][i];
printf ("row[%2d] : %d\n", k, sum);
}
return sum;
}
(note: the loop output within get_sum provides are running-total of the sum after the addition of each row elements. You can tailor this to meet your needs.)
Example Use/Output
$ ./bin/get_sum
row[ 0] : 60
row[ 1] : 145
row[ 2] : 255
-----------
sum : 255
Let me know if you have any questions.
You are indexing a 1-D array as if it is a 2-D array, but there is no need to define it as 2-D, and anyway, you initialise it as if it were a 1-D array.
#include <stdio.h>
void get_sum(int *q, int p, int n); // only one start
int main(void)
{
int num[] = { 10,11,12,13,14,15,16,17,18,19,20,21,22,23,24 }; // 1-D linear array
get_sum(num, 3, 5);
return 0;
}
void get_sum(int *q, int p, int n) // added return type
{
int k, i, sum;
for (k = 0; k < p; k++) {
sum = 0;
for (i = 0; i < n; i++) {
sum = *(q + n*k + i) + sum;
}
printf("%d\n", sum); // moved out of inner loop
}
}
Program output
60
85
110
Alternatively if you do want a 2-D array and then index into it as if it were a 1-D array, you can do this. Note I have initialised the array differently but get_sum is the same.
#include <stdio.h>
void get_sum(int *q, int p, int n); // only one start
int main(void)
{
int num[3][5] = {{10,11,12,13,14}, {15,16,17,18,19}, {20,21,22,23,24}};
get_sum(&num[0][0], 3, 5);
return 0;
}
void get_sum(int *q, int p, int n) // added return type
{
int k, i, sum;
for (k = 0; k < p; k++) {
sum = 0;
for (i = 0; i < n; i++) {
sum = *(q + n*k + i) + sum;
}
printf("%d\n", sum); // moved out of inner loop
}
}
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I've got a problem. I've tried to write program. This is command:
The user specifies a whole number n>0.
Program:
Allocates two arrays of numbers of type int size n+1
Using only these arrays and a small number of statically allocated variables, the program calculates recursively the n line of the Pascal triangle (all binomial symbols with an upper parameter equal to n)
Prints out the calculated values
Memory slowing down
Example
input: 5
output: 1 5 10 10 5 1
I wrote iteration, but I have no idea how change this for recursion.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n,i,k;
int * array_1;
int * array_2;
scanf("%d",&n);
if(n=='0') printf("%d", 1);
if(n=='1') printf("%d %d", 1, 1);
array_1 = (int*)calloc(n+1,sizeof(int));
array_2 = (int*)calloc(n+1,sizeof(int));
array_1[0] = 1;
array_1[1] = 1;
k=1;
while(k!=n)
{
for(i=0; i<=k+1; i++)
{
if(i==0)
{
array_2[0] = 1;
}
else if(i==n)
{
array_2[i] = 1;
}
else
{
array_2[i] = array_1[i] + array_1[i-1];
}
}
for(i=0; i<=n; i++)
{
array_1[i] = array_2[i];
array_2[i] = 0;
}
k++;
}
for(i=0; i<=n; i++)
{
printf("%d ", array_1[i]);
}
free(array_1);
free(array_2);
return 0;
}
The recursive version could look something like the following, with the actual work being left to fill-in under the two /* ... */ comments. The missing code essentially exists in the iterative version as posted, it just needs to be retrofitted here.
void recurse(int k, int n, int *array_1, int *array_2)
{
/*
print previously calculated k-th row in array_1
*/
// nothing left to do
if (k == n + 1) return;
/*
calculate next (k+1)-th row in array_2
*/
// swap arrays and repeat
recurse(k + 1, n, array_2, array_1);
}
int main()
{
int n, *array_1, *array_2;
if(scanf("%d", &n) != 1) return 1; // input error
if (n < 0) return 1; // invalid input
array_1 = (int*)calloc(n + 1, sizeof(int));
array_2 = (int*)calloc(n + 1, sizeof(int));
array_1[0] = 1;
recurse(1, n, array_1, array_2);
free(array_1);
free(array_2);
return 0; // done
}
Thanks everyone for answer :). This is my code:
#include <stdio.h>
#include <stdlib.h>
void recurse (int k, int n, int *array_1, int *array_2)
{
int i;
if(k==n+1) return;
for(i=1; i<=k+1; i++) array_2[i] = array_1[i] + array_1[i-1];
recurse(k+1, n, array_2, array_1);
}
void output(int n, int *array_1, int *array_2)
{
int i;
if(n%2!=0)
for(i=0; i<=n; i++) printf("%d ", array_1[i]);
else
for(i=0; i<=n; i++) printf("%d ", array_2[i]);
}
int main()
{
int n;
int * array_1;
int * array_2;
scanf("%d",&n);
if(n=='0')
{
printf("%d", 1);
return 0;
}
else if(n=='1')
{
printf("%d %d", 1, 1);
return 0;
}
array_1 = (int*)calloc(n+1,sizeof(int));
array_2 = (int*)calloc(n+1,sizeof(int));
array_1[0] = array_1[1] = array_2[0] = 1;
recurse(1, n, array_1, array_2);
output(n, array_1, array_2);
free(array_1);
free(array_2);
return 0;
}
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;
}
I have two integer lists say list_a and list_b.
I have a function say func(), and func(list_a) would produce n lists say:
list_a_1 list_a_2 list_a_3 list_a_4 ........... list_a_n
I have to run func() on all lists as produced above until I find one of those lists = list_b.
So below could be the possible representation of how the list grows:
list_a
============================================================================
list_a_1 list_a_2 list_a_3 list_a_4 ........... list_a_n LEVEL 1
============================================================================
list_a_1_1.... list_a_1_n list_a_2_1... list_a_2_n..... LEVEL 2
============================================================================
Suppose say we find list_a_1_n == list_b, then stop the function and return the LEVEL, which in our case is 2 (Level2).
I am not being able to do it :(
How to do it in C?
Please note, this is not a homework question.
I am trying to find Cyclic Kendal Tau distance between two inputs as I think I found a solution in terms of algorithm for this question. I want to check whether my algorithm is correct.
below is the code in Python:
import collections
def Transpose(alist):
leveloutput = []
n = len(alist)
for i in range(n):
x=alist[:]
x[i],x[(i+1)%n] = x[(i+1)%n],x[i]
leveloutput.append(x)
return leveloutput
def Cyc_Ken_Tau(start, goal):
queue = collections.deque([(start, 0)])
while True:
element, level = queue.popleft()
if element == goal:
return level
for new_list in Transpose(element):
queue.append((new_list, level + 1))
if __name__ == '__main__':
print "***********************************************************"
u = [2, 3, 4, 1]
v = [1, 2, 4, 3]
print "***********************************************************"
m = Cyc_Ken_Tau(u,v)
print "Cyclic Kendal Tau:",m
Also the partial code in C is as follows:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void print_array(int **a, int num_elements);
int **transpose(int n, int arr[n]);
int main(){
int a[] = {2, 3, 4, 1};
int **c;
int n = sizeof(a)/sizeof(*a);
int i;
printf("original\n");
print_array2(a,4);
printf("\n*****************************\n");
c= transpose(n, a);
print_array(c, n);
//deallocate
for(i=0;i<n;++i)
free(c[i]);
free(c);
return 0;
}
int **transpose(int n, int arr[n]){
int l = n;
int **b = malloc(l * sizeof(*b));//sizeof(*b) : sizeof(int *)
int i, j, k;
for (i = 0; i < l; i++) {
j = (i + 1) % l;
int *copy = malloc(l * sizeof(*copy));//sizeof(int)
for (k = 0; k < l; k++)
copy[k] = arr[k];
int t = copy[i];
copy[i] = copy[j];
copy[j] = t;
//printf("{%d, %d, %d, %d}\n", copy[0], copy[1], copy[2], copy[3]);
b[i] = copy;
}
return b;
}
void print_array(int **a, int num_elements){
int i, j;
for(i=0; i<num_elements; i++){
for(j=0; j<num_elements; j++)
printf("%d ", a[i][j]);
printf("\n");
}
}
void print_array2(int a[], int num_elements)
{
int i;
for(i=0; i<num_elements; i++)
{
printf("%d ", a[i]);
}
printf("\n");
}
But I am struggling with the Cyc_Ken_Tau function in C. Any help will be much much appreciated.
Let's say we have an array of m elements and we want to change randomly the position of exactly n of them, where of course 2 <= n <= m.
For example: if we have this array of 10 ints {1 2 3 4 5 6 7 8 9 10} and we ask for 4 of its elements to change positions randomly, a result could be {3 2 1 4 5 6 10 8 9 7}
What is the simplest way to program this in ANSI C? (pseudocode will also be just fine)
Step1). Generate a list of n random unique numbers between 1 and m. This list should NOT be sorted. Eg, for your example, the list could have been [10,7,1,3]
Step 2) do something like :
int save = array[list[0]];
For (i=0; i<n-1; i++) {
Array[list[i]] = array[list[i+1]];
}
Array[list[n-1]] = save;
Edit: actually, you'll have to have subtract 1 from each list[whatever] to allow for zero-based arrays - but I'm sure you get the idea :)
since at least two numbers must be swapped, i would pick two random numbers from array first and then swap them. they are added to array that holds swapped indexes. if there's more to swap, pick another number different than swapped ones and swap it with one of the previously swapped numbers.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void print_arr(int a[], int size) {
int i;
for (i = 0; i < size; i++) {
printf("%d ",a[i]);
}
printf("\n");
}
void swap(int a[], int i, int j) {
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
int next_idx(int swapped[], int s_count, int size) {
int n, i;
char in_arr;
while (1) {
in_arr = 0;
n = rand() % size;
for (i = 0; i < s_count; i++) {
if (swapped[i] == n) {
in_arr = 1;
break;
}
}
if (!in_arr) {
break;
}
}
return n;
}
void swap2_or_more(int a[], int size,int count) {
srand(time(NULL));
int i, j, s_count = 0;
int swapped[size];
i = rand() % size;
swapped[s_count] = i;
s_count++;
do {
j = rand() % size;
} while (i == j); // make sure indexes are different
swapped[s_count] = j;
s_count++;
swap(a, i, j);
count -= 2;
while (count) {
i = next_idx(swapped, s_count, size);
j = rand() % s_count;
swap(a, i, swapped[j]);
swapped[s_count] = i;
s_count++;
count--;
}
printf("swapped indexes:\n");
print_arr(swapped, s_count);
}
int main(void)
{
int a[] = {1,2,3,4,5,6,7,8,9,10};
swap2_or_more(a, 10, 5);
printf("array after swap:\n");
print_arr(a, 10);
return 0;
}
#include "stdio.h"
void main(){
int a[2][2]={1, 2, 3, 4};
int a[2][2]={1, 2, 3, 4};
display(a, 2, 2);
show(a, 2, 2);}
}
display(int *k, int r, int c){
int i, j, *z;
for(i = 0; i < r; i++){
z = k + i;
printf("Display\n");
for(j = 0; j < c; j++){
printf("%d", *(z + j));
}
}
}
show(int *q, int ro, int co){
int i, j;
for(i = 0; i < ro; i++){
printf("\n");
for(j = 0; j < co; j++){
printf("%d", *(q + i*co + j));
}
}
}
Output:
Display
12
23
Show
12
34
Why Display() is not showing 1223 while show() gives 1234? Both uses the same logic to display the 2d array. Can any one help please?
In display you are using two counters, i for rows and j for columns. Since the array is laid out sequentially in memory you need to increase i by the size of a column, i.e. c, each time you want to move from one row to the next. So, you should add i*c to k, not i.
The complete function:
display(int *k,int r,int c){
int i,j,*z;
for(i=0;i<r;i++){
z=k+i*c;
printf("Display\n");
for(j=0;j<c;j++){
printf("%d",*(z+j));
}
}
}
To access 2D array using pointers:
#define R 2
#define C 2
...
int A[R][C]={1, 2, 3, 4};
for(i=0;i<R;i++)
for(j=0;j<C;j++)
printf("%d ",*(*(A+i)+j));
...