0% found this document useful (0 votes)
54 views74 pages

Top 100 Codes

The PrepInsta Handbook provides comprehensive information on the Top 100 coding questions commonly asked in placement tests and interviews, combining both theoretical knowledge and practical coding examples. It includes a variety of topics such as number classification, mathematical operations, and algorithms, along with code snippets in multiple programming languages. The book aims to serve as a complete resource for candidates preparing for recruitment processes.

Uploaded by

riddhibarhate
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
54 views74 pages

Top 100 Codes

The PrepInsta Handbook provides comprehensive information on the Top 100 coding questions commonly asked in placement tests and interviews, combining both theoretical knowledge and practical coding examples. It includes a variety of topics such as number classification, mathematical operations, and algorithms, along with code snippets in multiple programming languages. The book aims to serve as a complete resource for candidates preparing for recruitment processes.

Uploaded by

riddhibarhate
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 74

PrepInsta Handbook for Top 100 Codes

For Placement Preparation

PrepInsta Technologies Pvt Ltd


1

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

First Edition ● The correct price of the book is already

May 2021
Edition: 1 (2021)
Published on GSM Paper with PrepInsta WaterMark

Publisher Address: K-3, Director Vidyamandir Shastri Price- Rs.999/-


Nagar, Meerut, UP, 250004 mentioned on this page. Any revised price on the
frontend or backend of the book is not
Type settings : PrepInsta Technologies Private Limited acceptable.

Printer Name: Creative Print Arts Address of the Publisher:

K-3, Director Vidyamandir Shastri Nagar, Meerut, UP,


All rights Reserved: 250004

● All the rights are reserved to the PrepInsta


Technologies and no part of the publication can Publication Team:
be stored or re-sold without the prior permission
of the publisher. PrepInsta Technologies Private Limited
3

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 23. Harshad Number 43 Chapter 24. Abundant Number 46

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

42. Check whether a character is a vowel or constant 78

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

Chapter 52. Finding Roots of a quadratic equations 91

5
6 ● Step 2. Enter the number.
● Step 3. If the number is less than or equal to zero,
check if it is zero.

Chapter 1. Positive or ● Step 4. If the number is zero, print, “, The


number is zero.”
● Step 5. If the number is less than zero, print, “The
number is negative.”
● Step 6. If the number is more than zero, print,
C++ Code : “The number is positive.”
● Step 7. Stop
Negative number
C Code :
The following concept will test whether a number is
#include<stdio.h>
positive or negative. It is done by checking where the
int main()
number lies on the number line. The following algorithm
{
will help to check this condition.
int num;
printf(“Insert a number: “);
● If the input number is greater than zero then it is a
scanf(“%d”, &num);
positive number.
//Condition to check if the number is negative or
● If the input number is less than zero it is a
positive
negative number.
if (num <= 0)
● If the number is zero then it is neither positive
{
nor negative.
if (num == 0)
printf(“The number is 0.”);
Same logic we have followed in the below C
else
program.Working printf(“The number is negative”);
}
● Step 1. Start else
printf(“The number is positive”); return 0;
return 0; }
}
#include<iostream>
using namespace std; Java Code :
int main() //Java program to check a number is positive or negative
{ import java.util.Scanner;
#ifndef ONLINE_JUDGE public class pos_or_neg
// for getting input from input.txt {
freopen(“input1.txt”, “r”, stdin); public static void main(String[] args)
// for writing output to output.txt
{
freopen(“output.txt”, “w”, stdout); //scanner class declaration
#endif
Scanner sc = new Scanner(System.in);
int no;2 //input from the user
cout<<“Enter a number:”; System.out.print("Enter a Number : ");
cin>>no;
int numb = sc.nextInt();
if(no==0) //condition for positive
{
if(numb > 0)
cout<<“0 is neither positive nor negative”;
} System.out.println("Positive");
else if(no>0)
//condition for negative
{ else if(numb < 0)
cout<<no<<“is a positive number”;
} System.out.println("Negative");
else
else
{
System.out.println("Zero");
cout<<no<<“is a negative number”;
}
7

//closing scanner class(not compulsory,


but good practice)
sc.close();
}
}
Python Code :
num = int(input("Insert a number:"))
if num > 0:
print("The number is Positive")
else:
print("The number is Negative")
Chapter 2. Even or Odd
number
We can determine whether a number is even or odd. This

can be tested using different methods. The test can be done

using simple methods such as testing the number’s

divisibility by 2. If the remainder is zero, the number is

even. If the remainder is not zero, then the number is odd.

The following algorithm describes how a C program can

test if a number is even or odd.

Example :

Number is 24

It is an even number because it is exactly divisible by 2

Number is 15

It is odd number because it is not divisible by 2


8

Working
● Step 1. Start

● Step 2. Enter a number. C Code :


#include<stdio.h>
● Step 3. If the number is divisible by 2, it is even. ●
int main()
Step 4. If the number is not divisible by 2, it is odd. {
int number;
● Step 5. Stop printf(“Insert a number \n“);
scanf(“%d”,&number);
Number");
//Checking if the number is divisible by 2 //closing scanner class(not compulsory,
if (number%2 == 0) but good practice)
printf(“The number is even\n“); sc.close();

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).

Step 3. Use formula to calculate the sum of N natural


int numb = sc.nextInt();
//condition for even number || Sum=(n*(n+1))/2.
if(numb % 2 == 0)
Step 4. Print sum of N Natural Number.
System.out.println("Even
Step 5. Stop
Number");
//condition for odd
else C Code :
#include<stdio.h>
System.out.println("Odd int main()
{
int sum = 0, n;
printf(“Enter the first N Natural Number\n“); Method 2:
scanf(“%d”,&n);
sum=(n*(n+1))/2; num = int(input("Enter the Number:"))
printf(“sum is %d”,sum); sum = (num * (num+1))/2
return 0; print("The Sum of N natural Number is {}".format(sum))
}
# This code is contributed by Shubhanshu Arya (Prepinsta
C++ Code : Placement Cell Student)
10
import java.util.*;
class prepinsta
{ Chapter 4. Sum Of N
public static void main(String[] aa){
Scanner sc=new Scanner(System.in);
int sum=0;
System.out.println(“Enter the vlue of n”); //display
int n=sc.nextInt(); Natural Numbers
for(int i=1;i<=n;i++)
In the C programming language, the user is allowed to
sum=sum+i;
insert any integer value. With the help of For loop, this C
}
program can calculate the sum of N natural numbers.
}
Within this program, the first printf statement will request
Java Code :
import java.util.*; the user to insert a number or value then the scanf
class prepinsta statement will allocate the user inserted value to integer
{
public static void main(String[] aa){ variable. The sum is calculated in the For loop.
Scanner sc=new Scanner(System.in);
int sum=0;
System.out.println(“Enter the value of n”); To perform the arithmetic operation of addition of n
int n=sc.nextInt(); numbers we use this conditions
for(int i=1;i<=n;i++) Example –
sum=sum+i; Enter Number 3
System.out.println(“Sum is ” +sum); N natural numbers 1,2,3,4,5,6,7,8…….
Where first 3 number is 1,2,3
} Then we will return sum of number = 6
} Working
● Step 1. Start
Python Code : ● Step 2. Enter a number (N).

● Step 3. Use “For loop” to iterate upto the user


Method 1:
inserted value.
num = int(input("Enter the Number:"))
value = 0 ● Step 4. The “For loop” will calculate the sum of
for i in range(1, num+1):
the user inserted value.
value = value + i
● Step 5. Stop
print("Sum of N natural numbers:", value)
{

C Code : int sum , N;


/* C Program to find Sum of N Numbers using For Loop */ cout << “Enter the limit: “;
#include<stdio.h> //user input
int main() cin >> N;
{ //calculating
//for initialize variable sum sum= N*(N+1)/2;
int Number, i, Sum = 0; cout<<“The Sum of first “<< N <<” Natural Numbers
//to take user input is “<< sum;
printf (“\n Kindly Insert an Integer Variable\n“); return 0;
scanf (“%d”, &Number); }

//use for loop for these condition Java Code :


for(i = 1; i <= Number; i++) //Java program to print the sum of n natural numbers
{
Sum = Sum + i; import java.util.Scanner;
} public class sum_of_n_natural_numbers
printf (“Sum of Natural Numbers = %d”, Sum);
{
return 0; public static void main(String[] args)
}
{

Output //scanner class declaration


Scanner sc = new Scanner(System.in);
Kindly insert an integer variable : 5
//input from user
Sum of Natural Numbers = 15
System.out.print("Enter a number : ");

C++ Code : int n = sc.nextInt();


//C++ Program //declare a variable to store sum
// Sum of n natural numbers
int sum=0;
#include<iostream>
using namespace std; //loop to add n natural numbers
int main()
11

for(int i = 1 ; i <= n ; i++)


sum=sum+i;
//display the sum
System.out.print("Sum of n natural
numbers is "+sum);
//closing scanner class(not compulsory,
but good practice)
sc.close();
Method 1:

} num = int(input("Enter the Number:"))


value = 0
}
for i in range(1, num+1):
value = value + i
Python Code :
print("Sum of N natural numbers:", value)
To use for loops start at 4 and end 8 and sum off inside the

no.in this range.


Method 2:

num = int(input("Enter the Number:")) Answer is 30(i.e 4+5+6+7+8=30).


sum = (num * (num+1))/2
print("The Sum of N natural Number is {}".format(sum))
Problem Description
# This code is contributed by Shubhanshu Arya (Prepinsta In this Program to find the sum of numbers in a given
Placement Cell Student)
range. In the C program we are using a for loop. In that
Chapter 5. Sum of numbers loop we have to start a first range given by the user and last
in a given range range also input by the user. And perform the arithmetic

operation of sum of number


The program given below accepts a range of values and

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

calculate this sum. provided numbers must be in integer format for

successful
Example:-Enter first and last range 4 and 8.
12

