Showing posts with label Programming. Show all posts
Showing posts with label Programming. Show all posts

Write Python Program using different techniques

Write Python Program using different techniques

We can write Python Program using different techniques. Every technique has its own advantages and disadvantages.

Python program is written using different techniques to solve the problem where radius is given and need to calculate the Area of the circle. 

Method 1: Using only main program. Here PI constant and r variable

PI=22/7
r=int(input("Enter a radius of the Circle? "))
print("Area of the Circle =" , PI*r*r)
r=int(input("Enter a radius of the Circle? "))
print("Area of the Circle =" , PI*r*r)

Sample Output
Enter a radius of the Circle? 7
Area of the Circle = 154.0
Enter a radius of the Circle? 14
Area of the Circle = 616.0

Method 2: the Procedure CirlceArea(r) is used to calculate the Area. here r is parameter

PI=22/7

def CirlceArea(r):
    print("Area of the Circle =" , PI*r*r)

r=int(input("Enter a radius of the Circle? "))
CirlceArea(r)
r=int(input("Enter a radius of the Circle? "))
CirlceArea(r)

Method 3: The function CirlceArea(r) is used. Here r is parameter. Function return the output as string. When we call the function value is given

PI=22/7

def CirlceArea(r):
    return f"Area of the Circle ={PI*r*r}"  

r=int(input("Enter a radius of the Circle? "))
print(CirlceArea(r))
r=int(input("Enter a radius of the Circle? "))
print(CirlceArea(r))

Method 4: MyCircle is used as class. Here PI is a constant and GetR(self,rr), CirlceArea(self) are methods. C1,C2 are objects in main program

class MyCircle:
    PI=22/7
    
    def GetR(self,rr):
        self.r=rr
    
    def CirlceArea(self):
        print("Area of the Circle =" , self.PI*(self.r*self.r))

r=int(input("Enter a radius of the Circle? "))
C1=MyCircle()
C1.GetR(r)
r=int(input("Enter a radius of the Circle? "))
C2=MyCircle()
C2.GetR(r)
C1.CirlceArea()
C2.CirlceArea()

Method 5: Instead if GetR(self,rr) method constructor is used. When we create the object constructor is called automatically

class MyCircle:
    PI=22/7
    
    def __init__(self,rr):
        self.r=rr
    
    def __str__(self):
        return f"Area of the Circle ={ self.PI*(self.r*self.r)}"

r=int(input("Enter a radius of the Circle? "))
C1=MyCircle(r)
r=int(input("Enter a radius of the Circle? "))
C2=MyCircle(r)
print(C1)
print(C2)

Python program to Calculate Your Name Number in Numerology

Python program to Calculate Your Name Number in Numerology
#Python program to Calculate Your Name Number in Numerology

def add(n):
    s=str(n)
    
    madd=n
    while (len(s))>1:
        i=0
        madd=0
        while i<=(len(s)-1):
            madd=madd+int(s[i])
            i=i+1
        s=str(madd)
        
    return madd

n=input("Enter a Name (only Alphabets)?")
 

c=list()
num=[1,2,3,4,5,8,3,5,1,1,2,3,4,5,7,8,1,2,3,4,6,6,6,5,1,7]
t=0.0
tot=0.0
for x in range(0,26):
    c.append(0) 

for x in n:
    x=x.upper()
    if (ord(x)>=65 and ord(x)<=91):        
        c[ord(x)-65]=c[ord(x)-65]+1

for l in range(0,26):
    t=(c[l]*num[l])
    tot=tot+t
    print(chr(l+65),"-",c[l],"-",num[l],"-",t,"-",tot )
    
print()    
print()
print ("Your Name Number in Numerology is =>",add(int(tot)))

Sample Output
Enter a Name (only Alphabets)?IsaacNewton
A - 2 - 1 - 2 - 2.0
B - 0 - 2 - 0 - 2.0
C - 1 - 3 - 3 - 5.0
D - 0 - 4 - 0 - 5.0
E - 1 - 5 - 5 - 10.0
F - 0 - 8 - 0 - 10.0
G - 0 - 3 - 0 - 10.0
H - 0 - 5 - 0 - 10.0
I - 1 - 1 - 1 - 11.0
J - 0 - 1 - 0 - 11.0
K - 0 - 2 - 0 - 11.0
L - 0 - 3 - 0 - 11.0
M - 0 - 4 - 0 - 11.0
N - 2 - 5 - 10 - 21.0
O - 1 - 7 - 7 - 28.0
P - 0 - 8 - 0 - 28.0
Q - 0 - 1 - 0 - 28.0
R - 0 - 2 - 0 - 28.0
S - 1 - 3 - 3 - 31.0
T - 1 - 4 - 4 - 35.0
U - 0 - 6 - 0 - 35.0
V - 0 - 6 - 0 - 35.0
W - 1 - 6 - 6 - 41.0
X - 0 - 5 - 0 - 41.0
Y - 0 - 1 - 0 - 41.0
Z - 0 - 7 - 0 - 41.0


Your Name Number in Numerology is => 5

Data file using Pascal Sample Program

Data file using Pascal

program studentdatafiles;

const
  fname=  'students.dat'   ;

type
   StudentRecord = Record
      s_name: String[25];
      s_add: String[30];
      s_phone: String[20];

   end;

var
   Student: StudentRecord;
   f: file of StudentRecord;
   n:char;
procedure Addrec() ;
begin
  Assign(f,fname);
  Rewrite(f);
  n:='Y'  ;
  while  (n='Y') do
  begin
        Write('Enter Your Name ?');
        Readln(Student.s_name);
        Write('Enter your Address ?');
        Readln(Student.s_add);
        Write('Enter your Phone No ?');
        Readln(Student.s_phone);

        Write(f,Student);
        Write('Do you have another record to write (Y/N)?' );
        Readln(n);
        writeln();
  end;

  Close(f);
