Search Logic Blocks

Saturday, January 25, 2020

Java: Let's Solve some problems

Problem : Write a program in which user enters a number. Through while / do-while loop, count by 1 starting from 0 till the entered number and get sum of all the consecutive numbers. 

Class WhileSum (WhileSum.java)
import java.util.Scanner;

public class WhileSum {
    public static void main(String args[]) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the number you want sum till");
        int number = sc.nextInt();
        int i = 1, sum = 0;
        while(i <= number) {
            sum += i;
            System.out.print(i + " ");
            i++;
        }
        System.out.println();
        System.out.println("Sum = " + sum);
    }
}
Problem : What will be the output of the following program?

Class BreakContinue (BreakContinue.java)
public class BreakContinue {
    public static void main(String args[]) {
        int sum = 0;
loop1:  for (int j = 10; j >= 1; j--) {
loop2:      for (int i = 1; i < 10; i++) {
                if (i == 2*j) {
                    System.out.println(i + " : " + j);
                    System.out.print("Continue");
                    System.out.println();
                    continue;
                }
                if (i == 4*j) {
                    System.out.println(i + " : " + j);
                    System.out.print("Break");
                    System.out.println();
                    break loop1;
                }
            }
        }
    }
}
Solution : 
8 : 4
Continue
6 : 3
Continue
4 : 2
Continue
8 : 2
Break

Exercise: What will be the correct result of following expression?
6 + 5 * 2 + 3 == 9 * 3 / 2 + 6 || false

Solution : 
6 + 5 * 2 + 3 == 9 * 3 / 2 + 6 || false =>
((6 + (5 * 2) + 3) == (((9 * 3) / 2) + 6)) || false =>
((6 + 10 + 3) == ((27 / 2) + 6)) || false =>
(19 == (13 + 6)) || false =>
(19 == 19) || false =>
true || false =>
true

Exercise: Are following variable names are legal / illegal?
  1. word123
  2. 23five.     X
  3. _next.      
  4. &6next_five.  X

No comments: