Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

In C programming language 2. The code below assigns a random number from 1 to 10

ID: 3771999 • Letter: I

Question

In C programming language

2. The code below assigns a random number from 1 to 10,000 into each element of array num. Write a function that receives the array as a parameter and returns the largest value of array.

srand((unsigned int) time(NULL)); for (i=0;i=MAX;i++) { num[i]=rand() % 1000+1; }

3. As a practical joke, a friend gives you an int array for your birthday. As if that weren't bad enough, your friend tells you that the array contains almost all 0's except for a small string of consecutive 1's contained somewhere in the middle. Overwhelmed by the novelty of this you decide to write a function that will print out the location of the first 1 in the array, the location of the last 1 in the array, and the total number of 1's in the list of consecutive 1 values. Given below is the function prototype:

void joke (int num[], int max);

where num is the array of int values and max contains the number of elements in the array.

Explanation / Answer

<code>

#include<stdio.h>
#include<math.h>

int main()
{
int ar[1000];
int i = 0;
for(i = 0;i < 1000;i++) {
ar[i] = rand() % 1000+1;
}
cout << largest(ar, 1000) << endl;
joke(num, 1000);
return 0;
}

int largest(int ar[], int n)
{
int j = 0;
int mx = 0;
for(j = 0;j < n;j++) {
if(ar[j] > mx) {
mx = ar[j];
}
}
return mx;
}

void joke(int ar[], int n)
{
int first = 0;
int last = 0;
int cnt = 0;
int i = 0;
int mx = 0;
int j;
while(i < n) {
if(ar[i] == 1) {
j = i;
if(first == 0) {
first = i;
}
last = i;
while(ar[j] == 1) {
cnt++;
j++;
}
if(cnt > mx) {
mx = cnt;
}
}
}

cout << "first 1 is at index " << first << endl;
cout << "last 1 is at index " << last << endl;
cout << "max. consecutive 1 are " << mx << endl;
}

</code>