100% found this document useful (1 vote)
1K views

Top 100 Codes

This document provides code solutions for determining whether an input number is positive, negative, or zero in C++, C, and Java. The algorithms first take in a number as input. They then check if the number is less than zero, greater than zero, or equal to zero to determine if it is negative, positive, or zero respectively. Output is printed stating the number is positive, negative, or neither based on the result of the comparisons.

Uploaded by

SURJIT VERMA
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
100% found this document useful (1 vote)
1K views

Top 100 Codes

This document provides code solutions for determining whether an input number is positive, negative, or zero in C++, C, and Java. The algorithms first take in a number as input. They then check if the number is less than zero, greater than zero, or equal to zero to determine if it is negative, positive, or zero respectively. Output is printed stating the number is positive, negative, or neither based on the result of the comparisons.

Uploaded by

SURJIT VERMA
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/ 94

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


mentioned on this page. Any revised price on the
May 2021 frontend or backend of the book is not
Edition: 1 (2021) acceptable.

Address of the Publisher:


Published on GSM Paper with PrepInsta WaterMark
K-3, Director Vidyamandir Shastri Nagar, Meerut, UP,
Publisher Address: K-3, Director Vidyamandir Shastri 250004
Nagar, Meerut, UP, 250004

Type settings : PrepInsta Technologies Private Limited Publication Team:

Printer Name: Creative Print Arts PrepInsta Technologies Private Limited

All rights Reserved:

● All the rights are reserved to the PrepInsta


Technologies and no part of the publication can
be stored or re-sold without the prior permission
of the publisher.

Price- Rs.600/-
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


4

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

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

//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 Java Code :
● Step 2. Enter a number. //Java Program to check a number is even or odd
import java.util.Scanner;
● Step 3. If the number is divisible by 2, it is even. public class even_or_odd
{
● Step 4. If the number is not divisible by 2, it is
public static void main(String[] args)
odd. {
//scanner class declaration
● Step 5. Stop Scanner sc = new Scanner(System.in);
//input from the user
System.out.print("Enter a Number : ");
C Code :
#include<stdio.h> int numb = sc.nextInt();
int main() //condition for even
{ if(numb % 2 == 0)
int number;
printf(“Insert a number \n“); System.out.println("Even
scanf(“%d”,&number); Number");
//condition for odd
//Checking if the number is divisible by 2 else
if (number%2 == 0)
printf(“The number is even\n“);
System.out.println("Odd
else Number");
printf(“The number is odd\n“); //closing scanner class(not compulsory,
return 0; but good practice)
} sc.close();

}
C++ Code : }

//C++ Program
// number is even or odd
Python Code :
#include num = int(input("Enter a Number:"))
using namespace std; if num % 2 == 0:
int main() print("Given number is Even")
{ else:
cout<<“Enter a number: “; print("Given number is Odd")
int check;
cin>>check; # This code is contributed by Shubhanshu Arya (Prepinsta
//checking whether the number is even or odd Placement Cell Student)
if(check % 2 == 0)
{
cout<<check<<” is an even number”;
}
else
{
cout<<check<<” is an odd number”;
}
return 0;
}
9

System.out.println(“Sum is ” +sum);
Chapter 3. Sum of First N
Natural numbers }

A Natural number is the same as Counting number.They }


are used to Count the numbers of real physical objects. Java Code :
Natural numbers start from 1 and go on infinite. The
positive numbers 1, 2, 3… are known as natural numbers. import java.util.*;
Example: class prepinsta
Natural number={1,2,,4,5,6,…….}. {
Formula for Sum of First N natural numbers is : n(n+1)/2. public static void main(String[] aa){
If you want to add the first 5 Natural numbers then we find Scanner sc=new Scanner(System.in);
the Sum of 1+2+3+4+5 =15. int sum=0;
System.out.println(“Enter the value of n”);
Working int n=sc.nextInt();
for(int i=1;i<=n;i++)
Step 1. Start sum=sum+i;
System.out.println(“Sum is ” +sum);
Step 2. Enter a number (N).

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


}
number || Sum=(n*(n+1))/2.

Step 4. Print sum of N Natural Number. Python Code :


Step 5. Stop
Method 1:

C Code : num = int(input("Enter the Number:"))


#include<stdio.h> value = 0
int main() for i in range(1, num+1):
{ value = value + i
int sum = 0, n;
printf(“Enter the first N Natural Number\n“); print("Sum of N natural numbers:", value)
scanf(“%d”,&n);
sum=(n*(n+1))/2;
printf(“sum is %d”,sum); Method 2:
return 0;
} num = int(input("Enter the Number:"))
sum = (num * (num+1))/2
C++ Code : print("The Sum of N natural Number is {}".format(sum))

import java.util.*; # This code is contributed by Shubhanshu Arya (Prepinsta


class prepinsta Placement Cell Student)

{
public static void main(String[] aa){
Scanner sc=new Scanner(System.in);
int sum=0;
System.out.println(“Enter the vlue of n”);
int n=sc.nextInt();
for(int i=1;i<=n;i++)
sum=sum+i;
10

Chapter 4. Sum Of N //display


printf (“Sum of Natural Numbers = %d”, Sum);
Natural Numbers
return 0;
In the C programming language, the user is allowed to
}
insert any integer value. With the help of For loop, this C
Output
program can calculate the sum of N natural numbers.
Kindly insert an integer variable : 5
Within this program, the first printf statement will request
Sum of Natural Numbers = 15
the user to insert a number or value then the scanf

statement will allocate the user inserted value to integer


C++ Code :
variable. The sum is calculated in the For loop. //C++ Program
// Sum of n natural numbers
To perform the arithmetic operation of addition of n #include<iostream>
numbers we use this conditions using namespace std;
Example – int main()
Enter Number 3 {
N natural numbers 1,2,3,4,5,6,7,8…….
Where first 3 number is 1,2,3 int sum , N;
Then we will return sum of number = 6 cout << “Enter the limit: “;
Working //user input
cin >> N;
● Step 1. Start //calculating
● Step 2. Enter a number (N). sum sum= N*(N+1)/2;
cout<<“The Sum of first “<< N <<” Natural Numbers
● Step 3. Use “For loop” to iterate upto the user is “<< sum;
return 0;
inserted value.
}
● Step 4. The “For loop” will calculate the sum of
Java Code :
the user inserted value.
//Java program to print the sum of n natural numbers
● Step 5. Stop
import java.util.Scanner;
public class sum_of_n_natural_numbers
C Code : {
/* C Program to find Sum of N Numbers using For Loop */ public static void main(String[] args)
#include<stdio.h>
int main() {
{ //scanner class declaration
//for initialize variable
Scanner sc = new Scanner(System.in);
int Number, i, Sum = 0;
//to take user input //input from user
printf (“\n Kindly Insert an Integer Variable\n“); System.out.print("Enter a number : ");
scanf (“%d”, &Number);

//use for loop for these condition int n = sc.nextInt();


for(i = 1; i <= Number; i++) //declare a variable to store sum
{
int sum=0;
Sum = Sum + i;
} //loop to add n natural numbers
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();

}
Chapter 5. Sum of numbers
} in a given range
Python Code : The program given below accepts a range of values and

Method 1: calculates their sum. The program uses a loop to calculate

the sum of the values provided by the user. The following


num = int(input("Enter the Number:"))
value = 0 section presents an algorithm followed by a C program to
for i in range(1, num+1):
value = value + i calculate this sum.

print("Sum of N natural numbers:", value)


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

Method 2: To use for loops start at 4 and end 8 and sum off inside the

num = int(input("Enter the Number:")) no.in this range.


sum = (num * (num+1))/2
print("The Sum of N natural Number is {}".format(sum))
Answer is 30(i.e 4+5+6+7+8=30).

# This code is contributed by Shubhanshu Arya (Prepinsta


Placement Cell Student) Problem Description
In this Program to find the sum of numbers in a given

range. In the C program we are using a for loop. In that

loop we have to start a first range given by the user and last

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 sum of the values provided by the user. Also, the

provided numbers must be in integer format for successful


12

calculation. The following section presents an algorithm }

followed by a C program to calculate this sum. //print the sum of number


printf(“Sum of number firstrang %d to lastrange %d is:
Example:-Enter first and last range 4 and 8. %d”,firstrange, lastrange, total);
}
Output
To use for loop start at 4 and end 8 and sum off inside the
Enter the value first range and last range:
no.in this range.
30
40
Answer is 30(i.e 4+5+6+7+8=30). sum of number firstrange 30 to lastrange 40 is : 385

