Intro to C You are given an array x of cstrings along with a

Intro to C:

You are given an array x of c-strings along with an int variable n that contains the number of elements in the array . You are also given an array of chars representing a string named mode that has been declared . Assign to mode the mode value of the array . (Assume there are no \"ties\".)

NOTE: The mode is the value that occurs most frequently.

EXAMPLE: Given \"msft\" \"appl\" \"msft\" \"csco\" \"ibm\" \"csco\" \"msft\", the mode is \"msft\" because it appears the most number of times in the list.

Solution

// C code to find mode of string array

#include <stdio.h>
#include <string.h>

int main()
{
// int variable n that contains the number of elements in the array
int n = 7;
// an array x of c-strings
char str[7][20] = {\"msft\" ,\"appl\" ,\"msft\", \"csco\", \"ibm\", \"csco\", \"msft\"};
char temp[20];
int i, j;

// sort the string array
for (i = 1; i < n; i++) {
for (j = 1; j < n; j++) {
if (strcmp(str[j - 1], str[j]) > 0) {
strcpy(temp, str[j - 1]);
strcpy(str[j - 1], str[j]);
strcpy(str[j], temp);
}
}
}

// chars representing a string named mode
// set mode to first element
char mode[20];
strcpy(mode,str[0]);

int max = 1;
int count = 1;

for (i = 1; i < n; i++)
{
// check if string are not equal
if(strcmp(str[i - 1], str[i]) < 0)
{
// update mode
if(count > max)
{
max = count;
strcpy(mode,str[i]);
}
count = 1;
}

else
{
count++;
}
}

// check mode for last element
if(count > max)
{
max = count;
strcpy(mode,str[i-1]);
}

printf(\"Mode: %s\ \", mode);
// output: Mode: msft


return 0;
}

Intro to C: You are given an array x of c-strings along with an int variable n that contains the number of elements in the array . You are also given an array o
Intro to C: You are given an array x of c-strings along with an int variable n that contains the number of elements in the array . You are also given an array o

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site