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
Price- Rs.600/-
3
Contents
C++ Code :
Chapter 1. Positive or
#include<iostream>
Negative number using namespace std;
int main()
The following concept will test whether a number is {
positive or negative. It is done by checking where the #ifndef ONLINE_JUDGE
number lies on the number line. The following algorithm // for getting input from input.txt
will help to check this condition. freopen(“input1.txt”, “r”, stdin);
// for writing output to output.txt
● If the input number is greater than zero then it is freopen(“output.txt”, “w”, stdout);
a positive number. #endif
● If the input number is less than zero it is a int no;2
negative number. cout<<“Enter a number:”;
● If the number is zero then it is neither positive cin>>no;
nor negative. if(no==0)
{
Same logic we have followed in the below C cout<<“0 is neither positive nor negative”;
program.Working }
else if(no>0)
● Step 1. Start {
● Step 2. Enter the number. cout<<no<<“is a positive number”;
● Step 3. If the number is less than or equal to zero, }
check if it is zero. else
● Step 4. If the number is zero, print, “, The {
number is zero.” cout<<no<<“is a negative number”;
● Step 5. If the number is less than zero, print, “The }
number is negative.” return 0;
● Step 6. If the number is more than zero, print, }
“The number is positive.”
● Step 7. Stop Java Code :
//Java program to check a number is positive or negative
C Code : import java.util.Scanner;
#include<stdio.h> public class pos_or_neg
int main() {
{ public static void main(String[] args)
int num; {
printf(“Insert a number: “); //scanner class declaration
scanf(“%d”, &num); Scanner sc = new Scanner(System.in);
//Condition to check if the number is negative or //input from the user
positive System.out.print("Enter a Number : ");
if (num <= 0) int numb = sc.nextInt();
{ //condition for positive
if (num == 0) if(numb > 0)
printf(“The number is 0.”);
else System.out.println("Positive");
printf(“The number is negative”); //condition for negative
} else if(numb < 0)
else
printf(“The number is positive”); System.out.println("Negative");
return 0; else
} System.out.println("Zero");
7
Example :
Number is 24
Number is 15
Working
● Step 1. Start Java Code :
● Step 2. Enter a number. //Java Program to check a number is even or odd
import java.util.Scanner;
● Step 3. If the number is divisible by 2, it is even. public class even_or_odd
{
● Step 4. If the number is not divisible by 2, it is
public static void main(String[] args)
odd. {
//scanner class declaration
● Step 5. Stop Scanner sc = new Scanner(System.in);
//input from the user
System.out.print("Enter a Number : ");
C Code :
#include<stdio.h> int numb = sc.nextInt();
int main() //condition for even
{ if(numb % 2 == 0)
int number;
printf(“Insert a number \n“); System.out.println("Even
scanf(“%d”,&number); Number");
//condition for odd
//Checking if the number is divisible by 2 else
if (number%2 == 0)
printf(“The number is even\n“);
System.out.println("Odd
else Number");
printf(“The number is odd\n“); //closing scanner class(not compulsory,
return 0; but good practice)
} sc.close();
}
C++ Code : }
//C++ Program
// number is even or odd
Python Code :
#include num = int(input("Enter a Number:"))
using namespace std; if num % 2 == 0:
int main() print("Given number is Even")
{ else:
cout<<“Enter a number: “; print("Given number is Odd")
int check;
cin>>check; # This code is contributed by Shubhanshu Arya (Prepinsta
//checking whether the number is even or odd Placement Cell Student)
if(check % 2 == 0)
{
cout<<check<<” is an even number”;
}
else
{
cout<<check<<” is an odd number”;
}
return 0;
}
9
System.out.println(“Sum is ” +sum);
Chapter 3. Sum of First N
Natural numbers }
{
public static void main(String[] aa){
Scanner sc=new Scanner(System.in);
int sum=0;
System.out.println(“Enter the vlue of n”);
int n=sc.nextInt();
for(int i=1;i<=n;i++)
sum=sum+i;
10
}
Chapter 5. Sum of numbers
} in a given range
Python Code : The program given below accepts a range of values and
Method 2: To use for loops start at 4 and end 8 and sum off inside the
loop we have to start a first range given by the user and last
C++ Code :
Working
//C++ Program
● Step 1. Initialize variables (firstrange,lastrange,
//Sum of Natural Numbers in a given range
total and i). #include<iostream>
using namespace std;
● Step 2. Input fistrange and lastrange by user. //main Program
int main()
● Step 3. We use “for loop” with the condition
{
(i=firstrange;i<= lastrange;i++).When loop will int sum = 0 , upper_limit, lower_limit;
cout << “Enter the lower limit: “;
work until i= secondrange. cin >> lower_limit;
● Step 4. The loop will start with i=firstrange and
end with i<= lastrange. cout << “Enter the upper limit: “;
cin >> upper_limit;
● Step 6. In the loop for every cycle total will be
Method 2:
Working
num = int(input("Enter the Number:")) Step 1: Start
sum = (num * (num+1))/2
print("The Sum of N natural Number is {}".format(sum)) Step 2: Insert two integers no1 and no2 from the user with
the if statement.
printf statement, if not then print no1 and no2 are equal
Step 6: Stop
C Code:
14
Java Code :
//where number 2 is greater
else if(no2 > no1) //Java program to find greatest of two numbers
printf(“%d is greatest”,no2); import java.util.Scanner;
public class greatest_of_two_numbers
//for both are equal {
else public static void main(String[] args)
printf(“%d and %d are equal”, no1, no2); {
//scanner class declaration
return 0; Scanner sc = new Scanner(System.in);
} //input first number
System.out.print("Enter the first
Output number : ");
int first = sc.nextInt();
Insert Two Numbers : 5 //input second number
6 System.out.print("Enter the second
6 is the Greatest number : ");
int second = sc.nextInt();
C++ Code :
//conditions
//C++ program if(first > second)
//Greatest of two numbers
System.out.println(first+" is
#include<iostream> greater than "+second);
using namespace std; else if(second > first)
System.out.println(second+"
//main program
is greater than "+first);
int main() else
{ System.out.println("Both
numbers are Equal");
int first,second;
//closing scanner class(not compulsory,
cout<<“Enter first number: “; but good practice)
sc.close();
cin>>first;
cout<<“Enter second number: “;
cin>>second; }
}
if(first==second)
Python Code :
{
first = int(input("Enter first number:"))
cout<<“both are equal”; second = int(input("Enter second number:"))
} if first > second:
print("First is Greater than Second")
else if(first>second)
else:
{ print("Second is Greater than First")
15
C code :
#include<stdio.h>
int main()
Chapter 7. Greatest of the {
int no1,no2,no3;
Three numbers
//Prompt user to insert any three integer variables
The C program to find the greatest of three numbers printf(“\nInsert value of no1, no2 and no3:”);
requires the user to insert three integers. Flow chart is also scanf(“%d %d %d”, &no1, &no2, &no3);
used in C programming to find the greatest number among
three integers inserted by the user. A simple if-else block is //for check of number 1 is greater
used to identify the greatest number. if((no1 > no2) && (no1 > no3))
printf(“\n Number1 is greatest”);
Problem Description
C programs to find the greatest of three numbers require //weather number 2 is grater
else if((no2 > no3) && (no2 > no1))
the user to insert three integers. Flow chart is also used in printf(“\n Number2 is greatest”);
C programming to find the greatest number among three
//other conditions are false than number 3 is greater
integers inserted by the user. A simple if-else block is else
printf(“\n Number3 is greatest”);
used to identify the greatest number. The program will return 0;
ask the user to insert three integer variables. And on the }
Output
basis of the inserted number, the program will equate and
Insert Value of No1, No2 and No3: 15, 200, 101
exhibit the greatest number as an output. This program
Number 2 is Greatest
uses no1, no2 & no3 as three integer variables that are
else }
{ Python code :
cout<<third<<” is the greatest”; first = int(input("Enter first number:"))
} second = int(input("Enter second number:"))
return 0; third = int(input("Enter third number:"))
}
Java code : if first > second and first > third:
//Java program to find greatest of three numbers print("First is Greater than Second and Third")
import java.util.Scanner; elif second > first and second > third:
public class greatest_of_three_numbers print("Second is Greater than First and Third")
{ else:
public static void main(String[] args) print("Third is Greater than First and Second")
{
//scanner class declaration # This code is contributed by Shubhanshu Arya (Prepinsta
Scanner sc = new Scanner(System.in); Placement Cell Student)
//input three numbers from user
System.out.print("Enter the first
number : ");
int first = sc.nextInt();
System.out.print("Enter the second
number : ");
int second = sc.nextInt();
System.out.print("Enter the third
number : ");
int third = sc.nextInt();
System.out.println();
//condition for first number
if(first > second && first > third)
System.out.println(first+" is
the greatest number.");
//condition for second number
else if(second > first && second >
third)
System.out.println(second+"
is the greatest number.");
//condition for third number
else if(third > first && third > second)
System.out.println(third+" is
the greatest number.");
//condition when all three numbers are
equal
else
System.out.println("All three
numbers are same");
//closing scanner class(not compulsory,
but good practice)
sc.close();
}
17
divisible by 4 is a leap year. But it is not only in this case Enter Year for find leap year or not : 2012
2012 is a leap Year
1900 is divisible by 4. But it is not a leap so it that case we
follows these conditions Enter Year for find leap year or not : 1900
1900 is not a leap Year
Python Code :
year = int(input("Enter Year:"))
if year % 4 == 0:
if year % 100 == 0:
if year % 400 == 0:
print("Yes, {} is Leap Year".format(year)) Chapter 9. Prime number
else:
A number is considered a prime number when it satisfies
print("No, {} is Leap Year".format(year))
else: the below conditions.
print("No, {} is Leap Year".format(year))
else:
print("No, {} is Leap Year".format(year)) Prime number is a number which can be divided by 1 and
itself
# This code is contributed by Shubhanshu Arya (Prepinsta
Placement Cell Student) A number which can not be divided by any other number
itself.
Problem Description
In this program we will find if a number is a prime number
below conditions.
● it is divisible by 1. }
● And it is divisible by itself return 0;
}
So it is a prime number. Output
Enter Number:6
Working 6 is not a Prime Number
Step 1. Read a “num” value to check prime or not.
Enter Number:13
Step 2. set i=1,div=0. 13 is a Prime Number
Step 3. if i<=num if true go to step 4, else go to step 7.
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
System.out.println("Prime Number"); Chapter 10. Prime number
else
System.out.println("Not a Prime within a given range
Number");
A number that is divisible only by itself and 1 (e.g. 2, 3, 5,
sc.close();
//closing scanner class(not mandatory but good practice) 7, 11).
} //end of main
method
} //end of class The C program reduces the number of iterations within the
Output :
for loop. It is made to identify or calculate the prime
prints the digits coming under the prime numbers. Users are
Working
Step 1: Start
21
//user input {
if(i % j == 0)
cin>>lowerLimit>>upperLimit;
count =
count+1;
cout<<“Prime numbers between “<<lowerLimit<<”
and “<<upperLimit<<” are:”<<endl; }
if(count == 2)
//finding prime numbers in the given range
C code :
Chapter 11. Sum of digits of
/* C program to take a number & calculate the sum of its
a number numbers */
This program in C programming calculates the sum of
#include<stdio.h>
numbers inserted by the user or in an inserted integer. The
int main()
program is taken as an input and stored in the variable
Step 1: Start
C++ code :
Step 2: Ask the user to insert an integer as an input.
//C++ Program
Step 3: Divide the integer by 10 in order to obtain quotient
//Sum of digits in a number
and remainder.
sum+=num%10;
num=num/10; Chapter 12. Reverse of a
}while(num!=0);
//output number
cout<<“\nSum of digits in given integer is: “<<sum;
In this program reverses a number entered by a user and
return 0;
} then prints it. For example, if a user will enter 6577756 as
//display sum of digits Step 6.When it becomes zero, print the output and exit
System.out.print("Sum of Digits =
Step 7. Stop.
"+sod);
//closing scanner class(not compulsory,
but good practice)
sc.close(); C code :
}
}
Python Code :
#include<stdio.h>
int main()
num = [int(d) for d in input("Enter the Number:")]
{
sum = 0
//Initialization of variables where rev='reverse=0'
for i in range(0, len(num)):
int number, rev = 0,store, left;
sum = sum + num[i]
{ {
//left is for remider are left public static void main(String[] args)
left= number%10; {
//scanner class declaration
//for reverse of no. Scanner sc = new Scanner(System.in);
rev = rev * 10 + left; //input from user
System.out.print("Enter a number : ");
//number /= 10;
number=number/10; int number = sc.nextInt();
System.out.print("Reverse of
} "+number+" is ");
//To show the user value int reverse = 0;
printf("Given number = %d\n",store); String s = "";
while(number != 0)
//after reverse show numbers {
printf("Its reverse is = %d\n", rev); int pick_last = number % 10;
//use function to convert
return 0; pick_last from integer to string
} s=s+
Output:- Integer.toString(pick_last);
Enter the number 123456 number = number / 10;
}
Given number = 123456 //display the reversed number
Its reverse is =654321 System.out.print(s);
//closing scanner class(not compulsory,
C Code but good practice)
//C++ Program sc.close();
//Reverse of a number
#include <iostream>
using namespace std; }
//main program }
int main()
{ Python Code
//variables initialization num = int(input("Enter the Number:"))
int num, reverse=0, rem; temp = num
cout<<“Enter a number: “; reverse = 0
//user input while num > 0:
cin>>num; remainder = num % 10
//loop to find reverse number reverse = (reverse * 10) + remainder
do num = num // 10
{
rem=num%10; print("The Given number is {} and Reverse is
reverse=reverse*10+rem; {}".format(temp, reverse))
num/=10;
}while(num!=0); # This code is contributed by Shubhanshu Arya (Prepinsta
//output Placement Cell Student)
cout<<“Reversed Number: “<<reverse;
return 0;
}
Java Code
//Java program to print reverse of a number
import java.util.Scanner;
public class reverse_of_number
26
number is palindrome or not. We are using a while loop and store= number;
//use this loop for check true condition
an else if statement in the C Program.
while (number > 0)
{
Ex:- A number is 123321 .If you read the number “123321” //left is for remider are left
left= number%10;
from reverse order, it is the same as “123321”.
String st = sc.next();
//string function for calculating length
of the string
int len = st.length();
//string variable to store reversed string
String st1 = "";
for(int i = 0 ; i < len ; i++)
{
//string function for getting
character at a particular index
char ch = st.charAt(i);
st1 = ch + st1;
}
//condition for checking palindrome by
using string function
if(st.equals(st1))
System.out.print("Palindrome");
else
System.out.print("Not
Palindrome");
//closing scanner class(not compulsory,
but good practice)
sc.close();
}
}
Python Code
28
#include<stdio.h>
Ex:- Enter any number 153. int main()
{
int num ,n,n1,c=0,mul=1,sum=0,r,f,i;
1**3 + 5**3 + 3**3 = 153
printf("enter any num: \n");
scanf("%d",&num);
Number is Armstrong n=num;
n1=num;
while(n!=0)
Working: {
r=n%10;
Step 1.Initialize variables num,n,n1,c=0,mul=1,sum=0,r,f,i . c++;
n=n/10;
Step 2.Input any number by user so read num variable.
}
Step 3.set n=num and n1=num for duplicate. while (num!=0)
{
Step 4.We use while loop with condition(n!=0). f=num%10;
Step 5.Than check the last digit of a number with condition mul=1;
for(i=1;i<=c;i++)
is reminder(r)=number(n)%10. {
mul=mul*f;
Step 6.Than increment of other variables for next step
}
(c++).
sum=sum+mul;
Step 7.Than find length of number with condition is num=num/10;
}
number(n)=number(n)/10.
if(n1==sum)
Step 8.repeat steps 4 to 6 until number (n)!=0. printf("Armstrong Number");
else
Step 9.Again we use the while loop with condition printf("Not an Armstrong Number");
(num!=0) for check return 0;
}
Step 10.the number is Armstrong or not. Output:-
enter any num: 1634
Step 11.Again check last digit for duplicity of number with
#include<iostream> else
#include<math.h> System.out.println("Not an
using namespace std; Armstrong Number");
//main Program //closing scanner class(not compulsory,
int main() but good practice)
{ sc.close();
int num, digit, sum = 0;
cout << “Enter a positive integer: “;
//user input }
cin >> num; }
int store = num;
//find sum of cubes of individual digits Python Code
do import math
{ value = int(input("Enter the Number: "))
digit = num % 10; num = [int(d) for d in str(value)]
sum = sum + pow(digit,3); sum = 0
num = num / 10; for i in range(0, len(num)):
}while(num != 0); sum = sum + math.pow(num[i], len(num))
//checking for ArmStrong number
if(sum == store) if sum == value:
cout << store << ” is an Armstrong number.”; print("Given number is Armstrong Number")
else else:
cout << store << ” is not an Armstrong number.”; print("Given Number is not Armstrong Number")
return 0;
} # This code is contributed by Shubhanshu Arya (Prepinsta
Placement Cell Student)
Java Code
//Java program to check whether a number is armstrong or
not
import java.util.Scanner;
public class armstrong_number_or_not
{
public static void main(String[] args)
{
//scanner class declaration
Scanner sc = new Scanner(System.in);
//input from user
System.out.print("Enter a number : ");
System.out.println("Armstrong Number");
30
C programming, the user is required to insert integer //for use this loop to store all number in given range
for(i = start + 1; i < end; ++i)
numbers. A n digit number is known as an Armstrong {
//store a duplicity value of given range
number, when the sum of the values of the digits raised to
temp2 = i;
nth power is equal to the number itself. For example: 153 = temp1 = i;
//display serious
Chapter 16. Fibonacci printf("%d ",n3);
}
Series upto nth term return 0;
}
The sequence is a Fibonacci series where the next number
Output:-
is the sum of the previous two numbers. The first two terms enter a limit of series
System.out.print("Enter the limit : "); # This code is contributed by Shubhanshu Arya (Prepinsta
Placement Cell Student)
int lim = sc.nextInt(); # Method 2
if(lim > 0)
{ num = int(input("Enter the Number:"))
int y = 0, z = 1, s; n1, n2 = 0, 1
//display starting two print("Fibonacci Series:", n1, n2, end=",")
numbers of series for i in range(2, num):
System.out.print("Fibonacci n3 = n1 + n2
Series : "+y+" "+z+" "); n1 = n2
//perform iterations till the n2 = n3
limit entered by the user print(n3, end=" ")
while(z <= lim)
{ print()
s=y+z;
y=z; # This code is contributed by Shubhanshu Arya (Prepinsta
z=s; Placement Cell Student)
//condition for
forcing z that it should not be printed when its value is
greater than limit
if(z <= lim)
System.out.print(z+" ");
}
}
else
System.out.print("Wrong
Input");
//closing scanner class(not compulsory,
but good practice)
sc.close();
}
}
Python Code
# Method 1
def fibonacciSeries(i):
if i <= 1:
return i
else:
return (fibonacciSeries(i - 1) + fibonacciSeries(i - 2))
if num <= 0:
print("Please enter a Positive Number")
else:
print("Fibonacci Series:", end=" ")
for i in range(num):
print(fibonacciSeries(i), end=" ")
34
number return 0;
}
In this program we will find the factorial of a number
Output:-
where the number should be entered by the user. Factorial Enter a number to calculate its factorial 4
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
}
Chapter 19 Factor of a return 0;
}
number Output:-
Enter an any number: 12
In this Program we will calculate the factors of any
Factors of a number 12 are: 1 2 3 4 6 12
numbers using C programming. The factors of a number
C ++ Code
are defined as the number we multiply two numbers and get
//C++ Program
the original number. The factor of a number is a real //Factors of a number
#include <iostream>
number which divides the original completely with zero using namespace std;
//main Program
remainder.
int main()
Ex- no is 16,5. {
int num;
16= 2 x 2 x 2 x 2 cout << “Enter a positive number: “;
5= 1 x 5 //user input
cin >> num;
Working cout << “Factors of “ << num << ” are: “ << endl;
//finding and printing factors
Step 1- Enter the number, to find their factor. for(int i = 1; i <= num; i++)
{
Step 2- Initialise the loop with u=1 to u<=number and
if(num % i == 0)
follow the following calculation cout << i << “\t“;
}
(i) check whether the number is divisible with u and u got return 0;
a result zero. }
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
1! + 4! scanf("%d",&number);
//To store a duplicity value of a given number
So it is a strong number. temp=number;
{ System.out.println("Strong
int num=ip%10; Number");//display the result
int fact = 1; else
//finding factorial of each digit of input System.out.println("Not a
for(int i=num;i>0;i–) Strong Number");
{ //closing scanner class(not compulsory,
fact=fact*i; but good practice)
} sc.close();
sum+=fact;
ip/=10;
} }
//checking for Strong Nunber }
if(sum==save)
{ Python Code
cout<<save<<” is a Strong Number”; #Enter the number to check
} print(‘Enter the number:’)
else n=int(input())
{ #save the number in another variable
cout<<save<<” is not a Strong Number”; temp=n
} sum=0
//logic ends #Implementation
return 0; while(temp):
} r=temp%10 # r will have the value of the unit place digit
temp=temp//10
Java Code fac=1
//Java program to check whether a number is a strong for i in range(1,r+1): #finding factorial
number or not fac=fac*i
import java.util.Scanner;
public class strong_number_or_not sum+=fac #adding all the factorial
{
public static void main(String[] args) if(sum==n):
{ print(‘Yes’, n ,‘is strong number’)
//scanner class declaration
Scanner sc = new Scanner(System.in); else:
//input from user print(‘No’ , n, ‘is not a strong number’)
System.out.print("Enter a number : ");
{
Chapter 21. Perfect number // Initialization of variables
int number,i=1,total=0;
In this program we will find the number is a perfect number
or not using C programming. so we will use the while loop // To take user input
printf("Enter a number: ");
and if else statement. Basically perfect number is a positive scanf("%d",&number);
number which is equal to the sum of all its divisors
while(i<number)
excluding itself. we have to find all divisors of that number {
if(number%i==0)
and find their sum, if the sum of divisors is equal to number {
it means the number is Perfect Number. Else sum is not total=total+i;
i++;
equal to number it means number is not a perfect number. }
}
//to condition is true
Ex:- Enter any number 6
if(total==number)
6 is a perfect number as 1 + 2 + 3 = 6. //display
printf("%d is a perfect number",number);
Number is 15 //to condition is false
else
15 is not a perfect number because 1+3+5=9
//display
printf("%d is not a perfect number",number);
Working: return 0;
}
Step 1- enter the number to be check Output:-
Step 2- initialize i with 1. Enter a number: 28
|Step 3- now execute the while loop, while i is less than the 28 is a perfect number
(i) if number is divided by the i, so add number with the Enter a number: 153
sum += i;
} Chapter 22. Automorphic
//checking for perfect number
if (sum == num) number
cout<< num <<” is a perfect number.”;
In this program we have to find whether the number is an
else
Automorphic number or not using C programming. An
cout<< num <<” is not a perfect number.”;
automorphic number is a number whose square ends with
return 0;
the same digits as number itself.
}
Java Code Automorphic Number in C Programming
//Java program to check whether a number is perfect or not
import java.util.Scanner; Example:
public class perfect_number_or_not ● 5=(5)2=25
{
public static void main(String[] args) ● 6=(6)2=36
{
//scanner class declaration ● 25=(25)2=625
Scanner sc = new Scanner(System.in);
//input from user ● 76=(76)2=5776
System.out.print("Enter a number : ");
● 376=(376)2=141376
int number = sc.nextInt();
//declare a variable to store sum of
These numbers are automorphic numbers.
factors
int sum = 0;
for(int i = 1 ; i < number ; i++) ● Automorphic number : C | C++ | Java
{
if(number % i == 0)
sum = sum + i;
}
//comparing whether the sum is equal Working
to the given number or not
if(sum == number)
System.out.println("Perfect Step 1- Enter the number to be checked.
Number");
else Step 2- store the number in a temporary variable.
System.out.println("Not an
Step 3- find the square of a given number and display it.
Perfect Number");
//closing scanner class(not compulsory,
but good practice)
Step4- Initialize the while loop until the number is not
sc.close();
equal to zero
}
} (i) Calculate the remainder of the temp,divided with the 10
Python Code and store in digit
n = int(input(“Enter any number: “))
sump= 0 (ii) divide the number with the 10 and store in the number.
for i in range(1, n):
Step 5- find modules of square with count and compare
if(n % i == 0):
sump= sump + i with temp
if (sump == n):
print(“The number is a Perfect number”) Step 6-if it is true display Automorphic or else not a
else:
print(“The number is not a Perfect number”)
43
System.out.println("Not an
Automorphic Number");
//closing scanner class(not compulsory,
but good practice)
sc.close();
}
} Chapter 23. Harshad
Python Code number
1st Approach
#enter the number to check In this program we will discuss if the number is harshad
print(‘Enter the number:’) number or not in C programming. In mathematics, a
n=int(input())
sq=n*n #square of the given number Harshad number is a number that is divisible by the sum of
co=0 #condition variable
its digits. We use a while loop statement with the following
while(n>0): #loop until n becomes 0
if(n%10!=sq%10): condition. Input consists of 1 integer.
print(‘Not Automorphic’)
co=1
break # come out of the loop if the above Ex– Number is 21
condition holds true
it is divisible by own sum (1+2) of its digit(2,1)
#reduce n and square
n=n//10 So it is harshad number
sq=sq//10
Some other harshad numbers are 156,54,120 etc.
if(co==0):
print(‘Automorphic’)
2nd Approach Working:
(iii) divide the temp with the 10 and store in the temp;
the res;
number.
Step 6- Stop.
45
if(p%sum1==0):
}
}
Output :
Enter a number : 18 print(“Harshad number”)
Harshad Number
Python Code
General Solution: Optimal solution:
p=n p=n
l=[] sum1=0
sum1=0 while(n>0):
while(n>0): sum1+=n%10
x=n%10 n=n//10
if(p%sum1==0):
print(“Harshad number”)
l.append(x)
else:
n=n//10
print(“Not harshad number”)
47
int main()
Chapter 24. Abundant
{
number
In this program to find the number is Abundant number or
//initialization variables
not. A number n is said to be Abundant Number to follow
these condition
int number,sum=0,c;
● the sum of its proper divisors is greater than the
number itself.
● And the difference between these two values is
called the abundance. //input from user
1,2,3,4,6 the sum of these factors is 16 it is greater than 12 printf("Enter a number : ");
so it is an Abundant number.
18, 20, 24, 30, 36, 66, 70, 72, 78, 80, 84, 88, 90, 96, 100,
//declare a variable to store sum of factors of the number
102, 104, 108, 112, 114, 120..
return 0;
C Code }
#include<iostream> System.out.println("Not an
using namespace std; Abundant Number");
//main Program //closing scanner class(not compulsory,
int main () but good practice)
{ sc.close();
int div, num, sum=0;
cout << “Enter the number to check : “;
//user input }
cin >> num; }
//loop to find the sum of divisors Output :
for (int i=1; i < num; i++) Enter a number : 12
{ Abundant Number
div = num % i;
if (div == 0) Python Code
sum += i; #enter the number to check
} print(‘Enter the number:’)
//checking for Abundant number n=int(input())
if (sum > num) sum=1 # 1 can divide any number
cout<< num <<” is an Abundant number.”; for i in range(2,n):
else if(n%i==0): #if number is divisible by i add the
cout<< num <<” is not an Abundant number.”; number
return 0; sum=sum+i
}
if(sum>n):
Java code print(n,‘is Abundant Number’)
//Java program to check whether a number is abundant
number or not else:
import java.util.Scanner; print(n,‘is not Abundant Number’)
public class abundant_number_or_not
{
public static void main(String[] args)
{
//scanner class declaration
Scanner sc = new Scanner(System.in);
//input from user
System.out.print("Enter a number : ");
?(n)/n = ?(m)/m //4 Using one variable for loop and second to check for
each number
for(int i=1;i<f_Num;i++)
Where ?(n) is the sum of divisors of n. {
//5 Condition check
For instance, for numbers 6 and 28,
if(f_Num % i == 0)
Divisors of 6 are- 1, 2, 3, and 6. f_DivisorSum = f_DivisorSum + i;
}
Divisors of 28 are- 1, 2, 4, 7, 14, and 28. //6 Calculating the sum of all divisors
for(int i=1;i<s_Num;i++)
Sum of the divisors of 6 and 28 are 12 and 56 respectively.
{
Also, the abundant index of 6 and 28 is 2. if(s_Num % i == 0)
s_DivisorSum = s_DivisorSum + i;
Therefore, 6 and 28 is a friendly pair. }
//7 Check condition for friendly numbers
Working
if((f_Num == s_DivisorSum) && (s_Num ==
Step 1. Start f_DivisorSum))
//finding and adding divisors of first number for(int i = 1 ; i < number1 ; i++)
if(first%i==0) {
sum1=sum1+i; if(number1 % i == 0)
} add1 = add1 + i;
for(int i=1; i<=second/2 ; i++) }
{ //logic for finding factors and
//finding and adding divisors of second number calculating sum of all those factors for number2
if(second%i==0) for(int i = 1 ; i < number2 ; i++)
sum2=sum2+i; {
} if(number2 % i == 0)
//checking for friendly pair add2 = add2 + i;
if(first==sum2 && second==sum1) }
cout<<“Friendly Pair(“<<first<<“,”<<second<<“)”; //condition for friendly pair number
else if(number1 == add2 && number2 ==
cout<<“Not a Friendly Pair”; add1)
} System.out.println("Number
//main program is Friendly Pair");
int main() else
{ System.out.println("Number
int first,second; is not Friendly Pair");
cout<<“Enter first number : “; //closing scanner class(not compulsory,
//user input but good practice)
cin>>first; sc.close();
cout<<“Enter second number : “;
//user input
cin>>second; }
//calling function }
findAmicable(first,second);
return 0;
Python Code
}
#’Enter the numbers to check’
n=int(input())
Java Code m=int(input())
//Java program to check whether a number is friendly pair import math
or not sum_n=1 + n #sum of divisor of n
import java.util.Scanner; sum_m=1 + m #sum of divisor of m
public class friendly_pair_or_not i=2
{ j=2
public static void main(String[] args) #finding divisor
{ while(i<=math.sqrt(n)):
//scanner class declaration if(n%i==0):
Scanner sc = new Scanner(System.in); if(n//i==i):
//input from user sum_n+=i
System.out.print("Enter First number :
"); else:
int number1 = sc.nextInt(); sum_n+=i + n//i
System.out.print("Enter Second
number : "); i=i+1
int number2 = sc.nextInt();
//declare two variables to store the while(j<=math.sqrt(m)):
addition of factors of both numbers which are entered by if(m%j==0):
user if(m//j==j):
int add1 = 0, add2 = 0; sum_m+=j
//logic for finding factors and
calculating sum of all those factors for number1 else:
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’)
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:-
Working:-
Step 1. Start
56
int n = 1;
System.out.print("HCF of "+num1+" Chapter 29. Binary to
and "+num2+" is ");
if( num1 != num2) Decimal to conversion :
{
The C program converts binary numbers to decimal
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
}
Step 6: Repeat the above steps with the quotient obtained
}
until the quotient becomes 0
C Code :
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 ; public static void main(String args[])
//base*=2; {
base = base * 2; Scanner sc = new Scanner(System.in);
} System.out.print("Enter a binary
//display binary number number : ");
printf("The Binary num is = %d \n", binary_val); int binary = sc.nextInt();
//display decimal number //Declaring variable to store decimal
printf("Its decimal equivalent is = %d \n", number
decimal_val); int decimal = 0;
return 0; //Declaring variable to use in power
}
int n = 0;
//writing logic for the conversion
while(binary > 0)
C++ Code : {
//C++ Program int temp = binary%10;
//Convert binary to decimal decimal +=
#include <iostream> temp*Math.pow(2, n);
#include <math.h> binary = binary/10;
using namespace std; n++;
//function to convert binary to decimal }
int convert(long n) System.out.println("Decimal number :
{ "+decimal);
int i = 0,decimal= 0; //closing scanner class(not compulsory, but good
//converting binary to decimal practice)
while (n!=0) sc.close();
{ }
int rem = n%10; }
n /= 10;
int res = rem * pow(2,i);
Python Code :
decimal += res;
i++; num = int(input("Enter number:"))
} binary_val = num
return decimal; decimal_val = 0
} base = 1
//main program while num > 0:
int main() rem = num % 10
{ decimal_val = decimal_val + rem * base
long binary; num = num // 10
cout << “Enter binary number: “; base = base * 2
cin >> binary;
cout << binary << ” in binary = “ << convert(binary) print("Binary Number is {} and Decimal Number is
<< ” in decimal”; {}".format(binary_val, decimal_val))
return 0;
}
Java Code :
//Java program to convert Binary number to decimal
number
import java.util.Scanner;
public class Binary_To_Decimal
59
}
60
int n = 0;
//writing logic for the conversion from
binary to decimal
while(binary > 0)
{
int temp = binary%10;
decimal +=
temp*Math.pow(2, n);
binary = binary/10;
n++;
}
int octal[] = new int[20];
int i = 0;
//writing logic for the conversion from
decimal to octal
while(decimal > 0)
{
int r = decimal % 8;
octal[i++] = r;
decimal = decimal / 8;
}
//printing result
System.out.print("Octal number : ");
for(int j = i-1 ; j >= 0 ; j--)
System.out.print(octal[j]);
//closing scanner class(not compulsory,
but good practice)
sc.close();
}
}
Python Code :
#take binary number
Bin_num = 0b10111
61
{
Chapter 31. Decimal to count++;
}
Binary conversion:
bin = bin + rem * base;
The C program to convert decimal numbers into binary
//number/=2;
numbers is done by counting the number of 1s. The
number = number / 2;
program practices module process and multiplication with
base = base * 10;
base 2 operation for converting decimal into binary
}
number. It further uses modulo operation to check for 1’s
//display
and hence increases the amount of 1s. The program reads
printf("Input num is = %d\n", dec_num);
an integer number in decimal in order to change or convert
printf("Its binary equivalent is = %ld\n", bin);
into a binary number.
printf("Num of 1's in the binary num is = %d\n", count);
return 0;
Ex:- (180)10=(11101000)2
}
Working:
Step 1: Start
Step 2: Ask the user to insert an integer number in decimal C++ Code :
as an input
Step 3: Check whether the entered number is less than or //C++ Program
equal to 0 //Decimal to binary conversion
Step 4: Check the divisibility of the number by 2 and store #include <iostream>
the remainder in the range #include <math.h>
Step 5: Increase the range by 1 using namespace std;
Step 6: After calculating, print the binary number and the //function to convert decimal to binary
number of 1s. long convert(int n)
Step 7: Stop {
long binary = 0;
int i = 1;
//converting decimal to binary
C Code : while (n!=0)
{
/*
int rem = n%2;
* C program to accept a decimal number and convert it to
n /= 2;
binary
binary += rem*i;
* and count the number of 1's in the binary number
i *= 10;
*/
}
return binary;
}
#include<stdio.h>
//main program
int main()
int main()
{
{
//for initialize a variables
int decimal;
long number, dec_num, rem, base = 1, bin = 0, count =
long binary;
0;
cout << “Enter a decimal number: “;
//To insert a number
//user input
printf("Insert a decimal num \n");
cin >> decimal;
scanf("%ld", &number);
//calling function
dec_num = number;
binary = convert(decimal);
while(number > 0)
cout << decimal << ” in decimal = “ << binary << ” in
{
binary” << endl ;
rem = number % 2;
return 0;
/* To count no.of 1s */
}
if (rem == 1)
62
Java Code :
//Java program to convert decimal number to binary
number
import java.util.Scanner;
public class Decimal_To_Binary Chapter 32. Decimal to
{
public static void main(String args[]) octal Conversion:
{
The C program to convert decimal to octal number accepts
//scanner class object creation
a decimal number from the user. This number is further
Scanner sc = new Scanner(System.in);
converted to its equivalent octal number after following a
//input from user
series of steps. The following section gives an algorithm for
System.out.print("Enter a Decimal
this conversion. It is then followed by a C program.
number : ");
int decimal = sc.nextInt();
Ex:- If a Decimal number is an octal number we use this
//integer array for storing binary digits
method
int binary[] = new int[20];
(143)10=(217)8
int i = 0;
//writing logic for the conversion
Working:
while(decimal > 0)
Step 1. Start
{
Step 2. The user enters a decimal number.
int r = decimal % 2;
Step 3. Divide the decimal number by 8 to obtain its
binary[i++] = r;
quotient and remainder. Store remainder in an array.
decimal = decimal/2;
Step 4. Repeat step 3 with the quotient until the quotient
}
becomes 0.
//printing result
Step 5. Print the remainder array in reverse order to get the
System.out.print("Binary number : ");
octal conversion
for(int j = i-1 ; j >= 0 ; j--)
Step 6. Stop
System.out.print(binary[j]+" ");
//closing scanner class(not compulsory,
but good practice)
sc.close(); C Code:
}
} //Program to convert Decimal number into octal number
#include<stdio.h>
int main()
Python Code : {
//Variable initialization
#take decimal number
long dec_num, rem, quotient;
dec_num = 124
int i, j, octalno[100];
#convert decimal number to binary
//Taking input from user
bin_num = bin(dec_num)
printf("Enter a number for conversion: ");
#print number
//Storing the value in dec_num variable
print('Number after conversion is :' + str(bin_num))
scanf("%ld",&dec_num);
quotient = dec_num;
i=1;
//Storing the octal value in octalno[] array
while (quotient!=0)
{
octalno[i++]=quotient%8;
quotient=quotient/8;
}
//Printing the octalno [] in reverse order
printf("\nThe Octal of %ld is:\n\n",dec_num);
63
Java Code :
//Java program to convert decimal number to octal number
import java.util.Scanner;
public class Decimal_To_Octal
{
public static void main(String args[])
{
//scanner class object creation
Scanner sc = new Scanner(System.in);
64
case '3':
Chapter 33. Octal to Binary printf("011"); break;
case '4':
conversion : printf("100"); break;
case '5':
Octal to binary conversion:-
printf("101"); break;
The C program helps to convert octal numbers to binary
case '6':
numbers. In this program, the user is asked to insert an
printf("110"); break;
octal number and by using a loop or if-else statement, the
case '7':
user can convert an octal number to binary number. An
printf("111"); break;
integer variable is required to be used in the program.
//for invalid case
default:
Working:
printf("\n Invalid octal digit %c ", octalnum[i]);
Step 1: Start
return 0;
Step 2: Ask the user to enter an octal number as an input.
}
Step 3: Store the inserted number in the array octal num.
i++;
Step 4: With the help of switch statement, evaluate every
}
number of the octal number
return 0;
Step 5: Print the equal binary value in a 3 digit number (Eg.
}
000)
Step 6: Do step 4 under the while loop.
Step 7: Stop
C++ Code :
//C++ Program
C Code : // Octal to Binary conversion
#include <iostream>
/*
#include <math.h>
* C Program to Convert Octal to Binary number
using namespace std;
*/
//Function to convert octal to binary
#include<stdio.h>
long convert(int octal)
#include<conio.h>
{
int decimal = 0, i = 0;
#define MAX 1000
long binary = 0;
//converting octal to decimal
int main()
while(octal != 0)
{
{
char octalnum[MAX];
int rem = octal%10;
//For initialize
int res=rem * pow(8,i);
long i = 0;
decimal += res;
//taking user input of octalnum
i++;
printf("Insert an octal number: ");
octal/=10;
scanf("%s", octalnum);
}
printf("Equivalent binary number: ");
i = 1;
while (octalnum[i])
//converting decimal to binary
{
while (decimal != 0)
//use switch case for multiple condition
{
switch (octalnum[i])
int rem = decimal % 2;
{
binary += rem * i;
case '0':
decimal /= 2;
printf("000"); break;
i *= 10;
case '1':
}
printf("001"); break;
return binary;
case '2':
}
printf("010"); break;
//main program
65
int n = 0;
//writing logic for the octal to decimal
conversion
while(octal > 0)
{
int temp = octal % 10;
decimal += temp *
Math.pow(8, n);
octal = octal/10;
n++;
}
int binary[] = new int[20];
int i = 0;
//writing logic for the decimal to binary
conversion
while(decimal > 0)
{
int r = decimal % 2;
binary[i++] = r;
decimal = decimal/2;
}
66
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++;
}
//printing result
System.out.println("Decimal number :
Chapter 35. Quadrants in
"+decimal);
//closing scanner class(not compulsory,
which a given coordinate
but good practice)
sc.close();
lies :
} The C program reads the coordinate point in a xy
} coordinate system and identifies the quadrant. The program
takes X and Y. On the basis of x and y value, the program
will identify on which quadrant the point lies. The program
Python Code : will read the value of x and y variables. If-else condition is
used to identify the quadrant of the given value.
#take octal number
#with prefix 0o[zero and o/O] Ex:- X and Y coordinates are 20, 30 these lie in 4th
oct_num = 0o512 quadrant because in mathematics quadrants rules are
#convert octal number to integer following
#integers are with base 10
deci_num = int(oct_num) ● x is positive integer and y is also positive
#print number integer so-that quadrant is a first quadrant.
print('Number after conversion is :' + str(deci_num)) ● x is negative integer and y is positive integer
so-that Quadrant is a second quadrant.
● x is negative integer and y is also negative
integer so -that Quadrant is a third quadrant.
● x is positive integer and y is negative integer
so-that is a first quadrant.
Working:
Step 1: Start
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
the given value
Step 4: Check the condition, if x variable’s value is greater
than 0 and the variable y is greater than 0.
Step 5: If the condition is true then print the output as the
first quadrant.
Step 6: If the condition is false then check the condition if x
is lesser than 0 and the y variable is greater than 0.
68
C++ Code :
//C++ program
//Quadrants in which coordinates lie
#include<iostream>
using namespace std;
//main program
int main()
69
{
Chapter 36. Permutations long int n,r,permutation,temp;
long int numerator, denominator;
in which n people can
// Insert the num of people
occupy r seats in a
printf("\nEnter the number of persons : ");
classroom :
scanf("%ld",&n);
C programming helps in identifying the r number of seats
that can be occupied by n number of people. Such a
// Insert the num of seats
program is known as the possible permutations. Here, We
need to write a code to find all the possible permutations in
printf("\nEnter the number of seats available : ");
which n people can occupy or number of seats in a
classroom/theater.
scanf("%ld",&r);
// Base condition
N students are looking to find r seats in a classroom. Some
// Swap n and r when n is less than r
of the seats are already occupied and only a few can be
accommodated in the classroom. The available seats are
if(n < r)
assumed as r and n number of people are looking to
{
accommodate within the room.
temp=n;
n=r;
Permutations in which n people can occupy r seats in a
r=temp;
classroom in C programming
}
Way 2 Of Asking Question
numerator=fact(n);
Write code to find all possible permutations in which n
denominator=fact(n-r);
people can occupy r seats in a theater
permutation=numerator/denominator;
printf("\nNum of ways people can be seated : ");
Working:
printf("%ld\n",permutation);
Step 1: Start
}
Step 2: Ask the user to insert n number of people and the
number of seats as r.
Step 3: Calculate permutation, p(n,r).
Step 4: Enter the program to calculate permutation P(n,r) = C++ Code :
n! / (n-r)!
Step 5: Print the calculated result. //C++ Program
Step 6: Stop //Permutations in which n people can occupy r seats
#include<iostream>
using namespace std;
//function for factorial
C Code : int factorial(int num)
{
#include<stdio.h>
int fact=1;
for(int i=num;i>=1;i–)
// Program to find the factorial of the number
fact*=i;
int factorial (long int x)
return fact;
{
}
long int fact=1,i;
//main program
for(i=1;i<=x;i++)
int main()
{
{
fact=fact*i;
int n,r;
}
cout<<“Enter number of people: “;
return fact;
//user input
}
cin>>n;
int main()
cout<<“Enter number of seats: “;
70
Java Code :
import java.util.*;
import java.io.*;
class PrepInsta
{
public static void main(String[] args)
{
int n, r, per, fact1, fact2;
Scanner sc = new Scanner(System.in);
System.out.println(“Enter the Value of n and r”);
n = sc.nextInt();
r = sc.nextInt();
fact1 = n;
for (int i = n – 1; i >= 1; i=i-1)
{
fact1 = fact1 * i; //calculating factorial (n!)
}
int number;
number = n – r;
fact2 = number;
for (int i = number – 1; i >= 1; i=i-1)
{
fact2 = fact2 * i; //calculating factorial ((n-r)!)
}
per = fact1 / fact2; //calculating nPr
System.out.println(per+“ways”);
}
}
Python Code :
#import math lib
import math
#take user inputs
71
}
Chapter 37. Maximum
number of handshakes:
Java Code :
In C programming, there’s a program to calculate the
number of handshakes. The user is asked to take a number // Java program to find maximum number of handshakes
as integer n and find out the possible number of import java.io.*;
handshakes. For example, if there are n number of people import java.util.*;
in a meeting and find the possible number of handshakes
made by the person who entered the room after all were class handshakes
settled. {
// Calculating the maximum number of handshakes
Working: static int maxHandshake(int n)
Step 1: Start {
Step 2: The user is asked to insert an integer value n, return (n * (n – 1)) / 2;
representing the number of people }
Step 3: Find nC2, and calculate as n * (n – 1) / 2.
Step 4: Print the outcome derived from the above program
Step 5: Stop // Driver code
public static void main (String[] args)
{
C Code : Scanner sc=newScanner(System.in);
int n = sc.nextLine();
// C program to find the maximum number of handshakesM
System.out.println( maxHandshake(n));
#include<stdio.h>
}
int main()
}
{
//fill the code
int num; Python Code :
scanf("%d",&num);
int total = num * (num-1) / 2; // Combination nC2 #take user inputs
printf("%d",total); N = int(input('Enter number of people available :'))
return 0; #formula
} no_of_handshakes = int(N *((N-1)/2))
#print number of no_of_handshakes
print('Maximum number of handshakes can be :' +
C++ Code : str(no_of_handshakes))
//C++ Program
//Maximum number of handshakes
#include<iostream>
using namespace std;
//main program
int main()
{
int p;
cout<<“Enter number of Persons: “;
//user input
cin>>p;
cout<<“Maximum number of handshakes: “;
//find maximum number of handshakes using formula
int max=p*(p–1)/2;
//printing output
cout<<max;
return 0;
72
else
Chapter 39. Replace all 0’s return replace(num);
}
with 1 in a given integer : int main()
{
The replace all program in C programming works to
long int num;
replace the numbers with zero, where the number must be
//To take user input
an integer. All the zeros (if encountered) in the given
printf("\nInsert the num : ");
program will be replaced by 1.
scanf("%d", &number);
//display final result
Ex- number is 12004509 all 0’s are replays of 1’s so
printf("\n Num after replacement : %d\n", Convert
number is 12114519.
(num));
return 0;
Working:
}
Step 1: Start
Step 2: The user is asked to insert an integer value as an C++ Code :
input
Step 3: Navigate the inserted integer digit by digit //C++ Program
Step 4: If 0 is found, then replace it with 1, and print the //Convert all 0’s to 1
integer variable #include<iostream>
Step 5: Stop using namespace std;
//main program
int main()
Question can come like Way 1
{
Write a code to change all zero's as one's (0s as 1s) in a
int num,num2=0;
given number? ex: 120014 needs to be printed as 121114
cout<<“Enter number: “;
//user input
Question can come like Way 2
cin>>num;
implement a c program to replace all 0's with 1 in a given
//checking for 0 input
integer as an input, all the 0's in the number has to be
if(num == 0)
replaced with 1.
num2=1;
//converting 0 to 1
while(num>0)
C Code : {
int rem = num%10;
// C program to replace all 0’s with 1 in a given integer if(rem == 0)
#include rem = 1;
int replace (long int num) num = num/10;
{ num2=num2*10+rem;
// Base case for recursion termination }
if (num == 0) //converted number
return 0; cout<<“Converted number is: “<<num2;
// Extract the last digit and change it if needed return 0;
int digit = num % 10; }
if (digit == 0)
digit = 1;
// Convert remaining digits and append the last digit
Java Code :
return replace(num/10) * 10 + digit;
//Java program to replace all 0's with 1 in a given integer :
}
import java.util.Scanner;
int Convert(long int num)
public class replace_0_to_1
{
{
if (num == 0)
public static void main(String[] args)
return 1;
{
75
}
}
Python Code :
Method 1 :
#taking Input
n=int(input())
#converting into string
n=str(n)
#then into the list
n=list(n)
r=” #empty string for addind it the item of list
for i in range(len(n)):
#if we find ‘0’ we will replace it with ‘1’
if(n[i]==‘0’):
n[i]=‘1’
r=r + n[i] #creating the new integer
del n
print(int(r))
Method 2 :
n=int(input(“Enter any number”))
s=str(n)
l=[]
76
if (Prime(i)) int c = 1;
{ for(int i = 2 ; i < n ; i++)
// condition for n-i to be a prime number {
if (Prime(n–i)) if(n % i == 0)
{ {
cout<<n <<” = “<< i <<” + “ << n–i<< c = 0;
endl; break;
check = 1; }
} }
} return c;
} }
if (check == 0)
cout<<n<<” cannot be expressed as the sum of
two prime numbers.”;
Python Code :
return 0; #take input
} Number = int(input('Enter the Number :'))
#initialize an array
arr = []
Java Code :
#find prime numbers
//Java program to check whether a number can be for i in range(2,Number):
expressed as a sum of two prime numbers flag = 0
import java.util.Scanner; for j in range(2,i):
public class number_as_sum_of_two_prime_numbers if i % j == 0:
{ flag = 1
public static void main(String[] args) #append prime numbers to array
{ if flag == 0:
//scanner class declaration arr.append(i)
Scanner sc = new Scanner(System.in); #possible combinations
//input from user flag = 0
System.out.print("Enter a number : "); for i in range(len(arr)):
for j in range(i+1,len(arr)):
int number = sc.nextInt(); #if condition is True Print numbers
int x = 0; if(arr[i] + arr[j] == Number):
for(int i = 2 ; i <= number/2 ; i++) flag = 1
{ print(str(arr[i]) + " and " + str(arr[j]) + ' are prime
if(prime_or_not(i) == 1) numbers when added gives ' + str(Number))
{ break
if(flag == 0):
if(prime_or_not(number-i) == 1) print('No Prime numbers can give sum of ' + str(Number))
{
cnt[k] += cnt[k-2];
Chapter 41. Count possible }
return cnt[a];
decodings of a given digit }
Chapter 42. Check whether elseif((c >= 'a' && c= 'A' && c <= 'Z'))
prinf("\n not a alphabet\n");
a character is a vowel or
else
consonant : printf("%c is a consonant", c);
Given a character, check if it is a vowel or consonant.
return 0;
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’,’
d’, ‘f’,…..) are consonants. In this article, we will show C++ Code :
you, How to write a C program to check Vowel or
Consonant with an example. //C++ Program to check whether alphabet is vowel or
consonant
Working: #include <iostream>
We check whether a given character matches any of the 5 using namespace std;
vowels. If yes, we print “Vowel”, else we print //main function
“Consonant”. int main()
{
This C program allows the user to enter any character and char c;
check whether the user specified character is Vowel or cout<<"Enter an alphabet: ";
Consonant using If Else Statement. cin>>c;
This program takes the character value(entered by user) as //checking for vowels
input.
And checks whether that character is a vowel or consonant if(c=='a'||c=='e'||c=='i'||c=='o'||c=='u'||c=='A'||c=='E'||c=='I'||c
using if-else statement. =='O'||c=='U')
Since a user is allowed to enter an alphabet in lowercase {
and uppercase, the program checks for both uppercase and cout<<c<<" is a vowel"; //condition
lowercase vowels and consonants. true input is vowel
And now we have to follow step’s of C programming }
else
{
C Code : cout<<c<<" is a consonant";
//condition false input is consonant
#include <stdio.h>
}
int main()
return 0;
{
}
char c;
int isLowerVowel, isUpperVowel;
printf("Enter an alphabet: "); Java Code :
scanf("%c",&c);
//JAVA Program to check whether the character entered by
//To find the corrector is lowercase vowel user is Vowel or Consonant.
isLowerVowel = (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c
== 'u'); import java.util.Scanner;
//To find the character is Upper case vowel public class vowelorconsonant
isUpperVowel = (c == 'A' || c == 'E' || c == 'I' || c == 'O' || c {
== 'U'); //class declaration
// compare to charector is Lowercase Vowel or Upper case public static void main(String[] args)
Vowel {
//main method declaration
if (isLowerVowel || isUpperVowel) Scanner sc=new Scanner(System.in);
printf("%c is a vowel", c); //scanner class object creation
//to check character is alphabet or not
System.out.println(" Enter a character");
80
char c = sc.next().charAt(0);
//taking a character c as input from user
else
printf("The entered character %c is not an Alphabet”, a);
return 0;
}
81
else
{
//input does not lie in range
cout<<alpha<<" is not an alphabet ";
}
return 0;
}
Java Code :
//Java program to check whether the character entered by
the user is an alphabet or not.
import java.util.Scanner;
public class alphabetornot
{
//class declaration
public static void main(String[] args)
{
//main method
declaration
char c;
Scanner sc = new Scanner(System.in);
//condition for
checking characters
if((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'))
82
You can compute the area of a Circle if you know its Java Code :
radius, by simple formula A = 3.14 * r * r in C
//Java program to calculate area of a circle
programming.We allow the user to enter radius, and then
import java.util.Scanner;
find the area of the cirle.
public class area_of_circle
{
Working:
public static void main(String[] args)
1. initialization of radius.
{
//scanner class declaration
2. calculate the area of circle
Scanner sc = new Scanner(System.in);
area=3.14*radius*radius.
//input from the user
System.out.print("Enter the radius of a
C Code : circle : ");
double radius = sc.nextFloat();
#include<stdio.h>
int main()
{
//formula for area of a circle
double area = 3.14 * radius * radius;
//for initialization of radius and area in a float datatype
float radius,area,pi=3.14;
System.out.println(area);
Chapter 45. Find the ASCII cout<<"The ASCII value of "<<val<<" is "<<(int)val;
return 0;
value of a character : }
ASCII value can be any integer number between 0 and 127
and consists of character variables instead of the character Java Code :
itself in C programming. The value derived after the
programming is termed as ASCII value. With the help of //Java program to print ASCII values of a character
casting the character to an integer, the ASCII value can be
derived. Every character has an individual ASCII value that import java.util.Scanner;
can only be an integer. Every time the character is stored class Main
into a variable, as a substitute for keeping the character {
itself, the ASCII value of the specific character will get public static void main(String[] args)
stored. {
Working: //scanner class object creation
Step 1: Start Scanner sc=new Scanner(System.in);
Step 2: Ask the user to insert any character
Step 3: The character will be assigned to the variable ‘a’ //input from user
Step 4: Scan the character variable to find out the ASCII System.out.print("Enter a Character: ");
value of the character char c=sc.next().charAt(0);
Step 5: Stop
//typecasting from character type to
integer type
C Code : int i = c;
/* C Program to identify ASCII Value of a Character */
//printing ASCII value of the character
#include<stdio.h>
System.out.println("ASCII value of
#include<conio.h>
"+c+" is "+i);
int main()
{
//closing scanner class(not compulsory,
char a;
but good practice)
sc.close();
printf("\n Kindly insert any character \n");
}
scanf("%c",&a);
}
printf("\n The ASCII value of inserted character = %d",a);
return 0;
} Python Code :
#user input
C++ Code : Char = input('Enter the character :')
#convert Char to Ascii value
//C++ program to calcualte ASCII value of Character
Asciival = ord(Char)
#include<iostream>
#print Value
using namespace std;
print(Asciival)
//main program
int main()
{
char val;
cout<<"Enter a character: ";
cin>>val;
}
Chapter 46. Find the prime
numbers between 1 to 100 :
C++ Code :
We know that the whole number is the basic counting
number 0,1,2,3….and so on.So A whole number greater //Cpp Code to find prime number between 1 to 100
than 1 that can not be made by multiplying other whole #include <iostream>
numbers. using namespace std;
///Main Function
Example-7 is a prime number because 7 is only divisible by int main()
one or itself.It can not be divisible by 2,3,4,5,6. {
int i,j,count=0;
So a prime number has two factors: 1 and the number itself
is called prime numberThe number 1 is neither prime nor //Print prime number between 1 to 100
composite. cout<<"print prime number between 1 to 100\n";
System.out.print(" "+i);
count=0;
}
}
Python Code :
#To find the prime numbers between 1 to 100
li=[] #list of prime numbers will be stored here
for i in range(2,101):
f=0
for j in range(2,i+1):
if(i!=j and i%j==0): #if any n
f=1
break
if(f==0):
li.append(i)
print(‘Prime numbers between 1 to 100:’)
print(*li,sep=‘ ‘)
C Code :
#include <stdio.h>
int main()
86
{ //output
//to initialize of variable cout<<"Number of digits in the given integer is: "<<digit;
int count=0; return 0;
int n,c; }
Python Code :
Chapter 49. Counting
def numToWords(num):
length_of_string = len(num); number of days in a given
if (length_of_string == 0):
print("String is Empty"); month of a year:
return;
if (length_of_string > 4): Number of days in any month of a year can vary
print("Please enter the string with supported length"); specifically in February as the cycle of leap year repeats in
return; every 4 years when the year is leap February gives the
ones_digits = ["zero", "one", "two", "three", "four", count to 29 days but the when the year is not leap it gives
"five", "six", "seven", "eight", "nine"]; count to 28 days and so no of days in a year varies from
tens_digits = ["", "ten", "eleven", "twelve", "thirteen", 365 to 366.
"fourteen", "fifteen", "sixteen", "seventeen", Rather than February every month gives the count of 30 or
"eighteen","nineteen"]; 31 days in any case whether the year is a leap or not.
multiple_of_ten = ["", "", "twenty", "thirty", "forty",
"fifty", "sixty", "seventy", "eighty", "ninety"]; Working:
power_of_ten = ["hundred", "thousand"]; ● Take user inputs like month and year.
print(num, ":", end = " "); ● Check if the given month is February.
if (length_of_string == 1): ● If True Check if the year is a year leap or not.
print(ones_digits[ord(num[0]) - '0']); ● If the year is a leap year Print 29 Days, Else Print
return; 28 Days.
x = 0; ● If Condition in Step 3 is False Check the month.
while (x < len(num)): if (length_of_string >= 3): ● Print the number of days assigned to a specific
if (ord(num[x]) - 48 != 0): Month.
print(ones_digits[ord(num[x]) - 48], end = " ");
print(power_of_ten[length_of_string - 3], end = "
");
C++ Code :
length_of_string -= 1;
else: //C++ program
if (ord(num[x]) - 48 == 1): //to display number of days in a month
sum = (ord(num[x]) - 48 + ord(num[x]) - 48); #include<iostream>
print(tens_digits[sum]); using namespace std;
return; //main Program
elif (ord(num[x]) - 48 == 2 and ord(num[x + 1]) - int main()
48 == 0): {
print("twenty"); //take user inputs for Month and year in integer
return; int Month,Year;
else: cout<<“\nEnter the Month :”;
i = ord(num[x]) - 48; cin>>Month;
if(i > 0): cout<<“\nEnter the Year :”;
print(multiple_of_ten[i], end = " "); cin>>Year;
else: //Check condition for Month and leap year
print("", end = ""); if(Month == 2 && (Year%4 == 0) || ((Year%100 == 0)
x += 1; && (Year%400 == 0)))
if(ord(num[x]) - 48 != 0): cout<<“Number of days is 29”;
print(ones_digits[ord(num[x]) - 48]); else if(Month == 2)
x += 1; cout<<“Number of days is 28”;
numToWords("1121") else if(Month == 1 || Month == 3 || Month == 5 ||
Month == 7 || Month == 8 || Month == 10 || Month == 12)
cout<<“Number of days is 31”;
else
cout<<“Number of days is 30”;
}
89
while(n)
{
n=n/10;
C++ Code :
//C++ program
//Strong Number or not
#include<iostream>
using namespace std;
//main Program
int main()
{
int Number,Divisor,count1;
91
Python Code :
#import math library
import math
#take user inputs
a = int(input('Enter value of a :'))
b = int(input('Enter value of b :'))
c = int(input('Enter value of c :'))
#check for value of a
if a == 0:
print("a cannot be zero")
#if a is greater than 0
else:
#calculate value of Function
val = b**2 - 4 * a * c
root = math.sqrt(abs(val))
#Check for roots and print according to their nature
if val > 0:
print("Two Real Roots")
print((-b + root)/(2 * a))
print((-b - root)/(2 * a))
elif val == 0:
print("One Real Root")
print(-b / (2*a))
else:
print("No Real Root")
print(- b / (2*a) , " + i", root)
print(- b / (2*a) , " - i", root)