1. Limited time only! Sign up for a free 30min personal tutor trial with Chegg Tutors
    Dismiss Notice
Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Homework Help: C: Squaring string represented as positive integer

  1. Dec 30, 2015 #1
    1. The problem statement, all variables and given/known data
    Write a program that will square the input positive integer represented as a string.
    2. Relevant equations
    3. The attempt at a solution

    Is there another way of squaring a string number instead of multiplying it by itself?
    Something like a pow() function for strings?
    If not, is it possible to the following program that adds two string numbers in order to find the product:
    Code (Text):

    #define MAX 100000

    typedef struct
      int arr[MAX];

    void read(NUMBER *add_num)
      int i,digit=0;
      char ch[101];
      for(i=0;i < MAX;i++)
      if(digit >= 0)

    void addition(NUMBER a,NUMBER b,NUMBER *add_res)
      int carry=0;
      int i,temp;
      for(i=0;i < MAX;i++)
      add_res->arr[i]=temp % 10;
      carry=temp / 10;

    void print(NUMBER *add_num)
      int i;

    int main()
      NUMBER x,y,z;
      printf("enter two positive integers: \n");
      printf("addition result: ");
      return 0;
  2. jcsd
  3. Dec 30, 2015 #2


    Staff: Mentor

    No, there isn't.
    To square a number represented as a string, you're going to have to do multiplication, digit by digit. For example, to multiply 12345 by 345, you need to do this:
    1. multiply 12345 by 5.
    2. multiply 12345 by 4, and multiply that result by 10.
    3. multiply 12345 by 3, and then multiply that result by 100.
    4. add together all of the partial products.

    Start with a simple example first to get things working.

    BTW, your example below compiled OK for me, after I changed scanf to scanf_s (I'm running VS 2013, and scanf is no longer supported by MSFT). When I tried to run your code, I got a stack overflow error on my machine, as your array is too large. 100,000 ints is 400,000 bytes. There's no reason I can think of to have an array of ints this size, as each digit of your answer is only one character, which could be stored in 100,000 bytes.

    One other thing -- there's no reason to have your struct, as it's just a wrapper around your array. Instead of passing the address of the struct to your functions, you could just as well pass the address of the array.
Share this great discussion with others via Reddit, Google+, Twitter, or Facebook

Have something to add?
Draft saved Draft deleted