LPU Java Unit 2 Lecture 9 COD Loops RB | LPUCOLAB

LPU Java Unit 2 Lecture 9 COD Loops RB | LPUCOLAB

LPU_Java_Unit 2_Lecture 9_COD_Loops_RB

1. Problem Statement

Ted, the computer science enthusiast, has accepted the challenge of writing a program that checks if the number of digits in an integer matches the sum of its digits.

Guide Ted in designing and writing the code to solve this problem using a 'do-while' loop.

Input format:
The input consists of an integer N, representing the number to be checked.

Output format:
If the sum is equal to the number of digits, print:
The number of digits in N matches the sum of its digits.

Else, print:
The number of digits in N does not match the sum of its digits.

Solution:

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int N = sc.nextInt();
        int digitCount = 0, digitSum = 0, temp = N;

        do {
            digitCount++;
            digitSum += temp % 10;
            temp /= 10;
        } while (temp != 0);

        if (digitCount == digitSum) {
            System.out.println("The number of digits in " + N + " matches the sum of its digits.");
        } else {
            System.out.println("The number of digits in " + N + " does not match the sum of its digits.");
        }
    }
}

2. Problem Statement

In a coding competition, you are tasked with a unique problem. You need to write a program that calculates the sum of the squares of the odd digits in a given integer.

Input format:
The input consists of a single integer N, representing the number whose odd digits will be squared and summed.

Output format:
The output prints an integer, representing the sum of the squares of the odd digits in the given integer.

Solution:

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int N = sc.nextInt();
        int sum = 0;

        while (N > 0) {
            int digit = N % 10;
            if (digit % 2 != 0) {
                sum += digit * digit;
            }
            N /= 10;
        }

        System.out.println(sum);
    }
}