end;
procedure Readrec() ;
begin
  Assign(f,fname);
  Reset(f);
  writeln('Name','Address','Phone');
  while not eof(f) do
   begin
      read(f,Student);
      writeln(Student.s_name,Student.s_add,Student.s_Phone);
   end;

   close(f);
end;

begin
   Addrec();
   Readrec();
   Readln;
end.

Sample Output


Data File using Pascal Program

Pascal and Python program to find the roots of a quadric equation

Pascal program to find the roots of a quadric equation.

{find the roots of a Quadric equation ax2+bx+c=0}
program Quad;

var
  a,b,c :integer;
  d:real;

function delta(a:integer;b:integer;c:integer):real ;
begin
  delta:=sqr(b) - 4*a*c;
end;


Begin
  write('Enter the value for a ?');
  readln(a);
  write('Enter the value for b ?');
  readln(b);
  write('Enter the value for c ?');
  readln(c);
  d:= delta(a,b,c) ;
  if d> 0 then
     begin
          Writeln('You have more than one Answers');
          Write('The answer are ',((-1*b)+sqrt(d))/2*a:10:2);
          Writeln('    ',((-1*b)-sqrt(d))/2*a:10:2);
     end
  else
      if d=0 then
         begin
           Writeln('You have only one Answer');
           Writeln('The answer is ',((-1*b)/2*a):10:2);

         end
      else
         Writeln('You have no Answers');

  readln;


end.

Python Program to find the roots of a quadric equation.

import math
def delta(a,b,c):
    return b*b - 4*a*c

a=int(input("Enter Value for a?"))
b=int(input("Enter Value for b?"))
c=int(input("Enter Value for c?"))

d=delta(a,b,c)
if d>0:
    print("There are two answers  - ", ((-1*b)+ math.sqrt(d))/(2*a)," - ",((-1*b)- math.sqrt(d))/(2*a))
    
elif(d==0):
    print("There is only one answer -", (-1*b)/(2*a))

else:
    print("There is no answer")

Sample output


Pascal Program to find the roots of a quadric equation


Pascal - Quadric equation solution

Exercises to Python GUI Programming

Tkinter - GUI Programming Python

Question 1


Write a Python GUI Program to find the Area of a Rectancle with the following features. Able to enter width and height of a rectangle by the users.

  • Proper Prompted Messages to user for the above input.
  • Button to calculate and display the area of the rectangle for the above input.
  • Font should be Helvetica and size 15

Answer - Sample Python GUI Program

from tkinter import *
from tkinter.font import *

def myclick():
    A=int(W.get())*int(H.get())
    label3.configure(text="Area of the Rectangle :" +str(A))

root = Tk(className='Python Examples - Find Area of a Rectangle')
myfont=Font(family='Helvetica', size=15, weight='bold' )

label1 =Label(text="Enter the Width of a Rectangle", width=40,font=myfont, fg='Red')
label2 = Label(text="Enter the Height of a Rectangle", width=40, font=myfont, fg='Red')
label3 = Label(text=" ", width=40, font=myfont, fg='Green')

W=Entry(font=myfont, width=4)
H=Entry(font=myfont, width=4)

button = Button(text = 'Click me', font=myfont,command = myclick)

label1.grid(row=0, column=0)
W.grid(row=0, column=1)
label2.grid(row=1, column=0)
H.grid(row=1, column=1)
button.grid(row=2, column=0,columnspan=2)
label3.grid(row=5,column=0)

root.geometry("600x500")

mainloop()

Sample Output Screen


Python GUI with Tkinter

Python Exercises for ICT Students

Question
Write a Python function to sum all elements in a list which is passed as parameter and return the sum value.

Answer
#function to sum list
def Lsum(L):
    s=0
    for i in L:
        s=s+i
    return s

#call the function
sales=[15000,20000,3000,12000,5000,8900]
print(Lsum(sales))

Question
The factorial of a positive integers n is defined as n x (n-1) x (n-2) x ......x 3 x 2 x1.
Write a python function to return the factorial value of a given integer.

Answer
#function to find factorial value to a given number
def fact(n):
    Fact=n
    while (n>1):
        n=n-1
        Fact=Fact*n        
    return Fact

#call the function
N=int(input("Enter a number?"))
print(fact(N))

Question
Write a Python program to transform the data from in.csv file content to out.csv file. Content of the in.csv file is given below. The out.csv file should have total value as additional data.
 
Peter,80,90
David,100,75
Black,50,60

 Answer
f1=open("in.txt","r")
f2=open("out.csv","w")
for line in f1:
    items=line.strip().split(",")
    tot=int(int(items[1])+int(items[2]))
    print(items[0],items[1],items[2],tot,file=f2)
f1.close()
f2.close() 

Question
  1. Describe how you would determine whether a given positive integer is odd or even
  2. Develop a flowchart to represent an algorithm, based on the method suggested in (i) above, to decide whether a given positive integer is odd or even.
  3. Convert the flowchart you have obtained for the above (ii) into a pseudo code.
  4. Convert the pseudo code obtained in (iii) into a Python program.

Answers
i) 
Divide the given integer by 2 and get the remainder. 
If the remainder is 0 then the number is even otherwise the number is odd. 
(note: if we divide any number by 2 then remainder will be 0 or 1 only)




ii)
Flowchart to find odd or even
iii)
Pseudo code
Start
input N
R=N%2      #divide the number by 2 and get the remainder to R
if (R=1) then
	display  "the number is odd"
else
	display "The number is even"
endif
End




