Top 100 Codes
Top 100 Codes
Preface:
This book contains all the information regarding Top 100 codes which is asked in Placement Tests and Interview Rounds.
Nowadays you will see many books and online pages providing information on Coding questions. Mostly those books contain
one section i.e either the coding questions or the theoretical part. There is no such proper book providing all the updated
information at one single place.
This book contains various questions and theory knowledge of all the types asked in Placement tests. This book carries all the
Top 100 codes asked during the whole Recruitment Process. .
It is hoped that the subject matter will instill trust in the applicants, and that the book will assist them in finding an ideal teacher.
Disclaimer: This book is made and published under the complete knowledge and expertise of the Author, however if there will be
any error then it will be taken care of in the next Revised edition. Constructive suggestions and feedback are most welcome by
our esteemed readers.
2
May 2021
Edition: 1 (2021)
Published on GSM Paper with PrepInsta WaterMark
Contents
Chapter 1- Positive or Negative Number 5 Chapter 2. Even or Odd Number 6 Chapter 3: Sum of first N
Natural numbers 8 Chapter 4: Sum of N Natural Numbers 9 Chapter 5- Sum of numbers in given range 10
Chapter 6- Greatest of two numbers 12 Chapter 7- Greatest of three numbers 14 Chapter 8: Leap year or not
16
Chapter 9: Prime number 17 Chapter 10: Prime Number with given range 19 Chapter 11: Sum of digits of
number 22 Chapter 12: Reverse of a number 23 Chapter 13. Palindrome number 25 Chapter 14. Armstrong
number 27 Chapter 15. Armstrong number of given range 29 Chapter 16. Fibonacci series of nth term 31
Chapter 17: Factorial of a number 33 Chapter 18: Power of a number 34 Chapter 19: Factor of a number 36
Chapter 20. Strong Number 37 Chapter 21. Perfect Number 40 Chapter 22. Automorphic Number 41
Chapter 25. Friendly Pair 48 Chapter 26. HCF 50 Chapter 27. LCM 52 Chapter 28. Greatest Common
Divisor 54 Chapter 29. Binary to decimal conversion 56
Chapter 30. Binary to octal conversion 58 Chapter 31. Decimal to binary conversion 60 Chapter 32. Decimal
to octal conversion 61 Chapter 33. Octal to Binary conversion 63 Chapter 34: Octal to Decimal Conversion 65
Chapter 35: Quadrants in which given coordinate lies 66 Chapter 36. Permutations in which n people can
occupy r seats in a classroom 68 Chapter 37. Maximum number handshakes 70 Chapter 38.Addition of two
fractions 71 Chapter 39. Replace all 0’s with 1 in a given integer 73 Chapter 40. Can a number be expressed
as a sum of two prime numbers 75 Chapter 41. Count possible decodings of a given digit sequence 77 Chapter
Chapter 43. Check whether a character is a alphabet or not 79 Chapter 44. Calculate the area of a circle 81
Chapter 45. Find the ASCII value of a character 82 Chapter 46. Find the prime numbers between 1 to 100 83
Chapter 47. Calculate the number of digits in an integer 84 Chapter 48. Convert digit/number to words 86
Chapter 49: Counting number of days in a given month of a year 87 Chapter 50: Finding Number of times x
digit occurs in a given input 88 Chapter 51. Finding number of integers which has exactly x divisors 89
5
6 ● Step 2. Enter the number.
● Step 3. If the number is less than or equal to zero,
check if it is zero.
Example :
Number is 24
Number is 15
Working
● Step 1. Start
else }
printf(“The number is odd\n“); }
return 0;
} Python Code :
num = int(input("Enter a Number:"))
if num % 2 == 0:
C++ Code :
print("Given number is Even")
//C++ Program else:
// number is even or odd print("Given number is Odd")
#include
using namespace std; # This code is contributed by Shubhanshu Arya (Prepinsta
int main() Placement Cell Student)
{ 9
cout<<“Enter a number: “;
int check;
cin>>check;
//checking whether the number is even or odd Chapter 3. Sum of First N
if(check % 2 == 0)
{
cout<<check<<” is an even number”;
} System.out.println(“Sum is ” +sum);
else
{
cout<<check<<” is an odd number”;
Natural numbers
} A Natural number is the same as Counting number.They
return 0; are used to Count the numbers of real physical objects.
} Natural numbers start from 1 and go on infinite. The
Java Code : positive numbers 1, 2, 3… are known as natural numbers.
//Java Program to check a number is even or odd Example:
import java.util.Scanner; Natural number={1,2,,4,5,6,…….}.
public class even_or_odd Formula for Sum of First N natural numbers is : n(n+1)/2.
{ If you want to add the first 5 Natural numbers then we find
public static void main(String[] args) the Sum of 1+2+3+4+5 =15.
{
//scanner class declaration Working
Scanner sc = new Scanner(System.in); Step 1. Start
//input from the user
System.out.print("Enter a Number : "); Step 2. Enter a number (N).
calculates their sum. The program uses a loop to calculate The program given below accepts a range of values and
the sum of the values provided by the user. The following calculates their sum. The program uses a loop to calculate
section presents an algorithm followed by a C program to the sum of the values provided by the user. Also, the
successful
Example:-Enter first and last range 4 and 8.
12
Example:-Enter first and last range 4 and 8. end with i<= lastrange.
number(total).
Answer is 30(i.e 4+5+6+7+8=30).
● Step 8. Stop
Working
● Step 1. Initialize variables (firstrange,lastrange, C Code :
total and i). #include <stdio.h>
int main()
● Step 2. Input fistrange and lastrange by user. ● {
//for initialization of variable
Step 3. We use “for loop” with the condition
int firstrange,lastrange, i=0, total= 0;
(i=firstrange;i<= lastrange;i++).When loop will
//to use user input first range & last range
printf(“Enter the value first range and last range\n“);
scanf(“%d\n%d”,&firstrange, &lastrange);
cout << “Enter the upper limit: “;
//use for loop for total no.inside the range cin >> upper_limit;
for(i = firstrange; i <= lastrange; i++){
//calculating sum of numbers in the given range
//total+=i; for(int i = lower_limit; i <= upper_limit; i++){
total = total + i; sum += i;
//print the sum of number }
printf(“Sum of number firstrang %d to lastrange %d is:
%d”,firstrange, lastrange, total); //printing output
} cout<<“The Sum of Natural Numbers from “ <<
Output lower_limit << ” to “ << upper_limit << ” is “ <<
sum; return 0;
Enter the value first range and last range: }
30
40 Java Code :
sum of number firstrange 30 to lastrange 40 is : 385 //Java program to print the sum of numbers in a given range
import java.util.Scanner;
C++ Code : public class sum_of_numbers_in_range
//C++ Program {
//Sum of Natural Numbers in a given range public static void main(String[] args)
#include<iostream> {
using namespace std; //scanner class declaration
//main Program Scanner sc = new Scanner(System.in);
int main() //input from user
{ System.out.print("Enter starting
int sum = 0 , upper_limit, lower_limit; number : ");
cout << “Enter the lower limit: “; int start = sc.nextInt();
cin >> lower_limit;
13
} Method 2:
}
num = int(input("Enter the Number:"))
Python Code : sum = (num * (num+1))/2
print("The Sum of N natural Number is {}".format(sum))
Method 1:
# This code is contributed by Shubhanshu Arya (Prepinsta
Placement Cell Student)
cout<<first<<” is greater than “<<second;
Chapter 6. Greatest of two int main()
{
numbers int no1, no2;
printf(“Insert two numbers:”);
In C programming language, the greatest of numbers can be scanf(“%d %d”,&no1, &no2);
identified with the help of IF-ELSE statements. The user is //Condition to check which of the two number is greater
asked to insert two integers. The numbers inserted are then //it will compare of number where number 1 is greater
if(no1 > no2)
calculated using a set of programs to get the correct output. printf(“%d is greatest”,no1);
It will find the highest number among them using IF-ELSE
//where number 2 is greater
Statement and start checking which one is larger to display else if(no2 > no1)
printf(“%d is greatest”,no2);
the largest number.
//for both are equal
else
Example – If the given numbers are 12 and 9 then greater
printf(“%d and %d are equal”, no1, no2);
number is 12
return 0;
}
12, 9= 12>9
Output
Working
Insert Two Numbers : 5
Step 1: Start 6
6 is the Greatest
Step 2: Insert two integers no1 and no2 from the user with
C++ Code :
the help of scanf statement. //C++ program
Step 3: Check if the no1 is bigger in value than no2 using //Greatest of two numbers
statement, if not then print no1 and no2 are equal using cout<<“Enter first number: “;
cin>>first;
printf statement.
cout<<“Enter second number: “;
Step 6: Stop
cin>>second;
if(first==second)
C Code: {
14
cout<<“both are equal”;
}
#include<stdio.h>
else if(first>second)
{
}
else
{
cout<<second<<” is greater than “<<first;
Chapter 7. Greatest of the
}
return 0;
C code :
}
#include<stdio.h> int main()
Java Code :
//Java program to find greatest of two numbers
import java.util.Scanner; Three numbers
public class greatest_of_two_numbers
{ The C program to find the greatest of three numbers requires
public static void main(String[] args) the user to insert three integers. Flow chart is also used in C
{ programming to find the greatest number among three
//scanner class declaration integers inserted by the user. A simple if-else block is used to
Scanner sc = new Scanner(System.in); identify the greatest number.
//input first number
Problem Description
System.out.print("Enter the first
number : "); C programs to find the greatest of three numbers require the
int first = sc.nextInt();
//input second number user to insert three integers. Flow chart is also used in C
System.out.print("Enter the second
programming to find the greatest number among three
number : ");
int second = sc.nextInt(); integers inserted by the user. A simple if-else block is used
//conditions
if(first > second) to identify the greatest number. The program will ask the
C++ code :
16
else
}
{ System.out.println();
cout<<third<<” is the greatest”; //condition for first number
} if(first > second && first > third)
return 0;
} System.out.println(first+" is
Java code : the greatest number.");
//Java program to find greatest of three numbers //condition for second number
import java.util.Scanner; else if(second > first && second >
public class greatest_of_three_numbers third)
{ System.out.println(second+"
public static void main(String[] args) is the greatest number.");
{ //condition for third number
//scanner class declaration else if(third > first && third > second)
Scanner sc = new Scanner(System.in);
//input three numbers from user System.out.println(third+" is
System.out.print("Enter the first the greatest number.");
number : "); //condition when all three numbers are
int first = sc.nextInt(); equal
System.out.print("Enter the second else
number : ");
int second = sc.nextInt();
System.out.print("Enter the third System.out.println("All three
number : "); numbers are same");
int third = sc.nextInt(); //closing scanner class(not compulsory,
but good practice) to check if the year is Leap or not.
sc.close();
Step 4. It is true display year is a leap year.
Python Code :
year = int(input("Enter Year:"))
if year % 4 == 0:
if year % 100 == 0:
if year % 400 == 0: other than 1 or itself is a prime number.
print("Yes, {} is Leap Year".format(year))
else: It should have only 2 factors. They are, 1 and the number
print("No, {} is Leap Year".format(year)) itself.
else:
print("No, {} is Leap Year".format(year))
else: Problem Description
print("No, {} is Leap Year".format(year))
In this program we will find if a number is a prime number
# This code is contributed by Shubhanshu Arya (Prepinsta or not with the help of a for loop or if else statement. A
Placement Cell Student)
number is considered a prime number when it satisfies the
Chapter 9. Prime number below conditions.
A number is considered a prime number when it satisfies
the below conditions. ● Prime number is a number which can be divided
by 1 and itself
● A number which can not be divided by any other
Prime number is a number which can be divided by 1 and
number other than 1 or itself is a prime number. ● It
itself should have only 2 factors. They are, 1 and the
number itself.
A number which can not be divided by any other number
Ex- Number is 13. it have only 2 factor
19
}
● it is divisible by 1.
● And it is divisible by itself //display
printf(“%d is not a prime number”,number);
So it is a prime number. return 0;
}
Output
Working
Step 1. Read a “num” value to check prime or not. Enter Number:6
6 is not a Prime Number
Step 2. set i=1,div=0.
Enter Number:13
Step 3. if i<=num if true go to step 4, else go to step 7.
13 is a Prime Number
Step 4. Check the condition num%i==0 if true then
int n = sc.nextInt();
//taking a number n as input
int count=0;
for(int i = 1 ; i <=n ; i++)
{
if(n % i == 0)
//condition for getting the factors of
number n
count=count+1;
}
if(count == 2)
//if factors are two then, number is prime else not these three numbers are prime numbers.
System.out.println("Prime Number");
else
System.out.println("Not a Prime Problem Description
Number"); The C program reduces the number of iterations within the
sc.close();
//closing scanner class(not mandatory but good practice) } for loop. It is made to identify or calculate the prime
//end of main method numbers within a given range of numbers inserted by the
} //end of class Output :
user. The program takes the range and identifies all the
5, 7, 11).
//display
prime(i); sc.close();
}
return 0;
}
}
Python Code :
first = int(input("Enter the first number:"))
Java Code : second = int(input("Enter the Second Number:"))
for i in range(first, second):
//Java program to print prime numbers in a given range
for j in range(2, i//2):
import java.util.Scanner; if i % j == 0:
public class prime_numbers_in_a_given_range break
else:
{ print("Prime Number", i)
public static void main(String[] args)
# This code is contributed by Shubhanshu Arya (Prepinsta
{
Placement Cell Student)
//scanner class object creation 23
Scanner sc=new Scanner(System.in);
//input from user
System.out.print("Enter Starting
Chapter 11. Sum of digits of
Number : ");
int start = sc.nextInt();
System.out.print("Enter Ending C code :
Number : ");
int end = sc.nextInt(); a number
System.out.println("Prime numbers
This program in C programming calculates the sum of
between "+start+" and "+end+" are : ");
//loop for finding and printing all primenumbers inserted by the user or in an inserted integer. The
numbers between given range
program is taken as an input and stored in the variable
for(int i = start ; i <= end ; i++)
{ number, denoted as no. Initially, the sum of the variable is
//logic for checking number zero, and then it is divided by 10 to obtain the result or
is prime or not
output.
count = 0;
no /= 10;
In this C program to allow the user enter any number and }
printf("Given number = %d\n", temp);
then it will divide the number into individual digits and add printf("Sum of the numbers %d = %d\n", temp, sum);
those individuals (Sum=sum+digit) digits using While Loop. return 0;
}
Output
Ex:- number is 231456 Insert a number: 16789
//C++ Program
Working:- //Sum of digits in a number
Step 1: Start
#include
Step 2: Ask the user to insert an integer as an input. Step 3:
using namespace std;
Divide the integer by 10 in order to obtain quotient and int main()
{
remainder. int num,sum=0;
cout<<“Enter any num : “;
Step 4: Increase the new variable with the remainder
//user input
received in the above step cin>>num;
//loop to find sum of digits
Step 5: Repeat the above steps with the quotient till the do
{
value of the quotient becomes zero.
Java Code
//Java program to calculate sum of digits of a
{
number import java.util.Scanner;
public class sum_of_digits
int no, temp, digit, sum = 0;
{
public static void main(String[] args)
printf ("Insert a number \n");
{
scanf ("%d", &no);
//scanner class declaration
Scanner sc = new Scanner(System.in);
temp = no;
//input from user
while (no > 0)
System.out.print("Enter a number : ");
{
digit = no % 10;
int number = sc.nextInt();
sum = sum + digit;
//declare a variable to store sum of
digits
int sod = 0;
while(number != 0) Working:-
{
int pick_last = number % 10;
sod = sod + pick_last; Step 1. Take the number which you have to reverse as
number = number / 10;
the input variable says number.
}
//display sum of digits Step 2. Obtain its quotient and remainder.
System.out.print("Sum of Digits =
"+sod); Step 3. Multiply the separate variable with 10 and add
//closing scanner class(not compulsory,
the obtained remainder to it.
but good practice)
sc.close(); Step 4. Do step 2 again for the quotient and step 3 for
}
the remainder obtained in step 4.
}
Python Code : Step 5, Repeat the process until the quotient becomes
{
{
//left is for remider are left number=number/10;
left= number%10;
}
//for reverse of no. //To show the user value
rev = rev * 10 + left; printf("Given number = %d\n",store);
C Code }
//C++ Program }
//Reverse of a number
#include <iostream> Python Code
using namespace std; num = int(input("Enter the Number:"))
//main program temp = num
int main() reverse = 0
{ while num > 0:
//variables initialization remainder = num % 10
int num, reverse=0, rem; reverse = (reverse * 10) + remainder
cout<<“Enter a number: “; num = num // 10
//user input
cin>>num; print("The Given number is {} and Reverse is {}".format(temp,
//loop to find reverse number reverse))
do
{ # This code is contributed by Shubhanshu Arya (Prepinsta
rem=num%10; Placement Cell Student)
reverse=reverse*10+rem; 26
num/=10;
}while(num!=0);
//output
cout<<“Reversed Number: “<<reverse; return 0; Chapter 13. Palindrome
}
Java Code
//Java program to print reverse of a number import
//input a numbers for user
java.util.Scanner;
public class reverse_of_number
public static void main(String[] args)
number
{ A palindrome number is a number that is given the same
//scanner class declaration
Scanner sc = new Scanner(System.in); number after reverse. In C programs to check if the input
//input from user
number is palindrome or not. We are using a while loop and
System.out.print("Enter a number : ");
an else if statement in the C Program.
int number = sc.nextInt();
System.out.print("Reverse of
"+number+" is "); Ex:- A number is 123321 .If you read the number “123321”
int reverse = 0;
from reverse order, it is the same as “123321”. In that
String s = "";
while(number != 0) number is a palindrome.
{
int pick_last = number % 10; A number is 12121. If we read the number “12121” from
//use function to convert
reverse order ,it is the same as 12121. It is also a
pick_last from integer to string
s=s+
palindrome number else
printf("it is not a Palindrome number");
return 0;
Working:- }
Output:-
Step 1.Take the number which you have to reverse and find
Enter the number
the palindrome as the input variable says number. Step
121121
2.Number is stored in his duplicity value as a duplicate
String st = sc.next();
//string function for calculating length
number
of the string
In this program we will find the number is Armstrong or not
int len = st.length();
//string variable to store reversed string where the number should be entered by the user. Basically
String st1 = "";
for(int i = 0 ; i < len ; i++) the sum of the cube of its digits is equal to the number itself
{ is called Armstrong number.
//string function for getting
character at a particular index
char ch = st.charAt(i); Ex:- Enter any number 153.
st1 = ch + st1;
}
//condition for checking palindrome by 1**3 + 5**3 + 3**3 = 153
using string function
if(st.equals(st1))
Number is Armstrong
System.out.print("Palindrome");
else Working:
System.out.print("Not
Palindrome"); Step 1.Initialize variables num,n,n1,c=0,mul=1,sum=0,r,f,i .
//closing scanner class(not compulsory,
but good practice) Step 2.Input any number by user so read num variable. Step
sc.close(); 3.set n=num and n1=num for duplicate.
reminder(r)=number(n)%10.
Python Code
temp = number Step 6.Than increment of other variables for next step
reverse = 0
(c++).
while number > 0:
remainder = number % 10 Step 7.Than find length of number with condition is
reverse = (reverse * 10) + remainder
number = number // 10 number(n)=number(n)/10.
num=num/10;
Step 15.The check if (n1==sum) display number is mul=1;
for(i=1;i<=c;i++)
armstrong
{
Step 16.Either false display number is not armstrong mul=mul*f;
}
Step 17.stop
sum=sum+mul;
C Code num=num/10;
}
if(n1==sum)
#include<stdio.h> printf("Armstrong Number");
int main() else
{ printf("Not an Armstrong Number");
int num ,n,n1,c=0,mul=1,sum=0,r,f,i; return 0;
printf("enter any num: \n"); }
scanf("%d",&num); Output:-
n=num; enter any num: 1634
n1=num;
while(n!=0) Armstrong Number.
{
r=n%10;
c++; enter any num: 135
n=n/10;
}
C ++ Code
while (num!=0)
//C++ Program
{
//Armstrong number or not
f=num%10;
29
#include<iostream>
else
#include<math.h>
using namespace std; Java Code
//main Program //Java program to check whether a number is armstrong or
int main() not
{ import java.util.Scanner;
int num, digit, sum = 0; public class armstrong_number_or_not
cout << “Enter a positive integer: “; {
//user input public static void main(String[] args)
cin >> num; {
int store = num; //scanner class declaration
//find sum of cubes of individual digits Scanner sc = new Scanner(System.in);
do //input from user
{ System.out.print("Enter a number : ");
digit = num % 10;
sum = sum + pow(digit,3); int number = sc.nextInt();
num = num / 10; int n = number;
}while(num != 0); int sum = 0;
//checking for ArmStrong number while(n != 0)
if(sum == store) {
cout << store << ” is an Armstrong number.”; int pick_last = n % 10;
else sum = sum + (pick_last *
cout << store << ” is not an Armstrong number.”; pick_last * pick_last);
return 0; n = n / 10;
} }
//condition for checking that the sum is
equal to the number or not
if(sum == number)
Working
System.out.println("Armstrong Number"); Step 1: Start
System.out.println("Not an
Armstrong Number"); Step 2: Insert the start and end value
//closing scanner class(not compulsory,
but good practice) Step 3: Repeat from I = start value to end value Step 4:
sc.close(); Repeat the process until the temporary number is not
equal to 0.
}
} Step 5: Remainder = temp%0
if sum == value:
Step 9: Else repeat the steps until the end number is
print("Given number is Armstrong Number")
else: encountered.
print("Given Number is not Armstrong Number")
C Code
# This code is contributed by Shubhanshu Arya (Prepinsta
Placement Cell Student)
30
#include<stdio.h>
int main()
is the sum of the previous two numbers. The first two terms 10
Input");
System.out.print("Wrong
number
//closing scanner class(not compulsory,
In this program we will find the factorial of a number
but good practice)
where the number should be entered by the user. Factorial Output:-
Enter a number to calculate its factorial 4
is a sequence of a number whose multiply by all previous
System.out.print(i+" ");
}
//closing scanner class(not compulsory,
but good practice)
sc.close();
}
}
Python Code
num = int(input("Enter the number:"))
factorial = 1
for i in range(1, num+1):
factorial = factorial * i
Ex:-|
That is 5*5*5=125
Working:
equal to zero.
36
Java Code
C Code //Java program to calculate power of a number
#include<stdio.h> import java.util.Scanner;
int main() public class Power_of_a_number
{ {
//To initialize variables public static void main(String[] args)
int number, expo,temp = 1; {
//scanner class declaration
//To take user input Scanner sc = new Scanner(System.in);
printf("Enter a base number: "); //input base value and exponent value
scanf("%d", &number); from user
//To display Exponent System.out.print("Enter the value of
printf("Enter an exponent: "); base : ");
scanf("%d", &expo); int base = sc.nextInt();
//use while loop when power is not equal to zero System.out.print("Enter the value of
while (expo != 0) exponent : ");
{ int exp = sc.nextInt();
//temp*=number //declare an integer variable to store the
temp = temp * number; result
--expo; int result = 1;
} //logic for calculating power of the
printf("power of a %d is %d",number, temp); entered number
return 0; while (exp != 0)
} {
Output:- result = result * base;
--exp;
Enter a base number: 6
Enter an exponent: 4 }
//print the result
power of a 6 is 1296
System.out.println("Answer = " + result);
//closing scanner class(not compulsory,
C++ Code
but good practice)
//C++ Program
sc.close();
//Power of a number }
#include <iomanip>
}
#include <iostream>
#include <math.h>
using namespace std;
Python Code
//main program base = int(input("Enter Base number:"))
int main() expo = int(input("Enter Expo Number:"))
{ temp = 1
double exp, base;
cout<<“Enter base: “; for i in range(0, expo):
//user input 1 temp = temp * base
cin>>base;
cout<<“Enter Exponent: “; print(temp)
cin>>exp;
37
Chapter 19 Factor of a
}
printf("%d ",u);
return 0;
number }
Output:-
In this Program we will calculate the factors of any Enter an any number: 12
numbers using C programming. The factors of a number are Factors of a number 12 are: 1 2 3 4 6 12
defined as the number we multiply two numbers and get the C ++ Code
original number. The factor of a number is a real number //C++ Program
//Factors of a number
which divides the original completely with zero remainder. #include <iostream>
using namespace std;
Ex- no is 16,5. //main Program
16= 2 x 2 x 2 x 2 int main()
{
5= 1 x 5 int num;
cout << “Enter a positive number: “;
Working //user input
cin >> num;
Step 1- Enter the number, to find their factor.
cout << “Factors of “ << num << ” are: “ << endl;
Step 2- Initialise the loop with u=1 to u<=number and //finding and printing factors
for(int i = 1; i <= num; i++)
follow the following calculation {
if(num % i == 0)
(i) check whether the number is divisible with u and u got
cout << i << “\t“;
a result zero. }
return 0;
(ii) now print the value of u. }
From this loop u got all the factors of the number.
Java Code
Step 3- Stop. //Java program to find factors of a number
import java.util.Scanner;
public class factors_of_a_number
C Code {
#include<stdio.h> public static void main(String[] args)
int main() {
{ //scanner class declaration
//To initialize variable Scanner sc = new Scanner(System.in);
int number, u; //input from user
//to take user input System.out.print("Enter a number : ");
printf("Enter an any number: ");
scanf("%d",&number); int number = sc.nextInt();
System.out.println("Factors of
printf("Factors of a number %d are: ", number); "+number+" are :");
//loop for finding factors of a number
//Use for loop this condition for(int i = 1 ; i <= number ; i++)
for(u=1; u<= number; u++) {
{ if(number % i == 0)
//now we check for true condition of this //printing factors
if (number%u == 0)
//display factor System.out.print(i+" ");
} but good practice)
//closing scanner class(not compulsory,
38
sc.close();
}
}
Python Code
number = int(input("Enter the Number:"))
for i in range(1, number+1):
if number % i == 0:
print(i, end=" ")
user. We will use the While Loop ,for loop and else if
5!=1 + 24 +120=145
is 145
39 int main()
{
//to initialize variables
1! + 4! int number,digit,sum=0,temp;
return 0;
Working: }
Output:-
Step 1- enter the number to be check Enter a number: 28
Step 2- initialize i with 1.
28 is a perfect number
|Step 3- now execute the while loop, while i is less than the
number so calculate the following expression. (i) if number Enter a number: 153
is divided by the i, so add number with the total and store it
153 is not a perfect number
in total
C++ Code
(ii)increment the i with 1.
//C++ Program
When i is equal to or greater than the number so loop will //Perfect Number or not
#include<iostream>
terminate. using namespace std;
//main Program
Step 4- now compare the entered number with the total
int main ()
number. {
int div, num, sum=0;
Step 5- if the total number is equal to the entered number so cout << “Enter the number to check : “;
//user input
the number is the perfect number.
cin >> num;
Step 6- Stop //loop to find the sum of divisors
for(int i=1; i < num; i++)
{
C Code div = num % i;
#include<stdio.h> if(div == 0)
int main() 42
int number,i=1,total=0;
sump= sump + i
if (sump == n):
sum += i; print(“The number is a Perfect number”)
} else:
print(“The number is not a Perfect number”)
number
Chapter 22. Automorphic In this program we have to find whether the number
//checking for perfect number is an Automorphic number or not using C
if (sum == num) programming. An automorphic number is a number
cout<< num <<” is a perfect number.”; whose square ends with the same digits as number
else itself.
cout<< num <<” is not a perfect number.”;
return 0; Automorphic Number in C Programming
} Example:
Java Code ● 5=(5)2=25
//Java program to check whether a number is perfect
or not import java.util.Scanner; ● 6=(6)2=36
public class perfect_number_or_not
{ ● 25=(25)2=625
public static void main(String[] args)
{ ● 76=(76)2=5776
//scanner class declaration
Scanner sc = new Scanner(System.in); ● 376=(376)2=141376
//input from user
System.out.print("Enter a number : ");
These numbers are automorphic numbers.
int number = sc.nextInt();
//declare a variable to store sum of
● Automorphic number : C | C++ | Java
factors
int sum = 0;
for(int i = 1 ; i < number ; i++)
{
if(number % i == 0) Working
sum = sum + i;
}
//comparing whether the sum is equal Step 1- Enter the number to be checked.
to the given number or not
if(sum == number) Step 2- store the number in a temporary variable.
System.out.println("Perfect
Number"); Step 3- find the square of a given number and
else
System.out.println("Not an display it.
Perfect Number");
//closing scanner class(not compulsory,
but good practice) Step4- Initialize the while loop until the number
sc.close();
is not equal to zero
C++ Code
44
System.out.println("Not an
Automorphic Number");
//closing scanner class(not compulsory,
but good practice)
sc.close();
Ex– Number is 21
}
} it is divisible by own sum (1+2) of its digit(2,1)
So it is harshad number
Python Code
1st Approach Some other harshad numbers are 156,54,120 etc.
#enter the number to check
print(‘Enter the number:’)
n=int(input()) Working:
sq=n*n #square of the given number
co=0 #condition variable Step 1- Enter the number to be checked.
while(n>0): #loop until n becomes 0
if(n%10!=sq%10): Step 2- store the number in a temporary variable. Step 3-
print(‘Not Automorphic’)
Initialise the while loop until the temp is not equal to zero
co=1
break # come out of the loop if the above condition (i) Calculate the remainder of the temp,divided with the 10
holds true
#reduce n and square and store in digit
n=n//10
(ii) add the digit with sum and store it in the sum. (iii)
sq=sq//10
divide the temp with the 10 and store in the temp; Step 4-
if(co==0):
print(‘Automorphic’) find modulus of the number with sum and store in the res;
2nd Approach
Step 5- if res equal to zero then the given number is a
n=int(input(“Enter any number”)) harshad number else the given number is not a harshad
x=n**2
a=str(n) number.
b=str(x)
Step 6- Stop.
y=len(a)
z=len(b)
45
if(z-b.find(a)==y):
print(“Automorphic”)
else:
C Code
print(“Not automorphic number”)
} print(“Harshad number”)
}
Output :
Enter a number : 18
else:
Harshad Number
Optimal solution:
Python Code
General Solution:
n=int(input(“Enter any number”))
p=n
sum1=0
l=[]
while(n>0):
sum1=0
sum1+=n%10
while(n>0):
n=n//10
if(p%sum1==0):
x=n%10
print(“Harshad number”)
l.append(x)
else:
n=n//10
47
int main()
Chapter 24. Abundant
number
int number,sum=0,c;
In this program to find the number is Abundant number or
so it is an Abundant number.
//declare a variable to store sum of factors of the number
Working
#include<stdio.h> #include<iostream>
{
System.out.println("Not an
//initialization variables
using namespace std; sc.close();
//main Program
int main ()
{ }
int div, num, sum=0; }
cout << “Enter the number to check : “; Output :
//user input Enter a number : 12
cin >> num; Abundant Number
//loop to find the sum of divisors
for (int i=1; i < num; i++) Python Code
{ #enter the number to check
div = num % i; print(‘Enter the number:’)
if (div == 0) n=int(input())
sum += i; sum=1 # 1 can divide any number
} for i in range(2,n):
//checking for Abundant number if(n%i==0): #if number is divisible by i add the
if (sum > num) number
cout<< num <<” is an Abundant number.”; sum=sum+i
else
cout<< num <<” is not an Abundant number.”; if(sum>n):
return 0; print(n,‘is Abundant Number’)
}
else:
Java code print(n,‘is not Abundant Number’)
//Java program to check whether a number is abundant 49
number or not
import java.util.Scanner;
public class abundant_number_or_not
{
Chapter 25. Friendly pair
public static void main(String[] args)
{
//scanner class declaration
Scanner sc = new Scanner(System.in); //1 Create two variables to use in first and second
//input from user
System.out.print("Enter a number : "); Two numbers are said to be friendly pairs if they have a
int number = sc.nextInt(); common abundancy index. Or, the ratio between the sum of
//declare a variable to store sum of
divisors of a number and the number itself. These numbers
factors of the number
int sum = 0; are also known as Amicable numbers.
//loop for calculating sum of factors of
the number
for(int i = 1 ; i < number ; i++) We can also say that two numbers n and m are friendly
{
numbers if
if(number % i == 0)
sum = sum + i;
} ?(n)/n = ?(m)/m
//condition for checking whether the
sum is greater than number or not
if(sum > number) Where ?(n) is the sum of divisors of n.
System.out.println("Abundant
For instance, for numbers 6 and 28,
Number");
else Divisors of 6 are- 1, 2, 3, and 6.
Abundant Number");
//closing scanner class(not compulsory, Divisors of 28 are- 1, 2, 4, 7, 14, and 28.
but good practice)
s_DivisorSum = s_DivisorSum + i;
Sum of the divisors of 6 and 28 are 12 and 56 respectively. }
Also, the abundant index of 6 and 28 is 2. //7 Check condition for friendly numbers
if((f_Num == s_DivisorSum) && (s_Num ==
Therefore, 6 and 28 is a friendly pair. f_DivisorSum))
Working else
{
Step 1. Start
printf("%d and %d are not Amicable
Step 2. Input the numbers 1 and 2. numbers\n",f_Num,s_Num);
}
Step 3. Initialize two variables, sum1 and sum 2 with zero. return 0;
}
Step 4. Assign sum 1 with the sum of all the divisors of
Output
number 1. Enter two numbers to check if Amicable or not : 12 13
12 and 13 are not Amicable numbers
Step 5. Assign sum 2 with the sum of all the divisors of
number 2. C ++ Code
//C++ Program
Step 6. If (sum 1==number1) and (sum 2==number 2), then //Friendly Pair(Amicable number) or not
#include<iostream>
print, “Friendly Numbers”
using namespace std;
Step 7. Else print “Not Friendly Numbers”. // function to check Friendly pairs
void findAmicable(int first, int second)
Step 8. Stop {
int sum1=0,sum2=0;
for(int i=1; i<=first/2 ; i++)
C Code {
#include<stdio.h>
50
int main()
{
numbers //finding and adding divisors of first number
int i;
int f_Num,s_Num;
//2 two more variables created to store the sum of the
divisors for(int i = 1 ; i < number1 ; i++)
int f_DivisorSum = 0; if(first%i==0)
int s_DivisorSum = 0; sum1=sum1+i;
}
//3 Asking user to enter the two numbers for(int i=1; i<=second/2 ; i++)
printf("Enter two numbers to check if Amicable or not {
: "); //finding and adding divisors of second number
scanf("%d %d",&f_Num,&s_Num); if(second%i==0)
sum2=sum2+i;
//4 Using one variable for loop and second to check for }
each number //checking for friendly pair
for(int i=1;i<f_Num;i++) if(first==sum2 && second==sum1)
{ cout<<“Friendly Pair(“<<first<<“,”<<second<<“)”;
//5 Condition check else
if(f_Num % i == 0) cout<<“Not a Friendly Pair”;
f_DivisorSum = f_DivisorSum + i; }
} //main program
//6 Calculating the sum of all divisors int main()
for(int i=1;i<s_Num;i++) {
{ int first,second;
if(s_Num % i == 0) cout<<“Enter first number : “;
//user input //condition for friendly pair number
cin>>first; if(number1 == add2 && number2 ==
cout<<“Enter second number : “; add1)
//user input System.out.println("Number
cin>>second; is Friendly Pair");
//calling function else
findAmicable(first,second); System.out.println("Number
return 0; is not Friendly Pair");
} //closing scanner class(not compulsory,
but good practice)
Java Code sc.close();
//Java program to check whether a number is friendly pair
or not
import java.util.Scanner; }
public class friendly_pair_or_not }
{
public static void main(String[] args) Python Code
{ #’Enter the numbers to check’
//scanner class declaration n=int(input())
Scanner sc = new Scanner(System.in); m=int(input())
//input from user import math
System.out.print("Enter First number : sum_n=1 + n #sum of divisor of n
"); sum_m=1 + m #sum of divisor of m
int number1 = sc.nextInt(); i=2
System.out.print("Enter Second j=2
number : "); #finding divisor
int number2 = sc.nextInt(); while(i<=math.sqrt(n)):
//declare two variables to store the if(n%i==0):
addition of factors of both numbers which are entered by if(n//i==i):
user sum_n+=i
int add1 = 0, add2 = 0;
//logic for finding factors and else:
calculating sum of all those factors for number1 sum_n+=i + n//i
{
if(number1 % i == 0) i=i+1
add1 = add1 + i;
} while(j<=math.sqrt(m)):
//logic for finding factors and if(m%j==0):
calculating sum of all those factors for number2 if(m//j==j):
for(int i = 1 ; i < number2 ; i++) sum_m+=j
{
if(number2 % i == 0) else:
add2 = add2 + i;
}
51
sum_m+=j + m//j
j=j+1
if(sum_n/n==sum_m/m):
print(‘Yes’ , n , ‘,’ , m ,‘ are friendly Pair’)
else:
print(‘No’, n , ‘,’ , m ,‘ are not friendly Pair’)
Chapter 26. Highest
Common Factor(HCF):
The HCF or the Highest Common Factor of two numbers is
the largest common factor of two or more values. The HCF
can be calculated using some simple mathematical tricks.
The following algorithm will determine how a c program
can calculate the HCF of two numbers.
Working :-
Step 1. Start
Step 2. Define variables P and Q
Step 3. Develop a loop from 1 to the maximum value of P
and Q.
52
else
System.out.println("Wrong Input");
//closing scanner class(not compulsory,
but good practice)
sc.close();
}
}
Python Code :
12 = 2 × 2 × 3
44 = 2 × 2 × 11
Working:-
● Initialize variable check1 and check2.
● Copy the value of n1 and n2 of variable .
● Initialize the while loop where condition is
while(check1!=check2).
54
int i;
int a =(num1 > num2)? num1 : num2;
for(i = a ; i <= num1*num2 ; i=i+a)
{
if(i % num1 == 0 && i %
num2 == 0)
break;
}
//printing result
System.out.println("LCM of "+num1+"
and "+num2+" is : "+i);
//closing scanner class(not compulsory,
but good practice)
sc.close();
}
}
Python Code :
num1 = int(input("Enter first number:"))
num2 = int(input("Enter Second Number:"))
Ex:-
lcmFinder(num1, num2)
the H.C.F or G.C.D of 12 and 14 is 2.
int n = 1;
System.out.print("HCF of "+num1+"
Chapter 29. Binary to
and "+num2+" is "); if( num1 != num2)
{
while(n != 0) numbers that are equivalent. A decimal number can be
{ obtained by multiplying every digit of binary digit with
//storing remainder power of 2 and totaling each multiplication outcome. The
n = num1 % num2; power of the integer starts from 0 and counts to n-1 where n
is assumed as the overall number of integers in binary
if(n != 0) number.
{
num1 = Ex:- (101100001) 2 =(353)10
num2;
num2 = To show on fig(1)
n;
} Working:-
} Step 1: Start
//result
System.out.println(num2); Step 3: The user is asked to enter a binary number as an
input
}
else Step 4: Store the quotient and remainder of the binary
System.out.println("Wrong number in the variable rem
Input");
//closing scanner class(not compulsory, Step 5: Multiply every digit of the entered binary number
but good practice) beginning from the last with the powers of 2
sc.close(); correspondingly
def gcdFunction(num1, num2): /** C program to convert the given binary number into
if num1 > num2: decimal**/
small = num2 #include<stdio.h>
else: int main()
small = num1 {
for i in range(1, small+1): int num, binary_val, decimal_val = 0, base = 1, rem;
if (num1 % i == 0) and (num2 % i == 0):
gcd = i printf("Insert a binary num (1s and 0s) \n");
print("GCD of two Number: {}".format(gcd)) scanf("%d", &num); /* maximum five digits */
//num/=10;
{
num = num / 10 ; base = base * 2;
//base*=2; }
//display binary number number
printf("The Binary num is = %d \n", binary_val); int decimal = 0;
//display decimal number //Declaring variable to use in power
printf("Its decimal equivalent is = %d \n",
decimal_val); int n = 0;
return 0; //writing logic for the conversion
} while(binary > 0)
{
int temp = binary%10;
decimal +=
C++ Code : temp*Math.pow(2, n);
//C++ Program binary = binary/10;
//Convert binary to decimal n++;
#include <iostream> }
#include <math.h> System.out.println("Decimal number :
using namespace std; "+decimal);
//function to convert binary to decimal //closing scanner class(not compulsory, but good
int convert(long n) practice)
{ sc.close();
int i = 0,decimal= 0; }
//converting binary to decimal }
while (n!=0)
{
Python Code :
int rem = n%10;
n /= 10; num = int(input("Enter number:"))
int res = rem * pow(2,i); binary_val = num
decimal += res; decimal_val = 0
i++; base = 1
} while num > 0:
return decimal; rem = num % 10
} decimal_val = decimal_val + rem * base
//main program num = num // 10
int main() base = base * 2
{
long binary; print("Binary Number is {} and Decimal Number is
cout << “Enter binary number: “; {}".format(binary_val, decimal_val))
cin >> binary; 59
cout << binary << ” in binary = “ << convert(binary)
<< ” in decimal”;
return 0;
} Chapter 30. Binary to Octal
Binary conversion:
The C program to convert decimal numbers into binary C Code :
numbers is done by counting the number of 1s. The
program practices module process and multiplication with /*
base 2 operation for converting decimal into binary * C program to accept a decimal number and convert it to
number. It further uses modulo operation to check for 1’s binary
and hence increases the amount of 1s. The program reads * and count the number of 1's in the binary number
an integer number in decimal in order to change or convert */
into a binary number.
Java Code :
//Java program to convert decimal number to binary
number
import java.util.Scanner; System.out.print(binary[j]+" ");
public class Decimal_To_Binary //closing scanner class(not compulsory,
{ but good practice)
public static void main(String args[]) sc.close();
{ }
//scanner class object creation }
Scanner sc = new Scanner(System.in);
//input from user
System.out.print("Enter a Decimal
number : "); Python Code :
int decimal = sc.nextInt(); #take decimal number
//integer array for storing binary digits dec_num = 124
int binary[] = new int[20]; #convert decimal number to binary
int i = 0; bin_num = bin(dec_num)
//writing logic for the conversion #print number
while(decimal > 0) print('Number after conversion is :' + str(bin_num))
{
int r = decimal % 2; Chapter 32. Decimal to
binary[i++] = r;
decimal = decimal/2; octal Conversion:
}
//printing result The C program to convert decimal to octal number accepts
System.out.print("Binary number : "); a decimal number from the user. This number is further
for(int j = i-1 ; j >= 0 ; j--) converted to its equivalent octal number after following a
series of steps. The following section gives an algorithm for
this conversion. It is then followed by a C program.
int n = 0;
//writing logic for the conversion
while(octal > 0)
{
int temp = octal % 10;
decimal += temp *
Math.pow(8, n);
octal = octal/10;
n++;
} will identify on which quadrant the point lies. The program
//printing result will read the value of x and y variables. If-else condition is
System.out.println("Decimal number : used to identify the quadrant of the given value.
"+decimal);
//closing scanner class(not compulsory, Ex:- X and Y coordinates are 20, 30 these lie in 4th
but good practice) quadrant because in mathematics quadrants rules are
sc.close(); following
}
} ● x is positive integer and y is also positive
integer so-that quadrant is a first quadrant.
● x is negative integer and y is positive integer
so-that Quadrant is a second quadrant.
Python Code :
● x is negative integer and y is also negative
#take octal number integer so -that Quadrant is a third quadrant.
#with prefix 0o[zero and o/O] ● x is positive integer and y is negative integer
oct_num = 0o512 so-that is a first quadrant.
#convert octal number to integer
#integers are with base 10 Working:
deci_num = int(oct_num)
#print number Step 1: Start
print('Number after conversion is :' + str(deci_num)) Step 2: The user asked to put value for x and y variables
Step 3: If-else condition is used to determine the value of
Chapter 35. Quadrants in the given value
Step 4: Check the condition, if x variable’s value is greater
which a given coordinate than 0 and the variable y is greater than 0.
Step 5: If the condition is true then print the output as the
lies : first quadrant.
Step 6: If the condition is false then check the condition if x
The C program reads the coordinate point in a xy is lesser than 0 and the y variable is greater than 0.
coordinate system and identifies the quadrant. The program
takes X and Y. On the basis of x and y value, the program
68
Working:
Step 1: Start
Step 2: Ask the user to insert n number of people and C++ Code :
the number of seats as r. //C++ Program
Step 3: Calculate permutation, p(n,r). //Permutations in which n people can occupy r seats
Step 4: Enter the program to calculate permutation P(n,r) = #include<iostream>
n! / (n-r)! using namespace std;
Step 5: Print the calculated result. //function for factorial
Step 6: Stop int factorial(int num)
{
int fact=1;
for(int i=num;i>=1;i–)
C Code :
fact*=i;
#include<stdio.h> return fact;
}
// Program to find the factorial of the number //main program
int factorial (long int x) int main()
{ {
long int fact=1,i; int n,r;
for(i=1;i<=x;i++) cout<<“Enter number of people: “;
{ //user input
fact=fact*i; cin>>n;
} cout<<“Enter number of seats: “;
return fact; 70
}
int main()
long int numerator, denominator; //user input
printf("\nEnter the number of persons : "); N = int(input('Enter the number of students :'))
cin>>r;
scanf("%ld",&n); //if there are more people than seats
if(r<n)
// Insert the num of seats {
cout<<“Cannot adjust “<<n<<” people on “<<r<<”
printf("\nEnter the number of seats available : "); seats”;
return 0;
scanf("%ld",&r); }
// Base condition //finding all possible arrangements of n people on r
// Swap n and r when n is less than r seats
// by using formula of permutation
int p = factorial(r)/factorial(r–n); int number;
//printing output number = n – r;
cout<<“Total arrangements: “<<p; fact2 = number;
return 0; for (int i = number – 1; i >= 1; i=i-1)
} {
fact2 = fact2 * i; //calculating factorial ((n-r)!)
}
Java Code :
per = fact1 / fact2; //calculating nPr
import java.util.*; System.out.println(per+“ways”);
import java.io.*; }
}
class PrepInsta
{
Python Code :
public static void main(String[] args)
{ #import math lib
int n, r, per, fact1, fact2; import math
Scanner sc = new Scanner(System.in); #take user inputs
System.out.println(“Enter the Value of n and r”); R = int(input('Enter the number of seats :'))
n = sc.nextInt(); #factorial by using factorial() function
r = sc.nextInt(); nume = math.factorial(N)
fact1 = n; deno = math.factorial(N-R)
for (int i = n – 1; i >= 1; i=i-1) #permutation = n! / (n-r)!
{ no_of_ways = nume//deno
fact1 = fact1 * i; //calculating factorial (n!) #print total no of ways
} print('Total number of ways are :' + str(no_of_ways))
71
number of handshakes:
//fill the code
In C programming, there’s a program to calculate the int num;
number of handshakes. The user is asked to take a number scanf("%d",&num);
as integer n and find out the possible number of int total = num * (num-1) / 2; // Combination nC2
handshakes. For example, if there are n number of people printf("%d",total);
in a meeting and find the possible number of handshakes
return 0;
made by the person who entered the room after all were
}
settled.
return 0;
} //logic for getting simplified fraction
int n = 1;
int p = num;
int q = den;
Java Code : if( num != den)
//Java program to add two fractions {
while(n != 0)
import java.util.Scanner;
public class add_two_fractions {
{ //storing remainder
public static void main(String[] args) n = num % den;
{
f1_deno = int(input('Enter the denominator for the
if(n != 0) 1st fraction :'))
{ f2_nume = int(input('Enter the numerator for 2nd
num = den; fraction :'))
den = n; f2_deno = int(input('Enter the denominator for the
} 2nd fraction :'))
} #check if denominators are same
} if(f1_deno == f2_deno):
System.out.println("("+p/den+" / #add numerator
"+q/den+")"); //closing scanner class(not compulsory, Fraction = f1_nume + f2_nume
but good practice) #print
sc.close(); print('Addition of two fractions are :' + str(Fraction) +
'/' + str(f1_deno))
} #if denominators are not same
} else:
#to find the sum
#denominators should be same
#apply cross Multiplication
Python Code : Fraction = (f1_nume * f2_deno) + (f2_nume *
#take inputs f1_deno) print('Addition of fractions are :' +
f1_nume = int(input('Enter the numerator for 1st str(Fraction) + '/' + str(f1_deno * f2_deno))
fraction :'))
74
two prime numbers : Step 6: If both i and (n – 1) are prime numbers, then the
given number can be represented as the sum of prime
numbers i and (n – 1).
The program in C takes a positive integer or number which
Step 7: Stop
is required to be inserted by the user. The program further
identifies whether that digit can be expressed as the sum of
two prime numbers. If the inserted number can be
expressed as sum of two prime numbers then, print the C Code :
integer can be expressed as sum of two prime numbers as a
result. // C program to check whether a number can be expressed
as a sum of two prime numbers
Working:
Step 1: Start #include<stdio.h>
Step 2: Ask the user to insert a number as an input. Step 3: int sum_of_two_primes(int n);
Initiate the value of i in a loop from 2 up to half the value int main()
of the entered number. {
Step 4: Check if i is a prime number. int n, i;
return 0;
printf(“Insert the num: “); }
scanf(“%d”, &n); int main()
int flag = 0; {
for(i = 2; i <= n/2; ++i) int check = 0, n;
{ cout<< “Enter a positive integer: “;
// Condition for i to be prime //user input
if(sum_of_two_primes(i) == 1) cin>>n;
{ for(int i = 1; i <= n/2;i++)
if(sum_of_two_primes(n-i) == 1) {
{ // condition for i to be a prime number
printf(“\n%d can be expressed as the sum of %d 77
and %d\n\n”, n, i, n – i);
flag = 1;
} if (Prime(i))
}
if(flag == 0)
printf(“%d cannot be expressed as the sum of two int c = 1;
primes\n”, n) {
// condition for n-i to be a prime number
return 0; if (Prime(n–i))
} {
cout<<n <<” = “<< i <<” + “ << n–i<<
int sum_of_two_primes(int n) endl;
{ check = 1;
int i, isPrime = 1; }
for(i = 2; i <= n/2; ++i) }
{ }
if(n % i == 0) if (check == 0)
{ cout<<n<<” cannot be expressed as the sum
isPrime = 0; of two prime numbers.”;
break; return 0;
} }
}
return isPrime;
Java Code :
}
//Java program to check whether a number can
be expressed as a sum of two prime numbers
import java.util.Scanner;
C++ Code :
public class
//C++ Program number_as_sum_of_two_prime_numbers {
//Number expressed as sum of two prime numbers public static void main(String[] args)
#include<iostream> {
using namespace std; //scanner class declaration
// Function to check prime number Scanner sc = new Scanner(System.in);
int Prime(int num) //input from user
{ System.out.print("Enter a number : ");
int div=0;
for(int i=1;i<=num;i++) int number = sc.nextInt();
{ int x = 0;
if(num%i==0) for(int i = 2 ; i <= number/2 ; i++)
div++; {
} if(prime_or_not(i) == 1)
if(div==2) {
return 1;
break
if(prime_or_not(number-i) == 1) if(flag == 0):
{ print('No Prime numbers can give sum of ' + str(Number))
78
System.out.println(number+ " = "+i+" +
"+(n
umb
er-i))
Chapter 41. Count possible
;x=
1;
}
}
}
}
cnt[k] += cnt[k-2];
if(x == 0)
Working:
Python Code :
Step 1: Start
#take input Step 2: User is required to insert a digit sequence as
Number = int(input('Enter the Number :')) an input
#initialize an array Step 3: Set count = 0
arr = [] Step 4: If the last number is not a zero, then return for
#find prime numbers the next remaining (n-1) numbers and add the results
for i in range(2,Number): then to the total count.
flag = 0 Step 5: If the last two digits form a valid variable (or
for j in range(2,i): smaller than 27), return for the remaining (n-2)
if i % j == 0: numbers and add the outcome to the total calculation.
flag = 1 Step 6: Stop
#append prime numbers to array
if flag == 0:
arr.append(i) C Code :
#possible combinations //C Program to Count possible decodings of a given
flag = 0 digit sequence
for i in range(len(arr)): #include<stdio.h>
for j in range(i+1,len(arr)): #include<math.h>
#if condition is True Print numbers
if(arr[i] + arr[j] == Number): int cnt_decoding_digits(char *dig, int a)
flag = 1 {
print(str(arr[i]) + " and " + str(arr[j]) + ' are // Initializing an array to store results
prime numbers when added gives ' + str(Number)) int cnt[a+1];
cnt[0] = 1; //user input
cnt[1] = 1; gets(digit);
int n = strlen(digit);
for (int k = 2; k <= a; k++) { cnt[k] = 0; //calling function and printing output
// If the last digit not equal to 0, then last digit cout<<"Number of decoding of the
must added to the number of words if (dig[k-1] > '0') sequence "<<digit<<" are
cnt[k] = cnt[k-1]; "<<countDecoding(digit,n);
return 0;
// In case second last digit is smaller than 2 and last digit }
is smaller than 7, then last two digits form a valid 79
character if (dig[k-2] == '1' || (dig[k-2] == '2' && dig[k-1]
< '7') )
return cnt[a];
}
Chapter 42. Check whether
int main()
{
char dig[15];
printf("\n Enter the sequence : "); elseif((c >= 'a' && c= 'A' && c <= 'Z'))
gets(dig);
int a = strlen(dig);
a character is a vowel
printf("\n Possible count of decoding of the
sequence : %d\n", cnt_decoding_digits(dig, a));
or consonant :
return 0; Given a character, check if it is a vowel or consonant.
} Vowels are in Uppercase ‘A’, ‘E’, ‘I’, ‘O’, ‘U’ and
Lowercase ‘a’, ‘e’, ‘i’, ‘o’, ‘u’. and All other characters
both uppercase and lowercase (‘B’, ‘C’, ‘D’, ‘F’,’ b’,
C++ Code :
‘c’,’ d’, ‘f’,…..) are consonants. In this article, we will
//Count possible decodings of a given digit show you, How to write a C program to check Vowel or
sequence #include<iostream> Consonant with an example.
#include<string.h>
using namespace std; Working:
//function to count the number of decodings We check whether a given character matches any of the
int countDecoding(char *digit, int n) 5 vowels. If yes, we print “Vowel”, else we print
{ “Consonant”.
int decodings[n+1];
decodings[0]=1; This C program allows the user to enter any character
decodings[1]=1; and check whether the user specified character is Vowel
//counting decodings or Consonant using If Else Statement.
for(int i=1;i<=n;i++) This program takes the character value(entered by user)
{ as input.
int q=digit[i]-48; And checks whether that character is a vowel or
int p=digit[i-1]-48; consonant using if-else statement.
if(q>0 && q<=26) Since a user is allowed to enter an alphabet in lowercase
decodings[i+1]=decodings[i];and uppercase, the program checks for both uppercase
if((q + p*10)>0 && (q + p*10) <=26) and lowercase vowels and consonants.
decodings[i+1] And now we have to follow step’s of C programming
+=decodings[i-1];
}
return decodings[n]; C Code :
}
#include <stdio.h>
//main program
int main()
int main()
{
{
char c;
char digit[20];
int isLowerVowel, isUpperVowel;
cout<<"Input: ";
printf("Enter an alphabet: ");
scanf("%c",&c); public class vowelorconsonant
{
//To find the corrector is lowercase vowel //class declaration
isLowerVowel = (c == 'a' || c == 'e' || c == 'i' || c == 'o' || public static void main(String[] args)
c == 'u'); {
//To find the character is Upper case vowel //main method declaration
isUpperVowel = (c == 'A' || c == 'E' || c == 'I' || c == 'O' || Scanner sc=new Scanner(System.in);
c == 'U'); //scanner class object creation
// compare to charector is Lowercase Vowel or Upper
case Vowel System.out.println(" Enter a character");
if (isLowerVowel || isUpperVowel)
printf("%c is a vowel", c);
//to check character is alphabet or not
prinf("\n not a alphabet\n");
else
printf("%c is a consonant", c);
return 0;
}
C++ Code :
//C++ Program to check whether alphabet is vowel
or consonant
#include <iostream>
using namespace std;
//main function
int main()
{
char c;
cout<<"Enter an alphabet: ";
cin>>c;
//checking for vowels
if(c=='a'||c=='e'||c=='i'||c=='o'||c=='u'||c=='A'||c=='E'||c=='I'|
|c =='O'||c=='U')
{
cout<<c<<" is a vowel"; //condition
true input is vowel
}
else
{
cout<<c<<" is a consonant";
//condition false input is consonant
}
return 0;
}
Java Code :
//JAVA Program to check whether the character entered
by user is Vowel or Consonant.
import java.util.Scanner;