Computer Science, asked by bucketfighter, 5 months ago

ccept a 2 digit number and get the digits seperately and display their sum

Answers

Answered by pushpendrayadav12009
1

Explanation:

To store 10 integer numbers array can be used. All integers will be stored in the array and using the for/while loop every integer can be checked that how many digits in the number. Take two variables, one to store all two digit numbers sum and one for all three digit numbers sum, initialize both variables with 0. If the number has 2 digits then add it to the first variable and if it has three-digit then add it to the second variable, remaining all numbers which have digits greater than 3 or less than 2 leave as it is.

import java.util.Scanner;

class Sum{

static int[] findSum(int[] a){

int sum2d=0, sum3d=0, count;

for(int i=0; i<a.length; i++){

int num = a[i];

count = 0;

//finding the total digits in the number

while(num!=0){

num /= 10;

count++;

}

if(count == 2) sum2d += a[i];

else if (count == 3) sum3d += a[i];

}

return (new int[] {sum2d, sum3d});

}

public static void main(String[] args) {

Scanner scan = new Scanner(System.in);

//Taking inputs from the user

System.out.print("How many numbers you want to enter: ");

int n = scan.nextInt();

int[] arr = new int[n];

System.out.printf("Enter %d numbers: \n", n);

for(int i=0; i<n; i++){

arr[i] = scan.nextInt();

}

//Calling findSum method

int[] result = findSum(arr);

System.out.printf("Sum of all two digit numbers = %d\n", result[0]);

System.out.printf("Sum of all Three digit numbers = %d\n", result[1]);

}

}

Answered by nehare2424
0
// a program to input a 2 digit number and display the sum of its digits
import Java.until.*;
public class Sum_digit
{
public static void main(String args[])
{
Scanner in=new Scanner(System.in);
int num,sum=0,rem=0;
System.out.println(“Enter a 2-digit number”);
num=in.nextInt();
for(int i=1;i<=2;i++)
{
rem=num%10;
sum=sum+rem;
num=num/10;
}
System.out.println(“Sum of the digits of”+num+”is”+sum);
}
}
Similar questions