Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
37 views

Coding Questions

The document lists 20 programming problems/exercises including: reversing a number, Fibonacci series, greatest common divisor, perfect numbers, checking if strings are anagrams, palindrome checking, character frequency counting, leap year checking, factorials, Armstrong numbers, natural number summation using recursion, matrix addition, checking if a string is a palindrome, binary to decimal conversion, checking if a character is a vowel/consonant, automorphic numbers, ASCII values, removing non-alphabetic characters from a string, Fibonacci series using recursion, and finding the largest of two numbers. Python and C code solutions are provided for each problem in 3 sentences or less.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
37 views

Coding Questions

The document lists 20 programming problems/exercises including: reversing a number, Fibonacci series, greatest common divisor, perfect numbers, checking if strings are anagrams, palindrome checking, character frequency counting, leap year checking, factorials, Armstrong numbers, natural number summation using recursion, matrix addition, checking if a string is a palindrome, binary to decimal conversion, checking if a character is a vowel/consonant, automorphic numbers, ASCII values, removing non-alphabetic characters from a string, Fibonacci series using recursion, and finding the largest of two numbers. Python and C code solutions are provided for each problem in 3 sentences or less.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 45

List Of Programs

1. Write a code to reverse a number


2. Write the code to find the Fibonacci series upto the nth term.
3. Write the code of Greatest Common Divisor
4. Write a code for the Perfect number
5. Write a code to check if two Strings are Anagram or not
6. Write a code to check if the given string is a palindrome or not
7. Write a code to calculate the frequency of characters in a string
8. Write to code to check whether a given year is leap year or not.
9. Write a code to find the factorial of a number.
10. Write the code to for Armstrong number
11. Write a program to find the sum of Natural Numbers using Recursion.
12. Write a program to add Two Matrices using Multi-dimensional Array.
13. Write code to check a String is palindrome or not?
14. Write a program for Binary to Decimal to conversion
15. Write a program to check whether a character is a vowel or consonant
16. Write a code to find an Automorphic number
17. Write a code to find Find the ASCII value of a character
18. Write a code to Remove all characters from string except alphabets
19. Write a code to find Fibonacci Series using Recursion
20. Find the Largest of the Two Numbers in C

Python Programming

1. Write a code to reverse a number

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


temp = num
reverse = 0
while num > 0:
remainder = num % 10
reverse = (reverse * 10) + remainder
num = num // 10

print("The Given number is {} and Reverse is {}".format(temp, reverse))

2. Write the code to find the Fibonacci series upto the nth term.

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


n1, n2 = 0, 1
print("Fibonacci Series:", n1, n2, end=" ")
for i in range(2, num):
n3 = n1 + n2
n1 = n2
n2 = n3
print(n3, end=" ")

print()
3. Write code of Greatest Common Divisor

num1 = int(input("Enter First Number:"))


num2 = int(input("Enter Second Number:"))

def gcdFunction(num1, num2):


if num1 > num2:
small = num2
else:
small = num1
for i in range(1, small+1):
if (num1 % i == 0) and (num2 % i == 0):
gcd = i
print("GCD of two Number: {}".format(gcd))

gcdFunction(num1, num2)

4. Write code of Perfect number

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


sump= 0
for i in range(1, n):
if(n % i == 0):
sump= sump + i
if (sump == n):
print(“The number is a Perfect number”)
else:
print(“The number is not a Perfect number”)

5. Write code to Check if two strings are Anagram or not

#take user input


String1 = input(„Enter the 1st string :‟)
String2 = input(„Enter the 2nd string :‟)
#check if length matches
if len(String1) != len(String2):
#if False
print(„Strings are not anagram‟)
else:
#sorted function sort string by characters
String1 = sorted(String1)
String2 = sorted(String2)
#check if now strings matches
if String1 == String2:
#if True
print(„Strings are anagram‟)
else:
print(„Strings are not anagram‟)
6. Write code Check if the given string is Palindrome or not

#take user input


String1 = input('Enter the String :')
#initialize string and save reverse of 1st string
String2 = String1[::-1]
#check if both matches
if String1 == String2:
print('String is palindromic')
else:
print('Strings is not palindromic')

7. Write code to Calculate frequency of characters in a string

#take user input


String = input('Enter the string :')
#take character input
Character = input('Enter character :')
#initiaalize int variable to store frequency
frequency = 0
#use count function to count frequency of character
frequency = String.count(Character)
#count function is case sencetive
#so it print frequency of Character according to given Character
print(str(frequency) + ' is the frequency of given character')

8. Write to code to check whether a given year is leap year or not.

year = int(input("Enter Year:"))


if (year%400 == 0) or (year%4==0 and year%100!=0):
print("Leap Year")
else:
print("Not a Leap Year")

9. Write a code to find the factorial of a number.

num = 5
output = 1
for i in range(2,num+1):
output*=i
print(output)

10. Write the code to for Armstrong number

number = 371
num = number
digit, sum = 0, 0
length = len(str(num))
for i in range(length):
digit = int(num%10)
num = num/10
sum += pow(digit,length)
if sum==number:
print("Armstrong")
else:
print("Not Armstrong")

11. Write a program to find the sum of Natural Numbers using Recursion.

def getSum(num):
if num == 1:
return 1
return num + getSum(num-1)

num = 5
print(getSum(num))

OR

def recursum(number):
if number == 0:
return number
return number + recursum(number-1)
number, sum = 6,0
print(recursum(number))