iv)
#Python Program
N=int(input("Enter a positive Integer?"))
R=N %2
if (R==1):
    print("The number is odd")
else:
    print("The number is even")


Sample Output
Enter a positive Integer?101
The number is odd

Enter a positive Integer?27
The number is odd 



Function to print whether a number is positive or negative and odd or even

Exercise to Learn selections in programming

Write a function to return a string to print whether a given number is positive or negative and odd or even.

Python Function to print whether a given number is positive or negative and odd or even

Program
#function
def PosnegAndOddEven(n):  
    if (n==0):
        x="zero"
    elif((n%2)==1):
        x="integer is odd and "
    else:
        x="integer is even and"
       
    if (n==0):
        x=x
    elif(n>0):
        x=x+ " Positive"
    else:
        x=x + " Negative"
        
    return x

#main
print(PosnegAndOddEven(0))
print(PosnegAndOddEven(2))
print(PosnegAndOddEven(-5))


Output
zero
integer is even and Positive
integer is odd and  Negative


Efficient Bubble Sort Programs

Efficient Bubble Sort Program

Bubble Sort is the one of the sorting algorithm to sort an array. The efficient bubble sort algorithm is given below as Pascal Program.

program Project1;
{procedure to swap two values}
Procedure swap(var x:integer;var y:integer)  ;
var
   temp: integer;
begin
     temp:=x;
     x:=y;
     y:=temp;
end;

{procedure to print a given array}
Procedure printArr(arr: Array of Integer)     ;
var
   i: integer;
begin
     for i:=0 to Length(arr)-1 do
     begin
          writeln(arr[i]);
     end;
 end;

{procedure to bubble sort the given array}
Procedure BubbleSort(var arr: Array of Integer);
var
   done: boolean;
   p,t,last:integer;

begin
     done:=False;
     t:=Length(arr)-1;
     while ((done=False)) do
     begin
          P:=0;
          done:=True;
          last:=t;
          while (p <last) do
          begin
               if (arr[p] > arr[p+1]) then
               begin
                    swap(arr[p],arr[p+1]);
                    t:=p;
                    done:=False;
               end;
               p:=p+1;
          end;
     end;
end;

{main Program}
var
  n: array [0..10] of integer;

begin
  n[0]:=1;
  n[1]:=2;
  n[2]:=3;
  n[3]:=10;
  n[4]:=20;
  n[5]:=25;
  n[6]:=50;
  n[7]:=60;
  n[8]:=70;
  n[9]:=80;
  n[10]:=100 ;
  BubbleSort(n);
  printArr(n);
  readln;
end.

Programs for Linear Search

Programs to Linear Search

Programs for Linear Search

Linear Search algorithm searches an element in a list/array which is not necessarily to be sorted. The algorithm will search entire list/array from beginning to end for the matching.

The Pascal, Python and Java programs are given for the Linear Search as a function which returns true if the element is found or it returns false.

Pascal Program for Linear Search

program LSearch;

Function LinearSearch(X: Integer; arr: Array of Integer): boolean;
var
   found: boolean;
   L,R:integer;

begin
     found:=False;
     if  (Length(arr) = 0) then
         LinearSearch:= found
     else
     begin
          L:=0;
          R:=Length(arr) - 1;
          while ((found=False) and (L<=R)) do
          begin
               if  (X=arr[L]) then
                   found:=True;
               L:=L+1;
	  end;
          LinearSearch:= found;
     end;
end;
{main program}
var
  n: array [0..9] of integer;
  inp: boolean;
  num:integer;

begin
  n[0]:=12;
  n[1]:=15;
  n[2]:=20;
  n[3]:=27;
  n[4]:=29;
  n[5]:=30;
  n[6]:=78;
  n[7]:=81;
  n[8]:=89;
  n[9]:=95;
  write('Enter a number to search?');
  readln(num);
  inp:=LinearSearch(num,n);
  writeln(inp);
  readln;
end.

Python Program for Linear Search

def LinearSearch(X, arr):
    found=False
    if  (len(arr)==0):
        return found
    else:
        L=0
        R=len(arr)-1
        while ((found==False) and  (L<=R)):
            if  (X==arr[L]):
                found=True
            L=L+1
        return found;		
#main program
AA=[20,30,4,7,8,20,100,150]
num=int(input("Enter a number?"))
F=LinearSearch(num,AA)
print("The number " ,num, "  found is : ", F)

Java program for Linear Search

import java.util.Scanner;
public class LinearSearch
{
	public boolean Search(int X, int[] arr)
	{
		boolean found;
		int L,R;	
		found=false;	
		if  ((arr.length)==0)
			return found;
		else
		{
			L=0;
			R=arr.length - 1;
			while ((found==false) && (L<=R))
			{
				if  (X==arr[L])
					found=true;
				L=L+1;	
			}
			return found;		
		}
	}
	//main
	public static void main(String arg[])
	{
		int[] AA;
		AA=new int[10];
		int num;
		boolean f;
		AA[0]=10;
		AA[1]=5;
		AA[2]=30;
		AA[3]=20;
		AA[4]=15;
		AA[5]=22;
		AA[6]=11;
		AA[7]=12;
		AA[8]=3;
		AA[9]=50;
		System.out.println("Enter a number to Search?");
		Scanner sc=new Scanner(System.in);
		num=sc.nextInt();
		LinearSearch LS= new LinearSearch();
		f=LS.Search(num,AA);
		System.out.println(f);		
	}
}


Binary search Programs

Binary Search Programs

Binary search Programs

Binary search is used to search an element in a sorted array. It is an efficient search algorithm in a sorted array. If the array is not sorted then the binary search is not working correctly. So when we use binary search algorithm; we have to make sure that the array is sorted.

