Saturday, October 20, 2018

Find the Smallest Number from 10 Numbers

Question

Draw flowchart, write pseudocode and Pascal program for the problem of finding the smallest number of 10 numbers.


Answer

Flowchart


flowchart to find smallest number
 
Pseudocode

Start
input number N
Min=N
Count=1
While Count <10
        Input number N
        if  N < Min
              Min=N
        endif
        Count=Count + 1
end while
print Min
end

Pascal Program

 
Program fimdsmallest;
var
  N:Integer;
  Count:integer;
  Min:integer;
begin
  write('Enter a Number ?');
  readln(N);
  Count:=1;
  Min:=N;
  while Count < 10 do
  begin
    write('Enter a Number ?');
    readln(N);
    if N < Min then
       Min:=N;
    Count:=Count+1;
  end;
  write('Minimum Number is :') ;
  writeln(Min);
  readln;
end.

Output Screen of the above Pascal program


FindSmallestNum



Java Assignments and Answers

Create a class called MyPoint, which models a 2D point with x and y cordinates. It contains:

  1. Two instance variables x(int) and y(int)
  2. A "no-arguments" contructor that contruct a point at (0,0).
  3. A constructor that constructs a point with given x and y cordinates.
  4. Getter and setter for the instance variables x and y.
    • setX(int x): set the value of x coordinate by passing the value.
    • setY(int y): set the value of y coordinate by passing the value.
    • getX(): return the value of x coordinate.
    • getY(): return the value of y coordinate.
  5. A method setXY() to set both x and y.
  6. A toString() method that returns a string description of the instance in the format "(x,y)"
  7. A method called distance(int x, int y) that returns the distance as a double value from this point to another point at the given (x,y) cordinate.
  8. An overloaded distance(MyPoint p) that returns the distance as a double value from this point to the given Mypoint instance p.

Distance of two points as calculates as given below.
distance of two points= sqrt((x1-x2)2 + (y1-y2)2)


Answer
 
class MyPoint
{
 int x;
 int y;

 public MyPoint()
 {
  this.x=0;
  this.y=0;
 }

 public MyPoint(int x,int y)
 {
  this.x=x;
  this.y=y;
 }

 public void setX(int x)
 {
  this.x=x;
 }

 public void setY(int x)
 {
  this.y=y;
 }
 
 
 public int getX()
 {
  return this.x;
 }

 public int getY()
 {
  return this.y;
 }

 public void setXY(int x,int y)
 {

  this.x=x;
  this.y=y;
 }

 public String toString()
 {
  return "(" + this.x + "," + this.y + ")";
 }


 public double distance(int x,int y)
 {
   
  double d1;
  d1=((this.x - x)*(this.x - x)) + ((this.y -y)* (this.y -y));
  return Math.sqrt(d1);
 }

 public double distance(MyPoint p)
 {
   
  MyPoint p1=new MyPoint();
  p1=p;
  double d1;
  d1=(this.x - p1.getX())*(this.x - p1.getX())+ (this.y - p1.getY())*(this.y - p1.getY());
  return Math.sqrt(d1);
 }
}

Create a class called MyCircle, which models a circle with a center(x,y) and a radius.The MyCircle class uses an instance of MyPoint class (created in the previous exercise) as its center.
The class should contain:

  1. Two private instance variables center(an instance of MyPoint) and radius(int).
  2. A constructor that construct a  circle with the given center's(x,y) coordinate and radius.
  3. An overloaded constructor that constructs a MyCircle by giving a MyPoint instance as center, and radius.
  4. Various getters and setter.
    • setCenter(MyPoint p): set the center coordinates by passing the MyPoint instance as center.
    • getCenter(): return the coordinate of the center point as MyPoint
    • setRadius(int r): set the value of radius by passing the value
    • getRadius(): return the value of the radius


Answer
 
class MyCircle
{
 private MyPoint center;
 private int radious;

 public MyCircle(int x,int y,int r)
 {
  center=new MyPoint();
  center.setXY(x,y);
  this.radious=r;
 }

 public MyCircle(MyPoint p,int r)
 {
  center=new MyPoint();
  center.setXY(p.getX(),p.getY());
  this.radious=r;
 }


 public void setCenter(MyPoint p)
 {
  center.setXY(p.getX(),p.getY());
  
 }

 public MyPoint getCenter()
 {
  return center;
  
 }