12. Write a program to add Two Matrices using Multi-dimensional Array.

# Program to add two matrices using nested loop

X = [[12,7,3],
[4 ,5,6],
[7 ,8,9]]

Y = [[5,8,1],
[6,7,3],
[4,5,9]]
result = [[0,0,0],
[0,0,0],
[0,0,0]]

# iterate through rows


for i in range(len(X)):
# iterate through columns
for j in range(len(X[0])):
result[i][j] = X[i][j] + Y[i][j]
for r in result:
print(r)

13. Write code to check a String is palindrome or not?

# function which return reverse of a string

def isPalindrome(s):
return s == s[::-1]

# Driver code
s = "malayalam"
ans = isPalindrome(s)

if ans:
print("Yes")
else:
print("No")

14. Write a program for Binary to Decimal to conversion

num = int(input("Enter number:"))


binary_val = num
decimal_val = 0
base = 1
while num > 0:
rem = num % 10
decimal_val = decimal_val + rem * base
num = num // 10
base = base * 2

print("Binary Number is {} and Decimal Number is {}".format(binary_val, decimal_val))

15. Write a program to check whether a character is a vowel or consonant

#get user input


Char = input()
#Check if the Char belong to set of Vowels
if (Char == 'a' or Char == 'e' or Char == 'i' or Char == 'o' or Char == 'u'):
#if true
print("Character is Vowel")
else:
#if false
print("Character is Consonant")

16. Write a code to find an Automorphic number


Automorphic Number: A number whose square ends with the same number is known as an
Automorphic number.

number = 376
square = pow(number, 2)
mod = pow(10, len(str(number)))

# 141376 % 1000
if square % mod == number:
print("It's an Automorphic Number")
else:
print("It's not an Automorphic Number")

17. Write a code to find Find the ASCII value of a character

#user input
Char = input('Enter the character :')
#convert Char to Ascii value
Asciival = ord(Char)
#print Value
print(Asciival)

18. Write a code to Remove all characters from string except alphabets

#take user input


String1 = input('Enter the String :')
#initialize empty String
String2 = ''
for i in String1:
#check for alphabets
if (ord(i) >= 65 and ord(i) <= 90) or (ord(i) >= 97 and ord(i) <= 122):
#concatenate to empty string
String2+=i
print('Alphabets in string are :' + String2)

19. Write a code to find Fibonacci Series using Recursion

#Function for nth Fibonacci number


def Fibo(n):
if n<0:
print("Incorrect input")
#1st Fibonacci number is 0
elif n==0:
return 0
#2nd Fibonacci number is 1
elif n==1:
return 1
else:
return Fibo(n-1)+Fibo(n-2)

#Main Program
print(Fibo(9))

20. Find the Largest of the Two Numbers in C

num1, num2 = 20 , 30
if num1>num2:
print(num1)
else:
print(num2)

OR
num1, num2 = 20 , 30
print((num1 if num1>num2 else num2))

OR
num1, num2 = 20, 30
print(max(num1,num2))

C programming

1. Write a code to reverse a number

#include
int main()
{
//Initialization of variables where rev='reverse=0'
int number, rev = 0,store, left;

//input a numbers for user


printf("Enter the number\n");
scanf("%d", &number);

store= number;
//use this loop for check true condition
while (number > 0)
{
//left is for remider are left
left= number%10;

//for reverse of no.


rev = rev * 10 + left;

//number /= 10;
number=number/10;

}
//To show the user value
printf("Given number = %d\n",store);

//after reverse show numbers


printf("Its reverse is = %d\n", rev);

return 0;
}

2. Write the code to find the Fibonacci series upto the nth term.

#include<stdio.h>

int main()
{
int n = 10;
int a = 0, b = 1;

// printing the 0th and 1st term


printf("%d, %d",a,b);

int nextTerm;

// printing the rest of the terms here


for(int i = 2; i < n; i++){
nextTerm = a + b;
a = b;
b = nextTerm;

printf("%d, ",nextTerm);
}

return 0;
}

3. Write code of Greatest Common Divisor

// The code used a recursive function to return gcd of p and q


int gcd(int p, int q)
{

// checking divisibility by 0
if (p == 0)
return q;
if (q == 0)
return p;

// base case
if (p == q)
return p;

// p is greater
if (p > q)
return gcd(p-q, q);

else
return gcd(p, q-p);
}

// Driver program to test above function


int main()
{
int p = 98, q = 56;
printf("GCD of %d and %d is %d ", p, q, gcd(p, q));
return 0;
}

4. Write code of Perfect number

#include
int main()
{
// Initialization of variables
int number,i=1,total=0;

// To take user input


printf("Enter a number: ");
scanf("%d",&number);

while(i<number)
{
if(number%i==0)
{
total=total+i;
i++;
}
}
//to condition is true
if(total==number)
//display
printf("%d is a perfect number",number);
//to condition is false
else
//display
printf("%d is not a perfect number",number);

return 0;
}

5. Write code to Check if two strings are Anagram or not

#include

int main()
{
//Initializing variables.
char str[100];
int i;
int freq[256] = {0};

//Accepting inputs.
printf("Enter the string: ");
gets(str);

//Calculating frequency of each character.


for(i = 0; str[i] != '\0'; i++)
{
freq[str[i]]++;
}

printf("The non repeating characters are: ");


for(i = 0; i < 256; i++)
{
if(freq[i] == 1)//Finding uniques charcters and printing them.
{
printf(" %c ", i);
}
}
return 0;
}

