maybe some one will need it sometime :
description:
func in c++ that will add (arythmetic) two string of postive integers
to change it to c :
use malloc insted of new.
Code:/*************************************************************************** * How to add two postive numbers? * * Sun Apr 22 09:25:07 2007 * Jabka Atu * ****************************************************************************/ /* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include <iostream> using namespace std; char* add_two_postive_numbers(char *first_value,char *second_value){ char *result=NULL; char i = 0; char ans = '0'; char carry = 0; char size_of_first = strlen(first_value); char size_of_second = strlen(second_value); char biggest_size = (size_of_first > size_of_second) ? size_of_first : size_of_second; char smallest_size = (size_of_first < size_of_second) ? size_of_first : size_of_second; char delta = size_of_first - size_of_second; if (size_of_first < size_of_second) { result=add_two_postive_numbers(second_value,first_value); return result; } result=new char[biggest_size + 2]; //one more for '\0' and for extra 1 result[biggest_size + 1] = '\0'; result[0] = '0'; for (i=0;i<size_of_second;i++) { ans=first_value[size_of_first - i-1] + second_value[size_of_second-i-1] + carry - '0'; carry=0; if (ans>'9') { carry=1; result[biggest_size - i] = ans - 10; } else { result[biggest_size - i] = ans; } } if(!carry) //since there is an option that there //will be no borrow i will cp it. { for(i = 0;i < delta; i++) { result[biggest_size-size_of_second - i] = first_value[size_of_first - size_of_second - i- 1]; } } if (carry) { for (i = 0;i < (delta) ;i++) { ans=first_value[size_of_first - size_of_second - i - 1] + carry; carry = 0; if (ans > '9') { carry = 1; result[biggest_size-size_of_second - i] = ans - 10 ; } else { result[biggest_size - size_of_second - i] = ans ; } }//end of for if (carry) { result[0]='1'; } }//end of if (exsitence of an carry return result; } int main(){ char *num; num=add_two_postive_numbers("10","100"); cout << num; delete [] num; return 0; }



LinkBack URL
About LinkBacks


