0

how to check how many times the function or the recuresion is been runed in C?

i want to check how many times recursion is happened in this program? #include <stdio.h> void printArray(int *A, int n) { for (int i = 0; i < n; i++) { printf("%d ", A[i]); } printf("\n"); } void merge(int A[], int mid, int low, int high) { int i, j, k, B[100]; i = low; j = mid + 1; k = low; while (i <= mid && j <= high) { if (A[i] < A[j]) { B[k] = A[i]; i++; k++; } else { B[k] = A[j]; j++; k++; } } while (i <= mid) { B[k] = A[i]; k++; i++; } while (j <= high) { B[k] = A[j]; k++; j++; } for (int i = low; i <= high; i++) { A[i] = B[i]; } } void mergeSort(int A[], int low, int high){ int mid; if(low<high){ mid = (low + high) /2; mergeSort(A, low, mid); mergeSort(A, mid+1, high); merge(A, mid, low, high); } } int main() { // int A[] = {9, 14, 4, 8, 7, 5, 6}; int A[] = {9, 1, 4, 14, 4, 15, 6}; int n = 7; printArray(A, n); mergeSort(A, 0, 6); printArray(A, n); return 0; }

31st May 2021, 10:52 AM
Dershil Jadav
Dershil Jadav - avatar
3 Respostas
+ 1
If it's for debugging purpose then better use a debugger to find out the same. If you want to make it a feature of some sort then just like YUGRAJ said, make a counter ( keep it global or more preferably static ) and then increment it on every iteration.
31st May 2021, 11:09 AM
Arsenic
Arsenic - avatar
+ 1
Global variables should be avoided at all costs. If you don't want to use a debugger, just declare a static int that you increment when the function is called. // Example code: static int s_IterationCount = 0; // Explanation of static: When a normal local variable is declared, it goes out of scope when a function ends execution. Declaring a variable as "static" allows the variable to persist after it goes out of scope. Thus, you can call the function once (s_IterationCount is 1 after execution), then it's called again (s_IterationCount is 2 now, because the variable persisted after the function ends returns, so the machine didn't reinitialize it). This works with recursion as well. // Why you should avoid non-const Global Variables Basically, non-const globals can be modified by any function, and in a larger program, one typo you don't catch could mean sifting through a lot of code finding the mistake you made. Static local variables do the job you want and reinforce good habits.
1st Jun 2021, 1:15 PM
Zibblobet
Zibblobet - avatar
0
Maybe declare a global variable and increment it in mergeSort function by that you can count it
31st May 2021, 11:04 AM
YUGRAJ