Thread: need help with problem

  1. #1
    Registered User
    Join Date
    Dec 2002
    Posts
    2

    need help with problem

    Create a function
    int position(char * s, char c)
    which takes a string parameter s and a char parameter c and returns
    i. the first position in s which is equal to c
    ii. -1 if c does not appear in s at all
    for example
    position("hello world",'w') will return 6
    position("hello world",'z') will return -1

    Create test5.c to test the function position. The main() function in test5 should


    i. use gets() to read in a string
    ii. print out the first position of each of the characters a, e, i, o and u in the string


    Greatful for any help offered.

  2. #2
    Registered User
    Join Date
    Dec 2002
    Posts
    2

    heres a function i did but i dont know how to combine it.

    #include <stdio.h>


    int position(char s, char c)
    {
    int i;
    int j;
    int pos;

    pos = -1;

    for(i = 0; pos == -1 && s[i] != '\0'; i++)
    {
    for(j = 0; pos == -1 && c[j] != '\0'; j++)
    {
    if(c[j] == s[i])
    {
    pos = i;
    }
    }
    }

    return pos;
    }


    Heres a function ive tried to use as a basis of the program, i know how to get and read a string but i dont know how to combine it with the above function so i can find positions of vowels in a string.

  3. #3
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,005
    From the prototype to the code, you lost the pointer declaration for s. And c is a single char, not a string, so there is no reason for the second loop.
    Code:
    int position(char *s, char c)
    {
        int i;
        for ( i = 0; s[i] != '\0'; i++ )
        {
            if ( c == s[i] )
            {
                return i;
            }
        }
        return -1;
    }
    >i. use gets() to read in a string
    In the future, avoid gets.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Need help understanding a problem
    By dnguyen1022 in forum C++ Programming
    Replies: 2
    Last Post: 04-29-2009, 04:21 PM
  2. Memory problem with Borland C 3.1
    By AZ1699 in forum C Programming
    Replies: 16
    Last Post: 11-16-2007, 11:22 AM
  3. Someone having same problem with Code Block?
    By ofayto in forum C++ Programming
    Replies: 1
    Last Post: 07-12-2007, 08:38 AM
  4. A question related to strcmp
    By meili100 in forum C++ Programming
    Replies: 6
    Last Post: 07-07-2007, 02:51 PM
  5. WS_POPUP, continuation of old problem
    By blurrymadness in forum Windows Programming
    Replies: 1
    Last Post: 04-20-2007, 06:54 PM