Thursday, April 9, 2020

Chapter - 12 C Language


An introduction to C Language

C is a high level programming language developed at AT & T’s (American Telegraph and Telephone) Bell Laboratories of USA in 1972. It was designed and written by a man named Dennis Ritchie. In the late seventies C began to replace the more familiar languages of that time like PL/I, ALGOL. It is general purpose high level programming language, which is used to develop business programs, text processing programs, database management programs and even to develop Operating System (OS). It is also known as structured programming language.
Structured Programming is a programming methodology that produces programs with clean flow, clear design, and a degree of modularity or hierarchical structure. Benefits of structured programming include ease of maintenance and ease of readability by other programmers.

Advantages of structured programming language

A large and complex program can be divided into several simpler and manageable sub modules.
Support simultaneously coding of modules by multiple programmers at a time.
Modules and functions once built here can be used in other programs.
It reduced testing and debugging time.
The program can be easily modified.
It is portable and occupies less memory space in computer.
Features/Characteristics of C language

It is structured programming language.
It is general purpose programming language.
It contains rich and powerful set of operators.
It contains rich and powerful set of declaration and data types.
It allows manipulation of internal process registers.
It is a middle level programming language that supports both high and low level programming languages. So, it is used to develop system software and application software.
Similarities in QBASIC and C language

Both languages can be used to develop structured programs.
Both languages support local and global variables.
Both languages support procedures.
Differences between QBASIC and C language