Pascal, Python and Java Programs are given below for Binary Search:

Pascal Program for Binary Search

 
program binsearch;

{Function for binary Search
first parameter - integer number which we search in the sorted array
second parameter - is the sorted array in which we search the number}

function BinarySearch(X: Integer; A: Array of Integer): boolean;
var
  L, R, M, Cur: Integer;
  answer :boolean;
begin
  answer := false;
  if Length(A) = 0 then Exit;
  L := Low(A);
  R := High(A);
  while ((L <= R) AND (answer = false)) do
  begin
    M := ((L+R) div 2);
    Cur := A[M];
    if (X = Cur) then begin
	answer := true;
    end;
    if (X > Cur) then
       L := M +1
    else
      R := M-1;

  end;
  BinarySearch := answer;
end;

{Main Program}
var
  n: array [0..9] of integer;
  inp: boolean;
  num:integer;

begin
  n[0]:=12;
  n[1]:=15;
  n[2]:=20;
  n[3]:=27;
  n[4]:=29;
  n[5]:=30;
  n[6]:=78;
  n[7]:=81;
  n[8]:=89;
  n[9]:=95;
  write('Enter a number to search?');
  readln(num);
  inp:=BinarySearch(num,n);
  writeln(inp);
  readln;
end.

Python Program for Binary Search

 
def BinarySearch(X, A):     
    if not A:
        print('Array Empty')
    else:
        answer=False
        L=0
        R=len(A)-1
        while ((L<=R) and (answer==False)):
            M=((L+R) // 2)
            Cur=A[M]
            if (X==Cur):
                answer=True
            if (X>Cur):
                L=M+1
            else:
                R=M-1
    return answer

n=[10,12,45,60,70,80,90]
num=int(input('Enter a number to Search?'))
inp=BinarySearch(num, n)
print('Search number ', num, ' is ' , inp)

Java Program for Binary Search

import java.util.Scanner;

public class BinarySearch
{

	public boolean Search(int X, int[] A)
	{
		int L,R,M, Cur;
		boolean answer;
		answer=false;	
		if (A.length== 0)  
		{
			return answer;
		}
		else
		{
			L=0;
  			R=A.length-1;
			while ((L <= R) && (answer == false)) 
			{
 				M =(int) Math.floor((L+R) / 2);
				Cur= A[M];
				if (X == Cur)
				{
					answer = true;
				}
    				if (X > Cur)
					L = M +1;
    				else
      					R = M-1;  				
			}
			return answer;
		}
	}

	//Main Program
	public static void main(String arg[])
	{
		int[] arr={10,30,45,67,80,90,100};
		boolean f;
		int num;
		Scanner sc = new Scanner(System.in);
		System.out.print("Enter a number to search in the array");
		num=sc.nextInt();
		BinarySearch bs=new BinarySearch();
		f=bs.Search(num,arr);
		System.out.println(f);

	}

}



Programs to Guess a number

Programs to Guess a number

Programs to Guess a number Which is generated Randomly by Computer

Questions
Create a program in any third generation language which asks the user to guess a number between 1 and 10, compare it to a random number which was generated by the computer. The program should provide three chances to the user to input. If the user enter the number correctly the program should end and print the message "Congratulations you won the game...." If he fails to guess the number then program should end and print the message "You lost the game.."

Python, Pascal, C# and Java Program are given below as the solutions for the above problem:

 
Python Program 

from random import randint
randnum=randint(1,10)
count=0
found=False
while ((found!=True) and (count <3)):
    guessnum=int(input("Enter a number between 1 and 10..."))
    if (guessnum==randnum):
        found=True
    count=count+1

if (found==True):
    print("Congratulations ...You won the game!")
else:
    print("You lost the game!")


Sample Output if we guess all three chances uncorrecly 

Enter a number between 1 and 10...2
Enter a number between 1 and 10...1
Enter a number between 1 and 10...7
You lose the game!


Sample Output if we guess second time correctly 

Enter a number between 1 and 10...8
Enter a number between 1 and 10...3
Congratulations ...You won the game!

 
Pascal Program 

program Project1;

var
  randnum, count, guessnum : byte;
  found:boolean;
begin
  randomize; {to initialize the random number generator}
  randnum:= random(10);
  count:=0;
  found:=false;
  while ((found <>True) and (count <3)) do
  begin
       write('Enter a number between 1 and 10...');
       readln(guessnum);
       if (guessnum=randnum) then
       begin
            found:=True;
       end;
       count:=count+1;
  end;
  if (found=True) then
    writeln('Congratulations ...You won the game!')
  else
    writeln('You lost the game!');

  readln;
end.

 
C# Program 

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            int num, count, gnum;
            Random r = new Random();
            num = Convert.ToInt32(r.Next(1,10));
            Boolean found;
            found = false;
            count = 0;
            while ((found!= true) && (count <3))
            {
                Console.Write("Enter a Number between 1 and 10?");
                gnum=Convert.ToInt32(Console.ReadLine());
                if (gnum==num)
                {
                    found = true;
                
                }
                count = count + 1;
            }
            if (found==true)
            {
                Console.WriteLine("Congratulations ...You won the game!");
            }
            else
            {
                Console.WriteLine("You lost the game!");
            }
            Console.ReadLine();
        }
    }
}


 
Java Program

import java.lang.Math;
import java.util.*;
public class Myguess
{
	public static void main(String[] args)
	{
		int num, count, gnum;
		num=(int)(Math.random()*10);	     
		Scanner sc= new Scanner(System.in);            
		Boolean found;
		found = false;
		count = 0;
		while ((found!= true) && (count <3))
		{
			System.out.print("Enter a Number between 1 and 10?");
			gnum=sc.nextInt();;
			if (gnum==num)
			{
				found = true;  
			}
			count = count + 1;
		}
		if (found==true)
		{
			System.out.print("Congratulations ...You won the game!");
		}
		else
		{
			System.out.print("You lost the game!");
		}            
	}    
}


