Thread: How to multiply number elements in a string?

  1. #1
    Registered User
    Join Date
    Apr 2011
    Posts
    12

    How to multiply number elements in a string?

    Hi guys well I have this problem, for some reason I'm not quite sure how to multiply an integer to each indicual element in a string.,

    Here's my code:

    Code:
     for (counter = 0 ; counter < strlen(data[i].groupCode) ; i++)
                     {
                          x = data2[i].groupCalc * i;
                          sum = sum + x;
    
                     }

    data2[i].groupCalc is an integer as well as i
    data[i].groupCode is the string.

    I tried putting it through a loop although got undesirable results. It seems as though instead of multiplying the indidual number it multiplies the entire string of number

    e.g.
    This is how I want it:

    457632
    |
    V
    4*2 = 8
    5*2 = 10
    7*2 = 14
    etc etc

    However this is how it turns out:
    457642 * 2 = 905284

    Any ideas?

  2. #2
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Code:
    for (counter = 0 ; counter < strlen(data[i].groupCode) ; i++)
                     {
                          x = data2[i].groupCalc * i;
                          sum = sum + x;
    
                     }
    First you should make up your mind which string you are operating on... You are using the length of one string to control a loop operating on a different string altogether.

    Second... do you want to multiply the ascii value of the digits or the numerical value represented by the digits?

    What you appear to want is this...
    Code:
    int MultiplyString(char *str, int mul)
      { int sum = 0;
         int x;
         int y = strlen(str);
         for (x = 0; x < y; x++)
            { sum += (str[x] -'0') * mul; }
         return sum; }
    Last edited by CommonTater; 05-04-2011 at 05:59 AM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Number of elements in multiarray
    By AcId9381 in forum C Programming
    Replies: 4
    Last Post: 12-10-2010, 12:54 PM
  2. number of non same elements
    By rafay_07 in forum C++ Programming
    Replies: 4
    Last Post: 12-07-2010, 12:40 PM
  3. number of elements in pointer
    By dayalsoap in forum C Programming
    Replies: 5
    Last Post: 05-11-2010, 11:40 PM
  4. How can I print the number of elements in this array?
    By steals10304 in forum C Programming
    Replies: 13
    Last Post: 08-18-2009, 08:41 PM
  5. Replies: 2
    Last Post: 08-03-2003, 10:01 AM