0% found this document useful (0 votes)
28 views7 pages

Java Flow Control Interview Programs

The document contains a collection of Java programs that demonstrate various flow control concepts, including checking even/odd numbers, finding the largest of three numbers, implementing a simple calculator, and more. Each program is presented with complete code and comments on its functionality. The examples cover a wide range of topics such as loops, conditionals, and string manipulation.

Uploaded by

slohitha465
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views7 pages

Java Flow Control Interview Programs

The document contains a collection of Java programs that demonstrate various flow control concepts, including checking even/odd numbers, finding the largest of three numbers, implementing a simple calculator, and more. Each program is presented with complete code and comments on its functionality. The examples cover a wide range of topics such as loops, conditionals, and string manipulation.

Uploaded by

slohitha465
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

■ Java Flow Control Interview Programs (Complete

Solutions)

1. Check if a number is Even or Odd


public class EvenOdd {
public static void main(String[] args) {
int n = 10;
if (n % 2 == 0)
[Link]("Even");
else
[Link]("Odd");
}
}

2. Find the Largest of Three Numbers


public class LargestOfThree {
public static void main(String[] args) {
int a = 10, b = 20, c = 15;
if (a >= b && a >= c)
[Link]("Largest: " + a);
else if (b >= a && b >= c)
[Link]("Largest: " + b);
else
[Link]("Largest: " + c);
}
}

3. Simple Calculator using switch


import [Link];
public class Calculator {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
int a = [Link]();
int b = [Link]();
char op = [Link]().charAt(0);
switch (op) {
case '+': [Link](a + b); break;
case '-': [Link](a - b); break;
case '*': [Link](a * b); break;
case '/': [Link](a / b); break;
default: [Link]("Invalid operator");
}
}
}

4. Factorial of a Number
public class Factorial {
public static void main(String[] args) {
int n = 5, fact = 1;
for (int i = 1; i <= n; i++) {
fact *= i;
}
[Link]("Factorial: " + fact);
}
}
5. Fibonacci Series up to N terms
public class Fibonacci {
public static void main(String[] args) {
int n = 10, a = 0, b = 1;
[Link](a + " " + b);
for (int i = 2; i < n; i++) {
int c = a + b;
[Link](" " + c);
a = b;
b = c;
}
}
}

6. Reverse a Number
public class ReverseNumber {
public static void main(String[] args) {
int n = 12345, rev = 0;
while (n > 0) {
rev = rev * 10 + n % 10;
n = n / 10;
}
[Link]("Reversed: " + rev);
}
}

7. Check if a Number is Palindrome


public class Palindrome {
public static void main(String[] args) {
int n = 121, temp = n, rev = 0;
while (n > 0) {
rev = rev * 10 + n % 10;
n /= 10;
}
if (temp == rev)
[Link]("Palindrome");
else
[Link]("Not Palindrome");
}
}

8. Sum of Digits of a Number


public class SumOfDigits {
public static void main(String[] args) {
int n = 1234, sum = 0;
do {
sum += n % 10;
n /= 10;
} while (n > 0);
[Link]("Sum: " + sum);
}
}

9. Prime Number Check


public class PrimeCheck {
public static void main(String[] args) {
int n = 29;
boolean isPrime = true;
if (n <= 1) isPrime = false;
else {
for (int i = 2; i <= n / 2; i++) {
if (n % i == 0) {
isPrime = false;
break;
}
}
}
[Link](isPrime ? "Prime" : "Not Prime");
}
}

10. Armstrong Number Check


public class Armstrong {
public static void main(String[] args) {
int n = 153, sum = 0, temp = n;
while (n > 0) {
int d = n % 10;
sum += d * d * d;
n /= 10;
}
if (temp == sum)
[Link]("Armstrong Number");
else
[Link]("Not Armstrong");
}
}

11. GCD of Two Numbers


public class GCD {
public static void main(String[] args) {
int a = 56, b = 98;
while (a != b) {
if (a > b) a -= b;
else b -= a;
}
[Link]("GCD: " + a);
}
}

12. Count Digits in a Number