Python Assignments and Answers

Question 1)
A canteen of a school sells 10 different types of foods. These food types are placed in a shelf. Students can select foods while walking alongside the shelf and keep them on a tray. These trays are available at the entrance of the canteen. A student, after selecting the food, should proceed to the cashier with the food tray for the payment.
You are asked to develop a computer program to calculate the payment due for a food tray. For this purpose, each food type is given a unique integer from 1 to 10.
The integer value assigned for each food type and its unit price is shown in the following table.

Food type - Price (Rs.)
1 - 10.00
2 - 12.00
3 - 15.00
4 - 10.00
5 - 25.00
6 - 45.00
7 - 50.00
8 - 25.00
9 - 10.00
10 - 12.00

a) State all the inputs required for the computer program and its expected output.
b) Draw a flowchart to represent the algorithm required to compute the payment due for a food tray.
c) transform the above flowchart into a Python program.


a)
Input
Need to input Food type but price of the food can be retrieved from the list
Need to input number of items (Qty) Finish the calculation need to have a key to end, -1 is used to end repetition.
Output
print the Payment due (Total amount to be paid to the bill)
b)

Flowchart and Python Program
 
c) Python program is given below

price=[10.00,12.00,15.00,10.00,25.00,45.00,50.00,25.00,10.00,12.00]
mytot=0
myitem=0
while myitem >-1 :
     myitem=int(input('Enter a item Number?'))
     if myitem>=0 and myitem<=9:
          myitem=int(myitem-1)
          myprice=price[myitem]
          myqty=float(input('Enter a item Qty'))
          mytot=mytot+float(myprice*myqty)
print('Your Total due is=',mytot)


Question 2)
What is the output of the python program given below

 
Program

j=10
y=4
if j < y or j!=4:
     j-=y
     print (j)
else:
     y*=j
     print (y)


Output
6


Python Program to find the roots of Quadric Equation

Python Program to find the roots of Quadric Equation

The standard form of a quadratic equation is
ax2 + bx + c = 0.
where a, b are the coefficients, x is the variable, and c is the constant.
The Formula to find the roots of a quadratic equation is.

Quadratic Formula = [-b ± √(b² - 4ac)]/2a

If the √(b² - 4ac) = 0 then, we get only one answer = -b/2a
If the √(b² - 4ac) > 0 then, we get two answers = [-b + √(b² - 4ac)]/2a and [-b - √(b² - 4ac)]/2a
If the √(b² - 4ac) < 0 then, we get no answer

Write a Python Program to input a,b,c and print the roots.

Answer

 
import math
print('Finding the roots of the Quadric Equations')
a=int(input('Enter coefficient of x square a?'))
b=int(input('Enter coefficient of x  b?'))
c=int(input('Enter constant c?'))
d=b**2 - (4*a*c)
if d<0:
    print('No Answers')
else:
    if d==0:
        print('Only One Answer', (-1*b)/2*a)
    else:
        print('There are two answers')
        dd=math.sqrt(d)
        print('One Answer is ', float((-1*b + dd)/2*a))
        print('Another Answer is ', float((-1*b - dd)/2*a))
 

Sample Output

 
Finding the roots of the Quadric Equations
Enter coefficient of x square a?1
Enter coefficient of x  b?-4
Enter constant c?4
Only One Answer 2.0


Finding the roots of the Quadric Equations
Enter coefficient of x square a?1
Enter coefficient of x  b?-5
Enter constant c?6
There are two answers
One Answer is  3.0
Another Answer is  2.0


Finding the roots of the Quadric Equations
Enter coefficient of x square a?5
Enter coefficient of x  b?1
Enter constant c?3
No Answers



Pascal Program to Count the vowels

Pascal Program to Count the vowels in a given String

 
{Pascal Program to Count the vowels  in a given String}
program CountVowels;
{ Define Variables }
var s:String;
       i,c:integer;
       x:char;
begin
   {enter the name}
   Write('Enter a String?');
   readln(s);
   s:=UpCase(s);
   c:=0;
   {count the vowels in the string}
   for i:=1 to length(s)   do
   begin
        x:=s[i];
        if ( (x='A') or (x='E') or (x='I') or (x='O') or (x='U')) then
        begin
           c:=c+1;
        end;
   end;
   {Display Number of vowels}
   writeln('------------------------------------');
   writeln('Number of vowels in the String ',s,' is=: ',c);
   writeln('------------------------------------');   
   readln;
end.

Pascal Program to Count the vowels in a given String using a user defined function

 
{Pascal Program for Count the vowels  in a given String}
program CountVowels;
{ Define Variables }
var s:String;
       i,c:integer;
       x:char;
{function to check whether given charcter is a vowel}
function checkVowel(v:char):boolean  ;
begin
     if ( (v='A') or (v='E') or (v='I') or (v='O') or (v='U')) then
        checkVowel :=true
     else
         checkVowel:=false;
end;
{Main Progrm}
begin
   {Enter a input String }
   Write('Enter a String?');
   readln(s);
   s:=UpCase(s);
   c:=0;
   {count the vowels in the string using above function}
   for i:=1 to length(s)   do
   begin
        x:=s[i];
        {call the defined function}
        if ( checkVowel(x)) then
        begin
           c:=c+1;
        end;
   end;
   {Display the Number of vowels}   
   writeln('------------------------------------');
   writeln('Number of vowels in the String ',s,' is=: ',c);
   writeln('------------------------------------');   
   readln;