 public void setRadious(int r)
 {
  this.radious=r;
  
 }

 public int getRadious()
 {
  return radious;
  
 }

 public String toString()
 {
    
  return " Circle @ (" + center.getX() + "," + center.getY() + ")  radious = " + radious;
 }

 public double getArea()
 {
  return (22/7)*radious*radious;
 }

}



Create a public class called TestMyCirlce and do the following:

  1. Create point p1 using no argument constructor.
  2. Set the X,Y coordinates
  3. Create point p2 using two arguments constructor.
  4. Display the distance between p1 and p2 points.
  5. Display the distance between p1 and given point by passing x,y coordinates of that point.
  6. Create a circle c1 using two arguments constructor. Pass the point p1 as the center.
  7. Display the area of the circle.
  8. Create a circle c2 using three arguments constructor.
  9. Display the area of the cirlce c2.


Answer
 
public class TestMyCircle
{
 public static void main(String arg[])
 {
  MyPoint p1=new MyPoint();
  p1.setXY(50,50);
  MyPoint p2=new MyPoint(100,100);
  System.out.println("Distance between p1 and p2  : " + p1.distance(p2));
 System.out.println("Distance between p1 and given point 200,200 : " + p1.distance(200,200));
  MyCircle c1=new MyCircle(p1,50);
  System.out.println("Area of the circle - two argument : " + c1.getArea());
  MyCircle c2=new MyCircle(250,250,150); 
  System.out.println("Area of the circle -three arguement : " + c2.getArea());

  
 }
}




Friday, October 19, 2018

GCE(O/L) Past Paper question and answer Flow chart

A teacher of a class of 35 students obtains the student preference to travel either by train or bus on their annual trip. The following flow chart with missing terms labelled A to E represents this scenario. Write down the appropriate terms for the labels A to E. (Any variable names that are used in your answer must be exactly as given in the question.)

GCE(O/L) Past Paper Question

Answer

A   -  0                    (bus_count=0)
B   -  35                   (student_count < 35)
C   -  train_count          (train_count=train_count + 1)
D   -  train_count          (train_count > bus_count)
E   -  tour by bus


Note
Pascal program is given for the above algorithm for extra knowledge.


program findTravelPreference;

var
  total_student:integer;
  student_count:integer;
  train_count:integer;
  bus_count:integer;
  student_preference:String;
begin
  total_student:=2;
  student_count:=0;
  train_count:=0;
  bus_count:=0;
  while student_count < 35 do
  begin
    writeln('Enter your prefernce Bus/Train');
    readln(student_preference);
    if student_preference='Bus' then
       bus_count:=bus_count + 1
    else
        train_count:=train_count +1;
    student_count:=student_count+1;
  end;
  if train_count > bus_count then
     writeln('tour by train')
  else
      writeln('tour by bus');
  readln;
end.
               



Pseudocode GCE(O/L) Past Paper Questions and Answers

Question 1

A School has 1000 students. The following pseudocode segment prints the admission numbers of students who attended the school everyday (i.e 210 days) in a particular year.

N=0
While N <1000
         get AdmissionNumber
         get NumberOfDays
         if NumberOfDays=210 then
         	print AdmissionNumber
         end if
         N=N+1
End while

Draw a flowchart to represent the above pseudocode. (Use the same variable names as given in the pseudocode in your flowchart.)


Answer


GCE(O/L) Past Paper Pseudocode answer

Note for extra knowledge
Pseudocode and flowcharts are designing tool/technic for algorithm. Once we correctly did it, it would be very easy to write in any programming languages.
Pascal Program is given below.


progrma printadno;
var
  N:integer;
  AdmissionNumber:integer;
  NumberOfDays:integer;
begin
  N:=0;
  while N < 1000 do
  begin
    writeln('Enter Addmission Number ?');
    readln(AdmissionNumber);
    writeln('Enter Number of days?');
    readln(NumberOfDays);
    if NumberOfDays=210   then
       Writeln(AdmissionNumber);
   N:=N+1;
  end;
end.



Thursday, October 18, 2018

Pascal Question GCE(O/L) MCQ and Essay

Question 1
Consider the following pascal programme
program repetition(input, output);
var x: integer;
begin
  x:=1;
  repeat
    write(x);
    x:=x+1;
  until x=3;
end.