6. Write code Check if the given string is Palindrome or not

#include
#include

int main()
{
//Initializing variable.
char str[100];
int i,length=0,flag=0;

//Accepting input.
printf("Enter the string : ");
gets(str);
length=strlen(str);

//Initializing for loop.


for(i=0;i<length/2;i++)
{
//Checking if string is palindrome or not.
if(str[i]==str[length-i-1])
flag++;

}
//Printing result.
if(flag==i)
printf("String entered is palindrome");
else
printf("String entered is not palindrome");

return 0;
}

7. Write code to Calculate frequency of characters in a string

#include

int main()
{
//Initializing variables.
char str[100];
int i;
int freq[256] = {0};

//Accepting inputs.
printf("Enter the string: ");
gets(str);

//Calculating frequency of each character.


for(i = 0; str[i] != '\0'; i++)
{
freq[str[i]]++;
}
//Printing frequency of each character.
for(i = 0; i < 256; i++)
{
if(freq[i] != 0)
{
printf("The frequency of %c is %d\n", i, freq[i]);
}
}
return 0;
}

8. Write to code to check whether a given year is leap year or not.

#include <stdio.h>
int main ()
{
int year;
scanf("%d",&year);

if(year % 400 == 0)
printf("%d is a Leap Year",year);

else if(year % 4 == 0 && year % 100 != 0)


printf("%d is a Leap Year",year);

else
printf("%d is not a Leap Year",year);

return 0;
}

9. Write a code to find the factorial of a number.

#include<stdio.h>
int main ()
{
int num = 5, fact = 1;

// Can't calculate factorial of a negative number


if(num < 0)
printf("Error");
else
{
for(int i = 1; i <= num; i++)
fact = fact * i;
}
printf("Fact %d: %d",num, fact);
}
// Time complexity: O(N)
// Space complexity: O(1)

10. Write the code to for Armstrong number

#include
#include

// Armstrong number is any number following the given rule


// abcd... = a^n + b^n + c^n + d^n + ...
// Where n is the order(length/digits in number)

// Example = 153 (order/length = 3)


// 153 = 1^3 + 5^3 + 3^3 = 1 + 125 + 27 = 153

// Example = 1634 (order/length = 4)


// 1634 = 1^4 + 6^4 + 3^4 + 4^4 = 1 + 1296 + 81 + 256 = 1634

// number of digits in a number is order


int order(int x)
{
int len = 0;
while (x)
{
len++;
x = x/10;
}
return len;
}