end.

Pascal Program to Count the vowels in a given String using Pascal Procedure with in/out parameter

 
{Pascal Program for Count the vowels  in a given String Using Procedure}
program CountVowels;
{ Define Variables }
var s:String;
       i,c:integer;
       x:char;
       ccv:boolean;
{Procedure to check whether given charcter is a vowel}
procedure checkVowel(v:char; var cv:boolean) ;
begin
     if ( (v='A') or (v='E') or (v='I') or (v='O') or (v='U')) then
        cv:=true
     else
         cv:=false;
end;
{Main Progrm}
begin
   {Enter a input String }
   Write('Enter a String?');
   readln(s);
   s:=UpCase(s);
   c:=0;
   {count the vowels in the string using above function}
   for i:=1 to length(s)   do
   begin
        x:=s[i];
        {call the procedure}
        ccv:=false;
        checkVowel(x,ccv);
        if (ccv=true) then
        begin
           c:=c+1;
        end;
   end;
   {Display the Number of vowels}
   writeln('------------------------------------');
   writeln('Number of vowels in the String ',s,' is=: ',c);
   writeln('------------------------------------');
   readln;
end. 


Click below link to Get Practical Explanation:




Array Exercises in Python

Question
Write a Python Program to print Maximum and Minimum number of a given array

 
from array import *

temper=array('i',[10,0,30,40,5,15,20,19,20,43])

def findmax(arr):
    mx=arr[0]
    for i in range(1,len(arr)):
        if arr[i]>mx:
            mx=arr[i]
    return mx

def findmin(arr):
    mn=arr[0]
    for i in range(1,len(arr)):
        if arr[i]<mn:
            mn=arr[i]
    return mn

print('Maximum',findmax(temper),sep=":")
print('Minimum',findmin(temper),sep=":")

Question
Input 3 months income and expenses of 5 companies and calculate the profit and print it. .

 
from array import *

#define 2D 
income=[[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0]]
expense=[[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0]]
profit=[[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0]]

#input 3 months income for 5 companies
for i in range(0,5):
    jan=int(input('A company Jan income?'))
    feb=int(input('A company Feb income?'))
    mar=int(input('A company mar income?'))
    income[i]=[jan,feb,mar]

#input 3 months expenses for 5 companies
for i in range(0,5):
    jan=int(input('A company Jan expenses?'))
    feb=int(input('A company Feb expenses?'))
    mar=int(input('A company mar expenses?'))
    expense[i]=[jan,feb,mar]

#Calculate profit and save in 2D array profit
for i in range(0,5):
    profit[i]=[income[i][0]-expense[i][0],income[i][1]-expense[i][1],
               income[i][2]-expense[i][2]]
    
#to print income details
for r in income:
    for c in r:
       print(c,end = " ")
    print()  

#to print expenses details
for r in expense:
    for c in r:
       print(c,end = " ")
    print()   

#to print profit details
for r in profit:
    for c in r:
       print(c,end = " ")
    print()    

Simple C# Console Programs

Learn C# with Examples and Exercises

Question 1
Create class Rectangle with instance data and write methods to input, calculate area and print the area.

 
Answer

using System;
class Rectangle
{
	double length;
	double width;
	double area;
	public void setData()
	{
		Console.Write("Entre value for length  ");
		length = Convert.ToDouble(Console.ReadLine());
		Console.Write("Entre value for Width  ");
		width = Convert.ToDouble(Console.ReadLine());         

	}
	public void calArea()
	{
		area = length * width;
	}
	public void displayData()
	{
		Console.WriteLine("Lenght={0}", length);
		Console.WriteLine("Width={0}", width);
		Console.WriteLine("Area={0}", area);
	}
	public static void Main(string[] args)
	{
		Rectangle r1=new Rectangle();
		r1.setData();
		r1.calArea();
		r1.displayData();
	}
}

Note: 
1) Save above program as Rectangle.cs 
2) Complie using csc Rectangle.cs
3) Run the Executable by double click


Question 2
Write any c# class with all type of constructor

 
Answer

using System;
class NewStudent
{
	string name = "Jhon";
	int age = 30;
	// Default Constructor
	public NewStudent()      
	{
		name = "White";
		age = 45;
		Console.WriteLine("Name={0}", name);
		Console.WriteLine("Age={0}" , age);
	}
	// Parametriazed Constructor 
	public NewStudent(string x, int y)  
	{
		name = x;
		age = y;
		Console.WriteLine("Name={0}", name);
		Console.WriteLine("Age={0}" , age);
	}
	// Copy Constructor
	public NewStudent(NewStudent S)      
	{
		name = S.name;
		age = S.age;
		Console.WriteLine("Name={0}", name);
		Console.WriteLine("Age={0}" , age);
	}
	// Private Constructor
	private NewStudent(string a)      
	{
		name = a;
		Console.WriteLine("Name={0}", name);
	}

	public static void Main(string[] args)
	{
		NewStudent s1=new NewStudent("Ganesh",40);
		NewStudent s2=new NewStudent();
		
	}
}


Question 3
Write any class as parent , and write a child class by using parent class.


Answer

using System;
class Father
{
	public string firstname = "White";
	protected string bank = "Commercial";
	internal string address = "16 Old Road";
	string designation = "Director";
}
class Child : Father
{
	public string secondname = "Red";
	public string degree = "Science";
	public void display()
	{
		Console.WriteLine("First Name is " + firstname);
		//Console.WriteLine(designation); //Can't access because it is private 
		Console.WriteLine("Second Name is " + secondname);
		Console.WriteLine("Address is " + address);
	}
	public static void Main(string[] args)
	{
		Child c1=new Child();
		c1.display();
	}
}