public class CountDigits {
public static void main(String[] args) {
int n = 987654, count = 0;
while (n > 0) {
n /= 10;
count++;
}
[Link]("Digits: " + count);
}
}

13. Check Leap Year


public class LeapYear {
public static void main(String[] args) {
int year = 2024;
if ((year % 400 == 0) || (year % 4 == 0 && year % 100 != 0))
[Link]("Leap Year");
else
[Link]("Not Leap Year");
}
}

14. Days in a Month (switch)


public class DaysInMonth {
public static void main(String[] args) {
int month = 2;
switch (month) {
case 1: case 3: case 5: case 7: case 8: case 10: case 12:
[Link]("31 days"); break;
case 4: case 6: case 9: case 11:
[Link]("30 days"); break;
case 2:
[Link]("28 or 29 days"); break;
default:
[Link]("Invalid month");
}
}
}

15. Sum of First N Natural Numbers


public class SumNatural {
public static void main(String[] args) {
int n = 10, sum = 0, i = 1;
do {
sum += i;
i++;
} while (i <= n);
[Link]("Sum = " + sum);
}
}

16. Swap Two Numbers Without Third Variable


public class SwapNumbers {
public static void main(String[] args) {
int a = 10, b = 20;
a = a + b;
b = a - b;
a = a - b;
[Link]("a = " + a + ", b = " + b);
}
}

17. Missing Number in Array


public class MissingNumber {
public static void main(String[] args) {
int[] arr = {1, 2, 4, 5};
int n = 5;
int sum = n * (n + 1) / 2;
int arrSum = 0;
for (int num : arr) arrSum += num;
[Link]("Missing Number: " + (sum - arrSum));
}
}

18. Find Duplicate Elements in Array


public class DuplicateElements {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 2, 5, 3};
for (int i = 0; i < [Link]; i++) {
for (int j = i + 1; j < [Link]; j++) {
if (arr[i] == arr[j])
[Link]("Duplicate: " + arr[i]);
}
}
}
}

19. Find Largest and Smallest in Array


public class MinMax {
public static void main(String[] args) {
int[] arr = {10, 50, 20, 90, 5};
int min = arr[0], max = arr[0];
for (int n : arr) {
if (n < min) min = n;
if (n > max) max = n;
}
[Link]("Min = " + min + ", Max = " + max);
}
}

20. Reverse a String


public class ReverseString {
public static void main(String[] args) {
String str = "hello";
String rev = "";
for (int i = [Link]() - 1; i >= 0; i--) {
rev += [Link](i);
}
[Link]("Reversed: " + rev);
}
}

21. Check if Two Strings are Anagrams


import [Link];
public class AnagramCheck {
public static void main(String[] args) {
String s1 = "listen";
String s2 = "silent";
char[] a1 = [Link]();
char[] a2 = [Link]();
[Link](a1);
[Link](a2);
if ([Link](a1, a2))
[Link]("Anagram");
else
[Link]("Not Anagram");
}
}
22. Find First Non-Repeated Character
public class FirstNonRepeated {
public static void main(String[] args) {
String str = "aabbcdeff";
for (int i = 0; i < [Link](); i++) {
char ch = [Link](i);
if ([Link](ch) == [Link](ch)) {
[Link]("First Non-Repeated: " + ch);
break;
}
}
}
}

23. Count Vowels and Consonants


public class CountVowels {
public static void main(String[] args) {
String str = "Interview";
int v = 0, c = 0;
str = [Link]();
for (char ch : [Link]()) {
if (ch >= 'a' && ch <= 'z') {
if ("aeiou".indexOf(ch) != -1)
v++;
else
c++;
}
}
[Link]("Vowels: " + v + ", Consonants: " + c);
}
}

24. Find Second Largest Element in Array


public class SecondLargest {
public static void main(String[] args) {
int[] arr = {10, 20, 4, 45, 99, 99};
int first = Integer.MIN_VALUE, second = Integer.MIN_VALUE;
for (int n : arr) {
if (n > first) {
second = first;
first = n;
} else if (n > second && n != first) {
second = n;
}
}
[Link]("Second Largest: " + second);
}
}