What is the correct output when the above program is executed ?
Answer
until x reach 3 the   repetition will work. The write statement which is above the increment statement  when x gets value 1 and 2 display it, when x gets 3 condition becomes true and repetition end.
(write statement in Pascal display the output horizontally)
The output of the program will be
1 2

Question 2
Consider the following pseudocode with label ® to calculate the sum of numbers from 1 to 100.

sum=0
num=0
repeat
  num=num+1
  sum=sum+num
until
®

for the above mentioned
pseudocode, what is the correct condition that matches with the label ®? 

Answer
The condition given should be false to work repeat until repetition. Sum is happening after increased the variable num by 1. Finally when the variable num gets 100, the value 100 should add to sum  and repetition should break. 
so the answer is 
num=100
 


Question 3
Consider the following pascal programme.
var 
  count:integer;
begin
  repeat
    count:=0;
    write('Hellow   ');
    count:=count+1;
  until count >4;
  while count > 4   do
    begin
    write('Hellow  ');
    count:=count -1;
    end;
  readln;

end.    
What is the correct output when the above program is executed ?

Answer
Count value start from 0.
Until condition is count >0.
Write command is above the increment statement of count variable.
The write statement is which is within the repetition, output 'Helow' will appear  when  count  0,1,2,3,4.
Once count get five break the repetition.
Now  count is 5.
It check the while condition count > 4, the result true so it write the output 'Hellow' and then decrease the count by 1.
Now count 4 then while condition get false.

So repeat until loop print hellow 5 times and while loop print hellow 1 time. total times is 6.

->6 times

Question 4
Consider the following program segment in pascal and write the output of the below program.

program myarr;
var
   num:array[0..4] of integer;
   i:integer;
begin
  num[0]:=15;
  num[2]:=18;
  num[4]:= 50;
  num[1]:=num[4]+10;
  num[3]:=num[0]+num[2];
  for i:=1 to 4 do
      writeln(num[i]);
  readln;

end. 

Answer
60
18
33
50

Explanation
Pascal Questions and Answers from Past Paper






Wednesday, October 17, 2018

Functions in Python with Exercises

How to write Python Functions

How to write Python Functions

Functions

Functions are useful for breaking up a large program to make it easier to read and maintain. (Decrease Complexity) 

They are also useful if find ourselves writing the same code at several different points in our program(Reusability of the code).

We can put that code in a function and call the function whenever we want to execute that code. (Remove Redundancy)

There are two types of functions Built in Functions and User defined functions. Functions those are provided by the language are called Built in Functions.

  • Functions help us to develop our own library. (User defined functions)
  • Functions are defined in Python with def and end with colon.
  • The code of the function are indented below def.


Some examples of User Defined Functions.

Example 1:
Python function to print a box

#define square
def my_square():
 print('|'*25)
 print('|',' '*21,'|')
 print('|',' '*21,'|')
 print('|',' '*21,'|')
 print('|'*25)
#call function
my_square()

Example 2:
Python function to print a box where width of the box is passed as parameter.

#define square
def my_square(n):
  print('|'*n)
  print('|',' '*(n-4),'|')
  print('|',' '*(n-4),'|')
  print('|',' '*(n-4),'|')
  print('|'*n)
#call function by giving the value to argument
my_square(35)
my_square(55)

Example 3:
Python Function returns  area of the circle where radius is passed as parameter .

#define a function to calculate area of circle
#radious is passed into function by a parameter
def circle_area(r):
  p=22/7
  return p*r*r
#the function circle_area() is called with print
print(circle_area(7))
print(circle_area(14))

Example 4:
Function with default arguments. Default arguments need to come at the end of the function definition, after all of the non-default arguments. 

def multiple_print(string, n=1):
  print(string * n) 
  print()

#call function with replace the default value 1 with 5
multiple_print('Hello', 5) 
#call function with default value 1
multiple_print('Hello')

Example 5:
Function to convert the Celcious to Fahrenheit. Celcious is passed as parameter and the function return the Fahrenheit value.

#define function in Python
def ctof(c):
 f=(c*9)/5+32;
 return f
#calling function by giving Celcious value which is input by user
cc=int(input('Enter Celcious value ?'))
print("Celcious " ,cc," =Fahrenheite",ctof(cc))  

Example 6:
Function with list as parameter

def mylist(list):
 return list
l=[]
for i in range(0,10):
 l.append(i)
     print(mylist(l))

Example 7:
Function to count each characters of a given string where string value is passed as parameter.

def char_search(n):
    string = n
    string=string.upper()
    for c in ('ABCDEFGHIJKLMNOPQRSTUVWXYZ'):
        char = c
        val = string.count(char)
        print(c,'Total = ',val)

yourname=input('Enter you Name?')
char_search(yourname)

Example 8:
Function to find whether a given number is odd number.

def find_odd(x):
    if x%2==1:
        return True
    else:
        return False
#call the function
print (find_odd(5))
print (find_odd(6))

Example 9:
Function to return a random number between 1 and 10.

#Python function to find a random number between 1 and 10.
def find_rand():
    from random import randint 
    x = randint(1,10)
    return x
#call the function
for i in range(10):
    print(find_rand())


Example 10:
Function to return numbers of vowels in a string where string is passed as parameter.

def count_vowels(s):
    a=s.count('a')
    e=s.count('e')
    i=s.count('i')
    o=s.count('o')
    u=s.count('u')
    return a+e+i+o+u
print (count_vowels('orange'))



Procedures and Functions Using Pascal

  • In computer programming, a subroutine is a sequence of program instructions that performs a specific task, packaged as a unit. This unit can then be used in programs wherever that particular task should be performed.
  • Subprograms may be defined within programs, or separately in libraries that can be used by many programs.
  • In different programming languages, a subroutine may be called as a procedure, a function, a routine, a method, or a subprogram. The generic term callable unit is sometimes used.
  • The content of a subroutine is its body, which is the piece of program code that is executed when the subroutine is called or invoked.
  • A function returns a value and a procedure just executes commands. The name function comes from math. It is used to calculate a value based on input. A procedure is a set of command which can be executed in order, even functions can have a set of commands but the difference is only in the returning a value part.
  • A subroutine may be written so that it expects to obtain one or more data values from the calling program.
  • The calling program provides actual values for these parameters, called arguments.
  • Different programming languages may use different conventions for passing arguments.
    Eg :
    Call by value : Argument is evaluated and copy of value is passed to subroutine,
    Call by reference : Reference to argument, typically its address is passed
  • Local data is accessible only from within the program in which the local data is declared. Local data is not visible or accessible to any program outside of the one where it is declared.
  • Global data is accessible from within the program in which the global data is declared or from within any other nested programs which are directly or indirectly contained in the program that declared the global data.

The advantages of breaking a program into subroutines
  • A complex programming task into simpler steps
  • Reducing duplicate code within a program
  • Enabling reuse of code across multiple programs
  • Hiding implementation details from users of the subroutine
  • Improving readability of code by replacing a block of code with a function call

Exercises Using Pascal



Procedure in Pascal with Global, Local Data without Parameter

var
 c:integer; {define global variable}

{procedure declaration with global,local data}
procedure ctof() ;
var
  f:real;   {define local variable}
begin
    f:=(c*9)/5+32;
    write('Celcious ',c,' = to farenheite',f:6:2);
end;

{main program}
begin
  write('Enter a celcious value?');
  readln(c);
  ctof();   {calling procedure}
  readln;
end.


Procedure in Pascal with Parameter - Call by value

var
  c:integer; {define global variable}

{procedure declaration with parameter }
procedure ctof(cc:integer) ;
var
  f:real;   {define local variable}
begin
    f:=(cc*9)/5+32;
    write('Celcious ',cc,' = to farenheite',f:6:2);
end;

{main program}
begin
  write('Enter a celcious value?');
  readln(c);
  ctof(c);   {calling procedure -> call by value}
  readln;
end.



Procedure in Pascal with Parameters - Call by Reference

{define Global data}
var
  c:integer;
  f:real; '

 {Define procedure with parameters -> Call by reference}
procedure ctof(cc:integer;var ff:real) ;
begin
    ff:=(cc*9)/5+32;
    write('Celcious ',cc,' = to farenheite',ff:6:2);
end;
{main program}
begin
  write('Enter a celcious value?');
  readln(c);
  ctof(c,f);   {calling procedure -> call by reference}
  readln;
end.


Function in Pascal with Parameter

{define Global data}
var
  c:integer;
  f:real;

 {Define function with parameters }
function ctof(cc:integer):real ;
var
  {local variable}
  ff:real;
begin
    ff:=(cc*9)/5+32;
    ctof:=ff;
end;
{main program}
begin
  write('Enter a celcious value?');
  readln(c);
  write('Celcious ',c,' = Fahrenheite ',ctof(c):5:2); {calling function with parameter}
  readln;
end. 

Watch Video with English Subtitle




Tuesday, October 16, 2018

Arrays in Pascal

Single dimension array in Pascal

var
   x:array[1..10] of integer;     {define single dimention array}
   i:integer;
begin
  {repetition to enter numbers into array}
  for i:=1 to 10 do
  begin
    write('Enter a Number ?');
    readln(x[i]);
  end;
  {repetition to print all array elements}
  for i:=1 to 10 do
  begin
    write(i);
    write('number is :');
    writeln(x[i]);
  end;
  readln;
end.

List is used as array in Python, If we write the above program in Python

#list in Python
mylist=[] # define list
# enter element into Python
for i in range(0,10):
    num=int(input("Enter a number ?"))
    mylist.append(num)
# print elments of list
print(mylist)


Python, Pascal program to Print Celsius and Fahrenheit table

Python Program

 
f=0
print ("Celsius","\t", "Fahrenheit")
print ("--------","\t", "----------")

for c in range(0,101,5):
    f=(9*c/5)+32
    print(c,"\t\t",f)

Python Program Using User Defined Function

   
def ctof(c):
    f=9*c/5+32
    return f

#print c - f table
print('Celcius','Fahrenheit',sep='\t:\t')
for c in range(0,101,10):
    print(c,ctof(c),sep='\t:\t')

print('Done')

CtoFTablePython

Click below link to watch Video for Practical  Explanation


Video Practical Explanation Python


Pascal Program to Print Celsius Fahrenheit table


 program CtoFTable;
var
  c:integer;
  f:real;
begin
  writeln('Celsius',#9, 'Fahrenheit');
  writeln('------------',#9,'------------');
  for c:=0 to 100 do
  begin
    f:=(9*c/5)+32;
    writeln(c,#9,f:8:2);
    inc(PInteger(@c)^ ,4);
  end;
  readln;
end.   

Pascal Program Using User Defined Function

program CtoFTable;
{Global Variable}
var
  c:integer;
  f:real;

{User define function to convert c to f}
function ctof(c:integer):real;
{Local Variable}
var
  ff:real ;
begin
  ff:=(9*c/5)+32;
  ctof:=ff;
end;

{main Program}
begin
  writeln('Celsius',#9#9, 'Fahrenheit');
  writeln('------------',#9,'------------');
  for c:=0 to 100 do
  begin
    f:=ctof(c);
    writeln(c,#9#9,f:8:2);
    inc(PInteger(@c)^ ,4);
  end;
  readln;
end.   

CtoFTablePascal

Note :

The formula to convert Fahrenheit to Celsius is
c/5=(f-32)/9

Monday, October 15, 2018

Python program to print Prime numbers

  • Python variables do not need explicit declaration to reserve memory space.
  • The declaration happens automatically when you assign a value to a variable.
  • The equal sign (=) is used to assign values to variables.
  • Statements always end in a NEWLINE.
  • A block is a group of statements in a program. code blocks are defined by their indentation in Python.

Sample Python Program with Output is given below
Print Prime numbers between 1 and 100


i=2
while i<=100:
    prime=True
    j=2
    while j<i and prime==True:
        if i % j ==0:
            prime=False
        j=j+1
    if prime==True:
        print(i)
    i=i+1


PythonSource


PythomOutputPrimeNumbers


Note

Efficient program than previous is given below
Reason for the new algorithm :
When we try to find the factors of number 20. The factors are 2,4,5,10,20. the last number is number itself. Previous number is less than half of the number. It is true for any number.

i=2
while i<=100:
    prime=True
    j=2
    while j<=int(i/2) and prime==True:
        if i % j ==0:
            prime=False
        j=j+1
    if prime==True:
        print(i)
    i=i+1

  
Click here to get the same program in Pascal




Python program to print number pattern Exercises and answers


Python Exercises to Print Patterns

  • Write a program that uses a for loop to print  below pattern.
    **********
    **********
    **********
    **********
    **********

    for i in range(5):
        print('*'*10)
  • Write a program that uses a for loop to print the numbers 1 2 3 4 5 6 7 8 9 10.

    for i in range(1,10+1,1):
        print(i,end=' ')
  • Write a program that uses a for loop to print the numbers 10,9,8,7,6,5,4,3,2,1.

    for i in range(10,1-1,-1):
        print(i,end=',')
  • Write a program that uses a for loop to print the numbers 8, 11, 14, 17, 20, ..., 83, 86, 89.

    for i in range(8,89+3,3):
        print(i,end=',')
  • Write a program that uses a for loop to print  below pattern.
    *
    **
    ***
    ****
    *****

    for i in range(4):
        print('*'*(i+1))
  • Write a program that uses a for loop to print  below pattern.
    *****
    ****
    ***
    **
    *

    for i in range(6,1-1,-1):
        print('*'*(i-1))
  • Write a program that asks the user for their name and how many times to print it. The program should print out the user’s name the specified number of times.

    Name=input('Enter Your Name?')
    times=eval(input('Enter How many times to repeat?'))
    for i in range(times):
        print(Name)

  • Write a program that uses a for loop to print the numbers 8, 11, 14, 17, 20, ..., 83, 86, 89.

    for i in range(8,89+3,3):
        print(i,end=',')
  • Python program to print number pattern as below
    1
    1 2
    1 2 3
    1 2 3 4
    1 2 3 4 5
    1 2 3 4 5 6
    1 2 3 4 5 6 7
    1 2 3 4 5 6 7 8
    1 2 3 4 5 6 7 8 9
    1 2 3 4 5 6 7 8 9 10

    mylist=[] # list
    for i in range(1,11):
        for j in range(1,i+1):
            mylist.append(j) # add element to list
        print(mylist)
        mylist.clear()
  • Python program to print number pattern as below
                   * 
                * * * 
              * * * * * 
            * * * * * * * 
          * * * * * * * * * 
        * * * * * * * * * * * 
      * * * * * * * * * * * * * 
    * * * * * * * * * * * * * * * 
  * * * * * * * * * * * * * * * * * 
* * * * * * * * * * * * * * * * * * * 

k = 0
rows = 10
for i in range(1, rows+1):
    for space in range(1, (rows-i)+1):
        print(end="  ")
    while k != (2*i-1):
        print("* ", end="")
        k = k + 1
    k = 0
    print()


Click below link to Learn Python Video Lession:



Python program to find Max Min number

Python program to find maximum and minimum numbers from the all input numbers. Terminate the input by entering a negative number.

Method 1
Simple Python program is given below using simple programming concepts.

num=int(input("Enter a Number?")) # enter first number
max=num;
min=num;
while  num>=0: #  repetition to get max and min, get other numbers until enter negative
    if num > max:
        max=num
    if num < min:
        min=num
    num=int(input("Enter a Number?"))
print("Maximum number is %d" % max)
print("Minimum number is %d" % min)

Note
The above program is written using only basics concepts without any data structure in Python.
No need to define variables in python.
Indentations are used in Python for blocking statements.
#  is used for comments

Method 2
Python program using List data structure where List data Structure is having inbuilt max(), min() functions.

num=eval(input('Enter a number?'))
L=[]
while  num>=0:
    L.append(num)
    num=eval(input('Enter a number?'))
if len(L)!=0:
    print("Maximum number is %d" % max(L))
    print("Minimum number is %d" % min(L))

Note
append() is a method of List in Python and max(), min() are again inbuilt functions of List.


Sunday, October 14, 2018

Pascal program to find max min

Draw a Flow chart and Write a Pascal program to input list of positive numbers; terminate the input by entering a negative number and Print the Maximum and the Minimum number of the list of numbers.

Find Maximum and Minimum numbers from list of positive numbers


program maxmin;

var
num,max,min:integer;

begin
  {enter first number}
  write('Enter a number?');
  readln(num);
  {assume first num is the max}
  max:=num;
  {assume first num is the min}
  min:=num;
  {loop to get 0 or positive numbers }
  while num >=0 do
       begin
       {new num is greater then max is new num}
       if num > max then
        max:=num
      else
           {new num is minimum then min is new num}
        if num < min then
        min:=num;
       {enter new number}
       write('Enter a number?');
       readln(num);
    {repetition end}
    end;
 {Check for first num negative}

    if (max > 0) then
    begin
        writeln('Maximm number is',max);
        writeln('Miimum Number is',min);
        writeln('Press return key to exit...');
    end
    else
        Writeln('No Number to Display');
readln;
end.


Click below link to Get Pascal Practical Explanation to count vowels in a given string



Pascal program to print prime numbers

Prime numbers

The number that is divisible only by itself and 1.
Pascal program to print prime numbers between 1 and hundred.

 
{Program to print prime numbers between 1 and 100}
program PrimeNumber;
const
  Num=100;
var
  i,j:integer;
  prime:boolean;

begin
  i:=2;
  while i<=Num do
  begin
     j:=2;
     prime:=True;
     while j<i do {to make it efficient here can use j<=i/2 :Reason: last factor of any number is number itself one before last number is always less than half of the value  }
     begin
        if i mod j= 0 then
        begin
          prime:=False;
        end;
        j:=j+1;
     end;
     if prime=True then
     begin
       writeln(i);
     end;
     i:=i+1;
  end;
  writeln('Press Enter to Exit....');
  readln;
end.

Output of the above Pascal Program


PascalProgramOutputofPrimeNumbers



Pascal program print number pattern

Pascal program to print number Pattern as below


NumberPatternPascalProgram

Pascal Program
 

program printnumpattern;
var
   i,j:integer;
begin
  i:=1;
  while i<=10 do {first repetition}
  begin
    j:=1;
    while j<=i do {second repetition within first}
    begin
          write(j,#9); {print numbers horizontally}
          j:=j+1;
    end; {second repetition end}
    write(#13#10); {to goto next line}
    i:=i+1; 
  end;{first repetition end}
  write('Press Enter to exit');
  readln;
end.


Pascal program to 1to100 using tab

Pascal program to print 1 to 100 using tab and one line upto 10


program onetohundredusetab
{define variable}
var
x:integer;
begin;
  x:=1;
  while x<=100 do
  begin
   write(x,#9); {#9 is for tab}
   if x mod 10 =0 then
    write(#13#10); {for new line}
   x:=x+1;
  end;
  readln;
end.


Pascal program to print multiplication table using all repetitions (while, for, repeat .. until)

Pascal program to print multiplication table using repetition "for" 
{define variables}
var
x, i: Integer;

begin {start main program}
     write('Please input formula Number?: '); {message to display to user}
     readln(x);
     for i:= 1 to 12 do
          writeln(x, ' * ', i, ' = ', x * i);
     writeln('Press enter key to close');
     readln;
end.    {end main program}   


Pascal program to print multiplication table using repetition "while"
var
x, i: Integer;
begin
     Write('Please input formula number? ');
     Readln(x);
     i:=1;
     while i<=12 do
     begin
           Writeln(x, ' * ', i, ' = ', x * i);
           i:=i+1;
     end;
Writeln('Press enter key to close');
Readln;
end.   

Pascal program to print multiplication table using repetition "repeat until"
var
x, i: Integer;
begin
     Write('Please input formula number? ');
     Readln(x);
     i:=1;
     repeat
           Writeln(x, ' * ', i, ' = ', x * i);
           i:=i+1;
     until i>12;
Writeln('Press enter key to close');
Readln;
end.


Output screen of the above Pascal Program (all the programs will give same output)

MultiplicatinTableUsingPascalProgram

Saturday, October 13, 2018

Repetitions in Pascal with examples (while, for, repeat until)

Loops/Repetitions in Pascal with examples

Loops are used to execute certain parts of code (statements) for a specific number of times, or until a condition is satisfied.
There are three type of loops/repetitions available in pascal.
They are

  • while
  • for
  • repeat … until

Pascal program to print one to hundred using “while”

program onetohundredwhile;
{define variable}
var
x: integer;
{main program}
begin {start of main program}
  {assign value to variable x}
  x:=1;
  while x<=100 do  {repeat until the condition is true}
  begin {start repetition}
       write(x,#9);
       x:=x+1;
  end; {end repetition}
  readln();
end.
LoopsInPascal

Pascal program to print one to hundred using “for”

program onetohundredwhilefor; 
var
x: integer;
{main program}
begin
   for x:=1 to 100 do {no block since having one statement only}
      writeln(x);
  readln();
end.     {end of main program}           

Pascal program to print one to hundred using “repeat...until”

program onetohundredrepeatuntil;
var
x: integer;
begin {start of main program}
  x:=1;
  repeat {start repetition}
    writeln(x);
    x:=x+1;
  until x>100; {repeat until the condition is false}
  readln(); 
end.  {end of main program}           

Note :

  • {} in pascal is used for comments, comments are not executed when program is compiled or executed.
  • begin .... end; is used to make a block of statements
  • readln() is used to wait until the enter key pressed to finish
  • #9 for tab