Using recursion to print strings in C - c

Let me start with saying I am not looking for someone to do this for me. I am hoping for a hint or suggestion.
I know there is a smarter way to do this. Code is posted below. I am trying to print an outline. My code works up to a depth of 3. (The depth is the number of subsections - so 3 would be section 1, section 1.A, and section 1.A.1). It also works for a width (number of sections and each type of subsection) of 26, where it is capped. However, to get a larger depth, it would involve many more loops. Not only is that terrible code, it also freezes up the terminal I'm working on.
I believe recursion would make it much nicer, but I'm struggling to grasp the idea when using a string (I understand when it is a number).Thanks!
#include <stdio.h>
int sec(int width, int snum) {
char section[100];
sprintf(section, "Section ");
printf("%s %i", section, snum);
return 0;
}
int ssec_num(int width, int i) {
char num[100];
sprintf(num, "%i", i);
printf(".%s", num);
}
int ssec_let(int width, char z) {
char let[100];
sprintf(let, ".%c", z);
printf("%s", let);
}
int main(int argc, char* argv[]) {
int depth = atoi(argv[1]);
int width = atoi(argv[2]);
int sec_int=1;
int sec_wid = width;
int let_wid;
int num_int;
int num_dep;
int num_wid;
int dep;
char z = 'A';
while(sec_wid > 0) {
sec(width, sec_int);
let_wid = width;
dep = depth-1;
printf("\n");
while(dep > 0) {
while(let_wid > 0) {
num_wid = width;
num_int = 1;
sec(width, sec_int);
ssec_let(let_wid, z);
printf("\n");
num_dep = depth-2;
while(num_dep > 0) {
while(num_wid > 0) {
sec(width, sec_int);
ssec_let(let_wid, z);
ssec_num(width, num_int);
num_wid--;
num_int++;
printf("\n");
num_dep--;
}
}
let_wid --;
z++;
}
dep --;
}
sec_int++;
sec_wid--;
z = 'A';
}
}
If depth is 3 and width is 2 then it would be
Section 1
Section 1.A
Section 1.A.1
Section 1.A.2
Section 1.B
Section 1.B.1
Section 1.B.2
Section 2
Section 2.A
Section 2.A.1
Section 2.A.2
Section 2.B
Section 2.B.1
Section 2.B.2

The algorithm you described uses a width to declare how many times each (sub)section is repeated. This kind of repetition you can achieve with a loop.
The algorithm also uses a depth to determine how many (sub)sections you have. Here is the tricky part, and you can use recursion to solve it. A recursive function is basically a function that calls itself a limited number of times. There must always be a condition to stop the recursion, otherwise the function would call itself until the call stack overflows, abnormally stopping the program execution.
For your problem, you can have a function that receives a counter, that determines at with (sub)section depth it currently is. It would loop width times (as described above) and call itself depth times, until the counter reaches the value of depth. This way, you'll have a function that has a depth number of (sub)sections, each with a width number of items.
As you need to print the (sub)sections at the previous depths, you can use a buffer to store the section values at each depth, like int buffer[MAX_DEPTH];, with #define MAX_DEPTH 100 to set the maximum depth your program supports.
Then you'll have something like
#include <stdio.h>
#define MAX_DEPTH 100
void print_section(const int *const buffer, const int current_depth) {
// print all the (sub)section values stored at the buffer so far
// use a loop like for (i = 0; i <= current_depth; i++)
}
void recursive(int *const buffer, const int current_depth,
const int depth, const int width) {
if (current_depth < depth) {
// continue recursion
int current_width;
for (current_width = 1; current_width <= width; current_width++) {
buffer[current_depth] = current_width;
print_section(buffer, current_depth);
recursive(buffer, current_depth + 1, depth, width);
}
}
// else stop recursion
}
int main(int argc, char* argv[]) {
// ...
int buffer[MAX_DEPTH];
recursive(buffer, 0, depth, width);
return 0;
}
You'll also need some extra logic to determine when to print a letter or a number at each (sub)section depth.
EDIT: To print the (sub)section title just use the following
void print_section(const int *const buffer, const int current_depth) {
int i;
printf("Section ");
for (i = 0; i <= current_depth; i++) {
printf(i == 0 ? "%i" : ".%i", buffer[i]);
}
printf("\n");
}

Related

A function in C runs for a set of values but gives Segmentation Fault: 11 for another