QBASIC is high level language whereas C language is a middle level language.
QBASIC supports both sub procedure and function procedure whereas C language supports only function procedure.
QBASIC is basically used for developing application software whereas C language is used to develop system software and application software.
Basic elements of C language are listed below
i. C Language character set
The C character set is a set of characters which are allowed to represent information in C language. The C character set consists of the alphabets (both upper case and lower case), the digits (0-9) and certain special symbols (+ - * & ^ % $ # @ ! ? > < etc ).

ii. Identifiers in C Language
In a C program every word is either classified as an identifier or a keyword. Identifiers are used to identify or name various program-elements such as variables, symbolic constants, functions, etc.



iii. keywords in C Language
Keywords are reserved words  which have special meaning for the C compiler. Keywords are not allowed to use as identifiers.  Keywords are also known as reserved words. There are 32 keywords in C. The keywords of C language are auto, double, int, struct, break, else, long, switch, case, enum, register, typedef, char, extern, return, union, const, float, short, unsigned, continue, for, signed, void, default, goto, sizeof, volatile, do, if, static, while.

iv. Data type in C Language
The data type in C language defines the amount of storage allocated to variables and the values that variables can accept. C language supports basic four data types. They are char, int, float and double.
The space occupies by int is 2 bytes, char is 1 byte, float is 4 bytes and double is 8 bytes.

Data type modifier
The keyword that modifies the size and range of the basic data types is known as Data Type Modifier. The modifiers define the amount of storage allocated to the variable. The C language uses four types of data type modifiers. They are signed, unsigned, long and short. The data type modifier changes the size and range of the data that can be stored in a variable.



v. Variables in C Language
In C language, you need to declare variables before you use them in a program. A variable declaration tells the compiler the name and type of a variable. If a program attempts to use a variable that has not been declared, the compiler generates an error message.
In C language to store a character, a Character variable is used, to store string, an array variable is used and to store numeric values, numeric variables like integer variables and floating point variables are used.

vi. Operators in C Language
An operator is a symbol that operates on a certain data type and manipulates them to produce the output. The operators used in C are listed below.

Arithmetic Operator
The arithmetic operator performs arithmetic operation on two operands. The following arithmetic operators are used in C +, -, /, *, % .



Unary Operators
A unary operator is an operator, which operates on one operand. The commonly used unary operators are increment (+ +) and decrement (- -) operators. The ++ operator increments the value of the variable by one, whereas the - - operator decrements the value of the variable by one. For example, x ++ is equivalent to x = x + 1 and x- - is equivalent to x = x-1.

Relational Operators
Relational operators compare two expressions and return result in term of True or False. The following relational operators are used in C language.
operators meaning expression <, <= , >= ,= = , ! = ,>

Logical Operators
A logical operator is used to combine relational expressions and returns the result either in True or False. The logical operators used in the C language are given below.
&&, ||, !.

Assignment Operator
An assignment operator (=) is used to assign a constant or a value of one variable to another.

Conditional Operator
A conditional operator checks for an expression, which returns either a true or a false value.

Header files in C Language
A header file is a standard file that contains definitions of variables and functions necessary for the functioning of a program. A header file is included in a program by using ‘#include’ directive. The header files in C language have .h extension. Some header files are listed below.

i. stdio.h
This is the standard input output header file that provides functions for performing input and output operations. It contains the declarations of I/O functions like printf ( ), scanf( ), putchar(), getchar() etc.



ii. string.h
The string header file provides many functions useful for manipulating strings which contains the declarations of library functions like strrev(), strlwr(), strupr(), strchr ( ), strcmp( ), strlenr( ),etc.

iii. math.h
The math.h file is standard header file that handles mathematical functions like sqrt(), pow(), etc.

iv. ctype.h
The ctype.h header file contains declarations for character classification functions like isspace(), isupper(), tolower() etc.

Some C Language programs are given below
/* this program displays the product of  two numbers*/
#include<stdio.h>
#include<conio.h>
void main()
        {
        int a, b, p;
        clrscr();
        a = 20;
        b =16;
        p= (a * b);
        printf(“product of  two numbers is %d”, p);
        getch();
        }

/* to check whether an input number is even or odd */
#include<stdio.h>
#include<conio.h>
void main()
        {
        int n, r;
        clrscr();
        printf(“Enter an integer”);
        scanf(“%d”,&n);
        r = n% 2;
        if(r==0)
                printf (“%d is even number”,n);
        else
                printf(“%d is odd number”,n);
        getch();
        }


Chapter - 11 File handling in QBASIC


Program file
A program file has a set of instructions and codes which are needed for data processing. It has .BAS as an extension.
Data file
A data file has collection of related data stored in a secondary storage device of computer. Such a collection of data in a row is known as a record. A record in a data file contains the detailed information of a person or anything. For example, a record of a data file related to ‘employee’ consists of employee name, post, department, date of birth and salary. A field is a particular data of a record.



Types of data file
1. Sequential Access File
Sequential access file, data is stored in sequential order. The data of a sequential access file can only be accessed sequentially. For example, if a sequential access data file has stored name of a person, address and age of some people then data of this file need to access in the same order as the data are stored in a row. Since the accessing of data from the sequential data file is done in sequential order, the accessing data takes long time if the data file contains large records.

2. Random access data file
A random access file allows us to write or read data from any location of the file. We can read or write any record directly in a random file without searching through all the records that precede it. Thus, reading and writing of data is faster than sequential access data file.

How to open a sequential data file?

OPEN statement is used to open a sequential data file.
Syntax 1: OPEN FOR AS # Filenumber
Where,
Filename is the name of the sequential data file.
Mode determines the operation of data file like OUTPUT, INPUT and APPEND. The different modes and their purposes are listed below.

OUTPUT mode
To create a new sequential data file and store data in it.



INPUT mode
To retrieve the contents of the existing data file.

APPEND mode
To add more records in the existing data file.
File number is a number from 1 to 255 that identifies the data file.

REM to create a new sequential data file and to store data.
CLS
OPEN “employee.dat” FOR OUTPUT AS # 1
DO
        INPUT “Enter employee name “;n$
        INPUT “Enter address”; a$
        INPUT “Enter post”;p$
        INPUT “Enter salary”; sal
        WRITE#1, n$,a$,p$,sal
        INPUT “Do you need more records (y/n)”; ch$
LOOP WHILE UCASE$(ch$) = “Y”
CLOSE#1
END



REM to display the content of datafile
CLS
OPEN “employee.dat” FOR INPUT AS # 1
PRINT “Name”, “Address”, “Post”, “Salary”
WHILE NOT EOF (1)
        INPUT#1, n$,a$,p$,sal
        PRINT n$,a$,p$,sal
WEND
CLOSE#1
END



REM add more records to the data file
CLS
OPEN “employee.dat” FOR APPEND AS # 1
DO
        INPUT “Enter employee name “;n$
        INPUT “Enter address”; a$
        INPUT “Enter post”;p$
        INPUT “Enter salary”; sal
        WRITE#1, n$,a$,p$,sal
        INPUT “Do you need more records (y/n)”; ch$
LOOP WHILE UCASE$(ch$) = “Y”
CLOSE#1
END

Chapter - 10 Modular Programming in QBASIC


The programming technique, in which a large and complex program is divided into small logical and manageable part of the program which can perform specific task, is known as modular programming. The small, logical and manageable part of the program is called procedure (module). Since the modular programming uses small block of functional codes, it is also called structured program.
Advantages of modular programming

A procedure can be reused in a program which reduces the length of the program.
It is suitable for a team work so that task can be divided with a team members.
The debugging of the program becomes easier and faster since they are divided into different modules.
The procedure can be tested and debugged separately.
The documentation of an individual procedure is simpler as compared to the documentation of a large and complex program.
Types of procedure
1. Sub Procedure
A Sub procedure is a small, logical and manageable functional part of a program which performs the specific tasks and does not return any value to the main module. A sub procedure can call another sub procedure in the program. A sub procedure is called by using CALL statement. When a sub procedure is called the program control transfers from the main module to the sub module and the execution of the codes in the sub module takes place. After the completion of execution of its codes the program control returns to the next statement of the calling module i.e. after the CALL statement.

2. Function procedure
A Function procedure is a small, logical and functional part of a program which performs the specific tasks and it returns a single value to the main module or calling module. The returned value of the function procedure may be string or number. So, there are two types of user defined functions. They are String Function and Numeric Function. Once the function procedures are defined in the program they can be used in the program. To use the function procedures in a program, the procedure needs to be called from the main module. The PRINT Statement or a variable is used to call the function procedure.



REM to display volume of cylinder
DECLARE SUB Volume ( r, h)
CLS
CONST pi=22/7
INPUT “Enter radius of a cylinder”; r
INPUT “Enter height of the cylinder”;h
CALL Volume (r, h)
END

SUB Volume (r, h)
          v = pi*r^2*h
          PRINT “Volume of the cylinder =”; v
END SUB



REM checks whether input integer is prime or composite.
DECLARE FUCNTION PRIME$(N)
INTPUT “Enter an integer”; N
PRINT “The number is  :” PRIME$(N)
END
FUNCTION PRIME$(N)
FOR P= 1 TO N
          IF N MOD P = 0 THEN C= C + 1
NEXT P
IF C=2 THEN
          PRIME$= “Prime”
ELSE
          PRIME$=”Composite”
END IF
END FUNCTION



REM to display longest student name among any ten names
DECLARE FUNCTION Longest$(n$( ))
CLS
DIM n$(10)
FOR P= 1 TO 10
          INPUT “Enter student name”;n$(P)
NEXT P
PRINT “The longest student name is “; Longest$(n$( ) )
END

Function Longest$(n$())
long$= n$(1)
FOR P = 2 TO 10
          IF LEN (n$(P))>LEN (l$) THEN long$= n$(P)
NEXT P
Longest$= long$
END FUNCTION

REM to display the number in an ascending order using an array with sub procedure.
DECLARE SUB SORT ( N( ) )
CLS
DIM N(10)
PRINT “Enter ten different numbers:”
FOR P= 1 TO 10
          INPUT N (P)
NEX P
CALL SORT (N ( ))
END



SUB SORT (N ( ))
FOR P= 1 TO 9
          FOR Q = 1 TO 10-P
                    IF N (Q)>N (Q+1) THEN SWAP N (Q), N (Q+1)
          NEXT Q
NEXT P
PRINT “Numbers are in ascending order:”
FOR P = 1 TO 10
          PRINT N (P)
NEXT P
END SUB

REM uses of global variable
DECLARE SUB Average ( )
COMMON SHARED a,b,c
CLS
INPUT “Enter three numbers “; a,b,c
CALL Average
END

SUB Average
          Avg=(a+b+c)/3
          PRINT “average= “;Avg
END SUB

Note: In the above program a,b,c are global variables and Avg is a local variable.



Chapter - 9 Review of Library Function


A function in QBASIC is a readymade small program or user made small program that can perform a specific task. The function manipulates the data passes to it and returns either a string  or a numeric value.  QBASIC supports two different kinds of functions.
i. User Defined Function
ii. Library Function
User Defined function is created by a user using function procedure to perform certain task which can’t perform by using library functions.
Library function is also known as Built-In function or Routine function. A library function in QBASIC may be string function or numeric function. A string library function can manipulate either string or numeric data and returns a string value. A function name having dollar sign ($) is string function. LEFT$(), Right$(), CHR$(), STR$( ), UCASE$( ), DATE$ ( ), MID$(), DATE$(), TIME$(), SPACE$(), LTRIM$(), RTRIM$(), INPUT$(), etc. are some example string functions.   A numeric function can manipulate either string or numeric data and returns a numeric value. A numeric library function name has no type declaration sign. CINT(), SQR(), ASC(), VAL(), LEN (), SGN( ),ABS( ), SIN( ), TAN( ), COS() etc. are some example of numeric library functions.

REM converts uppercase letters of a word in lowercase and vice versa.
CLS
INPUT “Enter a word”; W$
FOR k = 1 TO LEN (W$)
           E$= MID$(W$, k, 1)
           IF E$=UCASE$(E$) THEN
                      New$ =New$+ LCASE$(E$)
           ELSE
                      New$ =New$+ UCASE$(E$)
           END IF
NEXT k
PRINT “New word after converting case is :”; New$
END



REM removes vowels characters from the supplied word.
CLS INPUT “Enter a word:”; W$
FOR j= 1 TO LEN(W$)
           E$= UCASE$(MID$(W$, j, 1)
           IF E$<>”A” AND E$<>”E” AND E$<>”I” AND E$<>”O” AND E$<>”U” THEN
                      New$=New$+E$
           END IF
NEXT j
PRINT “New word is :”; New$
END

REM to check palindrome word.
CLS
INPUT “Enter a word”; W$
FOR j= LEN (W$) TO 1 STEP-1
           rev$= rev$+MID$(W$, j, 1)
NEXT P
IF W$=rev$ THEN
           PRINT “Palindrome word”
ELSE
           PRINT “Not palindrome word”
END IF
END



REM converts Decimal number into Binary Number.
CLS
INPUT “Enter a Decimal number”; N
M = N
DO WHILE N<> 0
           R= N MOD 2
           B$=STR$(R) + B$
           N= INT(N/2)
LOOP
Ans=VAL(B$)
PRINT “Binary equivalent of entered number is “; Ans
END



Chapter – 8 Review of Control Statements in QBASIC


IF Statements in QBASIC
1. IF …. THEN Statement
IF THEN Statement 
Or,
IF THEN
         Block of statements
END IF
Where, condition is a logical expression that evaluates either true or false.

2. IF….. THEN….. ELSE Statement
Syntax:
IF THEN
         Statement1
ELSE
         Statement2 
END IF
3. IF….. THEN….. ELSEIF….. ELSE Statement
Syntax:
IF THEN
         Statement1
ELSEIF THEN
         Statement2
ELSEIF THEN
         Statement3
         …….     
         ……….
         ………   
         ……….
ELSE
         Statement_N
END IF
REM find the greatest number among any 10 numbers.
CLS
FOR j=1 TO 10
         INPUT “Enter a number”;n
         IF n>g THEN g=n
END IF
PRINT “The largest number is “; g
END

REM finds the middle number among any three numbers.
CLS
INPUT “Enter any three numbers”; a, b, c
IF (a>b AND ac) THEN
         PRINT a; “ is the middle number.”
IF (b>c AND ba) THEN
         PRINT b; “ is the middle number.”
ELSEIF (c>a AND cb) THEN
         PRINT c; “is the middle number.”
END IF
END


SELECT CASE Statement
Syntax:
SELECT CASE testexpression
CASE expressionlist-1 
         [Statements Block-1]
[CASE expressionlist-2 
         [Statements Block-2]]
         ………
         ……….
         ………
         ……….
[CASE ELSE 
         [Statements Block-N]]
END SELECT

REM counts total number of vowels and consonants in a word.
CLS
INPUT “Enter a word“; W$
R$= UCASE$(W$)
FOR K= 1 TO LEN(R$)
         E$= MID$(R$, K, 1)
         SELECT CASE E$

         CASE “A”, “E”, “I”, “O”, “U”
                  x=x+1
         CASE ELSE
                  y=y+1
         END SELECT
NEXT K
PRINT “The number of vowels in the word :”;x
PRINT “The number of consonants in the word:”; y
END
Loops in QBASIC
The repetition of the statement block time and again till the condition is satisfied is known as loop. The looping statements supported by QBASIC program are
1. For Next Loop
Syntax:
FOR Variable = start TO end STEP (increment/decrement)
         [Block of statements]
NEXT Variable
REM displays first 10 even numbers and sum of those even numbers.
CLS
N=2
FOR P = 1 TO 10
         PRINT N;
         S=S+ N
         N = N + 2
NEXT P
PRINT “Sum of the first ten even numbers:”;S
END

2. WHILE …. WEND Loop
Syntax:
WHILE 
         [Statements block]
WEND

3. DO…LOOP
Syntax-I (Entry Control Loop Structure):
DO WHILE|UNTIL
         [Statements block]
LOOP

Syntax-II (Exit Control Loop Structure):
DO
         [Statements block]
LOOP WHILE|UNTIL
Where, Condition is the logical expression that evaluates as true or false.
REM Sum of digits of an integer
CLS
INPUT “Enter an integer”; N
DO
         R = N MOD 10
         S =S+ R
         N=INT(N/10)
LOOP WHILE N<>0
PRINT “Sum of digits”; S
END

REM Sum of digits of an integer
CLS
INPUT “Enter an integer”; N
DO
         R = N MOD 10
         S =S+ R
         N=INT(N/10)
LOOP UNTIL N=0
PRINT “Sum of digits”; S
END

Nested Loop
The loop inside a loop is called nested loop.
Syntax:
FOR Variable1 = start TO final STEP (Increment or Decrement)
FOR Variable2 = start TO final STEP (Increment or Decrement)
         [Statements block]
NEXT Variable2
NEXT Variable1

CLS
FOR j= 1 TO 5
FOR k = 1 TO j 
         PRINT k;
NEXT k
PRINT
NEXT j
END