Question 4
Write a Console or Windows application to illustrate the concept of Overloading in C#.


Answer

using System;
class Rect
{
	double length;
	double width;
	double area;
	public Rect()
	{
		length=0;
		width=0;
	}
	public void setData()
	{
		length=0;
		width=0;
	}
	public void setData(double l)
	{
		length=l;
		width=l;
	}
	public void setData(double l, double w)
	{
		length=l;
		width=w;
	}
	public void calArea()
	{
		area = length * width;
	}
	public void displayData()
	{
		Console.WriteLine("Lenght={0}", length);
		Console.WriteLine("Width={0}", width);
		Console.WriteLine("Area={0}", area);
		Console.WriteLine("------------------------------");
	}
	public static void Main(string[] args)
	{
		Rect r1=new Rect();
		r1.calArea();
		r1.displayData();
		Rect r2=new Rect();
		r2. setData(12);
		r2.calArea();
		r2.displayData();
		Rect r3=new Rect();
		r3. setData(10,15);
		r3.calArea();
		r3.displayData();
	}
}



C# Program for Database Connection with MySQL

Sample C# Windows application program to connect MySql Database to do operation such as Select, Add, Edit, Delete and update.

Database Name : Viber
Table Name : Viber_Users
Columns in Table : Member_Id, Member_Name, State, Country

Screen Design


   
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MySql.Data;
using MySql.Data.MySqlClient;
namespace WinApp
{
    public partial class Viber2 : Form
    {
		Database db = new Database();
		public Viber2()
        {
            InitializeComponent();
        }

        private void Viber2_Load(object sender, EventArgs e)
        {

        }


		class Database
		{
			private MySqlConnection con;
			private MySqlCommand cmd;
			private MySqlDataAdapter da;

			public Database() // Default Constructor
			{
				con = new MySqlConnection("server=localhost;user=ganesh;database=viber;password=DSHUc4kzLJCp1Gho");
			}
			public void openConnection()
			{
				con.Open();
			}

			public void closeConnection()
			{
				con.Close();
			}

			public int save_update_delete(string a)
			{
				openConnection();
				cmd = new MySqlCommand(a, con);
				int i = cmd.ExecuteNonQuery();
				closeConnection();
				return i;
			}
			public DataTable getData(string a)
			{
				openConnection();
				da = new MySqlDataAdapter(a, con);
				DataTable dt = new DataTable();
				da.Fill(dt);
				closeConnection();
				return dt;
			}
		}