int armstrong(int num, int len){

int sum = 0, temp, digit;


temp = num;

// loop to extract digit, find power & add to sum


while(temp != 0)
{
// extract digit
digit = temp % 10;

// add power to sum


sum = sum + pow(digit,len);
temp /= 10;
};

return num == sum;


}
// Driver Code
int main ()
{
int num, len;

printf("Enter a number: ");


scanf("%d",&num);

// function to get order(length)


len = order(num);

// check if Armstrong
if (armstrong(num, len))
printf("%d is Armstrong", num);
else
printf("%d is Not Armstrong", num);

11. Write a program to find the sum of Natural Numbers using Recursion.

#include<stdio.h>

int getSum(int sum,int n)


{
if(n==0)
return sum;

return n+getSum(sum,n-1);
}

int main()
{
int n, sum = 0;
scanf("%d",&n);

printf("%d",getSum(sum, n));

return 0;
}
// Time complexity : O(n)
// Space complexity : O(1)
// Auxilary space complexity : O(N)
// Due to function call stack

OR

#include
Numbers(int n);

int main() {

int num;

printf("Enter a positive integer: ");

scanf("%d", &num);

printf("Sum = %d", addNumbers(num));

return 0;

int addNumbers(int n) {

if (n != 0)

return n + addNumbers(n - 1);

else

return n;

12. Write a program to add Two Matrices using Multi-dimensional Array.

#include
int main() {
int r, c, a[100][100], b[100][100], sum[100][100], i, j;
printf("Enter the number of rows (between 1 and 100): ");
scanf("%d", &r);
printf("Enter the number of columns (between 1 and 100): ");
scanf("%d", &c);

printf("\nEnter elements of 1st matrix:\n");


for (i = 0; i < r; ++i)
for (j = 0; j < c; ++j) {
printf("Enter element a%d%d: ", i + 1, j + 1);
scanf("%d", &a[i][j]);
}

printf("Enter elements of 2nd matrix:\n");


for (i = 0; i < r; ++i)
for (j = 0; j < c; ++j) {
printf("Enter element a%d%d: ", i + 1, j + 1);
scanf("%d", &b[i][j]);
}

// adding two matrices


for (i = 0; i < r; ++i)
for (j = 0; j < c; ++j) {
sum[i][j] = a[i][j] + b[i][j];
}

// printing the result


printf("\nSum of two matrices: \n");
for (i = 0; i < r; ++i)
for (j = 0; j < c; ++j) {
printf("%d ", sum[i][j]);
if (j == c - 1) {
printf("\n\n");
}
}
return 0;
}

13. Write code to check a String is palindrome or not?

#include
#include

// A function to check if a string str is palindrome


voids isPalindrome(char str[])
{
// Start from leftmost and rightmost corners of str
int l = 0;
int h = strlen(str) - 1;

// Keep comparing characters while they are same


while (h > l)
{
if (str[l++] != str[h--])
{
printf("%s is Not Palindrome", str);
return;
}
}
printf("%s is palindrome", str);
}

// Driver program to test above function


int main()
{
isPalindrome("abba");
isPalindrome("abbccbba");
isPalindrome("geeks");
return 0;
}

14. Write a program for Binary to Decimal to conversion

#include<stdio.h>

int main()
{
int num, binary_val, decimal_val = 0, base = 1, rem;

printf("Insert a binary num (1s and 0s) \n");


scanf("%d", &num); /* maximum five digits */

binary_val = num;
while (num > 0)
{
rem = num % 10;
decimal_val = decimal_val + rem * base;
//num/=10;
num = num / 10 ;
//base*=2;
base = base * 2;
}
//display binary number
printf("The Binary num is = %d \n", binary_val);
//display decimal number
printf("Its decimal equivalent is = %d \n", decimal_val);
return 0;
}

15. Write a program to check whether a character is a vowel or consonant

#include
int main()
{
char c;
int isLowerVowel, isUpperVowel;
printf("Enter an alphabet: ");
scanf("%c",&c);

//To find the corrector is lowercase vowel


isLowerVowel = (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u');
//To find the character is Upper case vowel
isUpperVowel = (c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U');
// compare to charector is Lowercase Vowel or Upper case Vowel

if (isLowerVowel || isUpperVowel)
printf("%c is a vowel", c);
//to check character is alphabet or not

elseif((c >= 'a' && c= 'A' && c <= 'Z'))


prinf("\n not a alphabet\n");

else
printf("%c is a consonant", c);

return 0;
}

16. Write a code to find an Automorphic number

#include<stdio.h>

int checkAutomorphic(int num)


{
int square = num * num;

while (num > 0)


{
if (num % 10 != square % 10)
return 0;

// Reduce N and square


num = num / 10;
square = square / 10;
}
return 1;
}

int main()
{
//enter value
int num;
scanf("%d",&num);

//checking condition
if(checkAutomorphic(num))
printf("Automorphic");
else
printf("Not Automorphic");
return 0;
}

17. Write a code to find Find the ASCII value of a character

/* C Program to identify ASCII Value of a Character */


#include
#include
int main()
{
char a;

printf("\n Kindly insert any character \n");


scanf("%c",&a);

printf("\n The ASCII value of inserted character = %d",a);


return 0;
}

18. Write a code to Remove all characters from string except alphabets

#include <stdio.h>
int main()
{
//Initializing variable.
char str[100];
int i, j;

//Accepting input.
printf(" Enter a string : ");
gets(str);

//Iterating each character and removing non alphabetical characters.


for(i = 0; str[i] != '\0'; ++i)
{
while (!( (str[i] >= 'a' && str[i] <= 'z') || (str[i] >= 'A' && str[i] <= 'Z') || str[i] == '\0') )
{
for(j = i; str[j] != '\0'; ++j)
{
str[j] = str[j+1];
}
str[j] = '\0';
}
}
//Printing output.
printf(" After removing non alphabetical characters the string is :");
puts(str);
return 0;
}

19. Write a code to find Fibonacci Series using Recursion

//Fibonacci Series using Recursion


#include
int fibo(int n)
{
if (n <= 1)
return n;
return fibo(n-1) + fibo(n-2);
}

int main ()
{
int n = 9;
printf("%d", fib(n));
getchar();
return 0;
}

20. Find the Largest of the Two Numbers in C

include<stdio.h>
int main ()
{
int num1, num2;
num1=12,num2=13;
if (num1 == num2)
printf("both are equal");
else if (num1 > num2)
printf("%d is greater", num1);
else
printf("%d is greater", num2);

return 0;
}

C++ Programming

1. Write a code to reverse a number

//Reverse of a number
using namespace std;
//main program
int main()
{
//variables initialization
int num, reverse=0, rem;
cout<<"Enter a number: ";
//user input
cin>>num;
//loop to find reverse number
do
{
rem=num%10;
reverse=reverse*10+rem;
num/=10;
}while(num!=0);
//output
cout<<"Reversed Number: "<<reverse;
return 0;
}

2. Write the code to find the Fibonacci series upto the nth term.

#include<iostream>
using namespace std;

int main()
{
int num = 15;
int a = 0, b = 1;

// Here we are printing 0th and 1st terms


cout << a << ", " << b << ", ";

int nextTerm;

// printing the rest of the terms here


for(int i = 2; i < num; i++){
nextTerm = a + b;
a = b;
b = nextTerm;

cout << nextTerm << ", ";


}

return 0;
}

3. Write code of Greatest Common Divisor

//C++ Program
//GCD of Two Numbers
#include
using namespace std;
// Recursive function declaration
int findGCD(int, int);
// main program
int main()
{
int first, second;
cout<<"Enter First Number: ";
cin>>first;
cout<<"Enter second Number: ";
cin>>second;
cout<<"GCD of "<<first<<" and "<<second<<" is "<<findGCD(first,second);
return 0;
}
//body of the function
int findGCD(int first, int second)
{
// 0 is divisible by every number
if(first == 0)
{
return second;
}
if(second == 0)
{
return first;
}
// both numbers are equal
if(first == second)
{
return first;
}
// first is greater
else if(first > second)
{
return findGCD(first - second, second);
}
return findGCD(first, second - first);
}

4. Write code of Perfect number

#include
using namespace std;
//main Program
int main ()
{
int div, num, sum=0;
cout << "Enter the number to check : ";
//user input
cin >> num;
//loop to find the sum of divisors
for(int i=1; i < num; i++)
{
div = num % i;
if(div == 0)
sum += i;
}
//checking for perfect number
if (sum == num)
cout<< num <<" is a perfect number.";
else
cout<< num <<" is not a perfect number.";
return 0;
}

5. Write code to Check if two strings are Anagram or not

#include<iostream>
using namespace std;
int main()
{
//Initializing variables.
char str1[100],str2[100];
int first[26]={0}, second[26]={0}, c=0, flag=0;

//Accepting inputs.
cout<<"Enter First String: ";
gets(str1);
cout<<"Enter Second String: ";
gets(str2);

//Calculating frequencies of characters in first string.


while(str1[c] != '\0')
{
first[str1[c]-'a']++;
c++;
}

c=0;
//Calculating frequencies of characters in second string.
while(str2[c] != '\0')
{
second[str2[c]-'a']++;
c++;
}
//Checking if frequencies of both the strings are same or not.
for(c=0;c<26;c++)
{
if(first[c] != second[c])
flag=1;
}
//Priting result.
if(flag == 0)
{
cout<<"Strings are anagram.";
}
else
{
cout<<"Strings are not anagram.";
}
return 0;

6. Write code Check if the given string is Palindrome or not

#include
#include
using namespace std;

int main()
{
//Initializing variable.
char str[100];
int i,length=0,flag=0;

//Accepting input.
cout<<"Enter the string : "<<endl;
gets(str);
length=strlen(str);

//Initializing for loop.


for(i=0;i<length/2;i++)
{
//Checking if string is palindrome or not.
if(str[i]==str[length-i-1])
flag++;

}
//Printing result.
if(flag==i)
cout<<"String entered is palindrome";
else
cout<<"String entered is not palindrome";

return 0;
}

7. Write code to Calculate frequency of characters in a string

#include
using namespace std;

int main()
{
//Initializing variables.
char str[100];
int i;
int freq[256] = {0};

//Accepting inputs.
cout<<"Enter the string: ";
gets(str);

//Calculating frequency of each character.


for(i = 0; str[i] != '\0'; i++)
{
freq[str[i]]++;
}

//Printing frequency of each character.


for(i = 0; i < 256; i++)
{
if(freq[i] != 0)
{
cout<<"The frequency of "<<char(i)<<" is "<<freq[i]<<endl;
}
}
return 0;
}

8. Write to code to check whether a given year is leap year or not.

using namespace std;

int main()
{
int year;

cout << "Enter Year:" << endl;


cin >> year;

if(year % 400 == 0)
cout << year << " is a Leap Year";

else if(year % 4 == 0 && year % 100 != 0)


cout << year << " is a Leap Year";

else
cout << year << " is not a Leap Year";

return 0;
}

9. Write a code to find the factorial of a number.


#include<iostream>
using namespace std;
int main ()
{
int num = 6, fact = 1;

// Factorial of negative number doesn't exist


// Read more here - https://www.quora.com/Is-the-factorial-of-a-negative-number-possible
if(num < 0)
cout << "Not Possible";
else
{
for(int i = 1; i <= num; i++)
fact = fact * i;
}

cout << "Fact " << num << ": " << fact;
}
// Time complexity: O(N)
// Space complexity: O(1)

10. Write the code to for Armstrong number

#include<iostream>
#include<math.h>
using namespace std;

// Armstrong number is any number following the given rule


// abcd... = a^n + b^n + c^n + d^n + ...
// Where n is the order(length/digits in number)

// Example = 153 (order/length = 3)


// 153 = 1^3 + 5^3 + 3^3 = 1 + 125 + 27 = 153

// Example = 1634 (order/length = 4)


// 1634 = 1^4 + 6^4 + 3^4 + 4^4 = 1 + 1296 + 81 + 256 = 1634

// number of digits in a number is order


int order(int x)
{
int len = 0;
while (x)
{
len++;
x = x/10;
}
return len;
}
bool armstrong(int num, int len){

int sum = 0, temp, digit;


temp = num;

// loop to extract digit, find power & add to sum


while(temp != 0)
{
// extract digit
digit = temp % 10;

// add power to sum


sum = sum + pow(digit,len);
temp /= 10;
};

return num == sum;


}

// Driver Code
int main ()
{
//variables initialization
int num = 407, len;

// function to get order(length)


len = order(num);

// check if Armstrong
if (armstrong(num, len))
cout << num << " is armstrong";
else
cout << num << " is not armstrong";

return 0;
}

11. Write a program to find the sum of Natural Numbers using Recursion.

using namespace std;

int getSum(int n)
{
if(n==0)
return n;

return n + getSum(n-1);
}
int main()
{
int n;
cout << "Enter a number : ";
cin >> n;

int sum = getSum(n);

cout << sum;

return 0;
}

12. Write a program to add Two Matrices using Multi-dimensional Array.

#include <iostream>
using namespace std;

int main()
{
int r, c, a[100][100], b[100][100], sum[100][100], i, j;

cout << "Enter number of rows (between 1 and 100): ";


cin >> r;

cout << "Enter number of columns (between 1 and 100): ";


cin >> c;

cout << endl << "Enter elements of 1st matrix: " << endl;

// Storing elements of first matrix entered by user.


for(i = 0; i < r; ++i)
for(j = 0; j < c; ++j)
{
cout << "Enter element a" << i + 1 << j + 1 << " : ";
cin >> a[i][j];
}

// Storing elements of second matrix entered by user.


cout << endl << "Enter elements of 2nd matrix: " << endl;
for(i = 0; i < r; ++i)
for(j = 0; j < c; ++j)
{
cout << "Enter element b" << i + 1 << j + 1 << " : ";
cin >> b[i][j];
}

// Adding Two matrices


for(i = 0; i < r; ++i)
for(j = 0; j < c; ++j)
sum[i][j] = a[i][j] + b[i][j];

// Displaying the resultant sum matrix.


cout << endl << "Sum of two matrix is: " << endl;
for(i = 0; i < r; ++i)
for(j = 0; j < c; ++j)
{
cout << sum[i][j] << " ";
if(j == c - 1)
cout << endl;
}

return 0;
}

13. Write code to check a String is palindrome or not?

using namespace std;

int main()

char str1[20], str2[20];

int i, j, len = 0, flag = 0;

cout << "Enter the string : "; gets(str1); len = strlen(str1) - 1; for (i = len, j = 0; i >= 0 ; i--,
j++)

str2[j] = str1[i];

if (strcmp(str1, str2))

flag = 1;

if (flag == 1)

cout << str1 << " is not a palindrome";

else

cout << str1 << " is a palindrome";

return 0;

}
14. Write a program for Binary to Decimal to conversion

//C++ Program
//Convert binary to decimal
#include
#include using namespace std;
//function to convert binary to decimal
int convert(long n)
{
int i = 0,decimal= 0;
//converting binary to decimal
while (n!=0)
{
int rem = n%10;
n /= 10;
int res = rem * pow(2,i);
decimal += res;
i++;
}
return decimal;
}
//main program
int main()
{
long binary;
cout << "Enter binary number: ";
cin >> binary;
cout << binary << " in binary = " << convert(binary) << " in decimal";
return 0;
}

15. Write a program to check whether a character is a vowel or consonant

//C++ Program to check whether alphabet is vowel or consonant


#include <iostream>
using namespace std;
//main function
int main()
{
char c;
cout<<"Enter an alphabet: ";
cin>>c;
//checking for vowels
if(c=='a'||c=='e'||c=='i'||c=='o'||c=='u'||c=='A'||c=='E'||c=='I'||c=='O'||c=='U')
{
cout<<c<<" is a vowel"; //condition true input is vowel
}
else
{
cout<<c<<" is a consonant"; //condition false input is consonant
}
return 0;
}

16. Write a code to find an Automorphic number

//C++ Program
//Automorphic number or not
#include<iostream>
using namespace std;
//main program
int main()
{
int num,flag=0;
cout<<"Enter a positive number to check: ";
//user input
cin>>num;
int sq= num*num;
int store=num;
//check for automorphic number
while(num>0)
{
if(num%10!=sq%10)
{
flag=1;
break;
}
num=num/10;
sq=sq/10;
}
if(flag==1)
cout<<store<<" is not an Automorphic number.";
else
cout<<store<<" is an Automorphic number.";
return 0;
}

17. Write a code to find Find the ASCII value of a character

//C++ program to calcualte ASCII value of Character


#include<iostream>
using namespace std;

//main program
int main()
{
char val;
cout<<"Enter a character: ";
cin>>val;
//printing the ASCII value of input
//through typecasting

cout<<"The ASCII value of "<<val<<" is "<<(int)val;


return 0;
}

18. Write a code to Remove all characters from string except alphabets

#include <iostream>
using namespace std;
int main()
{
//Initializing variable.
char str[100];
int i, j;

//Accepting input.
cout<<"Enter a string : ";
gets(str);

//Iterating each character and removing non alphabetical characters.


for(i = 0; str[i] != '\0'; ++i)
{
while (!( (str[i] >= 'a' && str[i] <= 'z') || (str[i] >= 'A' && str[i] <= 'Z') || str[i] == '\0') )
{
for(j = i; str[j] != '\0'; ++j)
{
str[j] = str[j+1];
}
str[j] = '\0';
}
}
//Printing output.
cout<<"After removing non alphabetical characters the string is :";
puts(str);
return 0;
}

19. Write a code to find Fibonacci Series using Recursion

//Fibonacci Series using Recursion


#include<bits/stdc++.h>
using namespace std;

int fibo(int n)
{
if (n <= 1)
return n;
return fibo(n-1) + fibo(n-2);
}

int main ()
{
int n = 9;
cout << fibo(n);
getchar();
return 0;
}

20. Find the Largest of the Two Numbers in C

#include
using namespace std;

int main ()
{
int num1, num2;
num1=75,num2=85;

if (num1 == num2)
cout << "both are equal"; else if (num1 > num2)
cout << num1 << " is greater than " << num2;
else
cout << num2 << " is greater than " << num1;
return 0;
}
// Time Complexity : O(1)
// Space Complexity : O(1)

Java Programming

1. Write a code to reverse a number

import java.util.Scanner;

public class reverse_of_number

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

System.out.print("Reverse of "+number+" is ");

int reverse = 0;

String s = "";

while(number != 0)

int pick_last = number % 10;

//use function to convert pick_last from integer to string

s = s + Integer.toString(pick_last);

number = number / 10;

//display the reversed number

System.out.print(s);

//closing scanner class(not compulsory, but good practice)

sc.close();

2. Write the code to find the Fibonacci series upto the nth term.

public class Main


{
public static void main (String[]args)
{

int num = 15;


int a = 0, b = 1;

// Here we are printing 0th and 1st terms


System.out.print (a + " , " + b + " , ");

int nextTerm;
// printing the rest of the terms here
for (int i = 2; i < num; i++)
{
nextTerm = a + b;
a = b;
b = nextTerm;
System.out.print (nextTerm + " , ");
}

}
}

3. Write code of Greatest Common Divisor

import java.util.Scanner;
public class gcd_or_hcf
{
public static void main(String[] args)
{
//scanner class declaration
Scanner sc = new Scanner(System.in);
//input from the user
System.out.print("Enter the first number : ");
int num1 = sc.nextInt();
//input from the user
System.out.print("Enter the second number : ");
int num2 = sc.nextInt();
int n = 1;
System.out.print("HCF of "+num1+" and "+num2+" is ");
if( num1 != num2)
{
while(n != 0)
{
//storing remainder
n = num1 % num2;
if(n != 0)
{
num1 = num2;
num2 = n;
}
}
//result
System.out.println(num2);
}
else
System.out.println("Wrong Input");
//closing scanner class(not compulsory, but good practice)
sc.close();
}
}

4. Write code of Perfect number

import java.util.Scanner;
public class perfect_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
int sum = 0;
for(int i = 1 ; i < number ; i++)
{
if(number % i == 0)
sum = sum + i;
}
//comparing whether the sum is equal to the given number or not
if(sum == number)
System.out.println("Perfect Number");
else
System.out.println("Not an Perfect Number");
//closing scanner class(not compulsory, but good practice)
sc.close();
}
}

5. Write code to Check if two strings are Anagram or not

import java.util.Arrays;
import java.util.Scanner;
public class CheckIfTwoStringsAreAnagramAreNot {
static boolean isAnagram(String str1 , String str2) {
String s1 = str1.replaceAll("[\\s]", "");
String s2 = str2.replaceAll("[\\s]", "");
boolean status=true;

if(s1.length()!=s2.length())
status = false;
else {
char[] a1 = s1.toLowerCase().toCharArray();
char[] a2 = s2.toLowerCase().toCharArray();
Arrays.sort(a1);
Arrays.sort(a2);
status = Arrays.equals(a1, a2);
}
return status;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter two String :");
String s1 = sc.next();
String s2 = sc.next();
boolean status = isAnagram(s1,s2);
if(status)
System.out.println(s1+" and "+s2+" are Anagram");
else
System.out.println(s1+" and "+s2+" are not Anagram");
}
}

6. Write code Check if the given string is Palindrome or not

import java.util.Scanner;

public class StringIsAPalindromeOrNot {

public static void main(String[] args) {


Scanner sc =new Scanner(System.in);
System.out.println("Enter string");
String s = sc.next();
String rev = "";
for (int i = s.length()-1; i >=0 ; i--)
rev=rev+s.charAt(i);
if(s.equals(rev))
System.out.println("String is palindrome");
else
System.out.println("String is not palindrome");

7. Write code to Calculate frequency of characters in a string

import java.util.Scanner;

public class FrequencyOfCharactersInAString {


public static void main(String[] args) {
Scanner sc =new Scanner(System.in);
System.out.print("Enter String : ");
String str = sc.nextLine();
int[] freq = new int[str.length()];
int i, j;
//Converts given string into character array
char string[] = str.toCharArray();
for(i = 0; i <str.length(); i++) {
freq[i] = 1;
for(j = i+1; j <str.length(); j++) {
if(string[i] == string[j]) {
freq[i]++;

//Set string[j] to 0 to avoid printing visited character


string[j] = '0';
}
}
}
//Displays the each character and their corresponding frequency
System.out.println("Characters and their corresponding frequencies");
for(i = 0; i <freq.length; i++) {
if(string[i] != ' ' && string[i] != '0')
System.out.println(string[i] + "-" + freq[i]);
}
}
}

8. Write to code to check whether a given year is leap year or not.

// Leap year program in Java


// If the year satisfies either of the conditions, it's considered a leap year -
// 1. The year must be divisible by 400.
// 2. The year must be divisible by 4 but not 100.public class Main
{
public static void main (String[]args)
{

int year = 2020;

if (year % 400 == 0)
System.out.println (year + " is a Leap Year");

else if (year % 4 == 0 && year % 100 != 0)


System.out.println (year + " is a Leap Year");

else
System.out.println (year + " is not a Leap Year");

}
}

9. Write a code to find the factorial of a number.


//Java program to find factorial of a number
import java.util.Scanner;
public class LearnCoding
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number : ");
int num = sc.nextInt();

if(num >= 0)
{
System.out.println(num + " Factorial: " + getFact(num));
}
else
System.out.println("Negative Number: No Factorial");
}

private static int getFact(int num) {

if(num == 1 || num == 0)
return 1;

return num * getFact(num-1);


}
}

10. Write the code to for Armstrong number

public class Main


{
public static void main (String[]args)
{
int num = 407, len;

// function to get order(length)


len = order (num);

// check if Armstrong
if (armstrong (num, len))
System.out.println(num + " is armstrong");
else
System.out.println(num + " is armstrong");

static int order (int x)


{
int len = 0;
while (x != 0 )
{
len++;
x = x / 10;
}
return len;
}

static boolean armstrong (int num, int len)


{

int sum = 0, temp, digit;


temp = num;

// loop to extract digit, find power & add to sum


while (temp != 0)
{
// extract digit
digit = temp % 10;

// add power to sum


sum = sum + (int)Math.pow(digit, len);
temp /= 10;
};

return num == sum;


}
}

11. Write a program to find the sum of Natural Numbers using Recursion.

public class Main


{
public static void main (String[]args)
{

int n = 10;
int sum = getSum (n);

System.out.println (sum);
}

static int getSum (int n)


{
if (n == 0)
return n;

return n + getSum (n - 1);


}
}
12. Write a program to add Two Matrices using Multi-dimensional Array.

public class AddMatrices {

public static void main(String[] args) {


int rows = 2, columns = 3;
int[][] firstMatrix = { {2, 3, 4}, {5, 2, 3} };
int[][] secondMatrix = { {-4, 5, 3}, {5, 6, 3} };

// Adding Two matrices


int[][] sum = new int[rows][columns];
for(int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
sum[i][j] = firstMatrix[i][j] + secondMatrix[i][j];
}
}

// Displaying the result


System.out.println("Sum of two matrices is: ");
for(int[] row : sum) {
for (int column : row) {
System.out.print(column + " ");
}
System.out.println();
}
}
}

13. Write code to check a String is palindrome or not?

import java.util.Scanner;
public class Palindrome{

public static void main(String args[]) {

Scanner reader = new Scanner(System.in);


System.out.println("Please enter a String");
String input = reader.nextLine();

System.out.printf("Is %s a palindrome? : %b %n",


input, isPalindrome(input));

System.out.println("Please enter another String");


input = reader.nextLine();

System.out.printf("Is %s a palindrome? : %b %n",


input, isPalindrome(input));

reader.close();
}

public static boolean isPalindrome(String input) {


if (input == null || input.isEmpty()) {
return true;
}

char[] array = input.toCharArray();


StringBuilder sb = new StringBuilder(input.length());
for (int i = input.length() - 1; i >= 0; i--) {
sb.append(array[i]);
}

String reverseOfString = sb.toString();

return input.equals(reverseOfString);
}

14. Write a program for Binary to Decimal to conversion

//Java program to convert Binary number to decimal number


import java.util.Scanner;
public class Binary_To_Decimal
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
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
while(binary > 0)
{
int temp = binary%10;
decimal += temp*Math.pow(2, n);
binary = binary/10;
n++;
}
System.out.println("Decimal number : "+decimal);
//closing scanner class(not compulsory, but good practice)
sc.close();
}
}
15. Write a program to check whether a character is a vowel or consonant

//JAVA Program to check whether the character entered by user is Vowel or Consonant.

import java.util.Scanner;
public class vowelorconsonant
{
//class declaration
public static void main(String[] args)
{
//main method declaration
Scanner sc=new Scanner(System.in); //scanner class object creation

System.out.println(" Enter a character");


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

System.out.println(" Vowel");

else if((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z')) //condition
for the consonants

System.out.println(" Consonant");
else
System.out.println(" Not an Alphabet");

sc.close() //closing scanner class(not mandatory but good practice)


} //end of main method
} //end of class

16. Write a code to find an Automorphic number

//Java program to check whether a number is Automorphic number or not


import java.util.Scanner;
public class automorphic_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();
//Convert the number to string
String s1 = Integer.toString(number);
//Calculate the length
int l1 = s1.length();
int sq = number * number;
String s2 = Integer.toString(sq);
int l2 = s2.length();
//Create Substring
String s3 = s2.substring(l2-l1);
if(s1.equals(s3))
System.out.println("Automorphic Number");
else
System.out.println("Not an Automorphic Number");
//closing scanner class(not compulsory, but good practice)
sc.close();
}
}

17. Write a code to find Find the ASCII value of a character

//Java program to print ASCII values of a character

import java.util.Scanner;
class Main
{
public static void main(String[] args)
{
//scanner class object creation
Scanner sc=new Scanner(System.in);

//input from user


System.out.print("Enter a Character: ");
char c=sc.next().charAt(0);

//typecasting from character type to integer type


int i = c;

//printing ASCII value of the character


System.out.println("ASCII value of "+c+" is "+i);

//closing scanner class(not compulsory, but good practice)


sc.close();
}
}

18. Write a code to Remove all characters from string except alphabets

import java.util.Scanner;

class RemoveCharactersInAtringExceptAlphabets {

public static void main(String[] args) {


Scanner sc =new Scanner(System.in);
System.out.print("Enter String : ");
String s = sc.nextLine();
s=s.replaceAll("[^a-zA-Z]","");
System.out.println(s);
}
}

19. Write a code to find Fibonacci Series using Recursion

//Fibonacci Series using Recursion


class fibonacci
{
static int fibo(int n)
{
if (n <= 1)
return n;
return fibo(n-1) + fibo(n-2);
}

public static void main (String args[])


{
int n = 9;
System.out.println(fibo(n));
}
}

20. Find the Largest of the Two Numbers in C

// Write a program to find the largest of two numbers in java


public class Main
{
public static void main (String[]args)
{

int num1 = 50, num2 = 20;


if (num1 == num2)
System.out.println ("both are equal");
else if (num1 > num2)
System.out.println (num1 + " is greater");

else
System.out.println (num2 + " is greater");

}
}

You might also like