Finding the longest string in a 2d array in C - c

I wrote a function that finds the longest string in a 2d array, it works, partially. My problem is that it takes the first longest string that it finds without checking the other ones.
For example, the following list of strings:
eke
em
ekeke
eme
e
ememeememe
emem
ekekee
eooeeeeefe
eede
My function catches "ekeke" (the third string from the list) as the longest instead of "ememeememe ".
Here is my function:
void length(char str[][MAX])
{
int i = 0;
for(i = 1; i < LEN; i++)
{
if(strlen(str[i]) > strlen(str[i-1]))
{
if(strlen(str[i]) > strlen(str[i+1]))
{
printf("%s", str[i]);
break;
}
}
}
}
LEN is a constant, his value is 10.
MAX is a constant, his value is 50.
The strings are given by the user.
Thanks.

You are only comparing the previous and next strings. You need to check the lengths of all the strings.
void length(char str[][MAX])
{
size_t longest = strlen(str[0]);
szie_t j = 0;
for(size_t i = 1; i < LEN; i++)
{
size_t len = strlen(str[i]);
if(longest < len)
{
longest = len;
j = i;
}
}
printf("%s", str[j]);
}
I am assuming you have at least 1 string and handle corner cases (if user inputs less than LEN strings etc -- depends on how you fill the str with strings).

Related

Inconsistent output given by same code on different C compilers