25. Palindrome String


public class PalindromeString {
public static void main(String[] args) {
String str = "madam";
String rev = "";
for (int i = [Link]() - 1; i >= 0; i--) {
rev += [Link](i);
}
if ([Link](rev))
[Link]("Palindrome");
else
[Link]("Not Palindrome");
}
}

Common questions

Powered by AI

The algorithm for finding the greatest common divisor (GCD) used in the code is based on the Euclidean method, which is efficient due to its repeated subtraction approach that reduces the problem size at each step. The algorithm continues until both numbers are equal, indicating the GCD. This method is efficient because it reduces large numbers significantly faster than direct comparisons and divisions, converging quickly, particularly on high numerical inputs .

The program checks if a year is a leap year using the condition: if a year is divisible by 400 or divisible by 4 but not by 100, it is a leap year. This condition works because any year divisible by 400 is a leap year (e.g., 2000), and any year divisible by 4 but not 100 is also a leap year (e.g., 2024). However, if a year is divisible by 100 but not 400, it is not a leap year (e.g., 1900).

The algorithm for finding duplicates in an array is considered inefficient because it uses a nested loop, resulting in O(n^2) time complexity. Each element is compared with every other element, which makes it unsuitable for large datasets. This can be improved by using a HashSet to track seen elements, checking for duplicates in O(1) average time complexity, reducing the overall complexity to O(n).

The switch-case statement is strong for a simple calculator because it clearly parses different operations ('+', '-', '*', '/') into separate branches, offering readability and structured handling of each operation. It simplifies function decision-making compared to multiple if-else statements. However, its weakness includes limited operations—adding more operators needs case modifications. Additionally, it does not support complex expressions or the precedence of operations, requiring a more detailed parsing mechanism for those .

Swapping two numbers without a third variable is achieved using arithmetic operations. The logic is: a = a + b; b = a - b; a = a - b. This works because after the first operation, 'a' holds the sum of 'a' and 'b'. The second operation assigns to 'b' the difference between the sum and the original 'b', effectively giving it the original value of 'a'. Finally, the third operation assigns to 'a' the difference between the new 'b' (original 'a') and the sum, giving 'a' the original value of 'b'. This technique avoids the need for temporary storage .

The program checks if two strings are anagrams by converting the strings to character arrays, sorting them, and then comparing the sorted arrays with Arrays.equals(). This method works because anagrams have identical sorted character plots. However, its limitations include inefficiency due to sorting complexity O(n log n) and incorrect results if case sensitivity or spaces are involved since these are not addressed without preprocessing the strings .

The program checks if a number is an Armstrong number by calculating the sum of the cubes of its digits and comparing it to the original number. It uses a while loop to extract digits using the modulo operator, cubes each digit, adds to a sum, and divides the number to get the next digit. If the sum equals the original number, it confirms it as an Armstrong number, which is true for numbers where the sum of their cubic digits equals the number itself (e.g., 153).

The algorithm finds the first non-repeated character by iterating over the string and checking if a character's first and last index positions match. This method is straightforward but inefficient with O(n^2) complexity because it requires multiple index searches for potential matches. Improvement could involve utilizing a HashMap to store character occurrences, providing O(n) time complexity by updating counts during a single pass, and easily identifying the first unique character by another pass through the string .

The program implements the Fibonacci series iteratively using two initial numbers (0 and 1), generating the subsequent numbers by summing the last two. It is efficient for moderate values of N due to its linear time complexity O(n). However, for very large values of N, the computation time and growing size of the output can be a concern, and the iterative approach would consume significant memory and processing resources due to the direct print statements within a loop .

The use of a "do-while" loop in calculating the sum of digits is beneficial because it ensures that the loop executes at least once regardless of the number's value. This is more advantageous than a "while" loop when the number could potentially be zero, as a "while" loop might initially evaluate the loop condition as false and not execute. The "do-while" guarantees the loop body processes at least once, which is crucial when iterating and summing digits extracted from the least significant to most significant .

You might also like