		private void btn_add_Click(object sender, EventArgs e)
		{
			int i = db.save_update_delete("Insert into Viber_Users values (" + Convert.ToInt16(txt_memid.Text) 
				+ ",'" 	+ txt_memname.Text + "', '" + txt_state.Text + "', '" + txt_country.Text + "')");
			if (i == 1)
				MessageBox.Show("Data Inserted Succesfully", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
			else
				MessageBox.Show("Data not Inserted", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
		}

		private void btn_list_Click(object sender, EventArgs e)
		{
			dataGridView1.DataSource = db.getData("select * from viber_users");
		}

		private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)		
		{
			txt_memid.Text= dataGridView1.CurrentRow.Cells[0].Value.ToString();
			txt_memname.Text = dataGridView1.CurrentRow.Cells[1].Value.ToString();
			txt_state.Text = dataGridView1.CurrentRow.Cells[2].Value.ToString();
			txt_country.Text = dataGridView1.CurrentRow.Cells[3].Value.ToString();
		
		}

		private void btn_edit_Click(object sender, EventArgs e)
		{
			DialogResult dr = MessageBox.Show("Do you really want to Update?", "Infromation", MessageBoxButtons.YesNo, MessageBoxIcon.Information);

			if (dr.ToString() == "Yes")
			{
				int i = db.save_update_delete("Update Viber_Users set Member_Name= '" + txt_memname.Text
					+ "', State= '" + txt_state.Text
					+ "', Country= '" + txt_country.Text + "'"
					+ " where Member_Id= " + Convert.ToInt16(txt_memid.Text));

				if (i == 1)
					MessageBox.Show("Data Update Successfully", "Infromation", MessageBoxButtons.OK, MessageBoxIcon.Information);
				else
					MessageBox.Show("Data Cannot Update", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
		}

		private void btn_delete_Click(object sender, EventArgs e)
		{
			DialogResult dr = MessageBox.Show("Do you really want to Delete?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);

			if (dr.ToString() == "Yes")
			{
				int i = db.save_update_delete("Delete from Viber_Users where Member_Id= " + Convert.ToInt16(txt_memid.Text));
				if (i == 1)
					MessageBox.Show("Data Delete Successfully", "Infromation", MessageBoxButtons.OK, MessageBoxIcon.Information);
				else
					MessageBox.Show("Data Cannot Delete", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
		}

		private void btn_search_Click(object sender, EventArgs e)
		{
			if (txt_search.TextLength > 0)
			{
				if (rbn_id.Checked == true)
				{
					dataGridView1.DataSource = db.getData("select * from Viber_Users where Member_Id =" + Convert.ToInt16(txt_search.Text));
				}
				else
				{
					dataGridView1.DataSource = db.getData("select * from Viber_Users where Member_Name like '" + txt_search.Text + "%' ");
				}
			}
			else
			{
				dataGridView1.DataSource = db.getData("select * from Viber_Users");
			}
		}
	}
}
  



Pascal Program Exercises with Answers (Binary, Decimal Conversions)

Write a Pascal Program to convert a given Decimal number to equivalent Binary number?

 program DecimalToBinary;

var
  remainder, quotient, num,i:integer;
  binary,addbin:String;

begin
  write('Enter a Decimal Number?');
  read(num);
  addbin:='';
  binary:='';
  while (num >=2)  do
  begin
    remainder:= num mod 2;
    quotient:= num div 2;
    Str(remainder,binary);
    addbin:=addbin+binary;
    num:= quotient ;
  end;
  Str(num,binary);
  addbin:=addbin+binary;
  for i:=length(addbin) downto 1 do
  begin
      write(addbin[i]);
  end;
  readln;
end.  


Write a Pascal Program to convert a given Binary number to equivalent Decimal number?

 program BinarytoDecimal;
uses math,sysutils;

var
   binary:string;
   i,j,num:integer;
   decnum:float;

begin
  decnum:=0;
  write('Enter a Binary number ?');
  read(binary);
  write(chr(13));
  write('Binary number :');
  writeln(binary);
  write(chr(13));
  i:=length(binary);
  j:=0;
  while (i >=1) do
  begin
    num:=StrToInt(binary[i]) ;
    decnum:=decnum+(num * power(2,j));
    i:=i-1;
    j:=j+1;
  end;
  write('Equivalent decimal number is :');
  writeln(decnum:8:0);
  readln;
  readln;
end.
            
Pascal Program to Convert Binary to Decimal


Flow Chart and Pascal Program for Fibonacci Series

Draw a flow chart which generates Fibonacci series which  element's value is less than 100


Flow chart and Pascal Program for Fibonacci














Write a Pascal Program to generate Fibonacci series which  element's value is less than 100

program FibonacciSeries;

var
  previous, beforeprevious,current:integer;

begin
  writeln(chr(13));
  write('First 100 items of the Fibonacci series...');
  writeln(chr(13));
  write('------------------------------------------');
  writeln(chr(13));
  writeln(chr(13));
  current:=1;
  previous:=1;
  while (current <=100) do
  begin
    write(current);
    write(Chr(9));
    beforeprevious:=previous;
    previous:=current;
    current:= beforeprevious+previous;
  end;
  readln;
end.    

Note:
In mathematics, the Fibonacci numbers, commonly denoted Fn, form a sequence, called the Fibonacci sequence, such that each number is the sum of the two preceding ones, starting from 0 and 1.
Fn=Fn-1 +Fn-2
For n>1

Then the beginning of the sequence is :
0,1,1,2,3,5,8,13,21,34,55,89,144...

In some books, the value F0=0 is omitted, so that the sequence starts with F1=F2=1 and the recurrence
Fn=Fn-1+Fn-2
For n>2
1,1,2,3,5,8,13,21,34,55,89,144...


Pascal Program to Print Sequence 0,1,1,2,3,5,8,13,21,34,55,89... is given below.

program FibonacciSeries;

var
  previous, beforeprevious,current:integer;

begin
  writeln(chr(13));
  write('First 100 items of the Fibonacci series...');
  writeln(chr(13));
  write('------------------------------------------');
  writeln(chr(13));
  writeln(chr(13));
  current:=0;
  previous:=1;
  while (current  <=100) do
  begin
    write(current);
    write(Chr(9));
    beforeprevious:=previous;
    previous:=current;
    current:= beforeprevious+previous;
  end;
  readln;
end.             

Printing Fibonacci series using a recursive function

program recursiveFibonacci;
var
   i,n: integer;
function fibonacci(n: integer): integer;

begin
   if n=1 then
      fibonacci := 0

   else if n=2 then
      fibonacci := 1

   else
      fibonacci := fibonacci(n-1) + fibonacci(n-2);
end;

begin
   i:=1 ;
   while(n<=100) do
   begin
        n:= fibonacci (i);
        if n > 100 then
           break;
        write(n, '  ');
        i:=i+1;
   end;

   readln;
end.

Flowchart to find the largest of three numbers

Draw a flowchart to find the largest of three numbers x, y and z.

Flowchart and Pascal Program to Find Maximum of three numbers


Write a Pascal Program to find the largest of three numbers x, y and z.
Method I

program FindMaxFrom3;
var
  x,y,z,max :integer;

begin
  writeln('Enter a Number?');
  read(x);
  writeln('Enter a Number?');
  read(y);
  writeln('Enter a Number?');
  read(z);
  if (x > y) then
     if (z > x) then
        max:=z
     else
        max:=x
  else
    if (z > y) then
       max:=z
    else
        max:=y;
  writeln('Maximum number is :');
  write(max);
  readln;
end.  

Method II

program FindMaxOf3num;
var
  x,y,z,max :integer;

begin
  writeln('Enter a Number?');
  read(x);
  writeln('Enter a Number?');
  read(y);
  writeln('Enter a Number?');
  read(z);
  if (x > y) then
     max:=x
  else
      max:=y;

  if (z >max) then
     max:=z;
  writeln('Maximum number is :');
  write(max);
  readln;
  readln;
end.

or

We can use a Pascal procedure to find the maximum number of given three numbers as input parameters and maximum number as output parameter . Below Pascal program shows that

program findMaximum;
var
  m:integer;

procedure findMax(x, y, z: integer; var  max: integer)   ;
begin
   if (x > y) then
      max := x
   else
      max := y;

   if (z > max) then
      max := z;
end;

begin
     findMax(20,300,120,m);
     writeln(m);
     readln;
end.  

or

We can use a Pascal function to find maximum number from given three numbers by passing three numbers as input parameters and return the maximum number as return value. Below Pascal program shows that

program findMaximumFunction;
var
  m:integer;

function findMax(x, y, z: integer):integer   ;
var
  max:integer;
begin

   if (x > y) then
      max := x
   else
      max := y;

   if (z > max) then
      max := z;
   findMax:=max;
end;

begin
     m:=findMax(20,300,120);
     writeln(m);
     readln;
end.