calculation. The following section presents an algorithm


}
work until i= secondrange.
followed by a C program to calculate this sum.
● Step 4. The loop will start with i=firstrange and

Example:-Enter first and last range 4 and 8. end with i<= lastrange.

● Step 6. In the loop for every cycle total will be


To use for loop start at 4 and end 8 and sum off inside the
incremented by i.
no.in this range.
● Step 7. Then condition false print sum of

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

System.out.print("Enter ending number


: ");
int end = sc.nextInt();
//declare a variable to store sum
int sum = 0;
//loop to add n natural numbers
for(int i = start ; i <= end ; i++)
sum=sum+i;
//display the sum num = int(input("Enter the Number:"))
System.out.print("Sum of numbers in value = 0
the range from "+start+" to "+end+" is "+sum); //closing for i in range(1, num+1):
scanner class(not compulsory, value = value + i
but good practice)
sc.close(); print("Sum of N natural numbers:", value)

} 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

the if statement. #include<iostream>


using namespace std;
Step4: If no1 is greater, then print no1 using the printf
//main program
statement, if the case is vice versa then check whether no2
int main()
is greater than no1 with the help of elseif statement. Step {
5: If no2 is greater than no1, then print no2 using printf int first,second;

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

user to insert three integer variables. And on the basis of the


System.out.println(first+" is
greater than "+second); inserted number, the program will equate and exhibit the
else if(second > first)
greatest number as an output. This program uses no1, no2 &
System.out.println(second+"
is greater than "+first); no3 as three integer variables that are represented number1,
else
System.out.println("Both number2 and number3 respectively in the program.
numbers are Equal");
//closing scanner class(not compulsory,
but good practice) Working
sc.close();
Step 1: Start

Step 2: Take three integer values from the user.


}
} Step 3: If no1 is greater than no2 and no3, printf
Python Code :
“Number1 is greatest”.
first = int(input("Enter first number:"))
second = int(input("Enter second number:")) Step 4: If no2 is greater than no1 and no3, printf
if first > second:
“Number2 is greatest”.
print("First is Greater than Second")
else: Step 5: If both the conditions are false, then printf
print("Second is Greater than First")
15 “Number3 is greatest”.
Step 6: Stop
//C++ Program
{
//Greatest of three numbers
int no1,no2,no3;
#include<iostream>
using namespace std;
//Prompt user to insert any three integer variables
//main program
printf(“\nInsert value of no1, no2 and no3:”);
int main()
scanf(“%d %d %d”, &no1, &no2, &no3);
{
int first, second, third;
//for check of number 1 is greater
cout<<“Enter first number: “;
if((no1 > no2) && (no1 > no3))
cin>>first;
printf(“\n Number1 is greatest”);
cout<<“Enter second number: “;
cin>>second;
//weather number 2 is grater
cout<<“Enter third number: “;
else if((no2 > no3) && (no2 > no1))
cin>>third;
printf(“\n Number2 is greatest”);
//comparing first with other numbers
if((first >= second) && (first >= third))
//other conditions are false than number 3 is greater
{
else
cout<<first<<” is the greatest”;
printf(“\n Number3 is greatest”);
}
return 0;
//comparing Second with other numbers
}
else if((second >= first) && (second >= third)) {
Output
cout<<second<<” is the greatest”;
}
Insert Value of No1, No2 and No3: 15, 200, 101
Number 2 is Greatest

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.

Step 5. The false display year is not a leap


}
Python code : year. Step 6. Stop.
first = int(input("Enter first number:"))
second = int(input("Enter second number:"))
third = int(input("Enter third number:")) C Code :
#include<stdio.h>
if first > second and first > third: int main()
print("First is Greater than Second and Third") {
elif second > first and second > third: //initialization of Year
print("Second is Greater than First and Third") int year;
else:
print("Third is Greater than First and Second") //to take user input
printf(“Enter Year for find leap year or not :
# This code is contributed by Shubhanshu Arya (Prepinsta “); scanf(“%d”,&year);
Placement Cell Student)
17 //we use this statement for check leap year
if(((year%4==0)&&(year%100!=0)) ||
(year%400==0)) printf(“%d is a Leap Year”,year);
Chapter 8. Leap year or not //not leap year
else
return 0;

printf(“%d is not a Leap Year”,year); }


Output
In this program we have to find whether the year is a leap
Enter Year for find leap year or not : 2012
year or not. Generally we assume that year is exactly 2012 is a leap Year
divisible by 4 is a leap year. But it is not only in this case
Enter Year for find leap year or not : 1900
1900 is divisible by 4. But it is not a leap so it that case we 1900 is not a leap Year

follows these conditions C++Code :


//C++ Program
*It is exactly divisible by 100 //Leap year or not
#include<iostream>
*If it is divisible by 100, then it should also
using namespace std;
exactly divisible by 4 //main program
int main()
*And it is divisible by 400 {
//initialising variables
int year;
These all conditions are true: a leap year is a leap cout<<“Enter year to check: “;
year. Working //user input
cin>>year;
Step 1. Initialize variable “year” to find leap //checking for leap year
if( ((year % 4 == 0) && (year % 100 != 0)) || (year
year. Step 2. Take input from User. % 400==0) )
Step 3. We use this condition {
//input is a leap year
((year%4==0)&&(year%100!=0)) || (year%400==0)) cout<<year<<” is a leap year”;
} a leap year or not
else import java.util.Scanner;
{ public class LeapYear
//input is not a leap year {
cout<<year<< ” is not a leap year”; public static void main(String[] args)
} {
return 0; //scanner class declaration
} Scanner sc=new Scanner(System.in);
//input year from user
Java Code : System.out.println("Enter a Year");
int year = sc.nextInt();
//Java program to check whether a year entered by user is
18

//condition for checking year entered


by user is a leap year or not
if((year % 4 == 0 && year % 100 != 0) || year %
400 == 0)
System.out.println(year + " is a leap year.");
else
System.out.println(year + " is
not a leap year.");
//closing scanner class(not compulsory,
but good practice)
sc.close();
}
}

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

evaluate step 5, else go to step 6. C++ Code :


