Input and output in Pascal
Write and Writeln
These two built in procedures in PASCAL can be used to display an output on the screen. The 'Write' statement only displays the data on the screen but 'Writeln' in addition to displaying the data it also writes a newline character that moves the cursor to the next line. Consider the following write/writeln statements and their outputs.
Assume num=17 and in the following output '^' denotes a space character
Read, Readln
These two built in procedures are used to read some input from the keyboard.. The difference of the statements are that successive read statement obtain all the inputs from the same line while successive readln statements obtain the inputs from different lines.
Example:
Input two numbers and display the sum.
PROGRAM Example2;
VAR
A, B : Integer;
Total : Integer;
BEGIN
Write('Enter two integers : ' ');
Realdn(A,B);
Total :=A+B;
Writlen('Total =',Total);
END.
Control Constructs in Pascal
IF / THEN / ELSE
Example: Get the SUM of first five natural numbers
PROGRAM SumofNaturalNumbers;
VAR
N : integer;
Sum integer;
BEGIN
Sum:= 0;
N:= 1;
WHILEN<=5DO
BEGIN
Sum:= Sum + N;
N:= N + 1;
END;
Writeln('Sum of first 5 Natural Numbers = ', Sum);
END.
CASE Statement
Just like nested if statements used in the earlier programs the CASE statement can be used to perform multiple selection. CASE can be used with integer and char variables only.
The following program read a string from the keyboard and count each type of vowel non vowels (consonants ), and spaces in the string. The string is processed character by character for this purpose.
The best way to learn a programming language is by practicing. You need to write lots of codes to get the practice.
No comments:
Post a Comment