Part 1 - Java Programs
1(a) Sum of digits of a number
public class SumOfDigits {
public static void main(String[] args) {
int num = 1234, sum = 0;
int temp = num;
while (temp > 0) {
sum = sum + temp % 10;
temp = temp / 10;
}
System.out.println("Sum of digits of " + num + " = " + sum);
}
}
1(b) Reverse a number
public class ReverseNumber {
public static void main(String[] args) {
int num = 1234, rev = 0;
int temp = num;
while (temp > 0) {
rev = rev * 10 + temp % 10;
temp = temp / 10;
}
System.out.println("Reverse of " + num + " = " + rev);
}
}
1(c) Check palindrome number
public class PalindromeCheck {
public static void main(String[] args) {
int num = 121, rev = 0, temp = num;
while (temp > 0) {
rev = rev * 10 + temp % 10;
temp = temp / 10;
}
if (num == rev)
System.out.println(num + " is a Palindrome");
else
System.out.println(num + " is not a Palindrome");
}
}
1(d) Student details using class
class Student {
String name;
int rollNo;
int marks;
void display() {
System.out.println("Name: " + name);
System.out.println("Roll No: " + rollNo);
System.out.println("Marks: " + marks);
}
}
public class StudentDetails {
public static void main(String[] args) {
Student s1 = new Student();
s1.name = "Aman";
s1.rollNo = 1;
s1.marks = 85;
Student s2 = new Student();
s2.name = "Riya";
s2.rollNo = 2;
s2.marks = 90;
s1.display();
s2.display();
}
}
1(e) Find nCr and nPr
public class NCRNPR {
static int fact(int n) {
int f = 1;
for (int i = 1; i <= n; i++) {
f = f * i;
}
return f;
}
public static void main(String[] args) {
int n = 5, r = 2;
int ncr = fact(n) / (fact(r) * fact(n - r));
int npr = fact(n) / fact(n - r);
System.out.println("nCr = " + ncr);
System.out.println("nPr = " + npr);
}
}
1(f) Check vowel or consonant
public class VowelCheck {
public static void main(String[] args) {
char ch = 'e';
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' ||
ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U') {
System.out.println(ch + " is a Vowel");
} else {
System.out.println(ch + " is a Consonant");
}
}
}