Can anyone solve this question in C programming Language?

Stella Richards

New Member
Messages
1
Reaction score
0
Points
0
Hello,


Write code to solve the following problem. Define a function that takes a String as a parameter and returns an integer value. The function need to loop through each character in the input string to find a value of “x”. If a value of “x” is found in the string then return the position within the string where “x” is found else return -1.
 

wjh2303

New Member
Messages
139
Reaction score
0
Points
0
you might want to look up the atoi function (ascii to integer) and you might also want to do your homework yourself ;)
 

garrettroyce

Community Support
Community Support
Messages
5,609
Reaction score
250
Points
63
It sounds like more like a stristr (from php, I don't remember the C equivalent if there is one).

If I understand correctly, this function finds the letter "x" in a string and returns it's position. I'll try to get you started, I think you'll understand this better if you do most of it yourself :)

Code:
// Pseudo-code (will not compile in any language :P)
function findX(String)
    for i = 0 to length(String)
        if ... // figure out how to find what letter is at position "i" (your loop counter)
            return i
        else
            return -1
 

misson

Community Paragon
Community Support
Messages
2,572
Reaction score
72
Points
48
It sounds like more like a stristr (from php, I don't remember the C equivalent if there is one).

strchr(). There's also strstr() and strcasestr() in the std C library. Many of those basic PHP funcs are just wrappers for the C funcs.

@Stella Richards: normally in a case like this, I'd just link to "How to ask questions the smart way", but this is important enough to quote here:
Don't post homework questions

Hackers are good at spotting homework questions; most of us have done them ourselves. Those questions are for you to work out, so that you will learn from the experience. It is OK to ask for hints, but not for entire solutions.

If you suspect you have been passed a homework question, but can't solve it anyway, try asking in a user group forum or (as a last resort) in a “user” list/forum of a project. While the hackers will spot it, some of the advanced users may at least give you a hint.
You'd do well to read the rest of the document.

The functions garretroyce and I mentioned would be useful as comparison to check that your function works. You should also check if your language of choice supports foreach loops. Using foreach, you might be able to write a more general function that doesn't assume integer indices.
 
Top