Thread: Adding a Large number digit by digit

  1. #1
    Registered User
    Join Date
    Oct 2005
    Posts
    17

    Adding a Large number digit by digit

    I posted a previous thread but it is pretty much dead, so here is a new one.

    I'm trying to add to very large numbers digit by digit that the user inputs.
    I have it working as long as the numbers are the same length digit wise and the last number does not have a carry.

    I'm not sure how to shift the numbers and keep the program working the way its suppose to.

    Code:
    #include "stdafx.h"
    #include<stdio.h>
    #include<string.h>
    #include<stdlib.h>
    
    int main(int argc, char* argv[])
    {
    unsigned char number1 [256] = {'0'};
    unsigned char number2 [256] = {'0'};
    unsigned char result [256] = {'0'};
    int i, y=0, sum=0, carry=0;
    
    printf ("Please enter a number upto 255 digits long:\n");
    scanf ("%s", number1);
    printf ("Your first number is %s.\n",number1);
    
    printf ("Please enter another number upto 255 digits long:\n");
    scanf ("%s", number2);
    printf ("Your second number is %s.",number2);
    
    
    memset (result, 0, sizeof(result));
    
    
    	for(y=255; y>=0; y--) {
    		
    BACK:		
    		if( number1[y] == 0) {
    			y--;
    			goto BACK;
    		}
    		else if( number2[y] == 0) {
    			y--;
    			goto BACK;
    		}
    		else{
    		sum += carry;
    		sum += number1[y]-'0'+number2[y]-'0';
    		carry = sum/10;
    		result[y] = sum%10+'0';
    		sum = 0;}
    }
      printf("\nThe sum is %s.", result);
    
    
      return 0;
    }
    Thank you for your help.

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    There's still life in your other thread, and starting a new one just looks like bumping.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. help with prime factor for 12 digit number
    By nick2 in forum C Programming
    Replies: 15
    Last Post: 06-19-2009, 04:39 AM
  2. Number Guessing
    By blacknapalm in forum C Programming
    Replies: 2
    Last Post: 10-01-2008, 01:48 AM
  3. Nim Trainer
    By guesst in forum Game Programming
    Replies: 3
    Last Post: 05-04-2008, 04:11 PM
  4. Need help getting program print out the digit in words
    By cosmiccomputing in forum C Programming
    Replies: 26
    Last Post: 04-24-2008, 08:28 AM
  5. Array of boolean
    By DMaxJ in forum C++ Programming
    Replies: 11
    Last Post: 10-25-2001, 11:45 PM