user6913230 user6913230 - 1 month ago 5
C Question

Basic Functions in C

Hi there I am writing a program that needs to use a function to iterate through an array and pick out the index number that has a capital M then return that index number, and only for the first occurrence of a capital M. if no capital M is found, then return a value of -1. here is what I have at the moment (I could be way out in left field with this as I am new to functions).

#include <stdio.h>

int findM (char string[], int numVals){
int i = 0;
int indexM;

for (i = 0; i < numVals; ++i){
if (string[i] == 'M'){
indexM = string[i];
break;
}
else {
indexM = -1;
}
}
return indexM;
}

int main(void) {
char userString [15] = "M as in Mancy";
printf("%d",findM(userString, 15));
return 0;
}


in this example, the intended result is 0, as the first element of this string is a capital M, however, my result is 77 when compiled and ran. Thanks for any help guys!

Answer

you get this because you are inserting the ASCI value of M in the indexM variable, but you should instead hold the index of that character M, right? so do like below in your findM function :

for (i = 0; i < numVals; ++i){
if (string[i] == 'M'){
    indexM = i;
    break;
}
    else {
    indexM = -1;
   }
  }
    return indexM;
}
Comments