I am trying to find unique non-zero intersection between two sets. I have written a program which works for some set of arrays but gives segmentation fault for some. I have been trying to figure out why but have failed, any help will be greatly valued. The thing is the functions defined (NoRep and ComEle) are working fine but are unable to return the value to the assigned pointer in the case when Seg Fault is shown. Below is the code:
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#include<string.h>
int* ComEle(int ar_1[], int size_ar1, int ar_2[], int size_ar2);
int* NoRep(int a[], int l1);
int main ()
{
// Case 1: Gives segmentation fault
int A[10] = {1,1,0,2,2,0,1,1,1,0};
int B[10] = {1,1,1,1,0,1,1,0,4,0};
int *C = ComEle(A,10,B,10); printf("check complete\n");
// //Case 2: Does not give segmentation fault
// int A[4] = {2,3,4,5};
// int B[4] = {1,2,3,4};
// int *C = ComEle(A,4,B,4); printf("check complete\n");
}
//---------------- Local Functions --------------------//
int* ComEle(int ar_1[], int size_ar1, int ar_2[], int size_ar2) {
// sort of intersection of two arrays but only for nonzero elements.
int i=0, j=0, cnt1 = 0;
int temp1 = size_ar1+size_ar2;
int CE1[temp1]; for(i=0;i<temp1;i++) {CE1[i] = 0;}
/* Size of CE1 is knowingly made big enough to accommodate repeating
common elements which can expand the size of resultant array to
values bigger than those for the individual arrays themselves! */
for(i=0;i<size_ar1;i++) {
j = 0;
while(j<size_ar2) {
if(ar_1[i]==ar_2[j] && ar_1[i]!=0) {
CE1[cnt1] = ar_1[i];
cnt1++;
}
j++;
}
}
// Have to remove repeating elements.
int *CE = NoRep(CE1, cnt1);
for(i=0;i<(CE[0]+1);i++) {printf("CE:\t%d\n", CE[i]);}
printf("ComEle: %p\n",CE);
return(CE);
}
int* NoRep(int a[], int l1) {
int cnt = 0, i = 0, j =0;
int *NR; NR = (int*)calloc((l1), sizeof(int));
//int NR[l1]; for(i=0;i<l1;i++) {NR[i] = 0;}
for(i=0;i<l1;i++) {
j = 0;
while(j<i) {
if(a[i]==a[j]) {break;}
j++;
}
if(j == i) {
cnt++;
NR[cnt] = a[i];
}
}
NR[0] = cnt; // First element: # of relevant elements.
printf("NoRep: %p\n",NR);
return(NR);
}
Thanks again for your help!
Take a look at this code:
int temp1 = size_ar1+size_ar2;
int CE1[temp1]; for(i=0;i<temp1;i++) {CE1[i] = 0;}
/* Size of CE1 is knowingly made big enough to accommodate repeating
common elements which can expand the size of resultant array to
values bigger than those for the individual arrays themselves! */
for(i=0;i<size_ar1;i++) {
j = 0;
while(j<size_ar2) {
if(ar_1[i]==ar_2[j] && ar_1[i]!=0) {
CE1[cnt1] = ar_1[i];
cnt1++;
}
j++;
}
}
Here you have nested loops, i.e. a for-loop with a while-loop inside. So - in worst case - how many times can cnt1 be incremented?
The answer is size_ar1 * size_ar2
But your code only reserve size_ar1 + size_ar2 element for CE1. So you may end up writing outside the array.
You can see this very easy by printing cnt1 inside the loop.
In other words - your CE1 is too small. It should be:
int temp1 = size_ar1*size_ar2; // NOTICE: * instead of +
int CE1[temp1]; for(i=0;i<temp1;i++) {CE1[i] = 0;}
But be careful here - if the input arrays are big, the VLA gets huge and you may run in to stack overflow. Consider dynamic memory allocation instead of an array.
Besides the accepted answer: I have been missing a break statement in the while loop in ComEle function. It was not giving me the expected value of cnt1. The following will be the correct way to do it:
for(i=0;i<size_ar1;i++) {
j = 0;
while(j<size_ar2) {
if(ar_1[i]==ar_2[j] && ar_1[i]!=0) {
CE1[cnt1] = ar_1[i];
cnt1++;
break;
}
j++;
}
}
This will also do away with the requirement for a bigger array or dynamic allocation as suggested (and rightly so) by #4386427

