Q) Write an interactive Java program that adds two integers of up to 50 digits each (Represents integer as an array of digits).
1
Expert's answer
2013-06-28T04:56:50-0400
import java.util.* ;
public class Calculator { public static void main(String[] args) { Scanner s = new Scanner(System.in); System.out.print("Enter the first integer:"); String a = s.nextLine(); System.out.print("Enter the second integer:"); String b = s.nextLine(); int[] num1 = new int[a.length()]; int[] num2 = new int[b.length()]; for (int i=0;i<a.length();i++) { num1[i] = (int) a.charAt(i); num2[i] = (int) b.charAt(i); } int[] sum = new int[a.length()]; for (int n=b.length()-1;n>=0;n--) { if (num1[n]+num2[n]<10) { sum[n]=num1[n]+num2[n];
} if (num1[n]+num2[n]>=10) { sum[n]=(num1[n]+num2[n]); sum[n-1]=sum[n-1]+1; } } for (int d=0; d<a.length();d++) { System.out.print(sum[d]+" "); } } }
Comments
Q) Write an interactive Java program that adds two integers of up to 50 digits each (Represents integer as an array of digits).
Leave a comment