Step 5. set div=div+1. //C++ Program
//Check Prime or Not
Step 6. i=i+1, go to step 4. #include<iostream>
Step 7. check div, if div==2 display prime, else display not using namespace std;
int main()
prime. {
int i,num,div=0; //initializing variables
Step 8. Stop cout<<“Enter number:”;
cin>>num; //user input
for(i=1;i<=num;i++) //checking for number of divisor {
C Code :
if(num%i==0)
#include<stdio.h> {
int main() div++;
{ }
//initializing variables }
int c,number,div=0; if(div==2) //no divisors other than 1 and itself {
cout<<num<<” is a prime number”;
//user input }
printf(“Enter number: “); else
scanf(“%d”,&number); {
cout<<num<<” is not a prime number”;
//checking for number of divisor }
for(c=1;c<=number;c++) return 0;
{ }
if(number%c==0)
{ Java Code :
div++;
} //JAVA Program to check whether the number entered by
} user is Prime or not.
//no divisors other than 1 and itself import java.util.Scanner;
if(div==2) public class prime
{ { //class declaration public static void main(String[] args)
//display { //main method declaration
printf(“%d is a prime number”,number); Scanner sc=new Scanner(System.in);
} //scanner class object creation
else
{ System.out.println("Enter a number");
20

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

prime numbers between the given range as well as similarly


PythonCode :
prints the digits coming under the prime numbers. Users are
a=0
count = 0 required to take the range as input that will be stored in the
n=int(input(“Enter the number to check if it is prime or not:
variables num1 and num2 respectively.
“))
a = n // 2;
for i in range(2,a+1): Ex:- if a user enters a range as 40-50 In that range 41,43,47
if (n % i == 0):
print(“The given number is not prime”) these three numbers are prime numbers.
count = 1
break
Working
if (count == 0):
print(“The given number is prime”) Step 1: Start
21
Chapter 10. Prime number
within a given range Step 2: The user is asked to insert a given range of numbers

A number that is divisible only by itself and 1 (e.g. 2, 3,

5, 7, 11).
//display

as an input to find the prime numbers.


The C program reduces the number of iterations within the
Step 3: Find prime numbers within the given range that
for loop. It is made to identify or calculate the prime
should be only odd values.
numbers within a given range of numbers inserted by the

user. Step 4: Check whether the odd numbers are divisible by

any of the natural numbers


Ex:- if a user enters a range as 40-50 In that range 41,43,47
Step 5: Print the calculated prime numbers. 70, 80
Prime nums are
Step 6: Stop 71
73
79
C Code :
83
#include<stdio.h> Num of primes between 70 and 85 = 4
#include<stdlib.h>
void main()
{ C++ Code :
//To initialize variables
int num1, num2, i, j, flag, temp, count = 0; //C++ Program
//for taking user input
printf(“Insert the value of num1 and num2 \n“); //Prime numbers in a given range
scanf(“%d %d”, &num1, &num2);
//check condition first range is less than 2 #include<iostream>
if (num2 < 2)
using namespace std;
{
printf(“No prime nums found up-to %d\n“, num2);
//function to chek for prime number
exit(0);
}
void prime(int num)
//to display prime numbers
printf(“Prime nums are \n“);
{
temp = num1;
//if num1 modules 2 is equal to zero
int div=0;
if( num1 % 2 == 0)
{
//checking for number of divisor
//increment on that number.
num1++;
for(int i=1;i<=num;i++)
}
//use for loop with first rang and second rang
{
for (i = num1; i <= num2; i = i + 2)
{
if(num%i==0)
flag = 0;
for (j = 2; j <= i / 2; j++)
div++;
{
if ((i % j) == 0)
}
{
flag = 1;
//no divisors other than 1 and itself
break;
}
if(div==2)
}
//check if flag equal to zero
22
if (flag == 0)
{
cout<<num<<endl;
printf(“%d\n“, i);
count++;
}
}
int count;
//display total prime number b/w lie on given range
printf(“Num of primes between %d & %d = %d\n“, temp,
}
num2, count);
}
int main()
Output
{
Insert the value of num1 and num2:
for(int j = 1 ; j <= i ; j++)
cout<<“Enter range:”;
{
int lowerLimit, upperLimit; if(i % j == 0)
count =
//user input
count+1;
cin>>lowerLimit>>upperLimit; }
if(count == 2)
cout<<“Prime numbers between “<<lowerLimit<<”
and “<<upperLimit<<” are:”<<endl;
System.out.println(i);
//finding prime numbers in the given range }
//closing scanner class(not mandatory
for(int i=lowerLimit;i<=upperLimit;i++)
but good practice)

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

Given number: 16789


2+3+1+4+5+6=21
Sum of the numbers: 31
sum of digit of a given number is 21
C++ code :

//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.

Step 6: Printf the output or sum

Step 7: Stop sum+=num%10;


/* C program to take a number & calculate the sum of its num=num/10;
}while(num!=0);
numbers */
//output
#include<stdio.h> cout<<“\nSum of digits in given integer is:
“<<sum; return 0;
int main() }

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

zero. Step 6.When it becomes zero, print the output and


num = [int(d) for d in input("Enter the
Number:")] sum = 0 exit Step 7. Stop.
for i in range(0, len(num)):
sum = sum + num[i]

print("Sum of Digits of a Number: {}".format(sum)) C code :

# This code is contributed by Shubhanshu Arya


(Prepinsta Placement Cell Student)
#include<stdio.h>
24
int main()
{
//Initialization of variables where
Chapter 12. Reverse of a rev='reverse=0' int number, rev = 0,store, left;

number //input a numbers for user


printf("Enter the number\n");
In this program reverses a number entered by a user and scanf("%d", &number);

then prints it. For example, if a user will enter 6577756


store= number;
as input then 6577756 will be printed as output.
//use this loop for check true condition
while (number > 0)
This C program accepts an integer and reverses it.
25

{
{
//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);

//number /= 10; //after reverse show numbers


printf("Its reverse is = %d\n", rev); Integer.toString(pick_last);
number = number / 10;
return 0; }
} //display the reversed number
Output:- System.out.print(s);
Enter the number 123456 //closing scanner class(not compulsory,
but good practice)
Given number = 123456 sc.close();
Its reverse is =654321

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

variable (n1). Number 121121 is Palindrome number.

Step 3.Obtain its quotient and remainder. C++ Code


//C++ Program
Step 4.Multiply the separate variable with 10 and add the
//Palindrome or not
obtained remainder to it. #include <iostream>
using namespace std;
Step 5.Do step 2 again for the quotient and step 3 for the //main Program
int main()
remainder obtained in step 4.
{
Step 6.Then we check if reverse is equal to a number. int num, digit, reverse = 0;
cout << “Enter a positive integer: “;
Step 7.Its true display number is palindrome //user input
cin >> num;
Step 8.It is false display number is not a palindrome.
int temp = num;
Step 9.stop. //loop to find reverse
do
C Code {
digit = num % 10;
reverse = (reverse * 10) + digit;
#include<stdio.h> num = num / 10;
int main() 27
{
//Initialization of variables where rev='reverse=0'
int number, rev = 0,store, n1,left; } while (num != 0);
printf("Enter the number\n");
scanf("%d", &number);

//for duplicacy of number number = int(input("Enter the Number:"))


n1=number; cout << “The reverse of “<< temp <<” is “<< reverse
<< endl;
store= number; //checking for palindrome
//use this loop for check true condition if (temp == reverse)
while (number > 0) cout << “The number is a palindrome.”;
{ else
//left is for remider are left cout << “The number is not a palindrome.”;
left= number%10; return 0;
}
//for reverse of no.
rev = rev * 10 + left; Java Code
//Java program to check whether a string entered by user is
//number /= 10; palindrome or not.
number=number/10; import java.util.Scanner;
} public class palindrome_or_not
//To check reverse no is a Palindrome {
if(n1==rev) public static void main(String[] args)
printf("Number %d is Palindrome number",n1); {
//scanner class declaration
Scanner sc = new Scanner(System.in);
//input from user
System.out.print("Enter a String : "); Step 14.For find number is armstrong.

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.

Step 4.We use while loop with condition(n!=0). Step 5.Than


}
} check the last digit of a number with condition is

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.

if temp == reverse: Step 8.repeat steps 4 to 6 until number (n)!=0. Step


print("Given number {} is Palindrome".format(temp)) 9.Again we use the while loop with condition
else:
print("Given number {} is not (num!=0) for check
Palindrome".format(temp))
Step 10.the number is Armstrong or not.
# This code is contributed by Shubhanshu Arya (Prepinsta Step 11.Again check last digit for duplicity of number with
Placement Cell Student
28 condition is reminder(r1)=number(num)%10. Step 12.Than

we use for loop statement with condition is (i=1;i<=c).

Chapter 14. Armstrong Step 13.Use this code mul=mul*r1, sum=sum+mul,

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

Step 6: The result should be equal to the result plus the


Python Code
import math power (remainder n).
value = int(input("Enter the Number: "))
Step 7: temp = temp/10
num = [int(d) for d in str(value)]
sum = 0 Step 8: If the value of the result is equals to the value of
for i in range(0, len(num)):
sum = sum + math.pow(num[i], len(num)) number then print the number

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()

Chapter 15. Armstrong {


//For initializing variables
int start, end, i, temp1, temp2, rem, n = 0, result = 0;
//user give start and end point of a number
printf("Insert the start value and end value :");
scanf("%d %d", &start, &end); //to display pint of range
printf("\n Armstrong nums between %d an %d are: ",
number in a given range To start, end);

//for use this loop to store all number in given range


identify the Armstrong number between two intervals in C for(i = start + 1; i < end; ++i)
programming, the user is required to insert integer numbers. {
//store a duplicity value of given range
A n digit number is known as an Armstrong number, when
temp2 = i;
the sum of the values of the digits raised to nth power is temp1 = i;

equal to the number itself. For example: 153 =


while (temp1 != 0)
13+53+33=153 {
//temp1 /= 10;
Ex:- basically we know that Armstrong numbers in the given temp1=temp1/10;
range 0 to 999 are 1 2 3 4 5 6 7 8 9 153 370 371 407. ++n;
}
while (temp2 != 0)
{
rem = temp2 % 10; }
//result += pow(rem, n);
result=result+pow(rem,n); Java Code
//temp2 /= 10; //Java program to print armstrong numbers between
temp2=temp2/10; two intervals
} import java.util.Scanner;
//check true condition if result is equal to i public class
if (result == i) armstrong_numbers_between_two_intervals {
{ public static void main(String[] args)
//display {
printf("%d ", i); //scanner class declaration
} Scanner sc = new Scanner(System.in);
n = 0; //input from user
result = 0; System.out.print("Enter Starting
} Number : ");
printf("\n"); int start = sc.nextInt();
return 0; System.out.print("Enter Ending
} Number : ");
Output: int end = sc.nextInt();
Insert the start value and end value: 100, 500 Armstrong System.out.println("Armstrong
numbers between 100 and 500 are: 370, 371, 407. numbers between "+start+" and "+end+" are :
"); int n, sum;
C ++ Code //loop for finding and printing all prime
//C++ Program numbers between given range
//Armstrong number in a interval for(int i = start ; i <= end ; i++)
#include<iostream> {
#include<math.h> n = i;
using namespace std; sum = 0;
void armstrong(int num) //logic for checking number
{ is armstrong or not
int sum=0; while(n != 0)
int store = num; {
31

//find sum of cubes of individual digits int pick_last = n %


do 10;
{ sum = sum +
int digit = num % 10; (pick_last * pick_last * pick_last);
sum = sum + pow(digit,3); n = n / 10;
num = num / 10; }
}while(num > 0); if(sum == i)
//checking for ArmStrong number
if(sum == store) System.out.println(i);
cout << store <<“\t“; }
} //closing scanner class(not compulsory,
int main() but good practice)
{ sc.close();
int l_limit,u_limit;
cout<<“Enter the range:\n“;
cin>>l_limit>>u_limit; }
cout<<“Armstrong numbers between }
“<<l_limit<<” and “<<u_limit<<” are:\n“;
for(int i=l_limit;i<=u_limit;i++) Python code
armstrong(i); import math
return 0;
first = int(input("Enter first number:")) Step 6.Than display N3 as output and close the loop
second = int(input("Enter second number:"))
Step 7.Stop

def is_Armstrong(val: int) -> bool:


sum = 0
arr = [int(d) for d in str(val)] C Code
for i in range(0, len(arr)): #include<stdio.h>
sum = sum + math.pow(arr[i], len(arr)) int main()
if sum == val: {
print("{} number is Armstrong".format(val)) //To initialize variables
else: int n1=0,n2=1,n3,limit,i;
print("{} number is not Armstrong".format(val))
//To take user input
for i in range(first, second + 1): printf("enter a limit of series \n");
is_Armstrong(i) scanf( "%d",&limit);

# This code is contributed by Shubhanshu Arya printf("Fibonacci series %d %d ",n1,n2);


(Prepinsta Placement Cell Student)
32 //To use this loop for given length
for(i=2;i<limit;i++)
{
//n1 and n2 sum store in new variable n3
Chapter 16. Fibonacci n3=n1+n2;
n1=n2;
n2=n3;
printf("%d ",n3);
//display serious }
return 0;
}
Series upto nth term Output:-
enter a limit of series
The sequence is a Fibonacci series where the next number

is the sum of the previous two numbers. The first two terms 10

of the Fibonacci sequence start from 0,1,… Fibonacci series 0 1 1 2 3 5 8 13 21 34

Example: limit is Fibonacci series 8


C++ Code
Sequence is 0,1,1,2,3,5,8,13 //C++ Program
//Fibonacci Series upto n numbers
It's followed by an additional operation. Next number is the #include<iostream>
addition of before the first two numbers. using namespace std;
//main program
int main()
{
Working // initialising variables
int limit, first=0, second=1, next, num;
Step 1.Initialize variables limit, N1=0, N2=1, N3, i.
cout <<“Enter the limit of Fibonacci series”<<endl;
Step 2.To take user input for limit of seriousness. // user input
cin >> num;
Step 3.Display N1, N2 value . cout << “First “<<num<<” terms of Fibonacci series are
:- “<<endl;
Step 4.We use a loop with the condition(i=0;i<limit).
//loop for printing fibonacci series
Step 5.Compute N3 = N1 + N2 and n1=n2. && n2=n3. for(int p=0;p<num;p++)
{
if (p <= 1) sc.close();
next = p;
else
{ }
next = first + second; }
first = second;
second = next; Python Code
} # Method 1
cout<<next<<” “;
} def fibonacciSeries(i):
return 0; if i <= 1:
} return i
else:
Java Code return (fibonacciSeries(i - 1) + fibonacciSeries(i - 2))
//Java program to print fibonacci series up to n
import java.util.Scanner;
public class fibonacci if num <= 0:
{ print("Please enter a Positive Number")
public static void main(String[] args) else:
{ print("Fibonacci Series:", end=" ")
//scanner class declaration for i in range(num):
Scanner sc = new Scanner(System.in); print(fibonacciSeries(i), end=" ")
//input from user 33

# This code is contributed by Shubhanshu Arya


System.out.print("Enter the limit : "); (Prepinsta Placement Cell Student)
# Method 2
int lim = sc.nextInt();
if(lim > 0) num = int(input("Enter the Number:"))
{ n1, n2 = 0, 1
int y = 0, z = 1, s; print("Fibonacci Series:", n1, n2, end=",")
//display starting two for i in range(2, num):
numbers of series n3 = n1 + n2
System.out.print("Fibonacci n1 = n2
Series : "+y+" "+z+" "); n2 = n3
//perform iterations till the print(n3, end=" ")
limit entered by the user
while(z <= lim) print()
{
s=y+z; # This code is contributed by Shubhanshu Arya
y=z; (Prepinsta Placement Cell Student)
z=s; 34
//condition for
forcing z that it should not be printed when its value
is greater than limit
if(z <= lim) Chapter 17. Factorial of a
System.out.print(z+" ");
}
} printf("Factorial of a number %d is = %d\n", number,
else

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

numbers. Factorial of a number 4 is 24

Ex:- No is 5. C++ Code


5x4x3x2x1=120 //C++ Program
//Factorial of a number
Factorial of a 5=120 #include<iostream>
using namespace std;
Note:-Factorial of n number is 1*2*3*…n. You will
//main program
learn to calculate the factorial of a number using for int main()
{
loop in this example. //initializing variables
int fact=1,num;
Working
cout<<“Enter the number: “;
//user input
Step 1.Read the number n cin>>num;
//checking for negative input
Step 2.Initialize the variable i, fact=1,n if(num<0)
cout<<“Invalid input!!\nEnter whole numbers
Step 3.To take a user input for factorial of number Step
only”;
4.We use for loop with the condition(i=1;i<=number) Step // for positive numbers
else
5.Than do fact=fact*i {
for(int i=num;i>0;i–)
Step 6.Print the variable of fact.
{
Step 7.Stop fact*=i;
}
C Code cout<<“Factorial of “<<num<<” is “<<fact;
}
return 0;
#include <stdio.h> }
int main()
{
Java Code
//initialize of variable
//Java program to find factors of a number
int i, number, fact = 1;
import java.util.Scanner;
public class factors_of_a_number
//to take user input.
{
printf("Enter a number to calculate its factorial\n");
public static void main(String[] args)
scanf("%d", &number);
{
//scanner class declaration
//use this loop of following statement
Scanner sc = new Scanner(System.in);
for (i = 1; i<= number;i++)
//input from user
fact = fact * i;
System.out.print("Enter a number : ");
//display of factorial of a given number
int number = sc.nextInt();
fact);
System.out.println("Factors of
return 0; "+number+" are :");
}
35

//loop for finding factors of a number


for(int i = 1 ; i <= number ; i++)
{
if(number % i == 0)
//printing factors

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

print("Factorial of a Given Number:", factorial)

Chapter 18. Power of a


number
In this program we will calculate the power of a number

using C programming. We want to calculate the power of

any given number so you need to multiply that particular

number power of time.

Ex:-|

1. Let's suppose the number is 24 so we need to multiply

with 4 times 2. That is 2*2*2*2=16.

2. Number is 53 so we need to multiply with 3 times 5.

That is 5*5*5=125

Working:

Step 1– Enter the base number, the number in which you

just want to find the power of the number.

Step 2– Enter the exponential, the power of the number.

Step 3– Initialize while loop, while the exponential is not

equal to zero.
36

(i) do temp*number and store it in the temp. //user input 2


//calculating power using function
(ii) now reduce the exponential with -1. double res = pow(base, exp);
//printing result
Here you got the power of the number. cout << base << “^” << exp << ” = “ ;
cout << fixed <<setprecision(2)<<res<<endl;
Step 4– Now print the temp variable.| return 0;
}
Step 5- Stop.

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=" ")

# This code is contributed by Shubhanshu Arya (Prepinsta


Placement Cell Student)

Chapter 20. Strong number


In this program we will find a strong number of not using C

programming. Where the number should be entered by a

user. We will use the While Loop ,for loop and else if

statement in this program. In that program we use a user

defined function for finding the factorial of number t +

5!=1 + 24 +120=145

what will be used to find strong numbers?

Basically A strong number is a number whose sum of


factorials of digits is equal to the same number.Ex:- number

is 145
39 int main()
{
//to initialize variables
1! + 4! int number,digit,sum=0,temp;

//To take user input


printf("Enter a number:");
scanf("%d",&number); //To store a duplicity value of a given number
temp=number;
So it is a strong number.
//use this whenever number is not equal to 0
while(temp!=0)
Working: {
//for last digit
digit=temp%10;
Step 1- First we enter the number.
//now we call of factorial function
Step 2- copy the number into any temporary variable. Step 3- digit = factorial(digit);
//to improve of a sum on digit
until temp is not equal to 0, calculate the following statement sum=sum+digit;
temp=temp/10;
(i)digit=temp%10
}
(ii)now we find the factorial of a digit. //we check sum is equal to number its true
if(sum==number)
(iii)sum=sum+digit, add digit into a sum and store it in the {
sum. //display
printf("It is a Strong Number");
(iv)temp=temp/10.divid the temp with 10 }
//false condition
When temp became zero the above step stop to execute, Step 4- else
{
if the sum of these factorial numbers is equal to the entered
//display
number,so it is the strong number. printf("It is not Strong Number");
}
Step 5- Stop. return 0;
}
Output:-
C Code Enter a number: 145
#include<stdio.h>
It is a Strong Number
//find factorial of a number.
int factorial(int number)
{ Enter a number: 123
//to initialize of factorial
int i,fact=1; It is not Strong Number
//use for loop with this condition
for(i=1;i<=number;i++)
C ++ Code
{
//C++ program
//fact*=1;
//Strong Number or not
fact=fact*i;
#include<iostream>
}
using namespace std;
return fact;
//main Program
}
int main()
//to main function
{
int ip,sum=0; {
cout<<“Enter number to check: “; fac = 1;
//user input int r = n % 10;
cin>>ip; //calculating factorial of r
int save=ip; for(int i = r ; i >= 1 ; i--)
//logic to check for Strong Number starts fac = fac * i;
while(ip) //storing sum of factorial of
all digits of the number
sum = sum + fac;
n=n/10;
{ }
int num=ip%10; //condition for strong number
int fact = 1; if(sum == number)
//finding factorial of each digit of input 40
for(int i=num;i>0;i–)
{
fact=fact*i; System.out.println("Strong
} Number");//display the result
sum+=fact; else
ip/=10; System.out.println("Not a
} Strong Number");
//checking for Strong Nunber //closing scanner class(not compulsory,
if(sum==save) but good practice)
{ sc.close();
cout<<save<<” is a Strong Number”;
}
else }
{ }
cout<<save<<” is not a Strong Number”;
} Python Code
//logic ends #Enter the number to check
return 0; print(‘Enter the number:’)
} n=int(input())
#save the number in another variable
Java Code temp=n
//Java program to check whether a number is a strong sum=0
number or not #Implementation
import java.util.Scanner; while(temp):
public class strong_number_or_not r=temp%10 # r will have the value of the unit place
{ digit temp=temp//10
public static void main(String[] args) fac=1
{ for i in range(1,r+1): #finding factorial
//scanner class declaration fac=fac*i
Scanner sc = new Scanner(System.in);
//input from user sum+=fac #adding all the factorial
System.out.print("Enter a number : ");
if(sum==n):
int number = sc.nextInt(); print(‘Yes’, n ,‘is strong number’)
int fac,sum = 0;
int n = number; else:
while(n != 0) print(‘No’ , n, ‘is not a strong number’)
41

Chapter 21. Perfect number


{
// Initialization of variables

In this program we will find the number is a perfect number


// To take user input
or not using C programming. so we will use the while loop printf("Enter a number: ");
scanf("%d",&number);
and if else statement. Basically perfect number is a positive
while(i<number)
number which is equal to the sum of all its divisors
{
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 total=total+i;
i++;
it means the number is Perfect Number. Else sum is not
}
equal to number it means number is not a perfect number. }
//to condition is true
if(total==number)
Ex:- Enter any number 6 //display
printf("%d is a perfect number",number);
6 is a perfect number as 1 + 2 + 3 = 6.
//to condition is false
Number is 15 else
//display
15 is not a perfect number because 1+3+5=9 printf("%d is not a perfect number",number);

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

} (i) Calculate the remainder of the temp,divided with


}
Python Code the 10 and store in digit
n = int(input(“Enter any number: “)) (ii) divide the number with the 10 and store in the
sump= 0
for i in range(1, n): number. Step 5- find modules of square with count and
if(n % i == 0):
compare with temp //C++ Program
//Automorphic number or not #include<iostream>
Step 6-if it is true display Automorphic or else not a
using namespace std;
43 //main program
{
int num,flag=0;
Automorphic number cout<<“Enter a positive number to check: “; //user input
cin>>num;
int sq= num*num;
int store=num;
int main()
//check for automorphic number
Step 7- Stop. while(num>0)
{
if(num%10!=sq%10)
{
C Code flag=1;
#include<stdio.h> break;
}
int checkAutomorphic(int num) { num=num/10;
int square = num * num; sq=sq/10;
}
while (num > 0) if(flag==1)
{ cout<<store<<” is not an Automorphic number.”; else
if (num % 10 != square % 10) return 0; cout<<store<<” is an Automorphic number.”; return 0;
}
// Reduce N and square
num = num / 10; JavaCode
square = square / 10; //Java program to check whether a number is Automorphic
} number or not
return 1; import java.util.Scanner;
} public class automorphic_number_or_not
{
int main() public static void main(String[] args)
{ {
//enter value //scanner class declaration
int num; Scanner sc = new Scanner(System.in);
scanf("%d",&num); //input from user
System.out.print("Enter a number : ");
//checking condition
if(checkAutomorphic(num)) printf("Automorphic"); int number = sc.nextInt();
else //Convert the number to string
printf("Not Automorphic"); return 0; String s1 = Integer.toString(number);
} //Calculate the length
Output:- int l1 = s1.length();
6 int sq = number * number;
Automorphic String s2 = Integer.toString(sq);
int l2 = s2.length();
12 //Create Substring
Not Automorphic String s3 = s2.substring(l2-l1);
if(s1.equals(s3))
376
Not Automorphic System.out.println("Automorphic Number"); else

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”)

Chapter 23. Harshad int n = num;


number #include<stdio.h>
int main()
In this program we will discuss if the number is harshad {
//To initialize of variable
number or not in C programming. In mathematics, a int number,temp,sum = 0, digit, res;
Harshad number is a number that is divisible by the sum of
//To take user input
its digits. We use a while loop statement with the following printf("enter any number : ");
scanf("%d",&number);
condition. Input consists of 1 integer.
else
//store in temporary variable cout<<n<<” is not a harshad number”;
temp = number; return 0;
//use while loop with this condition }
while(temp!=0)
{ Java Code
//to find last digit //Java program to check whether a number is harshad
digit=temp % 10; number or not
//sum+=digit import java.util.Scanner;
sum = sum + digit; public class harshad_number_or_not
//temp/=10 {
temp = temp / 10; public static void main(String[] args)
} {
res = number % sum; //scanner class declaration
//check result is equal is to 0 Scanner sc = new Scanner(System.in);
if(res == 0) //input from user
//display System.out.print("Enter a number : ");
printf("%d is Harshad Number",number);
else int number = sc.nextInt();
//display //make a copy of original number
printf("%d is not Harshad Number",number); int n = number;
return 0; //declare a variable to store sum of
} digits
int result = 0;
//perform logic for calculating sum of
Output:- digits of a number
enter any number : 21 while(n != 0)
21 is Harshad Number {
int pick_last = n % 10;
enter any number : 15 result = result + pick_last;
15 is not Harshad Number n = n / 10;
}
C++ Code /*use condition to check whether the
//C++ Program number entered by
//Harshad number or not user is completely divisible by its sum
#include <iostream> of digits or not*/
using namespace std;
//main program if(number % result == 0)
int main() System.out.println("Harshad
{ Number");
int num,sum = 0; else
cout<<“Enter number: “; System.out.println("Not a
//user input Harshad Number");
cin>>num; 46
//loop to calculate the sum of digits
while(num > 0)
{ //closing scanner class(not compulsory,
int rem = num%10; but good practice)
sum = sum + rem; sc.close();
num = num/10;
}
//checking for harshad number
if(n % sum == 0) sum1=sum(l)
cout<<n<<” is a harshad number”;
if(p%sum1==0):

} print(“Harshad number”)
}
Output :
Enter a number : 18
else:
Harshad Number

Enter a number : 345


print(“Not harshad number”)
Not a Harshad Number
List of Top 100 Cod

Optimal solution:
Python Code

General Solution:
n=int(input(“Enter any number”))

n=int(input(“Enter any number”))


p=n

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:

print(“Not harshad number”)

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

not. A number n is said to be Abundant Number to follow

these condition //input from user

● the sum of its proper divisors is greater than the


number itself. printf("Enter a number : ");
● And the difference between these two values is
called the abundance.

Ex:- Abundant number 12 having a proper divisor is scanf("%d",&number);

1,2,3,4,6 the sum of these factors is 16 it is greater than 12

so it is an Abundant number.
//declare a variable to store sum of factors of the number

Some other abundant numbers

for(c = 1 ; c < number ; c++)


18, 20, 24, 30, 36, 66, 70, 72, 78, 80, 84, 88, 90, 96, 100,

102, 104, 108, 112, 114, 120..

Working

Step 1- Enter the number, to find the Abundant number. if(number % c == 0)


//sum+=c;
Step 2- Initialize the loop with c=1 to c<=number and sum = sum + c;
}
follow the following calculation
if(sum > number)
(i) check if the number is divisible with c and c got a //display the result
printf("Abundant Number");
result zero. else
//display
(ii) now sum=sum+c, add digit into a sum and store it in
printf("Not an Abundant Number");
the sum.
return 0;
Step 3. than check sum is greater than number print true. }

Step 4. else it is not a abundant number


C++ Code
Step 5- Stop. //C++ Program
//Abundant Number or not
48
C Code

#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

Step 4. Check if both P and Q are completely divided by


}
the same loop, if it does, store the number.
Step 5. Print the stored number as HCF.
Step 6. Stop
C Code :
#include <stdio.h>
int main()
{ if(first == second)
//for initialize variables {
int a, b, i, hcf; return first;
a = 12; }
b = 16; // first is greater
//find hcf of number else if(first > second)
for(i = 1; i <= a || i <= b; i++) {
{ return findGCD(first – second, second);
if( a%i == 0 && b%i == 0 ) }
hcf = i; return findGCD(first, second – first);
} }
//display hcf
printf("HCF = %d", hcf);
return 0; Java Code :
} //Java program to find GCD or HCF of two numbers
import java.util.Scanner;
public class gcd_or_hcf
{
C++ Code :
public static void main(String[] args)
//C++ Program {
//GCD of Two Numbers //scanner class declaration
#include<iostream> Scanner sc = new Scanner(System.in);
using namespace std; //input from the user
// Recursive function declaration System.out.print("Enter the first
int findGCD(int, int); number : ");
// main program int num1 = sc.nextInt();
int main() //input from the user
{ System.out.print("Enter the second number : ");
int first, second; int num2 = sc.nextInt();
cout<<“Enter First Number: “; int n = 1;
cin>>first; System.out.print("HCF of "+num1+" and "+num2+" is ");
cout<<“Enter second Number: “; if( num1 != num2)
cin>>second; {
cout<<“GCD of “<<first<<” and “<<second<<” is while(n != 0)
“<<findGCD(first,second); {
return 0; //storing remainder
} n = num1 % num2;
//body of the function
int findGCD(int first, int second) if(n != 0)
{ {
// 0 is divisible by every number num1 = num2;
if(first == 0) num2 = n;
{ }
return second; }
if(second == 0) //result
{ System.out.println(num2);
return first;
} }
// both numbers are equal
53

else
System.out.println("Wrong Input");
//closing scanner class(not compulsory,
but good practice)
sc.close();

}
}

Python Code :

num1 = int(input("Enter first number:"))


num2 = int(input("Enter Second Number:"))
arr = []
if num1 > num2:
smaller = num2
else:
smaller = num1
for i in range(1,smaller+1):
if (num1 % i == 0) and (num2 % i == 0):
arr.append(i)
print("The HCF of given numbers: {}".format(max(arr)))

Chapter 27. Lowest


Common Multiple (LCM) :
The Least Common Multiple (LCM) is also referred to as
the Lowest Common Multiple (LCM) and Least Common
Denominator (LCD). The least common multiple, or LCM,
is another number that’s useful in solving many math
problems. Let’s find the LCM of 12 and 44. One way to
find the least common multiple of two numbers is to first
list the prime factors of each number.

12 = 2 × 2 × 3

44 = 2 × 2 × 11

A C program can calculate the Lowest Common Multiple


(LCM) of two numbers. The method includes finding out
the maximum values among two numbers, which are
common in both the numbers. The algorithm below will
help to calculate the LCM of two numbers.

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

● In while loop there are two condition If //LCM of two numbers


check1<check2
● it is true use this condition check1=check1+n1; .
● Otherwise
● check2=check2+n2; . int findLCM(int,int);
● Print the value of check1 or check2. //main program
int main()
{
int first,second;
cout<<“Enter first number : “;
C Code : cin>>first;
#include<stdio.h> cout<<“Enter second number : “;
cin>>second;
void lcm_two_no(int,int); //calling function to find lcm
int main() cout<<findLCM(first,second)<<” is the LCM
{ of two numbers.”;
int n1,n2; return 0;
}
//to take user input n1,n2 //function to find lcm
printf("Enter two numbers: "); int findLCM(int first, int second)
scanf("%d %d",&n1,&n2); {
static int fact = first;
//call of user define function // if true then fact is the lcm
lcm_two_no(n1,n2); if(fact % first == 0 && fact % second == 0)
return 0; {
} return fact;
}
//function to calculate l.c.m //if false call function again
void lcm_two_no(int n1,int n2) else
{ {
int check1,check2; fact=fact + first;
//to use of duplicity value findLCM(first,second);
check1=n1; }
check2=n2; return fact;
}
//to find lcm of number
while(check1!=check2)
Java Code :
{
//for condition true //Java program to find LCM of two
if(check1< check2 numbers import java.util.Scanner;
check1=check1+n1; public class lcm
{
//for condition false public static void main(String[] args)
else {
check2=check2+n2; //scanner class declaration
} Scanner sc = new Scanner(System.in);
printf("\nL.C.M of %d and %d is: //input from the user
System.out.print("Enter the first
%d",n1,n2,check1); } number : ");
int num1 = sc.nextInt();
//input from the user
System.out.print("Enter the second
C++ Code : number : ");
//C++ program int num2 = sc.nextInt();
#include<iostream> //logic for finding lcm of both numbers
using namespace std;
55

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:"))

def lcmFinder(num1, num2):


if num1 > num2:
larger = num1
else:
larger = num2
while True:
if (larger % num1 == 0) and (larger % num2 == 0):
lcm = larger
break numbers. It is possible to calculate this number through
larger = larger + 1 simple mathematical calculations. The following algorithm
print("LCM of two given number:{}".format(lcm)) shows how the GCD of two numbers is calculated.

Ex:-
lcmFinder(num1, num2)
the H.C.F or G.C.D of 12 and 14 is 2.

The H.C.F or G.C.D of 16 and 12 is 4


Chapter 28. Greatest
Common Divisor : Working:-
Step 1. Start
The Highest Common Multiple or the Greatest Common
Divisor is the greatest number that exactly divides both
56

Step 2. Enter two numbers a and b.


{
Step 3. If a = 0, return b. Step 7. Else return a, b-a
Step 4. If b = 0, return a. Step 8. Stop
Step 5. If a is equal to b return a
Step 6. If a is greater than b, return a – b, and b
C Code :
cout<<“GCD of “<<first<<” and “<<second<<” is
// C program to calculate GCD of two numbers
“<<findGCD(first,second);
#include<stdio.h>
return 0;
// The code used a recursive function to return gcd of p and
}
q
//body of the function
int gcd(int p, int q)
int findGCD(int first, int second)
{
{
// 0 is divisible by every number
// checking divisibility by 0
if(first == 0)
if (p == 0)
{
return q;
return second;
}
if (q == 0)
if(second == 0)
return p;
{
return first;
// base case
}
if (p == q)
// both numbers are equal
return p;
if(first == second)
{
// p is greater
return first;
if (p > q)
}
return gcd(p-q, q);
// first is greater
else if(first > second)
else
{
return gcd(p, q-p);
return findGCD(first – second, second);
}
}
return findGCD(first, second – first);
// Driver program to test above function
}
int main()
{
int p = 98, q = 56;
printf("GCD of %d and %d is %d ", p, q, gcd(p, q)); Java Code :
return 0;
//Java program to find GCD or HCF of two numbers
}
import java.util.Scanner;
public class gcd_or_hcf
C++ Code : {
public static void main(String[] args)
//C++ Program
{
//GCD of Two Numbers //scanner class declaration
#include<iostream>
Scanner sc = new Scanner(System.in);
using namespace std; //input from the user
// Recursive function declaration
System.out.print("Enter the first
int findGCD(int, int); number : ");
// main program
int num1 = sc.nextInt();
int main()
//input from the user
int first, second;
System.out.print("Enter the second
cout<<“Enter First Number: “;
number : ");
cin>>first;
int num2 = sc.nextInt();
cout<<“Enter second Number: “;
cin>>second;
57

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

} Step 6: Repeat the above steps with the quotient obtained


} until the quotient becomes 0

Step 7: The sum of the numbers will give the


decimal number as a result, print the decimal val.
Python Code :
num1 = int(input("Enter First Number:")) Step 8: Stop
num2 = int(input("Enter Second Number:"))
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 */

gcdFunction(num1, num2) binary_val = num;


while (num > 0)
{
Decimal to conversion : rem = num % 10;
decimal_val = decimal_val + rem * base;
The C program converts binary numbers to decimal
58

//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

Java Code : printf("Equivalent octal value: %ld", octal_num);


//Java program to convert Binary number to decimal
number conversion :
import java.util.Scanner;
public class Binary_To_Decimal Binary to octal conversion can be easily done with the help
public static void main(String args[]) of simple calculations. The following section includes a
{ stepwise procedure for such a conversion. In this process, a
Scanner sc = new Scanner(System.in); binary number is inputted by a user and is later converted to
System.out.print("Enter a binary an octal number.
number : ");
int binary = sc.nextInt(); Working:
//Declaring variable to store decimal Step 1. Start
Step 2. Input a binary number {
Step 3. Divide the number into groups of three bits. Step 4. rem = binary % 10;
Multiply each bit from this group with the power of 2 and int res = rem * pow(2,i);
add them consecutively. decimal += res;
Step 5. Combine the results from all groups to generate the i++;
output. binary/=10;
Step 6. Print the octal number. }
Step 7. Stop i = 1;
//converting decimal to octal
while (decimal != 0)
{
C Code : rem = decimal % 8;
/** C Program to Convert Binary to Octal*/ octal += rem * i;
decimal /= 8;
#include<stdio.h> i *= 10;
}
int main() return octal;
}
{ //main program
//For initialize variables int main()
long int binary_num, octal_num = 0, j = 1, rem; {
long binary;
//Inserting the binary number from the user cout << “Enter a binary number: “;
//user input
cin >> binary;
printf("Enter a binary number: ");
//calling function
scanf("%ld", &binary_num);
int octal=convert(binary);
//printing output
// while loop for number conversion
cout << binary << ” in binary = “ << octal << ” in
octal “;
while(binary_num != 0)
return 0;
{
}
rem = binary_num % 10;
60
octal_num = octal_num + rem * j;
//j*=2
j = j * 2;
Java Code :
//binary_num/10;
binary_num = binary_num / 10;

#convert using oct() function


}
return 0; //Java program to convert binary number to octal number
} import java.util.Scanner;
public class Binary_To_Octal
C++ Code : {
public static void main(String args[])
//C++ Program {
//binary to octal conversion //scanner class object creation
#include <iostream> Scanner sc = new Scanner(System.in);
#include <math.h> //input from user
using namespace std; System.out.print("Enter a binary
//Function to convert binary to octal number : ");
int convert(long binary) int binary = sc.nextInt();
{ //Declaring variable to store decimal
int octal = 0, decimal = 0, i = 0,rem; number
//converting binary to decimal int decimal = 0;
while(binary != 0)
//Declaring variable to use in power decimal = decimal / 8;
}
int n = 0; //printing result
//writing logic for the conversion from System.out.print("Octal number : ");
binary to decimal for(int j = i-1 ; j >= 0 ; j--)
while(binary > 0) System.out.print(octal[j]);
{ //closing scanner class(not compulsory,
int temp = binary%10; but good practice)
decimal += sc.close();
temp*Math.pow(2, n); }
binary = binary/10; }
n++;
}
int octal[] = new int[20]; Python Code :
int i = 0; #take binary number
//writing logic for the conversion from Bin_num = 0b10111
decimal to octal Oct_num = oct(Bin_num)
while(decimal > 0) #print number
{ print('Number after conversion is :' + str(Oct_num))
int r = decimal % 8;
octal[i++] = r;
61

Chapter 31. Decimal to


{
count++;

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.

Ex:- (180)10=(11101000)2 #include<stdio.h>


int main()
Working: {
Step 1: Start //for initialize a variables
Step 2: Ask the user to insert an integer number in long number, dec_num, rem, base = 1, bin = 0, count =
decimal as an input 0;
Step 3: Check whether the entered number is less than //To insert a number
or equal to 0 printf("Insert a decimal num \n");
Step 4: Check the divisibility of the number by 2 and store scanf("%ld", &number);
the remainder in the range dec_num = number;
Step 5: Increase the range by 1 while(number > 0)
Step 6: After calculating, print the binary number and {
the number of 1s. rem = number % 2;
Step 7: Stop /* To count no.of 1s */
if (rem == 1)
}
int i = 1;
bin = bin + rem * base; //converting decimal to binary
//number/=2; while (n!=0)
number = number / 2; {
base = base * 10; int rem = n%2;
} n /= 2;
//display binary += rem*i;
printf("Input num is = %d\n", dec_num); i *= 10;
printf("Its binary equivalent is = %ld\n", bin); }
printf("Num of 1's in the binary num is = %d\n", count); return binary;
return 0; }
} //main program
int main()
{
int decimal;
C++ Code : long binary;
//C++ Program cout << “Enter a decimal number: “;
//Decimal to binary conversion //user input
#include <iostream> cin >> decimal;
#include <math.h> //calling function
using namespace std; binary = convert(decimal);
//function to convert decimal to binary cout << decimal << ” in decimal = “ << binary << ” in
long convert(int n) binary” << endl ;
{ return 0;
long binary = 0; }
62

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.

Ex:- If a Decimal number is an octal number we use this C++ Code :


method //C++ Program
(143)10=(217)8 //decimal to octal conversion
#include <iostream>
Working: #include <math.h>
Step 1. Start using namespace std;
Step 2. The user enters a decimal number. // Function to convert a decimal number to octal
Step 3. Divide the decimal number by 8 to obtain its int convert(int decimal)
quotient and remainder. Store remainder in an array. {
Step 4. Repeat step 3 with the quotient until the int i = 1, octal = 0;
quotient becomes 0. //converting decimal to octal
Step 5. Print the remainder array in reverse order to get the while (decimal != 0)
octal conversion {
Step 6. Stop int rem = decimal % 8;
decimal /= 8;
octal += rem * i;
i *= 10;
C Code:
}
//Program to convert Decimal number into octal number return octal;
#include<stdio.h> }
//main program
int main() int main()
{ {
//Variable initialization int decimal,octal;
long dec_num, rem, quotient; cout << “Enter a decimal number: “;
int i, j, octalno[100]; //user input
//Taking input from user cin >> decimal;
printf("Enter a number for conversion: "); //calling function
//Storing the value in dec_num variable octal = convert(decimal);
scanf("%ld",&dec_num); //printing output
quotient = dec_num; cout << decimal << ” in decimal = “ << octal << ” in
i=1; octal”;
//Storing the octal value in octalno[] array return 0;
while (quotient!=0) }
{
octalno[i++]=quotient%8;
quotient=quotient/8;
} Java Code :
//Printing the octalno [] in reverse order //Java program to convert decimal number to octal number
printf("\nThe Octal of %ld is:\n\n",dec_num); import java.util.Scanner;
63 public class Decimal_To_Octal
{
public static void main(String args[])
for (j=i-1;j>0;j--) {
//scanner class object creation
Scanner sc = new Scanner(System.in);
System.out.print("Enter a Decimal
//input from user number : ");
//display it int decimal = sc.nextInt();
printf ("%d", octalno[j]); //integer array for storing octal digits
return 0; int octal[] = new int[20];
} int i = 0;
//writing logic for the conversion
while(decimal > 0)
{
int r = decimal % 8;
C Code :
octal[i++] = r;
decimal = decimal/8; /*
} * C Program to Convert Octal to Binary number
//printing result */
System.out.print("Octal number : "); #include<stdio.h>
for(int j = i-1 ; j >= 0 ; j--) #include<conio.h>
System.out.print(octal[j]);
//closing scanner class(not compulsory, #define MAX 1000
but good practice)
sc.close(); int main()
} {
} char octalnum[MAX];
//For initialize
long i = 0;
Python Code :
//taking user input of octalnum
#take decimal number printf("Insert an octal number: ");
Dec_num = 598 scanf("%s", octalnum);
#convert using oct() function printf("Equivalent binary number: ");
Oct_num = oct(Dec_num) while (octalnum[i])
#print number {
print('Number after conversion is :' + str(Oct_num)) //use switch case for multiple condition
64 switch (octalnum[i])
{
case '0':

Chapter 33. Octal to Binary printf("000"); break;


case '1':
printf("001"); break;
case '2':
printf("010"); break;
case '3': printf("011"); break;
case '4':

conversion : printf("100"); break;


case '5':
printf("101"); break;
Octal to binary conversion:-
case '6':
The C program helps to convert octal numbers to binary
printf("110"); break;
numbers. In this program, the user is asked to insert an
case '7':
octal number and by using a loop or if-else statement, the
printf("111"); break;
user can convert an octal number to binary number. An
//for invalid case
integer variable is required to be used in the program.
default:
printf("\n Invalid octal digit %c ", octalnum[i]);
Working:
return 0;
Step 1: Start
}
Step 2: Ask the user to enter an octal number as an input.
i++;
Step 3: Store the inserted number in the array octal num.
}
Step 4: With the help of switch statement, evaluate every
return 0;
number of the octal number
}
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
// Octal to Binary conversion
#include <iostream> public class Octal_To_Binary
#include <math.h> {
using namespace std; public static void main(String args[])
//Function to convert octal to binary {
long convert(int octal) //scanner class object creation
{ Scanner sc = new Scanner(System.in);
int decimal = 0, i = 0; //input from user
long binary = 0; System.out.print("Enter a octal number
//converting octal to decimal : ");
while(octal != 0) int octal = sc.nextInt();
{ //Declaring variable to store decimal
int rem = octal%10; number
int res=rem * pow(8,i); int decimal = 0;
decimal += res; //Declaring variable to use in power
i++;
octal/=10; int n = 0;
} //writing logic for the octal to decimal
i = 1; conversion
//converting decimal to binary while(octal > 0)
while (decimal != 0) {
{ int temp = octal % 10;
int rem = decimal % 2; decimal += temp *
binary += rem * i; Math.pow(8, n);
decimal /= 2; octal = octal/10;
i *= 10; n++;
} }
return binary; int binary[] = new int[20];
} int i = 0;
//main program //writing logic for the decimal to binary
65 conversion
while(decimal > 0)
{
int main() int r = decimal % 2;
binary[i++] = r;
decimal = decimal/2;
}
//printing result System.out.print("Binary number : ");
{ for(int j = i-1 ; j >= 0 ; j--)
int octal; System.out.print(binary[j]+" ");
cout << “Enter an octal number: “; //closing scanner class(not compulsory,
//user input but good practice)
cin >> octal; sc.close();
//function call }
long binary = convert(octal); }
//printing output
cout << octal << ” in octal = “ << binary << ” in
Python Code :
binary”;
return 0; #octal number with prefix 0o/0O
} oct_num = 0o564
#using bin() to convert octal number to binary
bin_num = bin(oct_num)
Java Code :
#print binary Number
//Java program to convert octal number to binary number print('Number after conversion is :' + str(bin_num))
import java.util.Scanner;
66
Chapter 34. Octal to
Decimal conversion : C++ Code :
//C++ Program
It is easy to convert an octal number to a decimal number. //Octal to decimal conversion
For this, the user is asked to enter an octal number which is #include <iostream>
converted to a decimal number following a series of steps. #include <math.h>
The algorithm below illustrates this process in a step wise using namespace std;
process. It is then followed by a C program that converts an // Function to convert octal number to decimal
Octal number to a decimal number. int convert(int octal)
{
Working: int decimal = 0, i = 0;
Step 1. Start //converting octal to decimal
while (octal != 0)
Step 2. An octal number is taken as an input from the user. {
int rem = octal % 10;
Step 3. Multiply each digit of the octal number starting octal /= 10;
from the last digit with powers of 8. int res=rem*pow(8,i);
decimal += res;
Step 4. Add all the digits multiplied. i++;
}
Step 5. The total sum of the digits gives the return decimal;
decimal number. }
//main program
Step 6. Stop int main()
{
int octal;
cout << “Enter an octal number: “;
C Code :
//user input
/** C Program to Convert Octal to Decimal */ cin >> octal;
//calling function
#include<stdio.h> int decimal=convert(octal);
#include<math.h> //printing output
cout << octal << ” in octal = “ << decimal << ” in
int main() decimal”;
{ return 0;
//Variable Initialization }
long int oct, dec = 0;
int i = 0;
Java Code :
//Taking input from user
printf("Enter an octal number: "); //Java program to convert octal number to decimal number
scanf("%ld", &oct); import java.util.Scanner;
//Conversion of octal to decimal public class Octal_To_Decimal
while(oct != 0) {
{ public static void main(String args[])
dec = dec +(oct % 10)* pow(8, i++); {
//oct/=10; //scanner class object creation
oct = oct / 10; Scanner sc = new Scanner(System.in);
} //input from user
//display System.out.print("Enter a octal number
printf("Equivalent decimal number: %ld",dec); : ");
return 0; int octal = sc.nextInt();
}
67

//Declare variable to store decimal


number
int decimal = 0;
//Declare variable to use in power

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

Step 7: If the condition is true then print the output as a


{
second quadrant. Step 9: If the condition is true then print the output as the
Step 8: If the condition is false, execute another statement third quadrant.
to check if the value of x is less than 0 and y is less than 0. Step 10: If the condition is false, then check if x variable is
greater than 0 and the y value is less than 0. #include<iostream>
Step 11: If the condition is true then print the output as using namespace std;
the fourth quadrant. //main program
Step 12: If the condition is false, then execute another int main()
statement where x value is equal to 0 and y variable is int x, y;
equal to 0. cout<<“Enter coordinates: \n“;
Step 13: Print the output as an origin. cin>>x>>y;
Step 14: Stop //checking for quadrants and axis
if(x==0)
cout<<x<<“,”<<y<<” lies on y axis”;
C Code : else if(y==0)
#include<stdio.h> cout<<x<<“,”<<y<<” lies on x axis”;
int main() else if(x>0&&y>0)
cout<<x<<“,”<<y<<” lies in 1st quadrant”;
{
//for initialization of coordinates else if(x<0&&y>0)
int x, y; //user input cout<<x<<“,”<<y<<” lies in 2nd quadrant”;
printf("Insert the value for variable X and Y\n"); else if(x<0&&y<0)
scanf("%d %d", &x, &y); cout<<x<<“,”<<y<<” lies in 3rd quadrant”;
//find true condition of first quadrant else if(x>0&&y<0)
if (x > 0 && y > 0) cout<<x<<“,”<<y<<” lies in 4th quadrant”;
printf("point (%d, %d) lies in the First quadrant\n",x,y); else
//find second quadrant cout<<x<<“,”<<y<<” lies on the origin”;
else if (x < 0 && y > 0) return 0;
printf("point (%d, %d) lies in the Second }
quadrant\n",x,y);
//To find third quadrant Python Code :
else if (x < 0 && y < 0) #take inputs for X and Y
printf("point (%d, %d) lies in the Third X = int(input('Enter value for X-axis :'))
quadrant\n",x,y); Y = int(input('Enter value for Y-axis :'))
//To find Fourth quadrant #check for 1st quadrant
else if (x > 0 && y < 0) if X > 0 and Y > 0:
printf("point (%d, %d) lies in the Fourth print('X and Y lie at First quadrant')
quandrant\n",x,y); #check for 2nd quadrant
//To find dose not lie on origin elif X < 0 and Y > 0:
else if (x == 0 && y == 0) print('X and Y lie at Second quadrant')
printf("point (%d, %d) lies at the origin\n",x,y); #check for 3rd quadrant
return 0; elif X < 0 and Y < 0:
} print('X and Y lie at Third quadrant')
#check for fourth quadrant
elif X > 0 and Y < 0:
C++ Code : print('X and Y lie at Fourth
//C++ program quadrant')else: print('X and Y lie at
//Quadrants in which coordinates lie Origin')
69

Chapter 36. Permutations


{
long int n,r,permutation,temp;

in which n people can C programming helps in identifying the r number of seats


that can be occupied by n number of people. Such a
occupy r seats in a program is known as the possible permutations. Here, We
need to write a code to find all the possible permutations in
classroom : which n people can occupy or number of seats in a
classroom/theater.
if(n < r)
N students are looking to find r seats in a classroom. Some {
of the seats are already occupied and only a few can be temp=n;
accommodated in the classroom. The available seats are n=r;
assumed as r and n number of people are looking to r=temp;
accommodate within the room. }
numerator=fact(n);
Permutations in which n people can occupy r seats in a denominator=fact(n-r);
classroom in C programming permutation=numerator/denominator;
Way 2 Of Asking Question printf("\nNum of ways people can be seated : ");
Write code to find all possible permutations in which n printf("%ld\n",permutation);
people can occupy r seats in a theater }

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

// Insert the num of people

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

Chapter 37. Maximum


}

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.

Working: C++ Code :


Step 1: Start
//C++ Program
Step 2: The user is asked to insert an integer value
//Maximum number of handshakes
n, representing the number of people
#include<iostream>
Step 3: Find nC2, and calculate as n * (n – 1) / 2. Step 4:
using namespace std;
Print the outcome derived from the above program Step 5:
//main program
Stop
int main()
{
C Code : int p;
cout<<“Enter number of Persons: “;
// C program to find the maximum number of handshakesM //user input
#include<stdio.h> cin>>p;
int main() cout<<“Maximum number of handshakes: “;
{
//find maximum number of handshakes using formula LCM.
int max=p*(p–1)/2;
//printing output Working:
cout<<max; Step 1. Start.
return 0; Step 2.Initialize variables of numerator and
Java Code : denominator Step 3. Take user input of two fraction
Step 4. Find numerator using this condition (n1*d2)
// Java program to find maximum number of handshakes +(d1*n2 ) where n1,n2 are numerator and d1 and d2
import java.io.*; are denominator .
import java.util.*; Step 5. Find denominator using this condition (d1*d2)
for lcm.
class handshakes
Step 6. Calculate GCD of this new numerator
{
and denominator .
// Calculating the maximum number of handshakes
Step 7. Display a two value of this condition
static int maxHandshake(int n)
x/gcd,y/gcd); Step 8. Stop.
{
return (n * (n – 1)) / 2;
} C Code :
#include <stdio.h>
// Driver code int main()
public static void main (String[] args) {
{ //for initialize variables
Scanner sc=newScanner(System.in); int numerator1,
int n = sc.nextLine(); denominator1,numerator2,denominator2,x,y,c,gcd_n
System.out.println( maxHandshake(n)); o; //To take user input of numerators and
} denominators printf("\nEnter the numerator for 1st
} number : "); scanf("%d",&numerator1);
printf("\nEnter the denominator for 1st number :
"); scanf("%d",&denominator1);
Python Code : printf("\nEnter the numerator for 2nd number :
#take user inputs "); scanf("%d",&numerator2);
N = int(input('Enter number of people available :')) printf("\nEnter the denominator for 2nd number :
#formula "); scanf("%d",&denominator2);
no_of_handshakes = int(N *((N-1)/2)) //numerator
#print number of no_of_handshakes
print('Maximum number of handshakes can be :' + x=(numerator1*denominator2)+(denominator1*numerato
str(no_of_handshakes)) r2 );
//denominator
y=denominator1*denominator2;
72

Chapter 38. Addition of


// Trick part. Reduce it to the simplest form by using
two fractions: gcd. for(c=1; c <= x && c <= y; ++c)
{
n this C program we will find sum of two fraction using C if(x%c==0 && y%c==0)
gcd_no = c;
To find the sum of two fractions we will be using }
the concept of LCM and GCD. //To display fraction of givien numerators
and denominators
For example: we have to find the sum of 6/2 and 16/3 printf("\nThe added fraction is %d/%d
",x/gcd_no,y/gcd_no);
Firstly the LCM of 2 and 3 will be found. Using the printf("\n");
LCM we will convert the numerators i.e. 6 and 16 into return 0;
digits that can be added and sum of those digits is found, }
lastly normalization is done using the GCD of sum and
//scanner class declaration
Scanner sc = new Scanner(System.in);
//input from the user
C++ Code :
System.out.print("Enter numerator for first
//C++ Program fraction : ");
//Adding two fractions int num1 = sc.nextInt();
#include <iostream> System.out.print("Enter denominator for
using namespace std; first fraction : ");
//main Program int den1 = sc.nextInt();
int findGCD(int n1, int n2) System.out.print("Enter numerator for
{ second fraction : ");
int gcd; int num2 = sc.nextInt();
for(int i=1; i <= n1 && i <= n2; i++) System.out.print("Enter denominator for
{ second fraction : ");
if(n1%i==0 && n2%i==0) int den2 = sc.nextInt();
gcd = i; int num, den, x;
} System.out.print("("+num1+" / "+den1+") +
return gcd; ("+num2+" / "+den2+") = ");
} //logic for calculating sum of two
int main() fractions
{ if(den1 == den2)
int num1,den1; {
cout << “Enter numerator and denominator of num = num1 + num2 ;
first number: “; den = den1 ;
//user input }
cin >> num1 >> den1; else{
int num2,den2; num = (num1*den2) + (num2*den1);
cout << “Enter numerator and denominator of den = den1 * den2;
second number: “; }
//user input if(num > den)
cin >> num2 >> den2; x = num;
//finding lcm of the denominators else
int lcm = (den1*den2)/findGCD(den1,den2); x = den;
//finding the sum of the numbers for(int i = 1 ; i <= x ; i++)
int sum=(num1*lcm/den1) + (num2*lcm/den2); {
//normalizing numerator and denominator of if(num%i == 0 && den%i ==
result int num3=sum/findGCD(sum,lcm); 0)
lcm=lcm/findGCD(sum,lcm); {
//printing output num = num/i;
cout<<num1<<“/”<<den1<<” + den = den/i;
“<<num2<<“/”<<den2<<” = “<<num3<<“/”<<lcm; }
}
73

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

Chapter 39. Replace all 0’s


else
integer as an input, all the 0's in the number has to be
replaced with 1.
with 1 in a given integer :
The replace all program in C programming works to
replace the numbers with zero, where the number must be C Code :
an integer. All the zeros (if encountered) in the given
// C program to replace all 0’s with 1 in a given integer
program will be replaced by 1.
#include
int replace (long int num)
Ex- number is 12004509 all 0’s are replays of 1’s so
{
number is 12114519.
// Base case for recursion termination
if (num == 0)
Working:
return 0;
// Extract the last digit and change it if needed
Step 1: Start
int digit = num % 10;
Step 2: The user is asked to insert an integer value as an
if (digit == 0)
input
digit = 1;
Step 3: Navigate the inserted integer digit by digit Step
// Convert remaining digits and append the last digit
4: If 0 is found, then replace it with 1, and print the
integer variable
return replace(num/10) * 10 + digit;
Step 5: Stop
}
int Convert(long int num)
Question can come like Way 1 {
Write a code to change all zero's as one's (0s as 1s) in a if (num == 0)
given number? ex: 120014 needs to be printed as 121114 return 1;
return replace(num);
Question can come like Way 2 }
implement a c program to replace all 0's with 1 in a given int main()
{ if(num == 0)
long int num; num2=1;
//To take user input //converting 0 to 1
printf("\nInsert the num : "); while(num>0)
scanf("%d", &number); {
//display final result int rem = num%10;
printf("\n Num after replacement : %d\n", Convert if(rem == 0)
(num)); rem = 1;
return 0; num = num/10;
} num2=num2*10+rem;
}
//converted number
C++ Code : cout<<“Converted number is: “<<num2;
//C++ Program return 0;
//Convert all 0’s to 1 }
#include<iostream>
using namespace std;
//main program Java Code :
int main()
{ //Java program to replace all 0's with 1 in a given integer :
int num,num2=0; import java.util.Scanner;
cout<<“Enter number: “; public class replace_0_to_1
//user input {
cin>>num; public static void main(String[] args)
//checking for 0 input {
75

//scanner class declaration for i in s:


Scanner sc = new Scanner(System.in);
//input from the user
System.out.print("Enter the number :
");
int number = sc.nextInt();
//convert the number to string and then
calculate its length
String str = Integer.toString(number);
int len = str.length();
String str1 = "";
//use the logic to replace all 0's with 1
in a given integer
for(int i = 0 ; i < len ; i++)
{
if(str.charAt(i) == '0')
str1 = str1 + '1';
else
#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))

str1 = str1 + Method 2 :


str.charAt(i); n=int(input(“Enter any number”))
} s=str(n)
System.out.println("Output : "+str1); l=[]
//closing scanner class(not compulsory, if(i==‘0’):
but good practice) l.append(‘1’)
sc.close(); else:
l.append(i)
} ns=“”
} for i in l:
ns+=i
print(int(ns))
Python Code :
Method 1 :
76

Chapter 40. Can a number


}
Step 5: If i is a prime number, identify if (n – 1) is a prime
be expressed as a sum of number.

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)

System.out.println(+number+" cannot be expressed as decodings of a given


a sum of two prime numbers");
} digit sequence :
//function for checking number is prime or
not public static int prime_or_not(int n) The decoding programs are the most possible
{ questions asked and are largely practiced in C
for(int i = 2 ; i < n ; i++) programming. The program counts the number of
{ possible decodings of the
if(n % i == 0) entered digit by the user of the given sequence. For
{ example, if the digit sequence is “12” then there are
c = 0; two possible decodings for this – One of them is ‘AB’
break; when we decode 1 as ‘A’ and 2 as ‘B’. Now we can
} also decode this digit sequence “12” as ‘L’ when we
} decode digits 1 and 2 taken together as an integer 12
return c; Way 2 of asking Question
} Count possible decodings of a given digit sequence -

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;

You might also like