Progress Bar in C for an arbitrary long execution -- CONSOLE

I have tried my best to search not only stackOverflow but other website as well but could not find something to match my needs. What I am requesting is to be able to display a progress bar (e.g. Progress: ####.........). I don't really care for the % at the moment.
Now lies the problem. I can not simply do a 0-100 for loop as the code I wish to have executed and tracked lies within a while loop that runs for an arbitrary time (problem size depends on input of user thus, is not constant).
I have thought of keeping track of the number of iterations within an int variable and try to do a modulo by 2, 50 or 100 but as I have said, the number of iterations depends on the users input and thus, only manageable under specific conditions. No other output but the progress bar is done so I do a simple printf('#'); inside the while loop and all the pretty stuff outside it.
This is also a personal preference but don't mind if not included, I would like the progress bar to be 50 characters long so 100% execution = 50 '#' characters accordingly.
Any help is kindly appreciated.
So i wrapped the code from before nicelly and here is what i ended up with.
I used a little bit of oop concept and simulated the class of a ProgressBar. Here is how i designed the code for the ProgressBar:
struct tagProgressBarData
{
unsigned long nMaxLen;
unsigned long nCurLen;
char FillChr;
char EmptyChr;
char LeftMargin;
char RightMargin;
};
typedef struct tagProgressBarData PBD;
void InitProgressBar(PBD* p, unsigned long MaxLen, char Left, char Right, char Fill, char Empty);
void DrawProgressBar(PBD* p);
Before jumping to the definitions of InitProgressBar() and DrawProgressBar(), this is how you should use what i've made. Here is an example:
int main()
{
PBD data;
/** You can chose other characters and change the length too! */
InitProgressBar(&data, 50, '[', ']', '#', '.');
/** Now we do something which takes some time. */
/** Let's just calculate some random cubes. */
/** The N you talked about. */
unsigned int N;
printf("How many numbers to compute: ");
scanf("%u", &N);
printf("Calculating the cubes of the first %u numbers.\n", N);
DrawProgressBar(&data);
for(unsigned int i = 1; i <= N; i++)
{
unsigned int CubeResult = i*i*i;
unsigned long nProgress = ( ((unsigned long long)i) * data.nMaxLen) / N;
if (nProgress != data.nCurLen)
{
data.nCurLen = nProgress;
DrawProgressBar(&data);
}
}
return 0;
}
And now, the definition of the function that prints the progress bar:
void DrawProgressBar(PBD* p)
{
/** Move to the beginning of the line. */
printf("\r");
/** Print the left margin char. */
printf("%c", p->LeftMargin);
/** Make sure that MaxLen >= CurLen */
if (p->nMaxLen < p->nCurLen)
p->nCurLen = p->nMaxLen;
/** Print the progress with the Fill char. */
for(unsigned long i = 0; i < p->nCurLen; i++)
printf("%c", p->FillChr);
/** Complete whats left with the Fill char. */
for(unsigned long i = 0; i < p->nMaxLen - p->nCurLen; i++)
printf("%c", p->EmptyChr);
/** Print the right margin char. */
printf("%c", p->RightMargin);
}
I have also used this function to make my code in main more compact:
void InitProgressBar(PBD* p, unsigned long MaxLen, char Left, char Right, char Fill, char Empty)
{
p->nMaxLen = MaxLen;
p->nCurLen = 0;
p->LeftMargin = Left;
p->RightMargin = Right;
p->FillChr = Fill;
p->EmptyChr = Empty;
}
If you want to have some text before the progress bar but on the same line (something like Progress: [######.............]) you have to replace the printf("\r"); from the DrawProgressBar() with a for loop so you move back exactly the length of the progress bar.
Also, you need some variable (let's say bDrawn) which will tell you if the progress bar has been drawn at least once, so that the for loop will not move the cursor over the existing text at the left of the progress bar.
After trial and error, I may have found a solution but would like to check against someone.
Assuming these variables (all of type int):
num_iterations = 0, MAX_PROGRESS = 100, BAR_LENGTH = 50, num_items = N
I have printed a '#' character on:
if ((iteration / BAR_LENGTH) % (MAX_PROGRESS * BAR_LENGTH * num_items) == 0)
and get my desired result:
|<------------- Enumeration Complete ------------->|
|##################################################| COMPLETED
Though this gradually builds up, it is not of the form
|<------------- Enumeration Complete ------------->|
|##################################................|
Anything I can do with \r or \b?
I have also done this but seems to be very dependent on the number of items.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
int MAX_PROGRESS = 100;
int BAR_LENGTH = 0; // Length of Header
int num_items = 30;
void delay(int milliseconds) {
// Storing start time
clock_t start_time = clock();
// looping till required time is not achieved
while (clock() < start_time + milliseconds);
}
void initialiseProgressBar(char left, char right, char fill) {
printf("%c", left);
for (int i = 0; i < BAR_LENGTH; i ++) {
printf("%c", fill);
}
/** Print the right first (end of line) and then again the left (start of line)
* as the \r will be placed over it and rewrite from there resulting in one
* character less
*/
printf("%c\r%c", right, left);
}
void drawProgressBar(char c) {
// Print according to BAR_LENGTH
for (int i = 0; i < 100; i ++) {
double progress = (i / BAR_LENGTH) % (MAX_PROGRESS * BAR_LENGTH * num_items);
if (progress == 0) {
printf("%c", c);
delay(25);
}
// Redraw the stdout stream to show progressing bar
fflush(stdout);
}
}
int main(int argc, char* argv[]) {
// Header
char* header = "|<------------- Progress Bar ------------->|\n";
printf("%s", header);
BAR_LENGTH = strlen(header) - 3; // Account for newline and right character characters
initialiseProgressBar('[', ']', '.');
drawProgressBar('#');
// Footer -- TODO Find better way to finish this without hard coding
printf("] COMPLETED\n");
return 0;
}
Assuming you know the number of items you are calculating against (e.g. sorting a list, calculating different things etc), this should come in handy :).

Understanding returning values functions C

I'm trying to understand how the return value of a function works, through the following program that has been given to me,
It goes like this :
Write a function that given an array of character v and its dim, return the capital letter that more often is followed by its next letter in the alphabetical order.
And the example goes like : if I have the string "B T M N M P S T M N" the function will return M (because two times is followed by N).
I thought the following thing to create the function:
I'm gonna consider the character inserted into the array like integer thank to the ASCII code so I'm gonna create an int function that returns an integer but I'm going to print like a char; that what I was hoping to do,
And I think I did, because with the string BTMNMPSTMN the function prints M, but for example with the string 'ABDPE' the function returns P; that's not what I wanted, because should return 'A'.
I think I'm misunderstanding something in my code or into the returning value of the functions.
Any help would be appreciated,
The code goes like this:
#include <stdio.h>
int maxvolte(char a[],int DIM) {
int trovato;
for(int j=0;j<DIM-1;j++) {
if (a[j]- a[j+1]==-1) {
trovato=a[j];
}
}
return trovato;
}
int main()
{
int dim;
scanf("%d",&dim);
char v[dim];
scanf("%s",v);
printf("%c",maxvolte(v,dim));
return 0;
}
P.S
I was unable to insert the value of the array using in a for scanf("%c,&v[i]) or getchar() because the program stops almost immediately due to the intepretation of '\n' a character, so I tried with strings, the result was achieved but I'd like to understand or at least have an example on how to store an array of character properly.
Any help or tip would be appreciated.
There are a few things, I think you did not get it right.
First you need to consider that there are multiple pairs of characters satisfying a[j] - a[j+1] == -1
.
Second you assume any input will generate a valid answer. That could be no such pair at all, for example, ACE as input.
Here is my fix based on your code and it does not address the second issue but you can take it as a starting point.
#include <stdio.h>
#include <assert.h>
int maxvolte(char a[],int DIM) {
int count[26] = {0};
for(int j=0;j<DIM-1;j++) {
if (a[j] - a[j+1]==-1) {
int index = a[j] - 'A'; // assume all input are valid, namely only A..Z letters are allowed
++count[index];
}
}
int max = -1;
int index = -1;
for (int i = 0; i < 26; ++i) {
if (count[i] > max) {
max = count[i];
index = i;
}
}
assert (max != -1);
return index + 'A';
}
int main()
{
int dim;
scanf("%d",&dim);
char v[dim];
scanf("%s",v);
printf("answer is %c\n",maxvolte(v,dim));
return 0;
}
#include <stdio.h>
int maxvolte(char a[],int DIM) {
int hold;
int freq;
int max =0 ;
int result;
int i,j;
for(int j=0; j<DIM; j++) {
hold = a[j];
freq = 0;
if(a[j]-a[j+1] == -1) {
freq++;
}
for(i=j+1; i<DIM-1; i++) { //search another couple
if(hold==a[i]) {
if(a[i]-a[i+1] == -1) {
freq++;
}
}
}
if(freq>max) {
result = hold;
max=freq;
}
}
return result;
}
int main()
{
char v[] = "ABDPE";
int dim = sizeof(v) / sizeof(v[0]);
printf("\nresult : %c", maxvolte(v,dim));
return 0;
}

Recursively printing out the sections and subsections of an outline

Recursion is the one thing I have loads of trouble with. For this assignment we are supposed to print out an outline of sections and sub-sections. Take the following as an example.
Section 1
Section 1.A
Section 1.A.1
Section 1.A.2
Section 1.B
Section 1.B.1
Section 1.B.2
Section 2
Section 2.A
Section 2.A.1
Section 2.A.2
Section 2.B
Section 2.B.1
Section 2.B.2
This example has a depth of 3 and height of 2.
Here is my code thus far, which doesn't come anywhere near the correct output.
void printDepth(int depth, int width, int minusDepth, int minusWidth) {
int i = 0;
if(depth == 0)
printf("Section XX\n");
else {
printf("\t");
printDepth(depth -1, width, minusDepth, minusWidth);
}
}
Here is the call from main()
int minusDepth = 0;
int minusWidth = 0;
printDepth(depth, width, minusDepth, minusWidth);
However, for a depth = 4 and width = 5 this only prints out:
\t\t\t\tSection XX
I'm really not sure how to proceed. Recursion is the bane of my existence.
You need a loop that prints the sections at the current depth and executes height (which I call width instead) recursions. You also need to pass a string containing the current prefix of the section string.
#include <stdio.h>
#include <assert.h>
#include <math.h>
#define MAX_DEPTH 100
#define MAX_WIDTH 99 // NOTE: if you increase this then section's decl in printDepth needs to be updated too
void printDepth_r(int currDepth, int depth, int width, char *section, char *sub)
{
if (currDepth == depth) // recursion base case
return;
for (int i = 0; i < width; ++i)
{
// TODO: write to sub the subsection determined by (currDepth, width)
fprintf(stdout, "%*sSection %s\n", currDepth * 2, "", section);
// TODO: append "." to sub for descendant recursions
printDepth_r(currDepth + 1, depth, width, section, sub + /* TODO: num chars written to sub */);
}
}
int printDepth(int depth, int width)
{
char section[MAX_DEPTH * (2 + 1) + 1]; // NOTE: 2 == 1 + (int) (log(99) / log(10));
assert(sizeof(section) >= MAX_DEPTH * (1 + (int) (log(MAX_WIDTH) / log(10)) + 1) + 1);
if (depth > MAX_DEPTH || width > MAX_WIDTH)
return -1;
printDepth_r(0, depth, width, section, section);
return 0;
}
int main(int argc, char **argv)
{
printDepth(3, 2);
return 0;
}
Note that we pass the same values of depth, width and section to all of our recursions. So, if we wanted to reduce the amount of stack space the recursion eats at every level, then we could pull these out into a structure and pass 1 struct pointer to these 3 constants instead. Or, even better, we could store these values in thread local storage. Either way would allow deeper recursions before overflowing your stack.
#include <stdio.h>
void printDepth(int deep, int depth, int height, char *table) {
if(deep == depth)
return ;
int i, j;
char bak = table[deep];
for(i = 0; i < height; ++i){
printf("%*s%s", deep*2, "", "Section ");
for(j = 0; j <= deep; ++j){
if(j)
putchar('.');
putchar(table[j]);
}
putchar('\n');
printDepth(deep+1, depth, height, table);
table[deep]++;
}
table[deep] = bak;//restore
}
int main(void){
char table[] = "1A1";//Effective range up to 1-9 and A-Z
printDepth(0, 3, 2, table);
return 0;
}

Max in array and its frequency

How do you write a function that finds max value in an array as well as the number of times the value appears in the array?
We have to use recursion to solve this problem.
So far i am thinking it should be something like this:
int findMax(int[] a, int head, int last)
{
int max = 0;
if (head == last) {
return a[head];
}
else if (a[head] < a[last]) {
count ++;
return findMax(a, head + 1, last);
}
}
i am not sure if this will return the absolute highest value though, and im not exactly sure how to change what i have
Setting the initial value of max to INT_MIN solves a number of issues. #Rerito
But the approach OP uses iterates through each member of the array and incurs a recursive call for each element. So if the array had 1000 int there would be about 1000 nested calls.
A divide and conquer approach:
If the array length is 0 or 1, handle it. Else find the max answer from the 1st and second halves. Combine the results as appropriate. By dividing by 2, the stack depth usage for a 1000 element array will not exceed 10 nested calls.
Note: In either approach, the number of calls is the same. The difference lies in the maximum degree of nesting. Using recursion where a simple for() loop would suffice is questionable. To conquer a more complex assessment is recursion's strength, hence this approach.
To find the max and its frequency using O(log2(length)) stack depth usage:
#include <stddef.h>
typedef struct {
int value;
size_t frequency; // `size_t` better to use that `int` for large arrays.
} value_freq;
value_freq findMax(const int *a, size_t length) {
value_freq vf;
if (length <= 1) {
if (length == 0) {
vf.value = INT_MIN; // Degenerate value if the array was size 0.
vf.frequency = 0;
} else {
vf.value = *a;
vf.frequency = 1;
}
} else {
size_t length1sthalf = length / 2;
vf = findMax(a, length1sthalf);
value_freq vf1 = findMax(&a[length1sthalf], length - length1sthalf);
if (vf1.value > vf.value)
return vf1;
if (vf.value == vf1.value)
vf.frequency += vf1.frequency;
}
return vf;
}
Your are not thaaaat far.
In order to save the frequency and the max you can keep a pointer to a structure, then just pass the pointer to the start of your array, the length you want to go through, and a pointer to this struct.
Keep in mind that you should use INT_MIN in limits.h as your initial max (see reset(maxfreq *) in the code below), as int can carry negative values.
The following code does the job recursively:
#include <limits.h>
typedef struct {
int max;
int freq;
} maxfreq;
void reset(maxfreq *mfreq){
mfreq->max = INT_MIN;
mfreq->freq = 0;
}
void findMax(int* a, int length, maxfreq *mfreq){
if(length>0){
if(*a == mfreq->max)
mfreq->freq++;
else if(*a > mfreq->max){
mfreq->freq = 1;
mfreq->max = *a;
}
findMax(a+1, length - 1, mfreq);
}
}
A call to findMax will recall itself as many times as the initial length plus one, each time incrementing the provided pointer and processing the corresponding element, so this is basically just going through all of the elements in a once, and no weird splitting.
this works fine with me :
#include <stdio.h>
#include <string.h>
// define a struct that contains the (max, freq) information
struct arrInfo
{
int max;
int count;
};
struct arrInfo maxArr(int * arr, int max, int size, int count)
{
int maxF;
struct arrInfo myArr;
if(size == 0) // to return from recursion we check the size left
{
myArr.max = max; // prepare the struct to output
myArr.count = count;
return(myArr);
}
if(*arr > max) // new maximum found
{
maxF = *arr; // update the max
count = 1; // initialize the frequency
}
else if (*arr == max) // same max encountered another time
{
maxF = max; // keep track of same max
count ++; // increase frequency
}
else // nothing changes
maxF = max; // keep track of max
arr++; // move the pointer to next element
size --; // decrease size by 1
return(maxArr(arr, maxF, size, count)); // recursion
}
int main()
{
struct arrInfo info; // return of the recursive function
// define an array
int arr[] = {8, 4, 8, 3, 7};
info = maxArr(arr, 0, 5, 1); // call with max=0 size=5 freq=1
printf("max = %d count = %d\n", info.max, info.count);
return 0;
}
when ran, it outputs :
max = 8 count = 3
Notice
In my code example I assumed the numbers to be positive (initializing max to 0), I don't know your requirements but you can elaborate.
The reqirements in your assignment are at least questionable. Just for reference, here is how this should be done in real code (to solve your assignment, refer to the other answers):
int findMax(int length, int* array, int* maxCount) {
int trash;
if(!maxCount) maxCount = &trash; //make sure we ignore it when a NULL pointer is passed in
*maxCount = 0;
int result = INT_MIN;
for(int i = 0; i < length; i++) {
if(array[i] > result) {
*maxCount = 1;
result = array[i];
} else if(array[i] == result) {
(*maxCount)++;
}
}
return result;
}
Always do things as straight forward as you can.

Resources