C++ Code :
Working
//C++ Program
● Step 1. Initialize variables (firstrange,lastrange,
//Sum of Natural Numbers in a given range
total and i). #include<iostream>
using namespace std;
● Step 2. Input fistrange and lastrange by user. //main Program
int main()
● Step 3. We use “for loop” with the condition
{
(i=firstrange;i<= lastrange;i++).When loop will int sum = 0 , upper_limit, lower_limit;
cout << “Enter the lower limit: “;
work until i= secondrange. cin >> lower_limit;
● Step 4. The loop will start with i=firstrange and

end with i<= lastrange. cout << “Enter the upper limit: “;
cin >> upper_limit;
● Step 6. In the loop for every cycle total will be

incremented by i. //calculating sum of numbers in the given range


for(int i = lower_limit; i <= upper_limit; i++){
● Step 7. Then condition false print sum of sum += i;
}
number(total).

● Step 8. Stop //printing output


cout<<“The Sum of Natural Numbers from “ <<
lower_limit << ” to “ << upper_limit << ” is “ << sum;
C Code : return 0;
}
#include <stdio.h>
int main()
{ Java Code :
//for initialization of variable //Java program to print the sum of numbers in a given range
int firstrange,lastrange, i=0, total= 0; import java.util.Scanner;
public class sum_of_numbers_in_range
//to use user input first range & last range {
printf(“Enter the value first range and last range\n“); public static void main(String[] args)
scanf(“%d\n%d”,&firstrange, &lastrange); {
//scanner class declaration
//use for loop for total no.inside the range Scanner sc = new Scanner(System.in);
for(i = firstrange; i <= lastrange; i++){ //input from user
System.out.print("Enter starting
//total+=i; number : ");
total = total + i; int start = sc.nextInt();
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 Chapter 6. Greatest of two
System.out.print("Sum of numbers in
the range from "+start+" to "+end+" is "+sum); numbers
//closing scanner class(not compulsory,
but good practice) In C programming language, the greatest of numbers can be
sc.close();
identified with the help of IF-ELSE statements. The user is

asked to insert two integers. The numbers inserted are then


}
} calculated using a set of programs to get the correct output.

It will find the highest number among them using IF-ELSE


Python Code :
Statement and start checking which one is larger to display
Method 1:
the largest number.
num = int(input("Enter the Number:"))
value = 0
for i in range(1, num+1): Example – If the given numbers are 12 and 9 then greater
value = value + i number is 12

print("Sum of N natural numbers:", value)


12, 9= 12>9

Method 2:
Working
num = int(input("Enter the Number:")) Step 1: Start
sum = (num * (num+1))/2
print("The Sum of N natural Number is {}".format(sum)) Step 2: Insert two integers no1 and no2 from the user with

the help of scanf statement.


# This code is contributed by Shubhanshu Arya (Prepinsta
Placement Cell Student) Step 3: Check if the no1 is bigger in value than no2 using

the if statement.

Step4: If no1 is greater, then print no1 using the printf

statement, if the case is vice versa then check whether no2

is greater than no1 with the help of elseif statement.

Step 5: If no2 is greater than no1, then print no2 using

printf statement, if not then print no1 and no2 are equal

using printf statement.

Step 6: Stop

C Code:
14

#include<stdio.h> cout<<first<<” is greater than “<<second;


int main()
}
{
int no1, no2; else
printf(“Insert two numbers:”); {
scanf(“%d %d”,&no1, &no2);
cout<<second<<” is greater than “<<first;
//Condition to check which of the two number is greater }
//it will compare of number where number 1 is greater return 0;
if(no1 > no2)
printf(“%d is greatest”,no1); }

Java Code :
//where number 2 is greater
else if(no2 > no1) //Java program to find greatest of two numbers
printf(“%d is greatest”,no2); import java.util.Scanner;
public class greatest_of_two_numbers
//for both are equal {
else public static void main(String[] args)
printf(“%d and %d are equal”, no1, no2); {
//scanner class declaration
return 0; Scanner sc = new Scanner(System.in);
} //input first number
System.out.print("Enter the first
Output number : ");
int first = sc.nextInt();
Insert Two Numbers : 5 //input second number
6 System.out.print("Enter the second
6 is the Greatest number : ");
int second = sc.nextInt();
C++ Code :
//conditions
//C++ program if(first > second)
//Greatest of two numbers
System.out.println(first+" is
#include<iostream> greater than "+second);
using namespace std; else if(second > first)
System.out.println(second+"
//main program
is greater than "+first);
int main() else
{ System.out.println("Both
numbers are Equal");
int first,second;
//closing scanner class(not compulsory,
cout<<“Enter first number: “; but good practice)
sc.close();
cin>>first;
cout<<“Enter second number: “;
cin>>second; }
}
if(first==second)
Python Code :
{
first = int(input("Enter first number:"))
cout<<“both are equal”; second = int(input("Enter second number:"))
} if first > second:
print("First is Greater than Second")
else if(first>second)
else:
{ print("Second is Greater than First")
15

C code :
#include<stdio.h>
int main()
Chapter 7. Greatest of the {
int no1,no2,no3;
Three numbers
//Prompt user to insert any three integer variables
The C program to find the greatest of three numbers printf(“\nInsert value of no1, no2 and no3:”);
requires the user to insert three integers. Flow chart is also scanf(“%d %d %d”, &no1, &no2, &no3);
used in C programming to find the greatest number among
three integers inserted by the user. A simple if-else block is //for check of number 1 is greater
used to identify the greatest number. if((no1 > no2) && (no1 > no3))
printf(“\n Number1 is greatest”);
Problem Description

C programs to find the greatest of three numbers require //weather number 2 is grater
else if((no2 > no3) && (no2 > no1))
the user to insert three integers. Flow chart is also used in printf(“\n Number2 is greatest”);
C programming to find the greatest number among three
//other conditions are false than number 3 is greater
integers inserted by the user. A simple if-else block is else
printf(“\n Number3 is greatest”);
used to identify the greatest number. The program will return 0;
ask the user to insert three integer variables. And on the }
Output
basis of the inserted number, the program will equate and
Insert Value of No1, No2 and No3: 15, 200, 101
exhibit the greatest number as an output. This program
Number 2 is Greatest
uses no1, no2 & no3 as three integer variables that are

represented number1, number2 and number3 respectively C++ code :


//C++ Program
in the program.
//Greatest of three numbers
#include<iostream>
using namespace std;
Working //main program
int main()
Step 1: Start
{
Step 2: Take three integer values from the user. int first, second, third;
cout<<“Enter first number: “;
Step 3: If no1 is greater than no2 and no3, printf cin>>first;
“Number1 is greatest”. cout<<“Enter second number: “;
cin>>second;
Step 4: If no2 is greater than no1 and no3, printf cout<<“Enter third number: “;
cin>>third;
“Number2 is greatest”.
//comparing first with other numbers
Step 5: If both the conditions are false, then printf if((first >= second) && (first >= third))
{
“Number3 is greatest”. cout<<first<<” is the greatest”;
}
Step 6: Stop
//comparing Second with other numbers
else if((second >= first) && (second >= third))
{
cout<<second<<” is the greatest”;
}
16

else }
{ Python code :
cout<<third<<” is the greatest”; first = int(input("Enter first number:"))
} second = int(input("Enter second number:"))
return 0; third = int(input("Enter third number:"))
}
Java code : if first > second and first > third:
//Java program to find greatest of three numbers print("First is Greater than Second and Third")
import java.util.Scanner; elif second > first and second > third:
public class greatest_of_three_numbers print("Second is Greater than First and Third")
{ else:
public static void main(String[] args) print("Third is Greater than First and Second")
{
//scanner class declaration # This code is contributed by Shubhanshu Arya (Prepinsta
Scanner sc = new Scanner(System.in); Placement Cell Student)
//input three numbers from user
System.out.print("Enter the first
number : ");
int first = sc.nextInt();
System.out.print("Enter the second
number : ");
int second = sc.nextInt();
System.out.print("Enter the third
number : ");
int third = sc.nextInt();
System.out.println();
//condition for first number
if(first > second && first > third)

System.out.println(first+" is
the greatest number.");
//condition for second number
else if(second > first && second >
third)
System.out.println(second+"
is the greatest number.");
//condition for third number
else if(third > first && third > second)

System.out.println(third+" is
the greatest number.");
//condition when all three numbers are
equal
else

System.out.println("All three
numbers are same");
//closing scanner class(not compulsory,
but good practice)
sc.close();

}
17

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


Chapter 8. Leap year or not return 0;
In this program we have to find whether the year is a leap
}
year or not. Generally we assume that year is exactly Output

divisible by 4 is a leap year. But it is not only in this case Enter Year for find leap year or not : 2012
2012 is a leap Year
1900 is divisible by 4. But it is not a leap so it that case we

follows these conditions Enter Year for find leap year or not : 1900
1900 is not a leap Year

*It is exactly divisible by 100


C++Code :
*If it is divisible by 100, then it should also exactly //C++ Program
//Leap year or not
divisible by 4
#include<iostream>
*And it is divisible by 400 using namespace std;
//main program
int main()
These all conditions are true: a leap year is a leap year. {
Working //initialising variables
int year;
Step 1. Initialize variable “year” to find leap year. cout<<“Enter year to check: “;
//user input
Step 2. Take input from User.
cin>>year;
Step 3. We use this condition //checking for leap year
if( ((year % 4 == 0) && (year % 100 != 0)) || (year %
((year%4==0)&&(year%100!=0)) || (year%400==0)) to 400==0) )
{
check if the year is Leap or not.
//input is a leap year
Step 4. It is true display year is a leap year. cout<<year<<” is a leap year”;
}
Step 5. The false display year is not a leap year. else
Step 6. Stop. {
//input is not a leap year
cout<<year<< ” is not a leap year”;
C Code : }
return 0;
#include<stdio.h>
}
int main()
{
Java Code :
//initialization of Year
int year; //Java program to check whether a year entered by user is a
leap year or not
//to take user input import java.util.Scanner;
printf(“Enter Year for find leap year or not : “); public class LeapYear
scanf(“%d”,&year); {
public static void main(String[] args)
//we use this statement for check leap year {
if(((year%4==0)&&(year%100!=0)) || (year%400==0)) //scanner class declaration
printf(“%d is a Leap Year”,year); Scanner sc=new Scanner(System.in);
//input year from user
//not leap year System.out.println("Enter a Year");
else int year = sc.nextInt();
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:
print("Yes, {} is Leap Year".format(year)) Chapter 9. Prime number
else:
A number is considered a prime number when it satisfies
print("No, {} is Leap Year".format(year))
else: the below conditions.
print("No, {} is Leap Year".format(year))
else:
print("No, {} is Leap Year".format(year)) Prime number is a number which can be divided by 1 and

itself
# This code is contributed by Shubhanshu Arya (Prepinsta
Placement Cell Student) A number which can not be divided by any other number

other than 1 or itself is a prime number.

It should have only 2 factors. They are, 1 and the number

itself.

Problem Description
In this program we will find if a number is a prime number

or not with the help of a for loop or if else statement. 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
number other than 1 or itself is a prime number.
● It should have only 2 factors. They are, 1 and the
number itself.

Ex- Number is 13. it have only 2 factor


19

● it is divisible by 1. }
● And it is divisible by itself return 0;
}
So it is a prime number. Output

Enter Number:6
Working 6 is not a Prime Number
Step 1. Read a “num” value to check prime or not.
Enter Number:13
Step 2. set i=1,div=0. 13 is a Prime Number
Step 3. if i<=num if true go to step 4, else go to step 7.

Step 4. Check the condition num%i==0 if true then C++ Code :


evaluate step 5, else go to step 6. //C++ Program
//Check Prime or Not
Step 5. set div=div+1. #include<iostream>
Step 6. i=i+1, go to step 4. using namespace std;
int main()
Step 7. check div, if div==2 display prime, else display not {
int i,num,div=0; //initializing variables
prime.
cout<<“Enter number:”;
Step 8. Stop 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
{
//user input cout<<num<<” is a prime number”;
printf(“Enter number: “); }
scanf(“%d”,&number); else
{
//checking for number of divisor cout<<num<<” is not a prime number”;
for(c=1;c<=number;c++) }
{ return 0;
if(number%c==0) }
{
div++; Java Code :
} //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
//display public static void main(String[] args)
printf(“%d is a prime number”,number); { //main
} method declaration
else Scanner sc=new Scanner(System.in);
{ //scanner class object creation
//display
printf(“%d is not a prime number”,number); 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
System.out.println("Prime Number"); Chapter 10. Prime number
else
System.out.println("Not a Prime within a given range
Number");
A number that is divisible only by itself and 1 (e.g. 2, 3, 5,
sc.close();
//closing scanner class(not mandatory but good practice) 7, 11).
} //end of main
method
} //end of class The C program reduces the number of iterations within the
Output :
for loop. It is made to identify or calculate the prime

numbers within a given range of numbers inserted by the


PythonCode : user.
a=0
Ex:- if a user enters a range as 40-50 In that range 41,43,47
count = 0
n=int(input(“Enter the number to check if it is prime or not: these three numbers are prime numbers.
“))
a = n // 2;
for i in range(2,a+1): Problem Description
if (n % i == 0): The C program reduces the number of iterations within the
print(“The given number is not prime”)
count = 1 for loop. It is made to identify or calculate the prime
break
numbers within a given range of numbers inserted by the
if (count == 0):
print(“The given number is prime”) user. The program takes the range and identifies all the

prime numbers between the given range as well as similarly

prints the digits coming under the prime numbers. Users are

required to take the range as input that will be stored in the

variables num1 and num2 respectively.

Ex:- if a user enters a range as 40-50 In that range 41,43,47

these three numbers are prime numbers.

Working
Step 1: Start
21

Step 2: The user is asked to insert a given range of numbers //display


printf(“%d\n“, i);
as an input to find the prime numbers. count++;
Step 3: Find prime numbers within the given range that }
}
should be only odd values. //display total prime number b/w lie on given range
printf(“Num of primes between %d & %d = %d\n“,
Step 4: Check whether the odd numbers are divisible by
temp, num2, count);
any of the natural numbers }
Output
Step 5: Print the calculated prime numbers.
Insert the value of num1 and num2:
Step 6: Stop
70, 80
Prime nums are
C Code : 71
73
#include<stdio.h>
79
#include<stdlib.h>
83
void main()
Num of primes between 70 and 85 = 4
{
//To initialize variables
int num1, num2, i, j, flag, temp, count = 0;
C++ Code :
//for taking user input
printf(“Insert the value of num1 and num2 \n“); //C++ Program
scanf(“%d %d”, &num1, &num2);
//check condition first range is less than 2 //Prime numbers in a given range
if (num2 < 2)
{ #include<iostream>
printf(“No prime nums found up-to %d\n“, num2);
exit(0); using namespace std;
}
//to display prime numbers //function to chek for prime number
printf(“Prime nums are \n“);
temp = num1; void prime(int num)
//if num1 modules 2 is equal to zero
if( num1 % 2 == 0) {
{
//increment on that number. int div=0;
num1++;
} //checking for number of divisor
//use for loop with first rang and second rang
for (i = num1; i <= num2; i = i + 2) for(int i=1;i<=num;i++)
{
flag = 0; {
for (j = 2; j <= i / 2; j++)
{ if(num%i==0)
if ((i % j) == 0)
{ div++;
flag = 1;
break; }
}
} //no divisors other than 1 and itself
//check if flag equal to zero
if (flag == 0) if(div==2)
{
22

cout<<num<<endl; int count;


//loop for finding and printing all prime
}
numbers between given range

int main() for(int i = start ; i <= end ; i++)


{
{
//logic for checking number
is prime or not
cout<<“Enter range:”;
count = 0;
int lowerLimit, upperLimit; for(int j = 1 ; j <= i ; j++)

//user input {
if(i % j == 0)
cin>>lowerLimit>>upperLimit;
count =
count+1;
cout<<“Prime numbers between “<<lowerLimit<<”
and “<<upperLimit<<” are:”<<endl; }
if(count == 2)
//finding prime numbers in the given range

for(int i=lowerLimit;i<=upperLimit;i++) System.out.println(i);


}
prime(i);
//closing scanner class(not mandatory
but good practice)
return 0;
sc.close();
} }
}
Java Code :
Python Code :
//Java program to print prime numbers in a given range
first = int(input("Enter the first number:"))
import java.util.Scanner; second = int(input("Enter the Second Number:"))
public class prime_numbers_in_a_given_range for i in range(first, second):
for j in range(2, i//2):
{
if i % j == 0:
public static void main(String[] args) break
{ else:
print("Prime Number", i)
//scanner class object creation
Scanner sc=new Scanner(System.in); # This code is contributed by Shubhanshu Arya (Prepinsta
Placement Cell Student)
//input from user
System.out.print("Enter Starting
Number : ");
int start = sc.nextInt();
System.out.print("Enter Ending
Number : ");
int end = sc.nextInt();
System.out.println("Prime numbers
between "+start+" and "+end+" are : ");
23

C code :
Chapter 11. Sum of digits of
/* C program to take a number & calculate the sum of its
a number numbers */
This program in C programming calculates the sum of
#include<stdio.h>
numbers inserted by the user or in an inserted integer. The
int main()
program is taken as an input and stored in the variable

number, denoted as no. Initially, the sum of the variable is


{
zero, and then it is divided by 10 to obtain the result or

output. int no, temp, digit, sum = 0;

printf ("Insert a number \n");


In this C program to allow the user enter any number and scanf ("%d", &no);
then it will divide the number into individual digits and add
temp = no;
those individuals (Sum=sum+digit) digits using While while (no > 0)
{
Loop.
digit = no % 10;
sum = sum + digit;
Ex:- number is 231456 no /= 10;
}
printf("Given number = %d\n", temp);
2+3+1+4+5+6=21 printf("Sum of the numbers %d = %d\n", temp, sum);
return 0;
}
sum of digit of a given number is 21
Output
Insert a number: 16789

Given number: 16789


Working:-
Sum of the numbers: 31

Step 1: Start
C++ code :
Step 2: Ask the user to insert an integer as an input.
//C++ Program
Step 3: Divide the integer by 10 in order to obtain quotient
//Sum of digits in a number
and remainder.

Step 4: Increase the new variable with the remainder

received in the above step #include


using namespace std;
Step 5: Repeat the above steps with the quotient till the int main()
{
value of the quotient becomes zero.
int num,sum=0;
Step 6: Printf the output or sum cout<<“Enter any num : “;
//user input
Step 7: Stop cin>>num;
//loop to find sum of digits
do
{
24

sum+=num%10;
num=num/10; Chapter 12. Reverse of a
}while(num!=0);
//output number
cout<<“\nSum of digits in given integer is: “<<sum;
In this program reverses a number entered by a user and
return 0;
} then prints it. For example, if a user will enter 6577756 as

input then 6577756 will be printed as output.


Java Code
//Java program to calculate sum of digits of a number
import java.util.Scanner; This C program accepts an integer and reverses it.
public class sum_of_digits
{
public static void main(String[] args)
{
Working:-
//scanner class declaration
Scanner sc = new Scanner(System.in);
//input from user
Step 1. Take the number which you have to reverse as the
System.out.print("Enter a number : ");
input variable says number.
int number = sc.nextInt();
//declare a variable to store sum of Step 2. Obtain its quotient and remainder.
digits Step 3. Multiply the separate variable with 10 and add the
int sod = 0;
while(number != 0) obtained remainder to it.
{
Step 4. Do step 2 again for the quotient and step 3 for the
int pick_last = number % 10;
sod = sod + pick_last; remainder obtained in step 4.
number = number / 10;
} Step 5, Repeat the process until the quotient becomes zero.

//display sum of digits Step 6.When it becomes zero, print the output and exit
System.out.print("Sum of Digits =
Step 7. Stop.
"+sod);
//closing scanner class(not compulsory,
but good practice)
sc.close(); C code :
}
}
Python Code :
#include<stdio.h>
int main()
num = [int(d) for d in input("Enter the Number:")]
{
sum = 0
//Initialization of variables where rev='reverse=0'
for i in range(0, len(num)):
int number, rev = 0,store, left;
sum = sum + num[i]

//input a numbers for user


print("Sum of Digits of a Number: {}".format(sum))
printf("Enter the number\n");
scanf("%d", &number);
# This code is contributed by Shubhanshu Arya (Prepinsta
Placement Cell Student)
store= number;

//use this loop for check true condition


while (number > 0)
25

{ {
//left is for remider are left public static void main(String[] args)
left= number%10; {
//scanner class declaration
//for reverse of no. Scanner sc = new Scanner(System.in);
rev = rev * 10 + left; //input from user
System.out.print("Enter a number : ");
//number /= 10;
number=number/10; int number = sc.nextInt();
System.out.print("Reverse of
} "+number+" is ");
//To show the user value int reverse = 0;
printf("Given number = %d\n",store); String s = "";
while(number != 0)
//after reverse show numbers {
printf("Its reverse is = %d\n", rev); int pick_last = number % 10;
//use function to convert
return 0; pick_last from integer to string
} s=s+
Output:- Integer.toString(pick_last);
Enter the number 123456 number = number / 10;
}
Given number = 123456 //display the reversed number
Its reverse is =654321 System.out.print(s);
//closing scanner class(not compulsory,
C Code but good practice)
//C++ Program sc.close();
//Reverse of a number
#include <iostream>
using namespace std; }
//main program }
int main()
{ Python Code
//variables initialization num = int(input("Enter the Number:"))
int num, reverse=0, rem; temp = num
cout<<“Enter a number: “; reverse = 0
//user input while num > 0:
cin>>num; remainder = num % 10
//loop to find reverse number reverse = (reverse * 10) + remainder
do num = num // 10
{
rem=num%10; print("The Given number is {} and Reverse is
reverse=reverse*10+rem; {}".format(temp, reverse))
num/=10;
}while(num!=0); # This code is contributed by Shubhanshu Arya (Prepinsta
//output Placement Cell Student)
cout<<“Reversed Number: “<<reverse;
return 0;
}

Java Code
//Java program to print reverse of a number
import java.util.Scanner;
public class reverse_of_number
26

Chapter 13. Palindrome //input a numbers for user


printf("Enter the number\n");
number scanf("%d", &number);
A palindrome number is a number that is given the same
//for duplicacy of number
number after reverse. In C programs to check if the input n1=number;

number is palindrome or not. We are using a while loop and store= number;
//use this loop for check true condition
an else if statement in the C Program.
while (number > 0)
{
Ex:- A number is 123321 .If you read the number “123321” //left is for remider are left
left= number%10;
from reverse order, it is the same as “123321”.

In that number is a palindrome. //for reverse of no.


rev = rev * 10 + left;
A number is 12121. If we read the number “12121” from
//number /= 10;
reverse order ,it is the same as 12121. It is also a
number=number/10;
palindrome number }
//To check reverse no is a Palindrome
if(n1==rev)
Working:- printf("Number %d is Palindrome number",n1);
else
Step 1.Take the number which you have to reverse and find
printf("it is not a Palindrome number");
the palindrome as the input variable says number. return 0;
}
Step 2.Number is stored in his duplicity value as a Output:-
duplicate variable (n1). Enter the number

Step 3.Obtain its quotient and remainder. 121121

Step 4.Multiply the separate variable with 10 and add the


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

} while (num != 0); number = int(input("Enter the Number:"))


cout << “The reverse of “<< temp <<” is “<< reverse temp = number
<< endl; reverse = 0
//checking for palindrome while number > 0:
if (temp == reverse) remainder = number % 10
cout << “The number is a palindrome.”; reverse = (reverse * 10) + remainder
else number = number // 10
cout << “The number is not a palindrome.”;
return 0; if temp == reverse:
} print("Given number {} is Palindrome".format(temp))
else:
Java Code print("Given number {} is not
//Java program to check whether a string entered by user is Palindrome".format(temp))
palindrome or not.
import java.util.Scanner; # This code is contributed by Shubhanshu Arya (Prepinsta
public class palindrome_or_not Placement Cell Student
{
public static void main(String[] args)
{
//scanner class declaration
Scanner sc = new Scanner(System.in);
//input from user
System.out.print("Enter a String : ");

String st = sc.next();
//string function for calculating length
of the string
int len = st.length();
//string variable to store reversed string
String st1 = "";
for(int i = 0 ; i < len ; i++)
{
//string function for getting
character at a particular index
char ch = st.charAt(i);
st1 = ch + st1;
}
//condition for checking palindrome by
using string function
if(st.equals(st1))

System.out.print("Palindrome");
else
System.out.print("Not
Palindrome");
//closing scanner class(not compulsory,
but good practice)
sc.close();

}
}

Python Code
28

Step 14.For find number is armstrong.


Chapter 14. Armstrong
Step 15.The check if (n1==sum) display number is
number armstrong
In this program we will find the number is Armstrong or
Step 16.Either false display number is not armstrong
not where the number should be entered by the user.
Step 17.stop
Basically the sum of the cube of its digits is equal to the
C Code
number itself is called Armstrong number.

#include<stdio.h>
Ex:- Enter any number 153. int main()
{
int num ,n,n1,c=0,mul=1,sum=0,r,f,i;
1**3 + 5**3 + 3**3 = 153
printf("enter any num: \n");
scanf("%d",&num);
Number is Armstrong n=num;
n1=num;
while(n!=0)
Working: {
r=n%10;
Step 1.Initialize variables num,n,n1,c=0,mul=1,sum=0,r,f,i . c++;
n=n/10;
Step 2.Input any number by user so read num variable.
}
Step 3.set n=num and n1=num for duplicate. while (num!=0)
{
Step 4.We use while loop with condition(n!=0). f=num%10;
Step 5.Than check the last digit of a number with condition mul=1;
for(i=1;i<=c;i++)
is reminder(r)=number(n)%10. {
mul=mul*f;
Step 6.Than increment of other variables for next step
}
(c++).
sum=sum+mul;
Step 7.Than find length of number with condition is num=num/10;
}
number(n)=number(n)/10.
if(n1==sum)
Step 8.repeat steps 4 to 6 until number (n)!=0. printf("Armstrong Number");
else
Step 9.Again we use the while loop with condition printf("Not an Armstrong Number");
(num!=0) for check return 0;
}
Step 10.the number is Armstrong or not. Output:-
enter any num: 1634
Step 11.Again check last digit for duplicity of number with

condition is reminder(r1)=number(num)%10. Armstrong Number.

Step 12.Than we use for loop statement with condition is


enter any num: 135
(i=1;i<=c).

Step 13.Use this code mul=mul*r1, sum=sum+mul, C ++ Code


//C++ Program
num=num/10;
//Armstrong number or not
29

#include<iostream> else
#include<math.h> System.out.println("Not an
using namespace std; Armstrong Number");
//main Program //closing scanner class(not compulsory,
int main() but good practice)
{ sc.close();
int num, digit, sum = 0;
cout << “Enter a positive integer: “;
//user input }
cin >> num; }
int store = num;
//find sum of cubes of individual digits Python Code
do import math
{ value = int(input("Enter the Number: "))
digit = num % 10; num = [int(d) for d in str(value)]
sum = sum + pow(digit,3); sum = 0
num = num / 10; for i in range(0, len(num)):
}while(num != 0); sum = sum + math.pow(num[i], len(num))
//checking for ArmStrong number
if(sum == store) if sum == value:
cout << store << ” is an Armstrong number.”; print("Given number is Armstrong Number")
else else:
cout << store << ” is not an Armstrong number.”; print("Given Number is not Armstrong Number")
return 0;
} # This code is contributed by Shubhanshu Arya (Prepinsta
Placement Cell Student)
Java Code
//Java program to check whether a number is armstrong or
not
import java.util.Scanner;
public class armstrong_number_or_not
{
public static void main(String[] args)
{
//scanner class declaration
Scanner sc = new Scanner(System.in);
//input from user
System.out.print("Enter a number : ");

int number = sc.nextInt();


int n = number;
int sum = 0;
while(n != 0)
{
int pick_last = n % 10;
sum = sum + (pick_last *
pick_last * pick_last);
n = n / 10;
}
//condition for checking that the sum is
equal to the number or not
if(sum == number)

System.out.println("Armstrong Number");
30

scanf("%d %d", &start, &end);


Chapter 15. Armstrong
//to display pint of range
number in a given range printf("\n Armstrong nums between %d an %d are: ",
start, end);
To identify the Armstrong number between two intervals in

C programming, the user is required to insert integer //for use this loop to store all number in given range
for(i = start + 1; i < end; ++i)
numbers. A n digit number is known as an Armstrong {
//store a duplicity value of given range
number, when the sum of the values of the digits raised to
temp2 = i;
nth power is equal to the number itself. For example: 153 = temp1 = i;

13+53+33=153 while (temp1 != 0)


Ex:- basically we know that Armstrong numbers in the {
//temp1 /= 10;
given range 0 to 999 are 1 2 3 4 5 6 7 8 9 153 370 371 407. temp1=temp1/10;
++n;
}
Working while (temp2 != 0)
{
Step 1: Start rem = temp2 % 10;
//result += pow(rem, n);
Step 2: Insert the start and end value
result=result+pow(rem,n);
Step 3: Repeat from I = start value to end value //temp2 /= 10;
temp2=temp2/10;
Step 4: Repeat the process until the temporary number is }
not equal to 0. //check true condition if result is equal to i
if (result == i)
Step 5: Remainder = temp%0 {
//display
Step 6: The result should be equal to the result plus the
printf("%d ", i);
power (remainder n). }
n = 0;
Step 7: temp = temp/10 result = 0;
}
Step 8: If the value of the result is equals to the value of
printf("\n");
number then print the number return 0;
}
Output:
Step 9: Else repeat the steps until the end number is Insert the start value and end value: 100, 500
Armstrong numbers between 100 and 500 are: 370, 371,
encountered.
407.
C Code
C ++ Code
//C++ Program
//Armstrong number in a interval
#include<stdio.h> #include<iostream>
int main() #include<math.h>
{ using namespace std;
//For initializing variables void armstrong(int num)
int start, end, i, temp1, temp2, rem, n = 0, result = 0; {
//user give start and end point of a number int sum=0;
printf("Insert the start value and end value :"); 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:"))
second = int(input("Enter second number:"))
Java Code
//Java program to print armstrong numbers between two
intervals def is_Armstrong(val: int) -> bool:
import java.util.Scanner; sum = 0
public class armstrong_numbers_between_two_intervals arr = [int(d) for d in str(val)]
{ for i in range(0, len(arr)):
public static void main(String[] args) sum = sum + math.pow(arr[i], len(arr))
{ if sum == val:
//scanner class declaration print("{} number is Armstrong".format(val))
Scanner sc = new Scanner(System.in); else:
//input from user print("{} number is not Armstrong".format(val))
System.out.print("Enter Starting
Number : "); for i in range(first, second + 1):
int start = sc.nextInt(); is_Armstrong(i)
System.out.print("Enter Ending
Number : "); # This code is contributed by Shubhanshu Arya (Prepinsta
int end = sc.nextInt(); Placement Cell Student)
System.out.println("Armstrong
numbers between "+start+" and "+end+" are : ");
int n, sum;
//loop for finding and printing all prime
numbers between given range
for(int i = start ; i <= end ; i++)
{
n = i;
sum = 0;
//logic for checking number
is armstrong or not
while(n != 0)
{
32

//display serious
Chapter 16. Fibonacci printf("%d ",n3);
}
Series upto nth term return 0;
}
The sequence is a Fibonacci series where the next number
Output:-
is the sum of the previous two numbers. The first two terms enter a limit of series

of the Fibonacci sequence start from 0,1,… 10


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

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

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

}
}

Python Code
# Method 1

def fibonacciSeries(i):
if i <= 1:
return i
else:
return (fibonacciSeries(i - 1) + fibonacciSeries(i - 2))

if num <= 0:
print("Please enter a Positive Number")
else:
print("Fibonacci Series:", end=" ")
for i in range(num):
print(fibonacciSeries(i), end=" ")
34

printf("Factorial of a number %d is = %d\n", number,


Chapter 17. Factorial of a fact);

number return 0;
}
In this program we will find the factorial of a number
Output:-
where the number should be entered by the user. Factorial Enter a number to calculate its factorial 4

is a sequence of a number whose multiply by all previous Factorial of a number 4 is 24


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

int number = sc.nextInt();


//display of factorial of a given number
System.out.println("Factors of
"+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


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

C Code Java Code


#include<stdio.h> //Java program to calculate power of a number
int main() import java.util.Scanner;
{ public class Power_of_a_number
//To initialize variables {
int number, expo,temp = 1; public static void main(String[] args)
{
//To take user input //scanner class declaration
printf("Enter a base number: "); Scanner sc = new Scanner(System.in);
scanf("%d", &number); //input base value and exponent value
//To display Exponent from user
printf("Enter an exponent: "); System.out.print("Enter the value of
scanf("%d", &expo); base : ");
//use while loop when power is not equal to zero int base = sc.nextInt();
while (expo != 0) System.out.print("Enter the value of
{ exponent : ");
//temp*=number int exp = sc.nextInt();
temp = temp * number; //declare an integer variable to store the
--expo; result
} int result = 1;
printf("power of a %d is %d",number, temp); //logic for calculating power of the
return 0; entered number
} while (exp != 0)
Output:- {
Enter a base number: 6 result = result * base;
Enter an exponent: 4 --exp;
power of a 6 is 1296 }
//print the result
C++ Code System.out.println("Answer = " + result);
//closing scanner class(not compulsory,
//C++ Program
but good practice)
//Power of a number
sc.close();
#include <iomanip>
}
#include <iostream>
}
#include <math.h>
using namespace std;
//main program Python Code
int main() base = int(input("Enter Base number:"))
{ expo = int(input("Enter Expo Number:"))
double exp, base; temp = 1
cout<<“Enter base: “;
//user input 1 for i in range(0, expo):
cin>>base; temp = temp * base
cout<<“Enter Exponent: “;
print(temp)
37

}
Chapter 19 Factor of a return 0;
}
number Output:-
Enter an any number: 12
In this Program we will calculate the factors of any
Factors of a number 12 are: 1 2 3 4 6 12
numbers using C programming. The factors of a number
C ++ Code
are defined as the number we multiply two numbers and get
//C++ Program
the original number. The factor of a number is a real //Factors of a number
#include <iostream>
number which divides the original completely with zero using namespace std;
//main Program
remainder.
int main()
Ex- no is 16,5. {
int num;
16= 2 x 2 x 2 x 2 cout << “Enter a positive number: “;
5= 1 x 5 //user input
cin >> num;
Working cout << “Factors of “ << num << ” are: “ << endl;
//finding and printing factors
Step 1- Enter the number, to find their factor. for(int i = 1; i <= num; i++)
{
Step 2- Initialise the loop with u=1 to u<=number and
if(num % i == 0)
follow the following calculation cout << i << “\t“;
}
(i) check whether the number is divisible with u and u got return 0;
a result zero. }

(ii) now print the value of u. Java Code


From this loop u got all the factors of the number. //Java program to find factors of a number
import java.util.Scanner;
Step 3- Stop. public class factors_of_a_number
{
public static void main(String[] args)
C Code {
#include<stdio.h> //scanner class declaration
int main() Scanner sc = new Scanner(System.in);
{ //input from user
//To initialize variable System.out.print("Enter a number : ");
int number, u;
//to take user input int number = sc.nextInt();
printf("Enter an any number: "); System.out.println("Factors of
scanf("%d",&number); "+number+" are :");
//loop for finding factors of a number
printf("Factors of a number %d are: ", number); for(int i = 1 ; i <= number ; i++)
{
//Use for loop this condition if(number % i == 0)
for(u=1; u<= number; u++) //printing factors
{
//now we check for true condition of this System.out.print(i+" ");
if (number%u == 0) }
//display factor //closing scanner class(not compulsory,
printf("%d ",u); but good practice)
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

1! + 4! scanf("%d",&number);
//To store a duplicity value of a given number
So it is a strong number. temp=number;

//use this whenever number is not equal to 0


Working: while(temp!=0)
{
//for last digit
Step 1- First we enter the number.
digit=temp%10;
Step 2- copy the number into any temporary variable. //now we call of factorial function
digit = factorial(digit);
Step 3- until temp is not equal to 0, calculate the following //to improve of a sum on digit
sum=sum+digit;
statement
temp=temp/10;
(i)digit=temp%10 }
//we check sum is equal to number its true
(ii)now we find the factorial of a digit. if(sum==number)
(iii)sum=sum+digit, add digit into a sum and store it in the {
//display
sum. 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, else
{
Step 4- if the sum of these factorial numbers is equal to the //display
printf("It is not Strong Number");
entered number,so it is the 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 main() int ip,sum=0;
{ cout<<“Enter number to check: “;
//to initialize variables //user input
int number,digit,sum=0,temp; cin>>ip;
int save=ip;
//To take user input //logic to check for Strong Number starts
printf("Enter a number:"); while(ip)
40

{ System.out.println("Strong
int num=ip%10; Number");//display the result
int fact = 1; else
//finding factorial of each digit of input System.out.println("Not a
for(int i=num;i>0;i–) Strong Number");
{ //closing scanner class(not compulsory,
fact=fact*i; but good practice)
} sc.close();
sum+=fact;
ip/=10;
} }
//checking for Strong Nunber }
if(sum==save)
{ Python Code
cout<<save<<” is a Strong Number”; #Enter the number to check
} print(‘Enter the number:’)
else n=int(input())
{ #save the number in another variable
cout<<save<<” is not a Strong Number”; temp=n
} sum=0
//logic ends #Implementation
return 0; while(temp):
} r=temp%10 # r will have the value of the unit place digit
temp=temp//10
Java Code fac=1
//Java program to check whether a number is a strong for i in range(1,r+1): #finding factorial
number or not fac=fac*i
import java.util.Scanner;
public class strong_number_or_not sum+=fac #adding all the factorial
{
public static void main(String[] args) if(sum==n):
{ print(‘Yes’, n ,‘is strong number’)
//scanner class declaration
Scanner sc = new Scanner(System.in); else:
//input from user print(‘No’ , n, ‘is not a strong number’)
System.out.print("Enter a number : ");

int number = sc.nextInt();


int fac,sum = 0;
int n = number;
while(n != 0)
{
fac = 1;
int r = n % 10;
//calculating factorial of r
for(int i = r ; i >= 1 ; i--)
fac = fac * i;
//storing sum of factorial of
all digits of the number
sum = sum + fac;
n=n/10;
}
//condition for strong number
if(sum == number)
41

{
Chapter 21. Perfect number // Initialization of variables
int number,i=1,total=0;
In this program we will find the number is a perfect number

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

Working: return 0;
}
Step 1- enter the number to be check Output:-
Step 2- initialize i with 1. Enter a number: 28

|Step 3- now execute the while loop, while i is less than the 28 is a perfect number

number so calculate the following expression.

(i) if number is divided by the i, so add number with the Enter a number: 153

total and store it in total 153 is not a perfect number


(ii)increment the i with 1.
C++ Code
When i is equal to or greater than the number so loop will //C++ Program
//Perfect Number or not
terminate.
#include<iostream>
Step 4- now compare the entered number with the total using namespace std;
//main Program
number. int main ()
{
Step 5- if the total number is equal to the entered number so
int div, num, sum=0;
the number is the perfect number. cout << “Enter the number to check : “;
//user input
Step 6- Stop cin >> num;
//loop to find the sum of divisors
for(int i=1; i < num; i++)
C Code
{
#include<stdio.h>
div = num % i;
int main()
if(div == 0)
42

sum += i;
} Chapter 22. Automorphic
//checking for perfect number
if (sum == num) number
cout<< num <<” is a perfect number.”;
In this program we have to find whether the number is an
else
Automorphic number or not using C programming. An
cout<< num <<” is not a perfect number.”;
automorphic number is a number whose square ends with
return 0;
the same digits as number itself.
}
Java Code Automorphic Number in C Programming
//Java program to check whether a number is perfect or not
import java.util.Scanner; Example:
public class perfect_number_or_not ● 5=(5)2=25
{
public static void main(String[] args) ● 6=(6)2=36
{
//scanner class declaration ● 25=(25)2=625
Scanner sc = new Scanner(System.in);
//input from user ● 76=(76)2=5776
System.out.print("Enter a number : ");
● 376=(376)2=141376
int number = sc.nextInt();
//declare a variable to store sum of
These numbers are automorphic numbers.
factors
int sum = 0;
for(int i = 1 ; i < number ; i++) ● Automorphic number : C | C++ | Java
{
if(number % i == 0)
sum = sum + i;
}
//comparing whether the sum is equal Working
to the given number or not
if(sum == number)
System.out.println("Perfect Step 1- Enter the number to be checked.
Number");
else Step 2- store the number in a temporary variable.
System.out.println("Not an
Step 3- find the square of a given number and display it.
Perfect Number");
//closing scanner class(not compulsory,
but good practice)
Step4- Initialize the while loop until the number is not
sc.close();
equal to zero
}
} (i) Calculate the remainder of the temp,divided with the 10
Python Code and store in digit
n = int(input(“Enter any number: “))
sump= 0 (ii) divide the number with the 10 and store in the number.
for i in range(1, n):
Step 5- find modules of square with count and compare
if(n % i == 0):
sump= sump + i with temp
if (sump == n):
print(“The number is a Perfect number”) Step 6-if it is true display Automorphic or else not a
else:
print(“The number is not a Perfect number”)
43

Automorphic number int main()


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

System.out.println("Not an
Automorphic Number");
//closing scanner class(not compulsory,
but good practice)
sc.close();

}
} Chapter 23. Harshad
Python Code number
1st Approach
#enter the number to check In this program we will discuss if the number is harshad
print(‘Enter the number:’) number or not in C programming. In mathematics, a
n=int(input())
sq=n*n #square of the given number Harshad number is a number that is divisible by the sum of
co=0 #condition variable
its digits. We use a while loop statement with the following
while(n>0): #loop until n becomes 0
if(n%10!=sq%10): condition. Input consists of 1 integer.
print(‘Not Automorphic’)
co=1
break # come out of the loop if the above Ex– Number is 21
condition holds true
it is divisible by own sum (1+2) of its digit(2,1)
#reduce n and square
n=n//10 So it is harshad number
sq=sq//10
Some other harshad numbers are 156,54,120 etc.
if(co==0):
print(‘Automorphic’)
2nd Approach Working:

n=int(input(“Enter any number”)) Step 1- Enter the number to be checked.


x=n**2
Step 2- store the number in a temporary variable.
a=str(n)
b=str(x) Step 3- Initialise the while loop until the temp is not equal
y=len(a)
z=len(b) to zero
if(z-b.find(a)==y):
(i) Calculate the remainder of the temp,divided with the 10
print(“Automorphic”)
else: and store in digit
print(“Not automorphic number”)
(ii) add the digit with sum and store it in the sum.

(iii) divide the temp with the 10 and store in the temp;

Step 4- find modulus of the number with sum and store in

the res;

Step 5- if res equal to zero then the given number is a

harshad number else the given number is not a harshad

number.

Step 6- Stop.
45

C Code int n = num;


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

//closing scanner class(not compulsory, sum1=sum(l)


but good practice)
sc.close();

if(p%sum1==0):
}
}
Output :
Enter a number : 18 print(“Harshad number”)
Harshad Number

Enter a number : 345 else:


Not a Harshad Number
List of Top 100 Cod

print(“Not harshad number”)

Python Code
General Solution: Optimal solution:

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

p=n p=n

l=[] sum1=0

sum1=0 while(n>0):

while(n>0): sum1+=n%10

x=n%10 n=n//10

if(p%sum1==0):

print(“Harshad number”)
l.append(x)

else:
n=n//10
print(“Not harshad number”)
47

int main()
Chapter 24. Abundant
{
number
In this program to find the number is Abundant number or
//initialization variables
not. A number n is said to be Abundant Number to follow

these condition

int number,sum=0,c;
● the sum of its proper divisors is greater than the
number itself.
● And the difference between these two values is
called the abundance. //input from user

Ex:- Abundant number 12 having a proper divisor is

1,2,3,4,6 the sum of these factors is 16 it is greater than 12 printf("Enter a number : ");
so it is an Abundant number.

Some other abundant numbers scanf("%d",&number);

18, 20, 24, 30, 36, 66, 70, 72, 78, 80, 84, 88, 90, 96, 100,
//declare a variable to store sum of factors of the number
102, 104, 108, 112, 114, 120..

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

Step 1- Enter the number, to find the Abundant number.

Step 2- Initialize the loop with c=1 to c<=number and {

follow the following calculation

(i) check if the number is divisible with c and c got a


if(number % c == 0)
result zero. //sum+=c;
sum = sum + c;
(ii) now sum=sum+c, add digit into a sum and store it in }
the sum. if(sum > number)
//display the result
Step 3. than check sum is greater than number print true. printf("Abundant Number");
else
Step 4. else it is not a abundant number
//display
Step 5- Stop. printf("Not an Abundant Number");

return 0;
C Code }

#include<stdio.h> C++ Code


//C++ Program
//Abundant Number or not
48

#include<iostream> System.out.println("Not an
using namespace std; Abundant Number");
//main Program //closing scanner class(not compulsory,
int main () but good practice)
{ sc.close();
int div, num, sum=0;
cout << “Enter the number to check : “;
//user input }
cin >> num; }
//loop to find the sum of divisors Output :
for (int i=1; i < num; i++) Enter a number : 12
{ Abundant Number
div = num % i;
if (div == 0) Python Code
sum += i; #enter the number to check
} print(‘Enter the number:’)
//checking for Abundant number n=int(input())
if (sum > num) sum=1 # 1 can divide any number
cout<< num <<” is an Abundant number.”; for i in range(2,n):
else if(n%i==0): #if number is divisible by i add the
cout<< num <<” is not an Abundant number.”; number
return 0; sum=sum+i
}
if(sum>n):
Java code print(n,‘is Abundant Number’)
//Java program to check whether a number is abundant
number or not else:
import java.util.Scanner; print(n,‘is not Abundant Number’)
public class abundant_number_or_not
{
public static void main(String[] args)
{
//scanner class declaration
Scanner sc = new Scanner(System.in);
//input from user
System.out.print("Enter a number : ");

int number = sc.nextInt();


//declare a variable to store sum of
factors of the number
int sum = 0;
//loop for calculating sum of factors of
the number
for(int i = 1 ; i < number ; i++)
{
if(number % i == 0)
sum = sum + i;
}
//condition for checking whether the
sum is greater than number or not
if(sum > number)
System.out.println("Abundant
Number");
else
49

//1 Create two variables to use in first and second


Chapter 25. Friendly pair numbers
int i;
Two numbers are said to be friendly pairs if they have a
int f_Num,s_Num;
common abundancy index. Or, the ratio between the sum of //2 two more variables created to store the sum of the
divisors
divisors of a number and the number itself. These numbers int f_DivisorSum = 0;
int s_DivisorSum = 0;
are also known as Amicable numbers.

//3 Asking user to enter the two numbers


We can also say that two numbers n and m are friendly printf("Enter two numbers to check if Amicable or not
: ");
numbers if scanf("%d %d",&f_Num,&s_Num);

?(n)/n = ?(m)/m //4 Using one variable for loop and second to check for
each number
for(int i=1;i<f_Num;i++)
Where ?(n) is the sum of divisors of n. {
//5 Condition check
For instance, for numbers 6 and 28,
if(f_Num % i == 0)
Divisors of 6 are- 1, 2, 3, and 6. f_DivisorSum = f_DivisorSum + i;
}
Divisors of 28 are- 1, 2, 4, 7, 14, and 28. //6 Calculating the sum of all divisors
for(int i=1;i<s_Num;i++)
Sum of the divisors of 6 and 28 are 12 and 56 respectively.
{
Also, the abundant index of 6 and 28 is 2. if(s_Num % i == 0)
s_DivisorSum = s_DivisorSum + i;
Therefore, 6 and 28 is a friendly pair. }
//7 Check condition for friendly numbers
Working
if((f_Num == s_DivisorSum) && (s_Num ==
Step 1. Start f_DivisorSum))

Step 2. Input the numbers 1 and 2. else


{
Step 3. Initialize two variables, sum1 and sum 2 with zero.
printf("%d and %d are not Amicable
Step 4. Assign sum 1 with the sum of all the divisors of numbers\n",f_Num,s_Num);
}
number 1. return 0;
}
Step 5. Assign sum 2 with the sum of all the divisors of
Output
number 2. Enter two numbers to check if Amicable or not : 12 13
12 and 13 are not Amicable numbers
Step 6. If (sum 1==number1) and (sum 2==number 2), then

print, “Friendly Numbers” C ++ Code


//C++ Program
Step 7. Else print “Not Friendly Numbers”.
//Friendly Pair(Amicable number) or not
Step 8. Stop #include<iostream>
using namespace std;
// function to check Friendly pairs
C Code void findAmicable(int first, int second)
#include<stdio.h> {
int main() int sum1=0,sum2=0;
{ for(int i=1; i<=first/2 ; i++)
{
50

//finding and adding divisors of first number for(int i = 1 ; i < number1 ; i++)
if(first%i==0) {
sum1=sum1+i; if(number1 % i == 0)
} add1 = add1 + i;
for(int i=1; i<=second/2 ; i++) }
{ //logic for finding factors and
//finding and adding divisors of second number calculating sum of all those factors for number2
if(second%i==0) for(int i = 1 ; i < number2 ; i++)
sum2=sum2+i; {
} if(number2 % i == 0)
//checking for friendly pair add2 = add2 + i;
if(first==sum2 && second==sum1) }
cout<<“Friendly Pair(“<<first<<“,”<<second<<“)”; //condition for friendly pair number
else if(number1 == add2 && number2 ==
cout<<“Not a Friendly Pair”; add1)
} System.out.println("Number
//main program is Friendly Pair");
int main() else
{ System.out.println("Number
int first,second; is not Friendly Pair");
cout<<“Enter first number : “; //closing scanner class(not compulsory,
//user input but good practice)
cin>>first; sc.close();
cout<<“Enter second number : “;
//user input
cin>>second; }
//calling function }
findAmicable(first,second);
return 0;
Python Code
}
#’Enter the numbers to check’
n=int(input())
Java Code m=int(input())
//Java program to check whether a number is friendly pair import math
or not sum_n=1 + n #sum of divisor of n
import java.util.Scanner; sum_m=1 + m #sum of divisor of m
public class friendly_pair_or_not i=2
{ j=2
public static void main(String[] args) #finding divisor
{ while(i<=math.sqrt(n)):
//scanner class declaration if(n%i==0):
Scanner sc = new Scanner(System.in); if(n//i==i):
//input from user sum_n+=i
System.out.print("Enter First number :
"); else:
int number1 = sc.nextInt(); sum_n+=i + n//i
System.out.print("Enter Second
number : "); i=i+1
int number2 = sc.nextInt();
//declare two variables to store the while(j<=math.sqrt(m)):
addition of factors of both numbers which are entered by if(m%j==0):
user if(m//j==j):
int add1 = 0, add2 = 0; sum_m+=j
//logic for finding factors and
calculating sum of all those factors for number1 else:
51

sum_m+=j + m//j

j=j+1
if(sum_n/n==sum_m/m):
print(‘Yes’ , n , ‘,’ , m ,‘ are friendly Pair’)
else:
print(‘No’, n , ‘,’ , m ,‘ are not friendly Pair’)

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. if(second == 0)
Step 5. Print the stored number as HCF. {
Step 6. Stop return first;
}
// both numbers are equal
if(first == second)
C Code : {
#include <stdio.h> return first;
int main() }
{ // first is greater
//for initialize variables else if(first > second)
int a, b, i, hcf; {
a = 12; return findGCD(first – second, second);
b = 16; }
//find hcf of number return findGCD(first, second – first);
for(i = 1; i <= a || i <= b; i++) }
{
if( a%i == 0 && b%i == 0 )
Java Code :
hcf = i;
} //Java program to find GCD or HCF of two numbers
//display hcf import java.util.Scanner;
printf("HCF = %d", hcf); public class gcd_or_hcf
return 0; {
} public static void main(String[] args)
{
//scanner class declaration
Scanner sc = new Scanner(System.in);
C++ Code : //input from the user
//C++ Program System.out.print("Enter the first
//GCD of Two Numbers number : ");
#include<iostream> int num1 = sc.nextInt();
using namespace std; //input from the user
// Recursive function declaration System.out.print("Enter the second number : ");
int findGCD(int, int); int num2 = sc.nextInt();
// main program int n = 1;
int main() System.out.print("HCF of "+num1+" and "+num2+" is ");
{ if( num1 != num2)
int first, second; {
cout<<“Enter First Number: “; while(n != 0)
cin>>first; {
cout<<“Enter second Number: “; //storing remainder
cin>>second; n = num1 % num2;
cout<<“GCD of “<<first<<” and “<<second<<” is
“<<findGCD(first,second); if(n != 0)
return 0; {
} num1 = num2;
//body of the function num2 = n;
int findGCD(int first, int second) }
{ }
// 0 is divisible by every number //result
if(first == 0) System.out.println(num2);
{
return second; }
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 #include<iostream>
● it is true use this condition check1=check1+n1; . using namespace std;
● Otherwise int findLCM(int,int);
● check2=check2+n2; . //main program
● Print the value of check1 or check2. int main()
{
int first,second;
cout<<“Enter first number : “;
cin>>first;
C Code : cout<<“Enter second number : “;
#include<stdio.h> cin>>second;
//calling function to find lcm
void lcm_two_no(int,int); cout<<findLCM(first,second)<<” is the LCM of
int main() two numbers.”;
{ return 0;
int n1,n2; }
//function to find lcm
//to take user input n1,n2 int findLCM(int first, int second)
printf("Enter two numbers: "); {
scanf("%d %d",&n1,&n2); static int fact = first;
// if true then fact is the lcm
//call of user define function if(fact % first == 0 && fact % second == 0)
lcm_two_no(n1,n2); {
return 0; return fact;
} }
//if false call function again
//function to calculate l.c.m else
void lcm_two_no(int n1,int n2) {
{ fact=fact + first;
int check1,check2; findLCM(first,second);
//to use of duplicity value }
check1=n1; return fact;
check2=n2; }

//to find lcm of number


Java Code :
while(check1!=check2)
{ //Java program to find LCM of two numbers
//for condition true import java.util.Scanner;
if(check1< check2 public class lcm
check1=check1+n1; {
public static void main(String[] args)
//for condition false {
else //scanner class declaration
check2=check2+n2; Scanner sc = new Scanner(System.in);
} //input from the user
printf("\nL.C.M of %d and %d is: %d",n1,n2,check1); System.out.print("Enter the first
number : ");
} int num1 = sc.nextInt();
//input from the user
System.out.print("Enter the second
number : ");
C++ Code : int num2 = sc.nextInt();
//C++ program //logic for finding lcm of both numbers
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
larger = larger + 1
Chapter 28. Greatest
print("LCM of two given number:{}".format(lcm))
Common Divisor :
The Highest Common Multiple or the Greatest Common
lcmFinder(num1, num2)
Divisor is the greatest number that exactly divides both
numbers. It is possible to calculate this number through
simple mathematical calculations. The following algorithm
shows how the GCD of two numbers is calculated.

Ex:-

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

Working:-
Step 1. Start
56

Step 2. Enter two numbers a and b. {


Step 3. If a = 0, return b. int first, second;
Step 4. If b = 0, return a. cout<<“Enter First Number: “;
Step 5. If a is equal to b return a cin>>first;
Step 6. If a is greater than b, return a – b, and b cout<<“Enter second Number: “;
Step 7. Else return a, b-a cin>>second;
Step 8. Stop cout<<“GCD of “<<first<<” and “<<second<<” is
“<<findGCD(first,second);
return 0;
C Code : }
// C program to calculate GCD of two numbers //body of the function
#include<stdio.h> int findGCD(int first, int second)
// The code used a recursive function to return gcd of p and {
q // 0 is divisible by every number
int gcd(int p, int q) if(first == 0)
{ {
return second;
// checking divisibility by 0 }
if (p == 0) if(second == 0)
return q; {
return first;
if (q == 0) }
return p; // both numbers are equal
if(first == second)
// base case {
if (p == q) return first;
return p; }
// first is greater
// p is greater else if(first > second)
if (p > q) {
return gcd(p-q, q); return findGCD(first – second, second);
}
else return findGCD(first, second – first);
return gcd(p, q-p); }
}

// Driver program to test above function


Java Code :
int main()
{ //Java program to find GCD or HCF of two numbers
int p = 98, q = 56; import java.util.Scanner;
printf("GCD of %d and %d is %d ", p, q, gcd(p, q)); public class gcd_or_hcf
return 0; {
} public static void main(String[] args)
{
//scanner class declaration
C++ Code : Scanner sc = new Scanner(System.in);
//C++ Program //input from the user
//GCD of Two Numbers System.out.print("Enter the first
#include<iostream> number : ");
using namespace std; int num1 = sc.nextInt();
// Recursive function declaration //input from the user
int findGCD(int, int); System.out.print("Enter the second
// main program number : ");
int main() int num2 = sc.nextInt();
57

int n = 1;
System.out.print("HCF of "+num1+" Chapter 29. Binary to
and "+num2+" is ");
if( num1 != num2) Decimal to conversion :
{
The C program converts binary numbers to decimal
while(n != 0)
numbers that are equivalent. A decimal number can be
{
obtained by multiplying every digit of binary digit with
//storing remainder
power of 2 and totaling each multiplication outcome. The
n = num1 % num2;
power of the integer starts from 0 and counts to n-1 where n
is assumed as the overall number of integers in binary
if(n != 0)
number.
{
num1 =
Ex:- (101100001) 2 =(353)10
num2;
num2 =
To show on fig(1)
n;
}
Working:-
}
Step 1: Start
//result
System.out.println(num2);
Step 3: The user is asked to enter a binary number as an
input
}
else
Step 4: Store the quotient and remainder of the binary
System.out.println("Wrong
number in the variable rem
Input");
//closing scanner class(not compulsory,
Step 5: Multiply every digit of the entered binary number
but good practice)
beginning from the last with the powers of 2
sc.close();
correspondingly
}
Step 6: Repeat the above steps with the quotient obtained
}
until the quotient becomes 0

Step 7: The sum of the numbers will give the decimal


Python Code : number as a result, print the decimal val.

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)
{
rem = num % 10;
decimal_val = decimal_val + rem * base;
58

//num/=10; {
num = num / 10 ; public static void main(String args[])
//base*=2; {
base = base * 2; Scanner sc = new Scanner(System.in);
} System.out.print("Enter a binary
//display binary number number : ");
printf("The Binary num is = %d \n", binary_val); int binary = sc.nextInt();
//display decimal number //Declaring variable to store decimal
printf("Its decimal equivalent is = %d \n", number
decimal_val); int decimal = 0;
return 0; //Declaring variable to use in power
}
int n = 0;
//writing logic for the conversion
while(binary > 0)
C++ Code : {
//C++ Program int temp = binary%10;
//Convert binary to decimal decimal +=
#include <iostream> temp*Math.pow(2, n);
#include <math.h> binary = binary/10;
using namespace std; n++;
//function to convert binary to decimal }
int convert(long n) System.out.println("Decimal number :
{ "+decimal);
int i = 0,decimal= 0; //closing scanner class(not compulsory, but good
//converting binary to decimal practice)
while (n!=0) sc.close();
{ }
int rem = n%10; }
n /= 10;
int res = rem * pow(2,i);
Python Code :
decimal += res;
i++; num = int(input("Enter number:"))
} binary_val = num
return decimal; decimal_val = 0
} base = 1
//main program while num > 0:
int main() rem = num % 10
{ decimal_val = decimal_val + rem * base
long binary; num = num // 10
cout << “Enter binary number: “; base = base * 2
cin >> binary;
cout << binary << ” in binary = “ << convert(binary) print("Binary Number is {} and Decimal Number is
<< ” in decimal”; {}".format(binary_val, decimal_val))
return 0;
}

Java Code :
//Java program to convert Binary number to decimal
number
import java.util.Scanner;
public class Binary_To_Decimal
59

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


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

}
60

Java Code : #convert using oct() function


Oct_num = oct(Bin_num)
//Java program to convert binary number to octal number #print number
import java.util.Scanner; print('Number after conversion is :' + str(Oct_num))
public class Binary_To_Octal
{
public static void main(String args[])
{
//scanner class object creation
Scanner sc = new Scanner(System.in);
//input from user
System.out.print("Enter a binary
number : ");
int binary = sc.nextInt();
//Declaring variable to store decimal
number
int decimal = 0;
//Declaring variable to use in power

int n = 0;
//writing logic for the conversion from
binary to decimal
while(binary > 0)
{
int temp = binary%10;
decimal +=
temp*Math.pow(2, n);
binary = binary/10;
n++;
}
int octal[] = new int[20];
int i = 0;
//writing logic for the conversion from
decimal to octal
while(decimal > 0)
{
int r = decimal % 8;
octal[i++] = r;
decimal = decimal / 8;
}
//printing result
System.out.print("Octal number : ");
for(int j = i-1 ; j >= 0 ; j--)
System.out.print(octal[j]);
//closing scanner class(not compulsory,
but good practice)
sc.close();
}
}

Python Code :
#take binary number
Bin_num = 0b10111
61

{
Chapter 31. Decimal to count++;
}
Binary conversion:
bin = bin + rem * base;
The C program to convert decimal numbers into binary
//number/=2;
numbers is done by counting the number of 1s. The
number = number / 2;
program practices module process and multiplication with
base = base * 10;
base 2 operation for converting decimal into binary
}
number. It further uses modulo operation to check for 1’s
//display
and hence increases the amount of 1s. The program reads
printf("Input num is = %d\n", dec_num);
an integer number in decimal in order to change or convert
printf("Its binary equivalent is = %ld\n", bin);
into a binary number.
printf("Num of 1's in the binary num is = %d\n", count);
return 0;
Ex:- (180)10=(11101000)2
}
Working:
Step 1: Start
Step 2: Ask the user to insert an integer number in decimal C++ Code :
as an input
Step 3: Check whether the entered number is less than or //C++ Program
equal to 0 //Decimal to binary conversion
Step 4: Check the divisibility of the number by 2 and store #include <iostream>
the remainder in the range #include <math.h>
Step 5: Increase the range by 1 using namespace std;
Step 6: After calculating, print the binary number and the //function to convert decimal to binary
number of 1s. long convert(int n)
Step 7: Stop {
long binary = 0;
int i = 1;
//converting decimal to binary
C Code : while (n!=0)
{
/*
int rem = n%2;
* C program to accept a decimal number and convert it to
n /= 2;
binary
binary += rem*i;
* and count the number of 1's in the binary number
i *= 10;
*/
}
return binary;
}
#include<stdio.h>
//main program
int main()
int main()
{
{
//for initialize a variables
int decimal;
long number, dec_num, rem, base = 1, bin = 0, count =
long binary;
0;
cout << “Enter a decimal number: “;
//To insert a number
//user input
printf("Insert a decimal num \n");
cin >> decimal;
scanf("%ld", &number);
//calling function
dec_num = number;
binary = convert(decimal);
while(number > 0)
cout << decimal << ” in decimal = “ << binary << ” in
{
binary” << endl ;
rem = number % 2;
return 0;
/* To count no.of 1s */
}
if (rem == 1)
62

Java Code :
//Java program to convert decimal number to binary
number
import java.util.Scanner;
public class Decimal_To_Binary Chapter 32. Decimal to
{
public static void main(String args[]) octal Conversion:
{
The C program to convert decimal to octal number accepts
//scanner class object creation
a decimal number from the user. This number is further
Scanner sc = new Scanner(System.in);
converted to its equivalent octal number after following a
//input from user
series of steps. The following section gives an algorithm for
System.out.print("Enter a Decimal
this conversion. It is then followed by a C program.
number : ");
int decimal = sc.nextInt();
Ex:- If a Decimal number is an octal number we use this
//integer array for storing binary digits
method
int binary[] = new int[20];
(143)10=(217)8
int i = 0;
//writing logic for the conversion
Working:
while(decimal > 0)
Step 1. Start
{
Step 2. The user enters a decimal number.
int r = decimal % 2;
Step 3. Divide the decimal number by 8 to obtain its
binary[i++] = r;
quotient and remainder. Store remainder in an array.
decimal = decimal/2;
Step 4. Repeat step 3 with the quotient until the quotient
}
becomes 0.
//printing result
Step 5. Print the remainder array in reverse order to get the
System.out.print("Binary number : ");
octal conversion
for(int j = i-1 ; j >= 0 ; j--)
Step 6. Stop
System.out.print(binary[j]+" ");
//closing scanner class(not compulsory,
but good practice)
sc.close(); C Code:
}
} //Program to convert Decimal number into octal number
#include<stdio.h>

int main()
Python Code : {
//Variable initialization
#take decimal number
long dec_num, rem, quotient;
dec_num = 124
int i, j, octalno[100];
#convert decimal number to binary
//Taking input from user
bin_num = bin(dec_num)
printf("Enter a number for conversion: ");
#print number
//Storing the value in dec_num variable
print('Number after conversion is :' + str(bin_num))
scanf("%ld",&dec_num);
quotient = dec_num;
i=1;
//Storing the octal value in octalno[] array
while (quotient!=0)
{
octalno[i++]=quotient%8;
quotient=quotient/8;
}
//Printing the octalno [] in reverse order
printf("\nThe Octal of %ld is:\n\n",dec_num);
63

for (j=i-1;j>0;j--) //input from user


//display it System.out.print("Enter a Decimal
printf ("%d", octalno[j]); number : ");
return 0; int decimal = sc.nextInt();
} //integer array for storing octal digits
int octal[] = new int[20];
int i = 0;
//writing logic for the conversion
C++ Code : while(decimal > 0)
//C++ Program {
//decimal to octal conversion int r = decimal % 8;
#include <iostream> octal[i++] = r;
#include <math.h> decimal = decimal/8;
using namespace std; }
// Function to convert a decimal number to octal //printing result
int convert(int decimal) System.out.print("Octal number : ");
{ for(int j = i-1 ; j >= 0 ; j--)
int i = 1, octal = 0; System.out.print(octal[j]);
//converting decimal to octal //closing scanner class(not compulsory,
while (decimal != 0) but good practice)
{ sc.close();
int rem = decimal % 8; }
decimal /= 8; }
octal += rem * i;
i *= 10;
Python Code :
}
return octal; #take decimal number
} Dec_num = 598
//main program #convert using oct() function
int main() Oct_num = oct(Dec_num)
{ #print number
int decimal,octal; print('Number after conversion is :' + str(Oct_num))
cout << “Enter a decimal number: “;
//user input
cin >> decimal;
//calling function
octal = convert(decimal);
//printing output
cout << decimal << ” in decimal = “ << octal << ” in
octal”;
return 0;
}

Java Code :
//Java program to convert decimal number to octal number
import java.util.Scanner;
public class Decimal_To_Octal
{
public static void main(String args[])
{
//scanner class object creation
Scanner sc = new Scanner(System.in);
64

case '3':
Chapter 33. Octal to Binary printf("011"); break;
case '4':
conversion : printf("100"); break;
case '5':
Octal to binary conversion:-
printf("101"); break;
The C program helps to convert octal numbers to binary
case '6':
numbers. In this program, the user is asked to insert an
printf("110"); break;
octal number and by using a loop or if-else statement, the
case '7':
user can convert an octal number to binary number. An
printf("111"); break;
integer variable is required to be used in the program.
//for invalid case
default:
Working:
printf("\n Invalid octal digit %c ", octalnum[i]);
Step 1: Start
return 0;
Step 2: Ask the user to enter an octal number as an input.
}
Step 3: Store the inserted number in the array octal num.
i++;
Step 4: With the help of switch statement, evaluate every
}
number of the octal number
return 0;
Step 5: Print the equal binary value in a 3 digit number (Eg.
}
000)
Step 6: Do step 4 under the while loop.
Step 7: Stop
C++ Code :
//C++ Program
C Code : // Octal to Binary conversion
#include <iostream>
/*
#include <math.h>
* C Program to Convert Octal to Binary number
using namespace std;
*/
//Function to convert octal to binary
#include<stdio.h>
long convert(int octal)
#include<conio.h>
{
int decimal = 0, i = 0;
#define MAX 1000
long binary = 0;
//converting octal to decimal
int main()
while(octal != 0)
{
{
char octalnum[MAX];
int rem = octal%10;
//For initialize
int res=rem * pow(8,i);
long i = 0;
decimal += res;
//taking user input of octalnum
i++;
printf("Insert an octal number: ");
octal/=10;
scanf("%s", octalnum);
}
printf("Equivalent binary number: ");
i = 1;
while (octalnum[i])
//converting decimal to binary
{
while (decimal != 0)
//use switch case for multiple condition
{
switch (octalnum[i])
int rem = decimal % 2;
{
binary += rem * i;
case '0':
decimal /= 2;
printf("000"); break;
i *= 10;
case '1':
}
printf("001"); break;
return binary;
case '2':
}
printf("010"); break;
//main program
65

int main() //printing result


{ System.out.print("Binary number : ");
int octal; for(int j = i-1 ; j >= 0 ; j--)
cout << “Enter an octal number: “; System.out.print(binary[j]+" ");
//user input //closing scanner class(not compulsory,
cin >> octal; but good practice)
//function call sc.close();
long binary = convert(octal); }
//printing output }
cout << octal << ” in octal = “ << binary << ” in
binary”;
return 0;
Python Code :
} #octal number with prefix 0o/0O
oct_num = 0o564
#using bin() to convert octal number to binary
Java Code :
bin_num = bin(oct_num)
//Java program to convert octal number to binary number #print binary Number
import java.util.Scanner; print('Number after conversion is :' + str(bin_num))
public class Octal_To_Binary
{
public static void main(String args[])
{
//scanner class object creation
Scanner sc = new Scanner(System.in);
//input from user
System.out.print("Enter a octal number
: ");
int octal = sc.nextInt();
//Declaring variable to store decimal
number
int decimal = 0;
//Declaring variable to use in power

int n = 0;
//writing logic for the octal to decimal
conversion
while(octal > 0)
{
int temp = octal % 10;
decimal += temp *
Math.pow(8, n);
octal = octal/10;
n++;
}
int binary[] = new int[20];
int i = 0;
//writing logic for the decimal to binary
conversion
while(decimal > 0)
{
int r = decimal % 2;
binary[i++] = r;
decimal = decimal/2;
}
66

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 decimal
return decimal;
number.
}
//main program
Step 6. Stop
int main()
{
int octal;
C Code : cout << “Enter an octal number: “;
//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;
//Taking input from user Java Code :
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++;
}
//printing result
System.out.println("Decimal number :
Chapter 35. Quadrants in
"+decimal);
//closing scanner class(not compulsory,
which a given coordinate
but good practice)
sc.close();
lies :
} The C program reads the coordinate point in a xy
} coordinate system and identifies the quadrant. The program
takes X and Y. On the basis of x and y value, the program
will identify on which quadrant the point lies. The program
Python Code : will read the value of x and y variables. If-else condition is
used to identify the quadrant of the given value.
#take octal number
#with prefix 0o[zero and o/O] Ex:- X and Y coordinates are 20, 30 these lie in 4th
oct_num = 0o512 quadrant because in mathematics quadrants rules are
#convert octal number to integer following
#integers are with base 10
deci_num = int(oct_num) ● x is positive integer and y is also positive
#print number integer so-that quadrant is a first quadrant.
print('Number after conversion is :' + str(deci_num)) ● x is negative integer and y is positive integer
so-that Quadrant is a second quadrant.
● x is negative integer and y is also negative
integer so -that Quadrant is a third quadrant.
● x is positive integer and y is negative integer
so-that is a first quadrant.

Working:

Step 1: Start
Step 2: The user asked to put value for x and y variables
Step 3: If-else condition is used to determine the value of
the given value
Step 4: Check the condition, if x variable’s value is greater
than 0 and the variable y is greater than 0.
Step 5: If the condition is true then print the output as the
first quadrant.
Step 6: If the condition is false then check the condition if x
is lesser than 0 and the y variable is greater than 0.
68

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


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

C++ Code :
//C++ program
//Quadrants in which coordinates lie
#include<iostream>
using namespace std;
//main program
int main()
69

{
Chapter 36. Permutations long int n,r,permutation,temp;
long int numerator, denominator;
in which n people can
// Insert the num of people
occupy r seats in a
printf("\nEnter the number of persons : ");
classroom :
scanf("%ld",&n);
C programming helps in identifying the r number of seats
that can be occupied by n number of people. Such a
// Insert the num of seats
program is known as the possible permutations. Here, We
need to write a code to find all the possible permutations in
printf("\nEnter the number of seats available : ");
which n people can occupy or number of seats in a
classroom/theater.
scanf("%ld",&r);
// Base condition
N students are looking to find r seats in a classroom. Some
// Swap n and r when n is less than r
of the seats are already occupied and only a few can be
accommodated in the classroom. The available seats are
if(n < r)
assumed as r and n number of people are looking to
{
accommodate within the room.
temp=n;
n=r;
Permutations in which n people can occupy r seats in a
r=temp;
classroom in C programming
}
Way 2 Of Asking Question
numerator=fact(n);
Write code to find all possible permutations in which n
denominator=fact(n-r);
people can occupy r seats in a theater
permutation=numerator/denominator;
printf("\nNum of ways people can be seated : ");
Working:
printf("%ld\n",permutation);
Step 1: Start
}
Step 2: Ask the user to insert n number of people and the
number of seats as r.
Step 3: Calculate permutation, p(n,r).
Step 4: Enter the program to calculate permutation P(n,r) = C++ Code :
n! / (n-r)!
Step 5: Print the calculated result. //C++ Program
Step 6: Stop //Permutations in which n people can occupy r seats
#include<iostream>
using namespace std;
//function for factorial
C Code : int factorial(int num)
{
#include<stdio.h>
int fact=1;
for(int i=num;i>=1;i–)
// Program to find the factorial of the number
fact*=i;
int factorial (long int x)
return fact;
{
}
long int fact=1,i;
//main program
for(i=1;i<=x;i++)
int main()
{
{
fact=fact*i;
int n,r;
}
cout<<“Enter number of people: “;
return fact;
//user input
}
cin>>n;
int main()
cout<<“Enter number of seats: “;
70

//user input N = int(input('Enter the number of students :'))


cin>>r; R = int(input('Enter the number of seats :'))
//if there are more people than seats #factorial by using factorial() function
if(r<n) nume = math.factorial(N)
{ deno = math.factorial(N-R)
cout<<“Cannot adjust “<<n<<” people on “<<r<<” #permutation = n! / (n-r)!
seats”; no_of_ways = nume//deno
return 0; #print total no of ways
} print('Total number of ways are :' + str(no_of_ways))
//finding all possible arrangements of n people on r
seats
// by using formula of permutation
int p = factorial(r)/factorial(r–n);
//printing output
cout<<“Total arrangements: “<<p;
return 0;
}

Java Code :
import java.util.*;
import java.io.*;

class PrepInsta
{
public static void main(String[] args)
{
int n, r, per, fact1, fact2;
Scanner sc = new Scanner(System.in);
System.out.println(“Enter the Value of n and r”);
n = sc.nextInt();
r = sc.nextInt();
fact1 = n;
for (int i = n – 1; i >= 1; i=i-1)
{
fact1 = fact1 * i; //calculating factorial (n!)
}
int number;
number = n – r;
fact2 = number;
for (int i = number – 1; i >= 1; i=i-1)
{
fact2 = fact2 * i; //calculating factorial ((n-r)!)
}
per = fact1 / fact2; //calculating nPr
System.out.println(per+“ways”);
}
}

Python Code :
#import math lib
import math
#take user inputs
71

}
Chapter 37. Maximum
number of handshakes:
Java Code :
In C programming, there’s a program to calculate the
number of handshakes. The user is asked to take a number // Java program to find maximum number of handshakes
as integer n and find out the possible number of import java.io.*;
handshakes. For example, if there are n number of people import java.util.*;
in a meeting and find the possible number of handshakes
made by the person who entered the room after all were class handshakes
settled. {
// Calculating the maximum number of handshakes
Working: static int maxHandshake(int n)
Step 1: Start {
Step 2: The user is asked to insert an integer value n, return (n * (n – 1)) / 2;
representing the number of people }
Step 3: Find nC2, and calculate as n * (n – 1) / 2.
Step 4: Print the outcome derived from the above program
Step 5: Stop // Driver code
public static void main (String[] args)
{
C Code : Scanner sc=newScanner(System.in);
int n = sc.nextLine();
// C program to find the maximum number of handshakesM
System.out.println( maxHandshake(n));
#include<stdio.h>
}
int main()
}
{
//fill the code
int num; Python Code :
scanf("%d",&num);
int total = num * (num-1) / 2; // Combination nC2 #take user inputs
printf("%d",total); N = int(input('Enter number of people available :'))
return 0; #formula
} no_of_handshakes = int(N *((N-1)/2))
#print number of no_of_handshakes
print('Maximum number of handshakes can be :' +
C++ Code : str(no_of_handshakes))
//C++ Program
//Maximum number of handshakes
#include<iostream>
using namespace std;
//main program
int main()
{
int p;
cout<<“Enter number of Persons: “;
//user input
cin>>p;
cout<<“Maximum number of handshakes: “;
//find maximum number of handshakes using formula
int max=p*(p–1)/2;
//printing output
cout<<max;
return 0;
72

// Trick part. Reduce it to the simplest form by using gcd.


Chapter 38. Addition of two for(c=1; c <= x && c <= y; ++c)
{
fractions: if(x%c==0 && y%c==0)
gcd_no = c;
n this C program we will find sum of two fraction using C
}
//To display fraction of givien numerators and
To find the sum of two fractions we will be using the
denominators
concept of LCM and GCD.
printf("\nThe added fraction is %d/%d
",x/gcd_no,y/gcd_no);
For example: we have to find the sum of 6/2 and 16/3
printf("\n");
return 0;
Firstly the LCM of 2 and 3 will be found. Using the LCM
}
we will convert the numerators i.e. 6 and 16 into digits that
can be added and sum of those digits is found, lastly
normalization is done using the GCD of sum and LCM.
C++ Code :
Working:
Step 1. Start. //C++ Program
Step 2.Initialize variables of numerator and denominator //Adding two fractions
Step 3. Take user input of two fraction #include <iostream>
Step 4. Find numerator using this condition (n1*d2) using namespace std;
+(d1*n2 ) where n1,n2 are numerator and d1 and d2 are //main Program
denominator . int findGCD(int n1, int n2)
Step 5. Find denominator using this condition (d1*d2) for {
lcm. int gcd;
Step 6. Calculate GCD of this new numerator and for(int i=1; i <= n1 && i <= n2; i++)
denominator . {
Step 7. Display a two value of this condition x/gcd,y/gcd); if(n1%i==0 && n2%i==0)
Step 8. Stop. gcd = i;
}
return gcd;
C Code : }
int main()
#include <stdio.h>
{
int main()
int num1,den1;
{
cout << “Enter numerator and denominator of first
//for initialize variables
number: “;
int numerator1,
//user input
denominator1,numerator2,denominator2,x,y,c,gcd_no;
cin >> num1 >> den1;
//To take user input of numerators and denominators
int num2,den2;
printf("\nEnter the numerator for 1st number : ");
cout << “Enter numerator and denominator of second
scanf("%d",&numerator1);
number: “;
printf("\nEnter the denominator for 1st number : ");
//user input
scanf("%d",&denominator1);
cin >> num2 >> den2;
printf("\nEnter the numerator for 2nd number : ");
//finding lcm of the denominators
scanf("%d",&numerator2);
int lcm = (den1*den2)/findGCD(den1,den2);
printf("\nEnter the denominator for 2nd number : ");
//finding the sum of the numbers
scanf("%d",&denominator2);
int sum=(num1*lcm/den1) + (num2*lcm/den2);
//numerator
//normalizing numerator and denominator of result
int num3=sum/findGCD(sum,lcm);
x=(numerator1*denominator2)+(denominator1*numerator2
lcm=lcm/findGCD(sum,lcm);
);
//printing output
//denominator
cout<<num1<<“/”<<den1<<” +
y=denominator1*denominator2;
“<<num2<<“/”<<den2<<” = “<<num3<<“/”<<lcm;
73

return 0; //logic for getting simplified fraction


} int n = 1;
int p = num;
int q = den;
if( num != den)
Java Code : {
//Java program to add two fractions while(n != 0)
import java.util.Scanner; {
public class add_two_fractions //storing remainder
{ n = num % den;
public static void main(String[] args)
{ if(n != 0)
//scanner class declaration {
Scanner sc = new Scanner(System.in); num = den;
//input from the user den = n;
System.out.print("Enter numerator for first }
fraction : "); }
int num1 = sc.nextInt(); }
System.out.print("Enter denominator for first System.out.println("("+p/den+" / "+q/den+")");
fraction : "); //closing scanner class(not compulsory, but good
int den1 = sc.nextInt(); practice)
System.out.print("Enter numerator for second sc.close();
fraction : ");
int num2 = sc.nextInt(); }
System.out.print("Enter denominator for second }
fraction : ");
int den2 = sc.nextInt();
int num, den, x;
System.out.print("("+num1+" / "+den1+") +
Python Code :
("+num2+" / "+den2+") = "); #take inputs
//logic for calculating sum of two f1_nume = int(input('Enter the numerator for 1st fraction
fractions :'))
if(den1 == den2) f1_deno = int(input('Enter the denominator for the 1st
{ fraction :'))
num = num1 + num2 ; f2_nume = int(input('Enter the numerator for 2nd fraction
den = den1 ; :'))
} f2_deno = int(input('Enter the denominator for the 2nd
else{ fraction :'))
num = (num1*den2) + (num2*den1); #check if denominators are same
den = den1 * den2; if(f1_deno == f2_deno):
} #add numerator
if(num > den) Fraction = f1_nume + f2_nume
x = num; #print
else print('Addition of two fractions are :' + str(Fraction) + '/'
x = den; + str(f1_deno))
for(int i = 1 ; i <= x ; i++) #if denominators are not same
{ else:
if(num%i == 0 && den%i == #to find the sum
0) #denominators should be same
{ #apply cross Multiplication
num = num/i; Fraction = (f1_nume * f2_deno) + (f2_nume * f1_deno)
den = den/i; print('Addition of fractions are :' + str(Fraction) + '/' +
} str(f1_deno * f2_deno))
}
74

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

//scanner class declaration for i in s:


Scanner sc = new Scanner(System.in); if(i==‘0’):
//input from the user l.append(‘1’)
System.out.print("Enter the number : else:
"); l.append(i)
int number = sc.nextInt(); ns=“”
//convert the number to string and then for i in l:
calculate its length ns+=i
String str = Integer.toString(number); print(int(ns))
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
str1 = str1 +
str.charAt(i);
}
System.out.println("Output : "+str1);
//closing scanner class(not compulsory,
but good practice)
sc.close();

}
}

Python Code :
Method 1 :
#taking Input
n=int(input())
#converting into string
n=str(n)
#then into the list
n=list(n)
r=” #empty string for addind it the item of list
for i in range(len(n)):
#if we find ‘0’ we will replace it with ‘1’
if(n[i]==‘0’):
n[i]=‘1’
r=r + n[i] #creating the new integer
del n
print(int(r))

Method 2 :
n=int(input(“Enter any number”))
s=str(n)
l=[]
76

Chapter 40. Can a number }


}
be expressed as a sum of
if(flag == 0)
two prime numbers : printf(“%d cannot be expressed as the sum of two
primes\n”, n)
The program in C takes a positive integer or number which
is required to be inserted by the user. The program further
return 0;
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
int sum_of_two_primes(int n)
integer can be expressed as sum of two prime numbers as a
{
result.
int i, isPrime = 1;
for(i = 2; i <= n/2; ++i)
Working:
{
Step 1: Start
if(n % i == 0)
Step 2: Ask the user to insert a number as an input.
{
Step 3: Initiate the value of i in a loop from 2 up to half the
isPrime = 0;
value of the entered number.
break;
Step 4: Check if i is a prime number.
}
Step 5: If i is a prime number, identify if (n – 1) is a prime
}
number.
return isPrime;
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).
Step 7: Stop
C++ Code :
//C++ Program
C Code : //Number expressed as sum of two prime numbers
#include<iostream>
// C program to check whether a number can be expressed
using namespace std;
as a sum of two prime numbers
// Function to check prime number
int Prime(int num)
#include<stdio.h>
{
int sum_of_two_primes(int n);
int div=0;
int main()
for(int i=1;i<=num;i++)
{
{
int n, i;
if(num%i==0)
div++;
printf(“Insert the num: “);
}
scanf(“%d”, &n);
if(div==2)
int flag = 0;
return 1;
for(i = 2; i <= n/2; ++i)
return 0;
{
}
// Condition for i to be prime
int main()
if(sum_of_two_primes(i) == 1)
{
{
int check = 0, n;
if(sum_of_two_primes(n-i) == 1)
cout<< “Enter a positive integer: “;
{
//user input
printf(“\n%d can be expressed as the sum of %d
cin>>n;
and %d\n\n”, n, i, n – i);
for(int i = 1; i <= n/2;i++)
flag = 1;
{
}
// condition for i to be a prime number
77

if (Prime(i)) int c = 1;
{ for(int i = 2 ; i < n ; i++)
// condition for n-i to be a prime number {
if (Prime(n–i)) if(n % i == 0)
{ {
cout<<n <<” = “<< i <<” + “ << n–i<< c = 0;
endl; break;
check = 1; }
} }
} return c;
} }
if (check == 0)
cout<<n<<” cannot be expressed as the sum of
two prime numbers.”;
Python Code :
return 0; #take input
} Number = int(input('Enter the Number :'))
#initialize an array
arr = []
Java Code :
#find prime numbers
//Java program to check whether a number can be for i in range(2,Number):
expressed as a sum of two prime numbers flag = 0
import java.util.Scanner; for j in range(2,i):
public class number_as_sum_of_two_prime_numbers if i % j == 0:
{ flag = 1
public static void main(String[] args) #append prime numbers to array
{ if flag == 0:
//scanner class declaration arr.append(i)
Scanner sc = new Scanner(System.in); #possible combinations
//input from user flag = 0
System.out.print("Enter a number : "); for i in range(len(arr)):
for j in range(i+1,len(arr)):
int number = sc.nextInt(); #if condition is True Print numbers
int x = 0; if(arr[i] + arr[j] == Number):
for(int i = 2 ; i <= number/2 ; i++) flag = 1
{ print(str(arr[i]) + " and " + str(arr[j]) + ' are prime
if(prime_or_not(i) == 1) numbers when added gives ' + str(Number))
{ break
if(flag == 0):
if(prime_or_not(number-i) == 1) print('No Prime numbers can give sum of ' + str(Number))
{

System.out.println(number+ " = "+i+" + "+(number-i));


x = 1;
}
}
}
if(x == 0)

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


sum of two prime numbers");
}
//function for checking number is prime or not
public static int prime_or_not(int n)
{
78

cnt[k] += cnt[k-2];
Chapter 41. Count possible }
return cnt[a];
decodings of a given digit }

sequence : int main()


{
The decoding programs are the most possible questions
char dig[15];
asked and are largely practiced in C programming. The
printf("\n Enter the sequence : ");
program counts the number of possible decodings of the
gets(dig);
entered digit by the user of the given sequence.
int a = strlen(dig);
For example, if the digit sequence is “12” then there are
printf("\n Possible count of decoding of the sequence :
two possible decodings for this – One of them is ‘AB’
%d\n", cnt_decoding_digits(dig, a));
when we decode 1 as ‘A’ and 2 as ‘B’. Now we can also
return 0;
decode this digit sequence “12” as ‘L’ when we decode
}
digits 1 and 2 taken together as an integer 12
Way 2 of asking Question
Count possible decodings of a given digit sequence - C++ Code :
Working: //Count possible decodings of a given digit sequence
Step 1: Start #include<iostream>
Step 2: User is required to insert a digit sequence as an #include<string.h>
input using namespace std;
Step 3: Set count = 0 //function to count the number of decodings
Step 4: If the last number is not a zero, then return for the int countDecoding(char *digit, int n)
next remaining (n-1) numbers and add the results then to {
the total count. int decodings[n+1];
Step 5: If the last two digits form a valid variable (or decodings[0]=1;
smaller than 27), return for the remaining (n-2) numbers decodings[1]=1;
and add the outcome to the total calculation. //counting decodings
Step 6: Stop for(int i=1;i<=n;i++)
{
int q=digit[i]-48;
C Code : int p=digit[i-1]-48;
if(q>0 && q<=26)
//C Program to Count possible decodings of a given digit
decodings[i+1]=decodings[i];
sequence
if((q + p*10)>0 && (q + p*10) <=26)
#include<stdio.h>
decodings[i+1]
#include<math.h>
+=decodings[i-1];
}
int cnt_decoding_digits(char *dig, int a)
return decodings[n];
{
}
// Initializing an array to store results
//main program
int cnt[a+1];
int main()
cnt[0] = 1;
{
cnt[1] = 1;
char digit[20];
cout<<"Input: ";
for (int k = 2; k <= a; k++) { cnt[k] = 0;
//user input
// If the last digit not equal to 0, then last digit must
gets(digit);
added to the number of words if (dig[k-1] > '0')
int n = strlen(digit);
cnt[k] = cnt[k-1];
//calling function and printing output
cout<<"Number of decoding of the sequence
// In case second last digit is smaller than 2 and last digit
"<<digit<<" are "<<countDecoding(digit,n);
is smaller than 7, then last two digits form a valid character
return 0;
if (dig[k-2] == '1' || (dig[k-2] == '2' && dig[k-1] < '7') )
}
79

Chapter 42. Check whether elseif((c >= 'a' && c= 'A' && c <= 'Z'))
prinf("\n not a alphabet\n");
a character is a vowel or
else
consonant : printf("%c is a consonant", c);
Given a character, check if it is a vowel or consonant.
return 0;
Vowels are in Uppercase ‘A’, ‘E’, ‘I’, ‘O’, ‘U’ and
}
Lowercase ‘a’, ‘e’, ‘i’, ‘o’, ‘u’. and All other characters
both uppercase and lowercase (‘B’, ‘C’, ‘D’, ‘F’,’ b’, ‘c’,’
d’, ‘f’,…..) are consonants. In this article, we will show C++ Code :
you, How to write a C program to check Vowel or
Consonant with an example. //C++ Program to check whether alphabet is vowel or
consonant
Working: #include <iostream>
We check whether a given character matches any of the 5 using namespace std;
vowels. If yes, we print “Vowel”, else we print //main function
“Consonant”. int main()
{
This C program allows the user to enter any character and char c;
check whether the user specified character is Vowel or cout<<"Enter an alphabet: ";
Consonant using If Else Statement. cin>>c;
This program takes the character value(entered by user) as //checking for vowels
input.
And checks whether that character is a vowel or consonant if(c=='a'||c=='e'||c=='i'||c=='o'||c=='u'||c=='A'||c=='E'||c=='I'||c
using if-else statement. =='O'||c=='U')
Since a user is allowed to enter an alphabet in lowercase {
and uppercase, the program checks for both uppercase and cout<<c<<" is a vowel"; //condition
lowercase vowels and consonants. true input is vowel
And now we have to follow step’s of C programming }
else
{
C Code : cout<<c<<" is a consonant";
//condition false input is consonant
#include <stdio.h>
}
int main()
return 0;
{
}
char c;
int isLowerVowel, isUpperVowel;
printf("Enter an alphabet: "); Java Code :
scanf("%c",&c);
//JAVA Program to check whether the character entered by
//To find the corrector is lowercase vowel user is Vowel or Consonant.
isLowerVowel = (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c
== 'u'); import java.util.Scanner;
//To find the character is Upper case vowel public class vowelorconsonant
isUpperVowel = (c == 'A' || c == 'E' || c == 'I' || c == 'O' || c {
== 'U'); //class declaration
// compare to charector is Lowercase Vowel or Upper case public static void main(String[] args)
Vowel {
//main method declaration
if (isLowerVowel || isUpperVowel) Scanner sc=new Scanner(System.in);
printf("%c is a vowel", c); //scanner class object creation
//to check character is alphabet or not
System.out.println(" Enter a character");
80

char c = sc.next().charAt(0);
//taking a character c as input from user

if(c == 'A' || c == 'E' || c == 'I' || c == 'O' ||


c == 'U'

|| c == 'a' || c == 'e' || c == 'i' || c == 'o' || c


== 'u') //condition for the vowels
Chapter 43. Check whether
System.out.println(" Vowel");
a character is a alphabet or
else if((c >= 'A' && c <= 'Z') || (c >= 'a'
&& c <= 'z')) //condition for the consonants not :
System.out.println(" The C program checks whether the character entered is an
Consonant"); alphabet or not. The program makes use of character value
else inserted by the user. This value can range between
System.out.println(" Not an lowercase or uppercase alphabets, such as ‘a’ and <= ‘z’
Alphabet"); and ‘A’ and <= ’Z’. If the character inserted by the user lies
between the above category or ranges then the character is
sc.close() //closing scanner class(not an alphabet and if it does not lie within the given range then
mandatory but good practice) it is not.
} //end of main method
} //end of class Working:
Step 1: Start.
Step 2: Insert a character (by the user).
Step 3: Check whether the character lies between a to z and
Python Code : A to Z, if true, print “Alphabet”.
#get user input Step 4: condition is false print” not an alphabet”.
Char = input() Step 5: Stop
#Check if the Char belong to set of Vowels
if (Char == 'a' or Char == 'e' or Char == 'i' or Char == 'o' or C Code :
Char == 'u'):
#if true //C Program to find character is alphabet or not
print("Character is Vowel") #include<stdio.h>
else: #include<conio.h>
#if false int main()
print("Character is Consonant") {
char a;

//Requesting user to insert the character


printf("Insert any character: ");

//keeping the inserted character into the variable a


scanf("%c",&a);

if( (ch>='a' && ch<='z') || (ch>='A' && ch<=Z'))


printf("The inserted character %c is an Alphabet”, a);

else
printf("The entered character %c is not an Alphabet”, a);
return 0;
}
81

C++ Code : System.out.println(c + " is an


Alphabet");
//Character is Alphabet or not else
#include<iostream> System.out.println(c + " is
using namespace std; not an Alphabet");
sc.close();
//main program //closing scanner class(not compulsory, but good practice)
int main() } //end
{ of the main method
}
char alpha;
cout<<"Enter a character: ";
cin>>alpha; Python Code :
n=input()
//checking for alphabet using ASCII value
#ASCII value of the input
if((alpha>=65 && alpha<=90)||(alpha>=97 &&
x=ord(n)
alpha<=122))
if(65<=x<=90 or 97<=x<=122):
{
print(‘yes’ , n , ‘is an Alphabet’)
else:
//input lies in range
print(‘No’ , n , ‘is not an Alphabet’)
cout<<alpha<<" is an alphabet ";
}

else
{
//input does not lie in range
cout<<alpha<<" is not an alphabet ";
}
return 0;
}

Java Code :
//Java program to check whether the character entered by
the user is an alphabet or not.
import java.util.Scanner;
public class alphabetornot
{
//class declaration
public static void main(String[] args)
{
//main method
declaration
char c;
Scanner sc = new Scanner(System.in);

System.out.print("Enter a Character : ");


//Input character
c = sc.next().charAt(0);

//condition for
checking characters
if((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'))
82

cout<<"Enter the radius: ";


Chapter 44. Calculate the cin>>rad;
float circleArea = 3.14 * rad * rad;
area of a circle : cout<<"Area of the circle of radius "<<rad<<" is
"<<circleArea;
I am going to tell you about finding an area of a circle in C
return 0;
programming.The area of a circle is the number of square
}
units inside the circle. Standard formula to calculate the
area of a circle is: A=πr² .where π =22/7( value is 3.141 )

You can compute the area of a Circle if you know its Java Code :
radius, by simple formula A = 3.14 * r * r in C
//Java program to calculate area of a circle
programming.We allow the user to enter radius, and then
import java.util.Scanner;
find the area of the cirle.
public class area_of_circle
{
Working:
public static void main(String[] args)
1. initialization of radius.
{
//scanner class declaration
2. calculate the area of circle
Scanner sc = new Scanner(System.in);
area=3.14*radius*radius.
//input from the user
System.out.print("Enter the radius of a
C Code : circle : ");
double radius = sc.nextFloat();
#include<stdio.h>
int main()
{
//formula for area of a circle
double area = 3.14 * radius * radius;
//for initialization of radius and area in a float datatype
float radius,area,pi=3.14;
System.out.println(area);

// for use user input


//closing scanner class(not compulsory, but good
practice)
printf("Enter the Radius of a Circle : ");
sc.close();
scanf("%f",&radius);
}
}
//formula of area of circle

area = pi*radius*radius; Python Code :


from math import pi
printf("Area of Circle is: %f",area);
r=float(input(“Enter radius of circle :”))
return 0;
area=pi*r*r
}
print(“The area of circle is”,end=” “)
print(area)
from math import pi
C++ Code : d=float(input(“Enter diameter of circle :”))
area=(pi*d*d)/4
//C++ Program
print(“The area of circle is”,end=“”)
// area of circle
print(area)
#include<iostream>
using namespace std;
int main()
{
float rad;
83

Chapter 45. Find the ASCII cout<<"The ASCII value of "<<val<<" is "<<(int)val;
return 0;
value of a character : }
ASCII value can be any integer number between 0 and 127
and consists of character variables instead of the character Java Code :
itself in C programming. The value derived after the
programming is termed as ASCII value. With the help of //Java program to print ASCII values of a character
casting the character to an integer, the ASCII value can be
derived. Every character has an individual ASCII value that import java.util.Scanner;
can only be an integer. Every time the character is stored class Main
into a variable, as a substitute for keeping the character {
itself, the ASCII value of the specific character will get public static void main(String[] args)
stored. {
Working: //scanner class object creation
Step 1: Start Scanner sc=new Scanner(System.in);
Step 2: Ask the user to insert any character
Step 3: The character will be assigned to the variable ‘a’ //input from user
Step 4: Scan the character variable to find out the ASCII System.out.print("Enter a Character: ");
value of the character char c=sc.next().charAt(0);
Step 5: Stop
//typecasting from character type to
integer type
C Code : int i = c;
/* C Program to identify ASCII Value of a Character */
//printing ASCII value of the character
#include<stdio.h>
System.out.println("ASCII value of
#include<conio.h>
"+c+" is "+i);
int main()
{
//closing scanner class(not compulsory,
char a;
but good practice)
sc.close();
printf("\n Kindly insert any character \n");
}
scanf("%c",&a);
}
printf("\n The ASCII value of inserted character = %d",a);
return 0;
} Python Code :
#user input
C++ Code : Char = input('Enter the character :')
#convert Char to Ascii value
//C++ program to calcualte ASCII value of Character
Asciival = ord(Char)
#include<iostream>
#print Value
using namespace std;
print(Asciival)
//main program
int main()
{
char val;
cout<<"Enter a character: ";
cin>>val;

//printing the ASCII value of input


//through typecasting
84

}
Chapter 46. Find the prime
numbers between 1 to 100 :
C++ Code :
We know that the whole number is the basic counting
number 0,1,2,3….and so on.So A whole number greater //Cpp Code to find prime number between 1 to 100
than 1 that can not be made by multiplying other whole #include <iostream>
numbers. using namespace std;
///Main Function
Example-7 is a prime number because 7 is only divisible by int main()
one or itself.It can not be divisible by 2,3,4,5,6. {
int i,j,count=0;
So a prime number has two factors: 1 and the number itself
is called prime numberThe number 1 is neither prime nor //Print prime number between 1 to 100
composite. cout<<"print prime number between 1 to 100\n";

Working: //For loop for printing values between 1 to 100


for(i=2;i<=100;i++)
● First of all we will initialize i,j and count=0
{
variable.
for(j=1;j<=i;j++)
● the loop is start i=2 to less than equal 100 and
{
second loop start j=1 to less then or equal i.
if(i%j==0)
● the condition is i%j=0.
count++;
● and the value of count is incremented after the
iteration of the loop.
}
● and then count values equal to two then print the
if(count==2)
i. because the prime number has only two factors,
cout<<" "<<i;
one is 1 and another by the number.
count=0;
}
C Code : return 0;
}
//C Code to print prime number 1 to 100
#include <stdio.h>
Java Code :
//Java Program to find prime no 1 to 100
//Main function
public class Main
int main()
{
{
public static void main(String[] args)
int i,j,count=0;
{
int i,j,count=0;
//print values between 1 to 100
printf("The value between 1 to 100\n");
//print prime no between 1 to 100
System.out.println("prime number between 1 to 100\n");
for(i=2;i<=100;i++)
{
//loop for printing prime no between 1 to 100
for(j=1;j<=i;j++)
for(i=2;i<=100;i++)
{
{
if(i%j==0)
for(j=1;j<=i;j++)
count++;
{
}
if(i%j==0)
if(count==2)
count++;
printf("%d",i);
}
count=0;
if(count==2)
}
85

System.out.print(" "+i);
count=0;
}
}

Python Code :
#To find the prime numbers between 1 to 100
li=[] #list of prime numbers will be stored here
for i in range(2,101):
f=0
for j in range(2,i+1):
if(i!=j and i%j==0): #if any n
f=1
break

if(f==0):
li.append(i)
print(‘Prime numbers between 1 to 100:’)
print(*li,sep=‘ ‘)

Chapter 47. Calculate the


number of digits in an
integer :
Today, we will be learning how to code a C program for
finding the digits in an integer entered by a user. An integer
is made up of a group of digits, i.e; it is a combination of
digits from 0-9

Here we will use loops along with an arithmetic


operator.This program takes an integer from the user and
calculates the number of digits. For example: If the user
enters 6589, the output of the program will be 4.
Working:
Step 1: Start
Step 2: The user is asked to insert an integer or number
Step 3: The variable entered by user is stored in variable ‘a’
Step 4: The while loop is iterated till the last expression.
Step 5: After the count, printf “Number of digits”
Step 6: Stop

C Code :
#include <stdio.h>

int main()
86

{ //output
//to initialize of variable cout<<"Number of digits in the given integer is: "<<digit;
int count=0; return 0;
int n,c; }

//to take user input


printf("enter the number: ");
Java Code :
scanf("%d",&n); //Java program to find number of digits in an integer
c=n; import java.util.Scanner;
public classnumber_of_digits
//when number is zero {
if(n==0) public static void main(String[] args)
printf("digit is 1"); {
//false condition //scanner class declaration
Scanner sc = new Scanner(System.in);
else
{ //input from user
while(n!=0) System.out.print("Enter an Integer : ");
{
//find last digit of number int number = sc.nextInt();
n=n/10;
//count of a number //declare a variable to count number of
++count; digits
} int digit = 0;
printf("the total digit in giving number %d is : while(number != 0)
%d",c,count); {
} //pick last digit of the number
return 0; and count one by one
} int pick_last = number % 10;
digit++;
number = number / 10;
C++ Code :
}
//C++ Program
//Number of Digits in an Integer //display number of digits
System.out.print("Number of Digits =
#include<iostream> "+digit);
using namespace std;
//closing scanner class(not compulsory,
int main() but good practice)
{ sc.close();
}
int num,digit=0; }
cout<<"Enter any num : ";
//user input
cin>>num;
Python Code :
#get the user input
//loop to find number digits Integer = int(input('Enter an integer :'))
do #initialize the variable
{ #typecast the integer to string
num=num/10; #store the string
digit++; String = str(Integer)
} #use len() functiomn to find the length of a String
while(num!=0); #print it
print(len(String))
87

string tens_digits = {“”, “ten”, “eleven”, “twelve”,


Chapter 48. Convert “thirteen”, “fourteen”, “fifteen”, “sixteen”, “seventeen”,
“eighteen”,“nineteen”};
digit/number to words : string multiple_of_ten = {“”, “”, “twenty”, “thirty”,
“forty”, “fifty”, “sixty”, “seventy”, “eighty”, “ninety”};
The conversion of numbers in words is just a conversion of
string power_of_ten = {“hundred”, “thousand”};
numeric values to the English format of reading numbers.
cout<<num<<“:\n“;
This code supports the conversion of numbers from 0 –
if (length_of_string == 1){
9999 in English format. Digits have different places when
cout<<ones_digits[num[0] – ‘0’];
read from its ones place to above. Different places for
return;
numbers are:-
}
int x=0;
● Single digits:- Ones
while (x < strlen(num)){
● Two Digits:-Tens
if(length_of_string >= 3){
● Three Digits:- Hundreds
if (num[x] – 48 != 0){
● Four Digits:- Thousands
cout<<ones_digits[num[x] – 48]<<“\n“;
cout<<power_of_ten[length_of_string –
Working:
3]<<“\n“;
length_of_string–;
● Taking input as a string from the user.
}
● Check the length of the input.
}
● if the length is zero print ’empty’ and if the
else{
length is greater than 4 print ‘give a string of
if (num[x] – 48 == 1){
specific length’
sum = (num[x] – 48 + num[x] – 48);
● if length is between 1 – 4, Create arrays for
cout<<tens_digits[sum]);
different values.
return;
● Checking the length of the string.
}
● According to the place of the digit, we will show
else if(num[x] – 48 == 2 and num[x + 1] – 48 ==
the output.
0){
cout<<“twenty”;
C++ Code : return;
}
//C++ program else{
//convert number to text int i = num[x] – 48;
#include<iostream> if(i > 0){
#include<string.h> print(multiple_of_ten[i], end = ” “);
using namespace std; }
//main Program else{
void numToWords(string num) print(“”, end = “”);
{ }
int length_of_string = strlen(num); x += 1;
if (length_of_string == 0){ if(num[x] – 48 != 0){
cout<<“String is Empty”; cout<<ones_digits[num[x] – 48];
return; }
} }
}
if (length_of_string > 4){ x++;
cout<<“Please enter the string with supported }
length”; }
return; int main()
} {
string ones_digits = {“zero”, “one”, “two”, “three”, numToWords(“1121”);
“four”, “five”, “six”, “seven”, “eight”, “nine”}; return 0;
}
88

Python Code :
Chapter 49. Counting
def numToWords(num):
length_of_string = len(num); number of days in a given
if (length_of_string == 0):
print("String is Empty"); month of a year:
return;
if (length_of_string > 4): Number of days in any month of a year can vary
print("Please enter the string with supported length"); specifically in February as the cycle of leap year repeats in
return; every 4 years when the year is leap February gives the
ones_digits = ["zero", "one", "two", "three", "four", count to 29 days but the when the year is not leap it gives
"five", "six", "seven", "eight", "nine"]; count to 28 days and so no of days in a year varies from
tens_digits = ["", "ten", "eleven", "twelve", "thirteen", 365 to 366.
"fourteen", "fifteen", "sixteen", "seventeen", Rather than February every month gives the count of 30 or
"eighteen","nineteen"]; 31 days in any case whether the year is a leap or not.
multiple_of_ten = ["", "", "twenty", "thirty", "forty",
"fifty", "sixty", "seventy", "eighty", "ninety"]; Working:
power_of_ten = ["hundred", "thousand"]; ● Take user inputs like month and year.
print(num, ":", end = " "); ● Check if the given month is February.
if (length_of_string == 1): ● If True Check if the year is a year leap or not.
print(ones_digits[ord(num[0]) - '0']); ● If the year is a leap year Print 29 Days, Else Print
return; 28 Days.
x = 0; ● If Condition in Step 3 is False Check the month.
while (x < len(num)): if (length_of_string >= 3): ● Print the number of days assigned to a specific
if (ord(num[x]) - 48 != 0): Month.
print(ones_digits[ord(num[x]) - 48], end = " ");
print(power_of_ten[length_of_string - 3], end = "
");
C++ Code :
length_of_string -= 1;
else: //C++ program
if (ord(num[x]) - 48 == 1): //to display number of days in a month
sum = (ord(num[x]) - 48 + ord(num[x]) - 48); #include<iostream>
print(tens_digits[sum]); using namespace std;
return; //main Program
elif (ord(num[x]) - 48 == 2 and ord(num[x + 1]) - int main()
48 == 0): {
print("twenty"); //take user inputs for Month and year in integer
return; int Month,Year;
else: cout<<“\nEnter the Month :”;
i = ord(num[x]) - 48; cin>>Month;
if(i > 0): cout<<“\nEnter the Year :”;
print(multiple_of_ten[i], end = " "); cin>>Year;
else: //Check condition for Month and leap year
print("", end = ""); if(Month == 2 && (Year%4 == 0) || ((Year%100 == 0)
x += 1; && (Year%400 == 0)))
if(ord(num[x]) - 48 != 0): cout<<“Number of days is 29”;
print(ones_digits[ord(num[x]) - 48]); else if(Month == 2)
x += 1; cout<<“Number of days is 28”;
numToWords("1121") else if(Month == 1 || Month == 3 || Month == 5 ||
Month == 7 || Month == 8 || Month == 10 || Month == 12)
cout<<“Number of days is 31”;
else
cout<<“Number of days is 30”;
}
89

Chapter 50. Finding


Java Code: Number of times x digit
import java.io.*;
import java.util.*;
occurs in a given input :
class PrepInsta In this C++ program we will count the number of
{ occurrences of a given digit in the given input number.
public static void main(String args[]) The input may lie within the range of integer.
{
int month, year; If the digit does not occur in the input it should print 0 else
Scanner sc = new Scanner(System.in); the count of digits.
System.out.println(“enter the month and year: “);
month=sc.nextInt(); Sample Input :
year=sc.nextInt(); Enter a number : 897982
if(((month==2) && (year%4==0)) || Enter the digit : 9
((year%100==0)&&(year%400==0)))
{ Output : 2
printf(“Number of days is 29”); Explanation : The digit 9 occurs twice
}
else if(month==2) Working:
{
printf(“Number of days is 28”); 1. Start
} 2. Get the input value from the user.
else if(month==1 || month==3 || month==5 || month==7 || 3. Get the digit from the i/o console.
month==8 || month==10 || month==12) 4. Declare variables n,d,count
{ n – Given number
printf(“Number of days is 31”); d – Digit
} count – no. of occurrences
else 5. Take a while loop.
{ 6. Declare a variable k to store every digit of the number to
printf(“Number of days is 30”); be compared.
} 7. Compare k with the digit
} if k equals digit increment count.
} 8. n=n/10
Python Code : 9. Print the value of count.
#take user inputs for Month and year in integer 10. End
Month = int(input('Enter the Month :'))
Year = int(input('Enter the Year :'))
#Check condition for Month and leap year C++ Code :
if(Month == 2 and (Year%4 == 0) or ((Year%100 == 0) and
#include <bits/stdc++.h>
(Year%400 == 0))):
#if condition is TRUE
using namespace std;
print('Number of days is 29')
#if False check for other conditions
int main()
elif(Month == 2):
{
print('Number of days is 28')
//Declare variables
elif(Month == 1 or Month == 3 or Month == 5 or Month
== 7 or Month == 8 or Month == 10 or Month == 12):
int n; //given integer
print('Number of days is 31')
int d; //given digit
else:
int count=0; //declare counter variable
print('Number of days is 30')
cin >> n >> d; // take input from user
90

while(n)
{

int k = n%10; // to store the digits of the given input

n=n/10;

if(k==d) // compare the given digit with digit of input


{
count++; // increment counter variable
}
Chapter 51. Finding
}
number of integers which
cout << count; // display count of digits
has exactly x divisors:
return 0;
Numbers dividing with self or 1 are called prime numbers
}
but numbers having multiple divisors are called composite
numbers. In this c++ program, we will find the numbers
Python Code : with the exact number of divisors defined by the user. The
divisor of a number is defined as, when we divide a number
#take user inputs
‘a’ by other number ‘b’ and gives remainder zero, so the ‘b’
Number = int(input('Enter the Number :'))
will be considered as the divisor of the ‘a’. We will find the
Digit = (int(input('Enter the digit :')))
number of the divisor of the numbers and print them along
#initialize Strings
with the count of numbers.
String1 = str()
String2 = str()
Working:
#typecast int to str
● Take user inputs like Number and Divisors.
String1 = str(Number)
● Initialize a count variable with zero value.
String2 = str(Digit)
● Run a for loop with a range from 1 to Number+1.
#count and print the occurrence
● Initialize another count variable with zero.
#Count function will return int value
● Run other for loop ranging from 1 to iterator of
#so change it's type to string and concatenate it
1st for loop+1.
print('Digit count is :'str(String1.count(String2)))
● Check for complete division conditions and if
TRUE increment count2 by 1.
● Come out of for loop and check if count2 is
equal to Divisor.
● If TRUE increment count1 by 1 and print the
number with exact divisors.
● Print count1.

C++ Code :
//C++ program
//Strong Number or not
#include<iostream>
using namespace std;
//main Program
int main()
{
int Number,Divisor,count1;
91

cout<<“\nEnter range of number :”; System.out.print(i);


cin>>Number; System.out.print(” “);
cout<<“\nEnter exact number of divisors :”; c = c + 1;
cin>>Divisor; }
//count1 is to count total number of Numbers with }
exact divisor System.out.print(“\n\nTotal number of divisors= ” + c);
count1 = 0;
for(int i=0;i<=Number;i++) }
{
//count2 checks the total number of divisors public static void main (String[] args)
int count2 = 0 {
//loop to find number of divisors int n;
for(int j=1;j<=i;j++) System.out.print(“\nEnter the number of your choice : “);
{ Scanner sc = new Scanner(System.in);
if(i%j==0) n = sc.nextInt();
{ System.out.print(“\n Number which has exactly 9 divisors
count2++; are : “);
} check(n);
} }
if(count2==Divisor) }
{
count1++;
cout<<i<<” “;
Python Code :
} #user inputs
Number = int(input('Enter range of number :'))
} Divisor = int(input('Enter exact number of divisors :'))
cout<<“\n“<<count1; #count1 is to count total number of Numbers with exact
} divisor
count1 = 0
#driver loop
Java Code :
for i in range(1,Number+1):
import java.io.*; #count2 checks the total number of divisors
import java.util.Scanner; count2 = 0
import java.util.*; #loop to find number of divisors
public class Prepinsta for j in range(1,i+1):
{ if i % j == 0:
static int divisors(int num) count2+=1
{ else:
int count = 0; pass
for (int i = 1; i <= num; i++) if count2 == Divisor:
{ count1+=1
if (num % i == 0) #end = " " is used so it can print Numbers in same line
count = count + 1; print(i,end = " ")
} #for break in line between Numbers and total count
return count; print('')
} print(count1)

static void check(int n)


{
int c = 0;
for (int i = 1; i <= n; i++)
{
if (divisors(i) == 9)
{
92

root1 = (-b + sqrt(d)) / (2 * a);


Chapter 52. Finding Roots root2 = (-b – sqrt(d)) / (2 * a);
printf(“root1 = %.2lf \nroot2 = %.2lf”, root1, root2);
of a quadratic equation : }
In this C program, we will find the roots of a quadratic
// condition for real and equal roots
equation [ax2 + bx + c]. We can solve a Quadratic Equation
else if (d == 0) {
by finding its roots. Mainly roots of the quadratic equation
printf(“Equal Roots\n“);
are represented by a parabola in 3 different patterns like :
root1 = root2 = –b / (2 * a);
printf(“root1 = root2 = %.2lf;”, root1);
No Real Roots
}
One Real Root
Two Real Roots
// if roots are not real
We get the roots of the equation which satisfies any one of
else {
the above conditions :
r = –b / (2 * a);
X = [-b (+or-)[Squareroot(pow(b,2)-4ac)]]/2a
i = sqrt(-d) / (2 * a);
printf(“No Real Roots\n“);
Sample Test Case
printf(“root1 = %.2lf+%.2lfi \nroot2 = %.2f-%.2fi”, r,
Enter value of a :1
i, r, i);
Enter value of b :-7
}
Enter value of c :12
Output
return 0;
Two Real Roots
}
4.0
3.0

Working: Java Code :

Start. //Java Program to Find the Roots of a Quadratic Equation


Take input from user a,b,c.
Check the value of a i.e. a!=0. import java.util.*;
Calculate Discriminant (D) import java.io.*;
*D = b^2 – 4*a*c
If D>0 : Two real roots exist. public class PrepInsta {
If D=0 : Equal root exists. // Function to find and display the roots of quadratic
If D<0 : Imaginary root exists. equation
Display the existence of roots and the roots of the equation. public static void main(String[] args) {
End. Scanner sc= new Scanner(System.in);
double a,b,c;
System.out.println(“Enter the coefficients of the
quadratic equation”);
C Code : a = sc.nextDouble();
b = sc.nextDouble();
#include <math.h>
c = sc.nextDouble();
#include <stdio.h>
int main() {
double determinant = Math.pow(b,2) – 4*a*c;
double a, b, c, d, root1, root2, r, i;
if(determinant > 0){
printf(“Enter value of a, b and c: “);
System.out.println(“Roots are “ +
scanf(“%lf %lf %lf”, &a, &b, &c);
(-b+Math.sqrt(determinant))/(2*a)
+ ” and “ +
d = b * b – 4 * a * c;
(-b-Math.sqrt(determinant))/(2*a));
}else if (determinant == 0){
// condition for real and different roots
System.out.println(“Roots are “ + -b/(2*a));
if (d > 0) {
}
printf(“Two Real Roots\n“);
else{
93

System.out.println(“Roots are “ + -b/(2*a) + “+i” +


Math.sqrt(-determinant)/(2*a) + ” and “
+ -b/(2*a) + “-i” +
Math.sqrt(-determinant)/(2*a));
}
}
}

Python Code :
#import math library
import math
#take user inputs
a = int(input('Enter value of a :'))
b = int(input('Enter value of b :'))
c = int(input('Enter value of c :'))
#check for value of a
if a == 0:
print("a cannot be zero")
#if a is greater than 0
else:
#calculate value of Function
val = b**2 - 4 * a * c
root = math.sqrt(abs(val))
#Check for roots and print according to their nature
if val > 0:
print("Two Real Roots")
print((-b + root)/(2 * a))
print((-b - root)/(2 * a))
elif val == 0:
print("One Real Root")
print(-b / (2*a))
else:
print("No Real Root")
print(- b / (2*a) , " + i", root)
print(- b / (2*a) , " - i", root)

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy