CS practicals pgm-1 and 2
CS practicals pgm-1 and 2
Algorithm:
1. Start
2. Define a function ‘palindrome’ with one parameter as ’n’.
3. Assign a variable a with the value n.
4. Check if a is equal to reverse of a, if true then display string is
palindrome.
5. Otherwise, display string is not palindrome.
6. Start with no indentation, in main, get a string from the user
and save it in variable Str.
7. Call the function palindrome by passing Str as the argument.
8. Stop
Program:
def palindrome(n):
a=n
if a==a[::-1]:
print('String '+ a +' is Palindrome')
else:
print('String '+ a +' is not Palindrome')
Str=input('Enter a string:\t')
palindrome(Str)
Result:
Successfully completed the program to check whether a given
string is palindrome or not, using function.
#Write on left side
Ouput:
Enter a string: malayalam
String malayalam is Palindrome
Algorithm:
1. Start
2. Define a function ‘prime’ with one parameter as ’n’.
3. Assign two variables ‘a’ and ‘flag’ with the value n and 0
respectively.
4. Check if ‘a’ is zero, if true then display '0 is neither prime nor
composite'.
5. Otherwise, check if ‘a’ is one, if true then display '1 is not
prime’.
6. Otherwise, check if ‘a’ is two, if true then display '2 is prime’.
7. Otherwise, check if ‘a’ is divisible by any number from 2 to
a//2, if true then set flag as 1.
8. Check whether flag is 0 or 1, if 0 then display number is prime
otherwise display not prime.
9. Start with no indentation, in main, get a number from the
user and save it in variable m.
10. Call the function prime by passing m as the argument.
11. Stop
Program:
def prime(n):
a=n
flag=0
if a==0:
print(a+' is neither prime nor composite')
elif a==1:
print(a+' is not a prime')
elif a==2:
print(a+' is a prime')
else:
for i in range(2, a//2):
if n%i == 0:
flag=1
if flag==1:
print(str(a)+' is not a prime')
else:
print(str(a)+' is a prime')
m=int(input('Enter a number:\t'))
prime(m)
Result:
Successfully completed the program to check whether a given
number is prime or not, using function.
Enter a number:23
23 is a prime
Enter a number:14
14 is not a prime