I am no expert in C, but that looks like an infinite loop to me. The condition doesn’t change based on the loop-body.
Shouldn’t this be something like words[n-1][length]?
Well given the code doesn’t reach the final message - I assume it’s in fact an infinite loop.
So go ahead and print out values - the array, the chosen word, every step of the while-loop. Also add second condition to the while-loop, so it runs at most 50 times or so.
If you don’t know what your code is actually doing, just force it to tell you everything it’s doing and then look where something seems off.
Here is how it should be I think. I hope it helps.
#include <stdio.h>
#include <string.h>
int main()
{
int length = 0, n;
char words[5][50];
for(int i = 0; i < sizeof(words) / sizeof(words[0]); i++) {
printf("Enter string %d: ", i+1);
gets(words[i]);
}
printf("Which number to find the length: ");
scanf("%d", &n);
int i = 0;
while(words[n-1][i++]!= '\0') {
length++;
}
printf("The length of the word is: %d\n", length);
return 0;
}
words[n-1] gives access to a string at index n - 1 which is a pointer. To access a character you need to specify the index.
For example, if words[5][10] = { “Jordan”, “Nasan”, “Michael”, “Jerry”, “Joyce” } and n = 2;
words[2-1] is equal to “Nasan”, to access first character of the string “Nasan” use words[2-1][0].
Not exactly, i++ increases the value of i by one (increment) - AFTER it is called.
Though being able to call it this way, is fascinating.
Because the while-loop checks the condition every time before running the body, i is incrementing every loop, starting with it’s innitial value 0.
I think some languages support ++i, which does also increment i, but does so before returning the value.
int i = 0
int j = i++
// j = 0, i = 1
int k = ++i
// k = 2, i = 2
@Jagaya oh okay thank you for this info. I think I am already good with the post and pre increment stuff. But sometimes confused with it when used in loops.
It is great that you solved the challenge, but instead of posting your full working solution, it is best to stay focused on answering the original poster’s question(s) and help guide them with hints and suggestions to solve their own issues with the challenge.
Thanks, Jeremy. It is my first time here so I thought a full solution should help, but yeah what you said is good for learning, I will do that next time.
I really wanted to use the strlen function but I want to challenge myself to work on it without pre defined functions. I think using while loops is a good way to help me grasp the idea about arrays especially in strings with the null character and stuff.