Example Programs using Control statements in Java

 

✅ 1. Check if a Number is Even or Odd

Problem: Read a number and check whether it is even or odd.


import java.util.Scanner; public class EvenOddCheck { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("Enter a number: "); int num = sc.nextInt(); if (num % 2 == 0) System.out.println(num + " is Even."); else System.out.println(num + " is Odd."); } }

✅ 2. Find the Largest of Three Numbers

Problem: Take three numbers as input and find the largest among them.


import java.util.Scanner; public class LargestOfThree { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("Enter three numbers: "); int a = sc.nextInt(); int b = sc.nextInt(); int c = sc.nextInt(); if (a >= b && a >= c) System.out.println("Largest: " + a); else if (b >= a && b >= c) System.out.println("Largest: " + b); else System.out.println("Largest: " + c); } }

✅ 3. Print Multiplication Table of a Number

Problem: Read a number and print its multiplication table up to 10.


import java.util.Scanner; public class MultiplicationTable { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("Enter a number: "); int num = sc.nextInt(); for (int i = 1; i <= 10; i++) { System.out.println(num + " x " + i + " = " + (num * i)); } } }

✅ 4. Sum of Digits of a Number

Problem: Read an integer and find the sum of its digits.


import java.util.Scanner; public class SumOfDigits { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("Enter a number: "); int num = sc.nextInt(); int sum = 0; while (num != 0) { sum += num % 10; num /= 10; } System.out.println("Sum of digits: " + sum); } }

✅ 5. Check Whether a Number is Prime

Problem: Read a number and check if it is a prime number.


import java.util.Scanner; public class PrimeCheck { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("Enter a number: "); int num = sc.nextInt(); boolean isPrime = true; if (num <= 1) isPrime = false; else { for (int i = 2; i <= Math.sqrt(num); i++) { if (num % i == 0) { isPrime = false; break; } } } if (isPrime) System.out.println(num + " is a Prime Number."); else System.out.println(num + " is Not a Prime Number."); } }

Comments

Popular posts from this blog

Object Oriented Programming PBCST 304 KTU BTech CS Semester 3 2024 Scheme - Dr Binu V P

Object Oriented Programming PBCST 304 Course Details and Syllabus

Type casting in Java