Different compilers are giving different outputs for the same logic in my algorithm.
I wrote the following code for a C code exercise.
The code checks for the longest string in a string vector.
But the same logic gives two different outputs.
Here's what is happening. I have no idea what I did wrong.
First version - without a printf() inside the if condition
Here the if (j > longest) just attributes new values for int longest and int index.
#include <stdio.h>
int main(void) {
char *vs[] = {"jfd", "kj", "usjkfhcs", "nbxh", "yt", "muoi", "x", "rexhd"};
int longest, index = 0;
/* i is the index for elements in *vs[].
* "jfd" is 0, "kj" is 1... */
for (int i = 0; i < sizeof(*vs); i++) {
/* j if the index for string lengths in vs[].
* for "jfd", 'j' is 0, 'f' is 1... */
for (int j = 0; vs[i][j] != '\0'; j++) {
/* if j is longer than the previous longest value */
if (j > longest) {
longest = j;
index = i;
}
}
}
printf("Longest string = %s\n", vs[index]);
return 0;
}
I ran it on https://replit.com/. It gave the unexpected output for longest string of "jfd". https://replit.com/#Pedro-Augusto33/Whatafuck-without-printf?v=1
Second version - with a printf() inside the if condition
Now I just inserted a printf() inside the if (jf > longest) condition, as seen in the code block bellow.
It changed the output of my algorithm. I have no idea how or why.
#include <stdio.h>
int main(void) {
char *vs[] = {"jfd", "kj", "usjkfhcs", "nbxh", "yt", "muoi", "x", "rexhd"};
int longest, index = 0;
/* i is the index for elements in *vs[].
* "jfd" is 0, "kj" is 1... */
for (int i = 0; i < sizeof(*vs); i++) {
/* j if the index for string lengths in vs[].
* for "jfd", 'j' is 0, 'f' is 1... */
for (int j = 0; vs[i][j] != '\0'; j++) {
/* if j is longer than the previous longest value */
if (j > longest) {
printf("Whatafuck\n");
longest = j;
index = i;
}
}
}
printf("Longest string = %s\n", vs[index]);
return 0;
}
I also ran it on https://replit.com/. It gave the expected output for longest string of "usjkfhcs". https://replit.com/#Pedro-Augusto33/Whatafuck-with-printf?v=1
Trying new compilers
After replit.com giving two different outputs, I tried another compiler to check if it also behaved strangely. https://www.onlinegdb.com/online_c_compiler gives random outputs. Sometimes it's "jfd", sometimes it's "usjkfhcs". https://onlinegdb.com/iXoCDDena
Then I went to https://www.programiz.com/c-programming/online-compiler/ . It always gives the expected output of "usjkfhcs".
So, my question is: why are different compilers behaving so strangely with my algorithm? Where is the flaw of my algorithm that makes the compilers interpret it different?
The code does not make sense.
For starters the variable longest was not initialized
int longest, index = 0;
So using it for example in this statement
if (j > longest) {
invokes undefined behavior.
In this for loop
for (int i = 0; i < sizeof(*vs); i++) {
the expression sizeof( *vs ) is equivalent to expression sizeof( char * ) and yields either 4 or 8 depending on the used system. It just occurred such a way that the array was initialized with 8 initializers. But in any case the expression sizeof( *vs ) does not provide the number of elements in an array and its value does not depend on the actual number of elements.
Using the if statement within the for loop in each iteration of the loop
for (int j = 0; vs[i][j] != '\0'; j++) {
/* if j is longer than the previous longest value */
if (j > longest) {
longest = j;
index = i;
}
}
Also does not make sense. It does not calculate the exact length of a string that is equal to j after the last iteration of the loop. So in general such a loop shall not be used for calculating length of a string.
Consider a string for example like "A". Using this for loop you will get that its length is equal to 0 while its length is equal to 1..
It seems you are trying to find the longest string a pointer to which stored in the array.
You could just use standard C string function strlen declared in header <string.h>. If to use your approach with for loops then the code can look the following way
#include <stdio.h>
int main(void)
{
const char *vs[] = { "jfd", "kj", "usjkfhcs", "nbxh", "yt", "muoi", "x", "rexhd" };
const size_t N = sizeof( vs ) / sizeof( *vs );
size_t longest = 0, index = 0;
for ( size_t i = 0; i < N; i++ )
{
size_t j = 0;
while ( vs[i][j] != '\0' ) ++j;
if ( longest < j )
{
longest = j;
index = i;
}
}
printf( "Longest string = %s\n", vs[index] );
printf( "Its length = %zu\n", longest );
return 0;
}

Print array of strings vertically

I know how to print a single string vertically.
char test[100] = "test";
int i;
for(i=0;i<strlen(test);i++){
printf("%c\n",test[i]);
}
Which will give me:
t
e
s
t
But how can I print an array of strings vertically? For example:
char listOfTest[2][10] = {"testing1","quizzing"};
So it can return:
tq
eu
si
tz
iz
gi
1g
Simply loop through the first string and print each character at index i in the first string and the second string till you reach the null terminator of first string
NOTE: this only work when string 1 and string2 are equal in length and will need modification for other test cases
#include <stdio.h>
int main(void)
{
char listOfTest[2][10] = {"testing1","quizzing"};
int i = 0;
//loop through string 1 till NULL is reach
while (listOfTest[0][i])
{
//prints char at index i in string 1 and 2
printf("%c%c\n", listOfTest[0][i], listOfTest[1][i]);
//increment the index value
i++;
}
return (0);
}
Simply print a character from both strings.
(Better to test for the null character rather than repeatedly call strlen().)
for(i = 0; listOfTest[0][i] && listOfTest[1][i]; i++) {
printf("%c%c\n", listOfTest[0][i], listOfTest[1][i]);
}
To extend to n strings ...
size_t num_of_strings = sizeof listOfTest/sizeof listOfTest[0];
bool done = false;
for (size_t i = 0; listOfTest[0][i] && !done; i++) {
for (size_t n = 0; n < num_of_strings; n++) {
if (listOfTest[n][i] == '\0') {
done = true;
break;
}
printf("%c", listOfTest[n][i]);
}
printf("\n");
}

Finding the longest and shortest string in an inputted array

This is my first time using S.O but Im having trouble with my simple program. Im learning C and Im trying to sort an array of 10 strings (that the user inputs) to find the largest and smallest string and print that on screen at the end, as well as the length of the string. My maximum length is running fine however Im having difficulty when trying to find the minimum length, it just keeps saying " The smallest word is '≡■`☻♦' with 4 characters." I have tried to create a nested loop for the minimum length so that it compares each string in the array against the next as well as the minimum that is stored in the minLength variable. I have no clue why these random symbols are appearing and where its getting this from. Any advice would be much appreciated! Thank you
#include <stdio.h>
#include <string.h>
int main()
{
int maxLength = 0;
int maxIndex = 0;
int minIndex = 0;
char word_length[10][20];
printf("Please type 10 words: --------------------- \n \n");
/*USER ENTERS 10 WORDS*/
for (i = 0; i < 10; i++)
{
scanf("%s", &word_length[i]);
}
/*SEARCH FROM INDEX POINTER 0-10*/
for (i = 0; i < 10; i++)
{
/*NEW VARIABLE LENGTH IS UPDATED TO LENGTH OF EACH STRING HELD IN EACH POINTER IN WORD_LENGTH ARRAY*/
int length1 = strlen(word_length[i]);
/*IF THE NEW LENGTH IS BIGGER THAN THE PREVIOUS MAXIMUM LENGTH, THE MAXIMUM LENGTH SCORE IS UPDATED*/
/*THE MAXINDEX VARIABLE KEEPS A RECORD OF WHICH ARRAY POSITION THIS STRING IS HELD IN*/
if (length1 > maxLength)
{
maxLength = length1;
maxIndex = i;
}
/*NEW VARIABLE LENGTH IS UPDATED TO LENGTH OF EACH STRING HELD IN EACH POINTER IN WORD_LENGTH ARRAY*/
int length2 = strlen(word_length[i]);
int next_length2 = strlen(word_length[++i]);
int minLength = strlen(word_length[1]);
/*IF THE NEW LENGTH IS SMALLER THAN THE PREVIOUS MINIMUM LENGTH, THE MINIMUM LENGTH SCORE IS UPDATED*/
/*THE MININDEX VARIABLE KEEPS A RECORD OF WHICH ARRAY POSITION THIS STRING IS HELD IN*/
if (length2 < next_length2)
{
if (length2 < minLength)
{
minLength = length2;
minIndex = i;
}
}
}
/*THE BIGGEST WORD IS DISPLAYED ON SCREEN USING THE MAXINDEX POINTER*/
printf("The biggest word is '%s' with %d characters\n", word_length[maxIndex], maxLength);
printf("The smallest word is '%s' with %d characters\n", word_length[minIndex], minLength);
return 0;
}
For starters this call of scanf
scanf("%s",&word_length[i]);
should be rewritten at least like
scanf("%s", word_length[i]);
Though it would be safer to write
scanf("%19s", word_length[i]);
The both for loops like this
for (i=0;i<11;i++)
use an incorrect condition.
You have to write
for ( i=0; i < 10;i++)
The variable minLength is not declared in the block scope of the function main.
In this the for loop used for searching a string with the minimal length there is used a locally declared variable minLength
for (i = 0; i < 11; i++)
{
/*NEW VARIABLE LENGTH IS UPDATED TO LENGTH OF EACH STRING HELD IN EACH POINTER IN WORD_LENGTH ARRAY*/
int length2 = strlen(word_length[i]);
int next_length2 = strlen(word_length[++i]);
int minLength = strlen(word_length[1]);
^^^^^^^^^^^^^
There is no need to use two for loops. It is enough to use one loop.
It can look the following way
size_t maxIndex = 0;
size_t minIndex = 0;
size_t maxLength = strlen( word_length[0] );
size_t minLength = strlen( word_length[0] );
for ( size_t i = 1; i < 10; i++ )
{
size_t length = strlen( word_length[i] );
if ( maxLength < length )
{
maxLength = length;
maxIndex = i;
}
else if ( length < minLength )
{
minLength = length;
mibIndex = i;
}
}
printf("The biggest word is '%s' with %zu characters\n", word_length[maxIndex], maxLength);
printf("The smallest word is '%s' with %zu characters\n", word_length[minIndex], minLength);

Find if 2 strings are composed of same letters

I have a problem, this function should return 1 if secret is composed of same letters than letters_guessed.
It works fine, as long as letters_guessed has atleast 1 same letter which are in the secret. If there is same letter 2 times or more, it does not work. I know why, but I can not solve it because I can not remove same letters.
I can not remove same letters from letters_guessed array, because it is constant, and I can not change it to nonconstant.
Again ...
If:
secret = "cat"
letters_guessed = "txaoc"
return 1
**Right**
If:
secret = "dog"
letters_guessed = "gefxd"
return 0
**Right**
If:
secret = "car"
letters_guessed = "ccr"
return 1
**Wrong, How can I solve this?**
Sorry for my bad English and long explanation.
Here is my program:
int is_word_guessed(const char secret[], const char letters_guessed[])
{
int same = 0;
for(int i = 0; i < strlen(letters_guessed); i++)
{
for(int j = 0; j < strlen(secret); j++)
{
if(letters_guessed[i] == secret[j])
same++;
}
}
if (same == strlen(secret))
return 1;
else
return 0;
}
You can:
make a copy of your strings in order to flag already counted letters (since you tell you don't want to modify the strings, I suggest making a copy first in order to discard already counted letters);
get sorted versions of your strings and then compare them with a single loop; this solution would also provide a better complexity (you could get O(n log n) instead of your current O(n^2)).
One way to do this without modifying the strings is to count the occurrences of letters in the strings. When the guess has more occurrences of a letter than the secret, it's a miss. The case where a letter occurs in the guess that isn't in the secret is just a special case, because then the count of occurrences in the secret is zero.
In practice, you don't keep two separate counts: Add the letters of the guess to the count first, then remove the letters of the secret. As soon as one count drops below zero, it's a miss.
You can make use of the fact that there are only 256 different chars and keep the counts in an array. The index to the array is the letter's ASCII code. Be careful not to access the array at negative indices. C's char isn't guaranteed to be unsigned, so you could cast it or use an unsigned temporary variable or chose not to consider negative values.
Here's an implementation:
int contains(const char *guess, const char *secret)
{
int count[256] = {0}; // start with all-zero array
while (*guess) {
unsigned char c = *guess++;
count[c]++;
}
while (*secret) {
unsigned char c = *secret++;
if (count[c] == 0) return 0;
count[c]--;
}
return 1;
}
You can keep iteration in memory by maintaining an array of all 26 alphabets.
Assumptions:- All letters should be in lower case. Secret should not have repeated letters.
Logic:- Make array entry to 1 if we have considered that letter. 97 is ascii value of 'a'
// declare header file
#include "string.h"
int is_word_guessed(const char secret[], const char letters_guessed[])
{
int same = 0;
int alphabets[26];
// make all enteries 0
for (int k = 0; k <= 25; k++)
{
alphabets[k] = 0;
}
for (int i = 0; i < strlen(letters_guessed); i++)
{
for (int j = 0; j < strlen(secret); j++)
{
if (letters_guessed[i] == secret[j] && (alphabets[(char)letters_guessed[i] - 97] == 0))
{
same++;
alphabets[(char)letters_guessed[i] - 97] = 1;
}
}
}
if (same == strlen(secret))
return 1;
else
return 0;
}
It's easy.
In Haskell it would be:
all (`elem` letters_guessed) secret
in other words: All chars in secret must be in letters_guessed.
In C its (not tested):
// Iterate though string 'secret' until there is a char not
// part of 'letters_guessed'. If there is none, return 1
unsigned check(char *secret, char *letters_guessed) {
unsigned length_secret = length(secret);
unsigned length_guessed = length(letters_guessed);
for (int i = 0; i < length_secret; i++) {
if (!elem(secret[i], letters_guessed) {
return 0;
}
}
return 1;
}
// Check if char 'current' is part of 'string'
unsigned elem(char current, char *string) {
unsigned length = length(string);
unsigned found = 0;
for (int i = 0; i < length; i++) {
if (current == string[i]) {
return 1;
}
}
return 0;
}

C program - largest word in a 2d array string [duplicate]

I wrote a function that finds the longest string in a 2d array, it works, partially. My problem is that it takes the first longest string that it finds without checking the other ones.
For example, the following list of strings:
eke
em
ekeke
eme
e
ememeememe
emem
ekekee
eooeeeeefe
eede
My function catches "ekeke" (the third string from the list) as the longest instead of "ememeememe ".
Here is my function:
void length(char str[][MAX])
{
int i = 0;
for(i = 1; i < LEN; i++)
{
if(strlen(str[i]) > strlen(str[i-1]))
{
if(strlen(str[i]) > strlen(str[i+1]))
{
printf("%s", str[i]);
break;
}
}
}
}
LEN is a constant, his value is 10.
MAX is a constant, his value is 50.
The strings are given by the user.
Thanks.
You are only comparing the previous and next strings. You need to check the lengths of all the strings.
void length(char str[][MAX])
{
size_t longest = strlen(str[0]);
szie_t j = 0;
for(size_t i = 1; i < LEN; i++)
{
size_t len = strlen(str[i]);
if(longest < len)
{
longest = len;
j = i;
}
}
printf("%s", str[j]);
}
I am assuming you have at least 1 string and handle corner cases (if user inputs less than LEN strings etc -- depends on how you fill the str with strings).

Resources