0% found this document useful (0 votes)
497 views165 pages

Cs Xii Notes PDF

Uploaded by

awarabellawindy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
497 views165 pages

Cs Xii Notes PDF

Uploaded by

awarabellawindy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 165

INCLUDES

 Notes
 Assignments
 Exercises
 Model Test
Papers
 MCQs
 Solution for
Practicals
PREFACE
This book contains a comprehensive guide line to C and MS-Access students. This book has
been designed by considering the course outline of XII Computer Science. Nothing is
perfect, but we do believe in striving for perfection.
TABLE OF CONTENTS

S# Contents Page #

0 Course Introduction 3

1 List of Assignments 4

2 List of Class Tests 7

3 Chapter 1: Concepts of Computer Programming 8

4 Chapter 2: Algorithms and Flow Charts 17

5 Chapter 3: C Language Fundamentals 26


6
Chapter 4: Operators and Expressions 41
7
Chapter 5: Conditional Statements 49
8
Chapter 6: I/O Statements 63
9
Chapter 7: Iterations and its Types 67

10 Chapter 8: Functions 79

11 Chapter 9: Database System Concepts 87

12 Chapter 10: MS-Access 103

13 Chapter 11: Practical Programming Problems In C 110

14 Chapter 12: Microsoft Access Practicals 126

15 Chapter 13: Questions and Answers for Self Practice 152

16 Chapter 14: Test Papers for Preparation 167

17 Chapter 15: Multiple Choice Questions 178

2|Page Muhammad Umair Ayub


COURSE INTRODUCTION
Course Contents
C Language
MS-Access

Theory Paper Pattern


Section A 15
Qs Type = MCQs
No of Qs to be attempted = All Compulsory
Section B 36
Qs Type = Short Answer Questions
No of Qs = 09
No of Qs to attempt = 06
Section C 24
Qs Type = Long Answer Questions
No of Qs = 03
No of Qs to attempt = 02
Total Marks 75

Practical Paper Pattern


File 05
Viva 07
Algorithm 01
Flow Chart 02
Source Code 04
Output 01
Access Procedure and Output --------------- 05
Total 25

List of Chapters
Ch 1 Concepts of Computer Programming
Ch 2 Algorithms and Flow Charts
Ch 3 C Language Fundamentals
Ch 4 Operators and Expressions
Ch 5 Conditional Statements
Ch 6 Input and Output Function
Ch 7 Iterations and its Types
Ch 8 Functions
Ch 9 Database Concepts
Ch 10 MS Access

3|Page Muhammad Umair Ayub


LIST OF ASSIGNMENTS

No Description Due
Date
1 Write an algorithm of preparing tea and draw flow chart.
Write an algorithm of starting and running a car.

2 Write a program to print the following lines of text


My Name is Ali
I am Pakistani
My religion is Islam.

3 Write a program using escape sequence to print the


following out put
We
Love Pakistan. We
Found it
On 14th Aug 1947
We will develop our Homeland

4 Write a program using I/O functions, take input for your


Form No, Name Class and session and also print them. Use
escape sequence wherever necessary.

5 Write a detailed note on C language data types and


demonstrate them by a C program

6 Write a Program, Take input for the marks of the five


subjects and calculate the percentages for each, Find the
total marks and calculate the total percentage.

7 Convert the following Mathematical equations in C syntax.


1. K=a2+b2+2ab
2. Z=√3y +2xy+z3
3. H=(abc+a3b2c+2ab)/3xy
4. P=a3+b3+3ab+√xy
5. D=(a2+b2)/2ab
6. Z= Ax2+Bxy+C
7. F=pq/p+q
8. a2+b2+c2+|p|
9. g=aπ2/slop
10. K= sin2θ+cos2θ

8 Write a Program and draw flow chart, take input for basic
4|Page Muhammad Umair Ayub
salary, calculate house rent allowance as 5% of the basic
salary and travel allowance as 8% of the basic pay,
calculate gross pay, deduct 2% tax of the basic pay and
finally calculate the net pay.

9 Write a program using if statement, take input for basic


salary, if basic salary is greater than 10000 calculate 7%
house rent allowance of the basic salary. And travel
allowance as 5% of the basic salary. Calculate the gross pay
and deduct 3% tax of the gross pay, than calculate the net
pay.

10 Write a program to construct a simple calculator using


switch statement and also draw its flowchart.

11 (a) Write a program using for loop to generate the following


series and also draw its flow chart.
1 3 5 7 9 11 13 15 17 19
(b) Write a program using for loop to generate the following
series and also draw its flow chart.
1 1 3 9 5 25 7 49 9 81
12 (a) Write a program using for loop to generate the following
series and also draw its flow chart.
2 4 6 8 10 12 14 16 18 20

(b) Write a program using for loop to generate the following


series and also draw its flow chart.
2 4 4 16 6 36 8 64 10 100

13 (a) Write a program using for loop to generate the following


series and also draw its flow chart.
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
(b) Print this pyramid using loops

* * * * * * * *
* * * * * *
* * * *
* *

5|Page Muhammad Umair Ayub


14 Write a detailed note on most commonly used MS Access
data types and their properties.

15 Write a note on MS Access objects and explain each with


examples

16 Write the complete steps of creating a table of student


having at least ten attributes of various data types. Mention
about all the constraints and data dictionary.

17 Solve the quadratic equation and find the solution set by


taking input for all the variables involved. Also draw flow
chart.

18 Differentiate
a. Operators and Operands
b. Predefined and Programmer defined functions
c. Increment and decrement operators
d. Break and Continue
e. Table and Query
f. Primary Key and Foreign Key
g. Table and Query
h. Form and Report
i. Wizard Mode and Design View

6|Page Muhammad Umair Ayub


LIST OF CLASS TESTS

N Description Due
o Date
1 Describe in detail the system development life cycle and its
phases

2 Describe the most commonly used data types of C in detail.

3 How many types of computer languages are being used?


Describe in detail.

4 Define the following terms with examples


 Variables
 Constants
 Identifiers
 Keywords
 Format Specifier
 Address Operator
 Escape Sequence
 IDE

5 How many types of Operators are used in C language.


Describe the relational and arithmetic operators with syntax
and example codes.

6 Write a note on if-else statement with syntax and example


codes.

7 Describe all the three types of iterative control structures of C


with example programs.

8 Explain MS Access Objects in Detail.

7|Page Muhammad Umair Ayub


CHAPTER ONE

CONCEPTS OF COMPUTER
1
PROGRAMMING

OBJECTIVE:
When you have completed this chapter, you will be able
to know about the

Short Answer Questions


Q1. What is a computer language? Explain with example.
Q2. How many types of computer languages are there? Explain.
Q3. How many types of programming languages are there regarding
structure?
Q4. Define a computer program. Also give an example.
Q5. How do you define software?
Q6. Briefly Describe the historical background of C language

Long Answer Questions


Q1. Explain debugging process in detail.
Q2. Discuss system development life cycle in detail
Q3. What is a language translator? Also explain its types.

8|Page Muhammad Umair Ayub


CHAPTER #1
CONCEPTS OF COMPUTER PROGRAMMING

==============Short Questions and Answers===========

Q1. What is a computer language? Explain with example.

Computer Language
A computer language is defined as the source of communication to the
computer system which provides all the materials to develop programs and
consequently complete software.
Explanation
A language provides all the material to develop software. Software is a
collection of programs which works integratedly and a program is a
collection of instructions which are written in a specific computer language.
There are a number of languages being used for application and system
software.
Examples
C language
CPP
Java
Visual Basic

Q2. How many types of computer languages are there? Explain.

Types of Computer Languages


Computer languages are categorized in the following three types:

1. Low Level Language


A low level language is based on machine language or codes near to
the machine language.
Explanation
A low level language is the computer's machine language. It can
directly control the hardware. It is complex but having a lot of
features. It is normally used to develop system software.
Examples
Machine Language
Assembly Language
2. High Level Language
A computer language having programming codes near to the human
language is called a high level language.
Explanation
A high level language is used to develop both type of software. It is
normally used to develop application software.

9|Page Muhammad Umair Ayub


Examples
C++, JAVA, PASCAL, VB, NET etc.
3. Middle Level Language
A computer language having both the characteristics of a high level
and a low level language is called a middle level language.
Explanation
Using a middle level language we can not only control the hardware
but also we can develop application programs. Only few languages are
there which contains both the characteristics of a high and a low level
language.
Examples
C

Q3. How many types of programming languages are there regarding


structure?

Types of Programming Languages Regarding Structure


Computer languages have the following types regarding structure,
instruction set & methodology of writing codes.
 Procedure Oriented
 Object Oriented
 Visual Programming

 Procedure Oriented
A procedure language uses the traditional approach for
programming using pre-defined and programmer defined
function and procedures. The control structure plays an
important role.
Examples
C, COBOL, PASCAL etc.

 Object Oriented
An object oriented language uses classes and objects having
specific properties and methods for a comprehensive
programming. It is a better approach than a procedure
oriented language.
Examples
C++, JAVA etc.

 Visual Programming
A visual programming language provides a graphical or
windows like environment for programming. It contains visual

10 | P a g e Muhammad Umair Ayub


objects like text boxes, buttons, combo boxes, lists and forms
etc.
Examples
VB6, .Net

Q4. Define a computer program. Also give an example.

Program
A program is defined as collection of instructions in a computer language to
perform a specific task.
Explanation
The programs are the components of software which are integrated with
each other. A program contains a number of instructions which are definitely
written in a computer language.
Example
The following is a C language program which prints three lines of text.
void main()
{
clrscr();
printf(“\t\t\t------*****WeLc0mE***** ----- \n”);
printf(“How are you???\n”);
printf(“It is my first program!!!”);
getch();
}

Q5. How do you define software?

Software
Software is a collection of integrated programs having a definite purpose.
Explanation
The software is a computer program which is built using some computer
language. It is a collection of programs which works integratedly. The
software that controls and manages the hardware is called system software
and the software which facilitates the user is called application software.
Example
MS- Word
MS-Excel
Typing Master
Operating System
etc.

11 | P a g e Muhammad Umair Ayub


Q6. Briefly describe the historical background of C language

Introduction to C Language
C is a powerful programming language developed by Dennis Ritchie at AT &
T Bell laboratories of USA in 1972.
Historical Background
In the early ages of computer programming, there used to be special
purpose programming languages. For example COBOL (common business
oriented language) was being used to develop business application.
Fortran(formula translation language) was being used to solve mathematical
and technical problems. Pascal language was being used to solve scientific
problems. There was a need of such kind of language which can be used in
any kind of programming as general purpose language.
Development of C language
C was evolved from the earlier language BCPL (Basic Combined
Programming Language) which was developed in 1967 by Martian Richards
at the Cambridge University. BCPL was developed as a language for writing
system software specially operating system and compilers.
In 1970 Ken Thompson at Bell laboratories developed a language based on
BCPL and called it B language means the first letter of BCPL. Dennis Ritchie
was the programmer who developed B language further as a new language
and gave it the name of “C” the second letter of BCPL.

==============Long Questions and Answers============

Q1. Explain debugging process in detail.

The Debugging Process


The process through which a program can be made error free and
properly functional is called debugging process. Several tools have
been divided for finding and removing three types of errors, as follows
 Desk Checking
In the desk checking, a programmer checks a printout of the program
while sitting at a desk. The programmer goes through the listing line
by line looking for syntax, logic and runtime errors. In other words,
desk checking is a sort of proof-reading.
 Manual Testing With Sample Data
Both correct and incorrect data are run through the program-
manually, not with a computer-to test for correct processing results.
This is called dry run of program. If any error is found then it is
removed before further testing.

12 | P a g e Muhammad Umair Ayub


 Structured Walkthrough
A structured walkthrough is a process in which three or four
programmers, including the creator of the program, review (walk
through) the program. They analyze it for completeness, accuracy, and
quality of design and then discuss their conclusions.
 Attempt At Translation
The program is run through a computer, using a translator program.
The translator attempts to translate the written program from the
programming language (such as C or PASCAL) into the machine
language of 1s and 0s. Before the program will run, it must be free of
syntax errors. These syntax errors will be identified by the translating
program.
 Testing Sample Data On The Computer
When all syntax errors have been corrected in the program
statements, we must plan the sample data carefully to make sure you
test every part of the program. This step is sometimes called alpha
testing.
 Run Real-World Data
After testing with sample data, the program may run fine-in the
laboratory. However, if the program is going to be sold commercially,
it is released to a selected set of users to be tested with real data,
called beta testing. The selected users locate errors that were
overlooked during the regular testing phase and report them to the
company that is developing the program. After beta testing, the
program may need additional debugging before it is released to stores.

Q2. Explain the steps in programming.


OR
Discuss system development life cycle in detail

Steps Involved in Programming

The process of programming which is also called software engineering


involves the following steps.
 Defining the Problem
 Planning the Solution
 Coding the Program
 Testing the Program
 Documenting the Program

13 | P a g e Muhammad Umair Ayub


1. DEFINING THE PROBLEM
The very first task for a programmer is to have a clear understanding of
the problem, that what the problem is and how it will be solved. The
following steps are considered important.
a) Determining Program Objectives
The programmer defines what are the major tasks and the main
purpose of the program. The programmer defines a clear boundary
about the goals of the program.
b) Determining the Desired Out Put
It needs to be defined that what type of reports are required in the
form of Hard Copy or Soft Copy.
c) Determining the Input Data
The input requirements are identified by the programmer so that the
desired output can be obtained.
d) Determining the Processing Requirements
The requirements for the hardware and software need to be defined in
the problem definition. So this task is also included in the first step.
2. PLANNING THE SOLUTION
After defining the problem the programmer is supposed to plan for the
solution using some design tools, these techniques include the following:-
a. Top – Down Program Design In this approach the solution is
divided into parts which are called modules. These modules
integratedly work to solve the problem.
b. Algorithm
An algorithm is the step by step process to solve the problem. It
describes the logical and processing flow of the program in the finite
steps.

14 | P a g e Muhammad Umair Ayub


c. Flow chart
The flow chart is a pictorial representation of the program logic which
makes easy to understand the program.
3. CODING THE PROGRAM
When the solution has been planned and designed it needs to be
implemented using the programming language. This process is called
coding. According to requirement a reasonable programming language is
selected to implement the solution.
4. TESTING THE PROGRAM
Once the program has been coded completely the next phase is the
implementation. By the implementation the programmer comes to know
the physical and logical errors which are supposed to be debug. The
program is tested regarding all types of errors that are syntax errors,
logical errors and run time errors. The testing phase makes sure that the
program fulfills all the objectives which is required for the user.
5. DOCUMENTING THE PROGRAM
Documentation is an essential phase of the programming process. It is
not a separate phase. It is continued with all the steps in programming
from problem definition to testing.

Q3. What is a language translator? Also explain its types.


Language Translator
A program which translates the source code into machine language is called
a language translator.
Explanation
The language code is written in the form of a program, it needs to be
translated so that it can be understood by the CPU and this task is done by a
program which is known as language translator.
Example
C language Compiler
VB Interpreter
Types of Language Translators
There are mainly two types of language translators
 Compiler
 Interpreter
Compiler
A compiler is a language translator which translates all the program
instructions at once and gives output.
Explanation
Some languages use the compiler to translate the source code program into
machine language. The compiler translates all the instructions at once and it
does not print the result until and unless any error found.
Example
C compiler

15 | P a g e Muhammad Umair Ayub


CPP compiler
Interpreter
An interpreter is a language translator which translates a program
instruction line by line.
Explanation
Some languages use the interpreter to translate the source code program
into machine language. The interpreter translates the instructions one after
another as these are written in the program. An instruction is executed if it
does not contain any error and an instruction is not executed if it contains
any error.
Example
C compiler
CPP compiler

16 | P a g e Muhammad Umair Ayub


CHAPTER TWO

ALGORITHMS AND FLOW


2
CHARTS

OBJECTIVE:
When you have completed this chapter, you will be able
to know about the

Short Answer Questions


Q1. Define algorithm and give its example
Q2. Describe method of writing algorithm is general English.
Q3. Describe method of writing algorithm using pseudo code.
Q4. For what purpose flow chart is used explain its symbols.

Long Answer Questions


No long questions in this chapter

Problems
Example algorithms and flow chart

17 | P a g e Muhammad Umair Ayub


CHAPTER # 2
ALGORITHMS AND FLOW CHARTS

=============Short Questions and Answers============

Q1. Define algorithm and give its example

Algorithm
Step by step process to solve any problem is called an algorithm
Characteristics of an algorithm
The following are some important characteristics of an algorithm.
 The number of steps in an algorithm is finite.
 The steps mentioned in an algorithm strictly follow a sequence to
get the desired result.
 The algorithm must get the final result of the problem in the form
of a comprehensive solution.
 The algorithm can be written to solve any business, scientific,
technical and even general life problem.

Methods to write an algorithm


There are two important methods to write an algorithm.
 General English
 Pseudo Code
Now we discuss them one by one

Q2. Describe method of writing algorithm is general English.

General English (A method to write an algorithm)


In general English the algorithm is written in the commonly used words
of English with the step number.
Example Problem
Compute the distance traveled by a train in which is running with the
speed of 160km/h and reaches its destination in 1 hour 45 minutes.
Write an algorithm to compute the distance traveled by train.
Algorithm
Step 1: Start
Step 2: Enter a Value for Speed
Step 3: Enter a Value for Time
Step 4: Calculate Distance using Formula Speed*Time
Step 5: Write the Value of Distance
Step 6: End

18 | P a g e Muhammad Umair Ayub


Q3. Describe method of writing algorithm using pseudo code.

Pseudo Code (A method to write an algorithm)


The pseudo code is a particular way to write an algorithm. The pseudo
code uses specified words for different purposes. The pseudo code is
near to the computer language. The following are the specific words
which are used in a pseudo code.

Start : To start the algorithm


Exit : To end the algorithm
Read : To take input in a variable
Write : To print the value of a variable
If Then : For condition checking
Repeat : For iteration

Example Problem
Write an algorithm to add two numbers and for printing the result.
Algorithm
Step 1: Start
Step 2: Read X
Step 3: Read Y
Step 4: Set Z=X+Y
Step 5: Write Z
Step 6: Exit

19 | P a g e Muhammad Umair Ayub


Q4. For what purpose flow chart is used explain its symbols.
Flow Chart
A flow chart is a diagrammatic representation for the flow of a program.
It shows flow of all the instructions being used in a program
sequentially.
Symbols
The following are the symbols which are used most commonly in a flow
chart.
Name Purpose Symbol
Terminal Start / End

I/O Symbol Input/Output

Process Assignment or
Equation

Flow Lines To show Flow

Decision For Condition


Checking

On Page To Connect
Connector Different Parts
on the same
page
Off Page To Connect
Connector Different Parts
from one page
to another

20 | P a g e Muhammad Umair Ayub


Example Problem 2.1
Write a program which uses arithmetical operators to
calculate the area of a triangle, volume of a sphere, etc.

Algorithm
Step1. Start
Step2. Read a, b, r, T, S
Step3. Set T = (1.0/2.0)*(a*b)
Step4. Set S = (4.0/3.0)*(3.142)*(r*r*r)
Step5. Write T, S
Step6. Exit

Flow Chart

*******************

Example Problem 2.2


Calculate the factorial of a number. which is greater than 8 write algorithm
and draw flow chart
Algorithm
Step1. Start.
Step2. Set f = 1, i = 0
Step3. Read num
Step4. Repeat WHILE num <= 8.
a. Write Error! You have enter no. less than 8
b. Read num
[End of outer WHILE loop]
Step5. Repeat FOR n = 1 to num
a. Set f = f * 1
[End of FOR Loop]
Step6. Write f
Step7. Exit

21 | P a g e Muhammad Umair Ayub


Flow Chart

*******************

22 | P a g e Muhammad Umair Ayub


Example Problem 2.3
Write a program that reads and prints the data using Escape sequence,
(asking the name, age, height and gender of a student).

Algorithm

Step1. Start
Step2. Read name
Step3. Read age
Step4. Read height
Step5. Read gender
Step6. Write name
Step7. Write age
Step8. Write height
Step9. Write gender
Step10. Exit

*******************

Example Problem 2.4


Write a program, which uses switch and break statements.
Algorithm
Step1. Start.
Step2. Read num1, num2
Step3. Read switch op
Step4. IF switch op = „+‟
Write num1 + num2

23 | P a g e Muhammad Umair Ayub


IF switch op = „-‟
Write num1-num2
IF switch op = „*‟
Write num1 * num2
IF switch op = „/‟
Write num1 / num2
Step5. ELSE
Write Unknown operator
Step6. Exit

Flow Chart

*******************

24 | P a g e Muhammad Umair Ayub


Example Problem 2.5
Write an algorithm and draw flow chart to generate the multiplication
table ranging from 2 to 10.

Algorithm
Step1. Start
Step2. Read num
Step3. IF num>=2 and num<=10 then
Step4. Repeat FOR i = 1 to 10
a. Set t = num * i
b. Write t
[End of FOR Loop]
Step5. ELSE
Write Error!!!
[End of IF-ELSE structure]
Step6. Exit
Flow Chart

25 | P a g e Muhammad Umair Ayub


CHAPTER THREE

C LANGUAGE
3
FUNDAMENTALS

OBJECTIVE:
When you have completed this chapter, you will be able
to know about the
Short Answer Questions
Q1. What is a variable? Describe rules to define a variable.
Q2. What is a constant? Why it is used in programming?
Q3. What is a header file? Describe its purpose.
Q4. What is a C statement? Mention example.
Q5. For what purpose the key words are used in C language?
Q6. Define preprocessor directive with example.
Q7. What are identifiers? Describe with example.
Q8. What is an input statement? Give example.
Q9. What is an output statement? Give example.
Q10. What is a format specifier? Describe format specifiers used in C.
Q11. Define address operator with example code.
Q12. What are the methods to write comments in C?
Q13. Define and explain escape sequences.
Q14. Define data type. How many data types are used in C language?
Long Answer Questions
Q1. Describe the IDE of C language in detail.
Q2. What is structured programming? Describe program development life
cycle.
Q3. Convert the mathematical equations in C equivalent.
Problems
Example problems and source codes

26 | P a g e Muhammad Umair Ayub


CHAPTER # 3
C LANGUAGE FUNDAMENTALS

=============Short Questions and Answers============

Q1. What is a variable? Describe rules to define a variable.

Variable
A variable is a programming ingredient in the form of an identifier defined by
the programmer. It is a location in a memory on which the character or
numeric data can be stored.
Explanation
A variable is declared using some data type which defines the type of the
data. It is necessary to follow the rules while defining the variable name.
A variable has got the following characteristics:
 It‟s name.
 The data type which defines its size.
 The address on which it is located in the memory.
 The value which is stored in it.
Rules for Variable Names
The following rules must be followed while declaring a variable
 The first letter must be non numeric
 No space, commas or special characters can be used in a variable
name.
 The underscore (_) can be used in a variable name.
 The reserved words like int, void, for, if etc cannot be used as
variable names.
 While writing a C program which has an extension of “.C” the
variable must be stored in the beginning of the main function.
 It is better to use a variable name up to eight characters.
Example
int marks;
float percentage;
Q2. What is a constant? Why it is used in programming?

Constant
The constants are the fixed value memory locations identified by an
identifier given by the programmer.
Explanation
The constant values cannot be change throughout the program. The
constant may be of any data types.
 Integer constant.
 Floating point constant.
 Character constant.

27 | P a g e Muhammad Umair Ayub


Example:
const float Pi=3.142; const int weekday=7; const char gender=‟f‟;

Q3. What is a header file? Describe its purpose.

Header File
Header files are the library files of the C language, which hold the particular
codes of the library functions.
Explanation
There are a number of library files in C language holding different functions
for different purposes like I/O functions and mathematical function.
Example
stdio.h, math.h, conio.h etc.

Q4. What is a C statement? Mention example.


Statement
A C language statement may be a collection of variables, constants,
identifiers or functions.
Explanation
The C language uses single line statement or multiple line statement. A
single line statement is terminated by the semicolon and multiple line
statement is a block of statements enclosed in braces.
Example
c=a+b;
total=a+b+c;

Q5. For what purpose the key words are used in C language?
Keywords
The C language provides some reserved words having standard and pre-
defined meanings in C, which are called keywords.
Explanation
The keywords appear in white color in the IDE of C; they have their special
purposes and cannot be used as a variable or function name. There are a
number of keywords present in C relevant to different types of programming
tasks.
Example
void if auto for while
int float continue break do

Q6. Define preprocessor directive with example.


Pre-Processor Directive
The pre-processor directive is also a technique to define any type of constant
or any type of other data.

28 | P a g e Muhammad Umair Ayub


Explanation
In this technique # define term is used to define constant. The instructions
of a pre-processor directive are written before starting the main function.
Example
# define Pi 3.142
# define weekday 7
# define gender “female”
# define answer “y”

Q7. What are identifiers? Describe with example.


Identifiers
Identifiers are the names given to different program elements like variables
and functions. These names uniquely identify the variables or functions.
Explanation
These following rules must be followed while creating identifiers.
 An identifier must start with a letter or (rarely) an underscore (_).
 An identifier can contain letters, digits, or underscore (_).
 An identifier cannot contain spaces, commas, or any other special
characters.
 An identifier cannot consist of more than 31 characters.
 An identifier must conform to case sensitivity.
Example:
The following names are some identifiers
x y1 y2 sum_1 tot_marks
Name SNO _auto N2N

Q8. What is an input statement? Give example.


Input Statement
The input statement is defined as the instruction which is used to take input
for the data from the user.
Explanation
In C language the input is taken from a function called input function. C
provides some functions for different types of input of data according to the
requirement of the user.
Example
scanf(), gets(), getche() etc

Q9. What is an output statement? Give example.


Output Statement
The output statement is defined as the instruction which is used to print data
or message from the memory to the screen.

29 | P a g e Muhammad Umair Ayub


Explanation
In C language the output is given by the function called output function. C
provides some functions for different types of output of data and messages
according to the requirement of the user.
Example
printf(), puts(), putchar()

Q10. What is a format specifier? Describe different format specifier


used in C.
Format Specifier
The format specifier is a C language code which specifies the format of data
for variable of a particular data type.
Explanation
The format specifier is used by the input and output statement. Without
using a specific
format specifeir
Date Format
the Description data for
Type Specifier
a variable
cannot be
int Integer quantity %d
stored or
char Single character %c retrieved
by a float Floating point number %f
double Double-precision floating % lf
point number.
String Array of characters %s

particular memory location.


Example

30 | P a g e Muhammad Umair Ayub


Q1. Define address operator with example code.
Address Operator
The address operator is defined as the C language code which is used to
specify the location of variable
Example
In C programming while using pointers or while taking input, the
programmer needs to mention the address of the memory location or
variable. This task is done by the address operator. It is denoted by &.
Example
Scanf(“%d”,&num);
The “&”operator mentions that address of the variable num to store the
integer value on accurate memory location.

Q12. What are the methods to write comments in C?


Comments
In C language the programmer can write his/her own views along with the
program instructions that is known as comments.
Explanation
Comments are not the part and parcel of the program. The comments are
written to better understand the task done in a specific statement. The
compiler does not read the words or sentences written in comments.
The comments are of two types in C
 Single Line Comments
 Multiple Line Comments
A single line comment is started with the double slash //. In this way only
one line is written as comment. The multiple line comment starts with /* and
ends with */. A paragraph or more than one line can be written in a multiple
line comment.
Example
// initialize the variable
/* This function takes input for the year of birth and current year and
returns the age*/
Q13. Define and explain escape sequences.
Escape Sequence
The escape sequence is the special purpose C language code used for
different purposes.
Explanation
These codes are used with the character '\' backslash. These are used in the
input or output statements for the setting of cursor location and for some
other special purposes. The programmer can make indents, spaces, or line
spacing using the escape sequence. Sometimes it is used to print the
characters like backslash, inverted commas, sign of interrogation etc.
Example

31 | P a g e Muhammad Umair Ayub


Escape Meaning Result at Execution
Sequence
\n New Line Moves the Cursor at the beginning of the new
line
\t Tab Moves the cursor to the next tab.
\r Carriage Moves the cursor to the beginning of the line
Return
\a Alert Produces a beep
\b Back Space Move the cursor to the previous character.
\\ Back Slash To print back slash
\‟ Single Quote To print single quote
\” Double Quote To print double quote
\? Question Mark To print question mark

Q14. Define data type. How many data types are used in C language?
Data Type
A data type defines that what type of data is to be used in a program.
Explanation
The C language supports several different types of data, each of which may
be represented differently within the computer‟s memory. The basic data
types, their descriptions and the memory requirement for each data type are
listed in the following table.
Example

Typical Range
Date
Description Memory
Type
Requirement
int Integer quantity 2 bytes
char Single character 1 byte
float Floating point number 4 bytes
double Double-precision floating 8 bytes
point number.

=============Long Questions and Answers=============


Q1. Describe the IDE of C language in detail.
IDE
The IDE (Integrated Development Environment) is the programming
environment for a specific language which provides the facilities of editing,
compilation, debugging and running of a program.
Explanation

32 | P a g e Muhammad Umair Ayub


Muhammad Uwais BIT-MCS (KU)
Computer Science XII 2015-2016

An IDE contains the menus having commands which help the programmer
for easy to use programming from editing of the source code up to the on
screen output. The IDE contains the commands having short cut keys to
facilitate the programmer. It displays the error, warning and alerts to inform
the programmer about a specific problem.
Example
IDE of C language
IDE of Visual Basic 6

IDE of C Language
The IDE of C language has got a blue color editor for the editing of source
code. It displays different programming text in different colors. The
important menus of C language IDE are as follows:

 File
 Edit
 Search
 Run
 Compile
 Debug
 Project
 Options
 Window
 Help
A number of commands are there which
are required for the different
programming options.

Q2. What is structured programming?


Describe program development life
cycle.
Diagrammatic structure
of a C program
& its development cycle
C Program
In C language a program has a specified
format. From the editing of the source
code to the execution of the program it
passes through the following steps.
Syntax of Main Function
#include <….>
#include<….>
void main(void) // Function name
{ // Start of Function

Page 33 V: 03
Statement 1; // Function
Statement 2; // Body
…….
} // End of function
Program Demonstration
Our first example prints the text “This is my first C program” on the screen.
The program 3.1 shows the structure of complete C program.
Program
# include <stdio.h>
void main (void)
{
print f (“This is my first C program”);
}
The Development Cycle
The phase through which the C program passes is called a development
cycle These steps are as follows.
 Editing source code
 Compiling the program
 Linking the program
 Running the program
1. Editing Source Code
In the very first step an algorithm in going to be coded completely and
file is saved with the extension of .C or .CPP
2. Compiling the Program
Once a program has been edited, it needs to be compiled so that errors
can be shown. If no errors are there and object file having the same file
name but with extension of .OBJ is created.
3. Linking the Program
This step covers the inclusion of library files or other user defined header
files which function are used in the program.
4. Running the Program
If no syntax and linking error are there, the program can be run
successfully but any run time error can also produce problem in the
program output. When the program is going to run, a file is created
having same file name but it will have extension of .EXE

Q3. Convert the following mathematical equations in C equivalent.

1. C = x2 + 2xy + y2

Solution:
C = pow(x,2) + 2 * x * y + pow (y,2);

34 | P a g e
2. K= a3 + 3ab(a+b) + b3
Solution:
K= pow(a,3) + 3* a*b*(a+b) + pow(b,3);

3. M = ( x + y) ( x – y)
( x + 3) ( x – 3)

Solution:
M= (( x + y) * ( x – y )) / ( ( x + 3 ) * ( x – 3 ));

4. N = x2  y 2
Solution:
N = Sqrt ( pow ( x,2 ) + pow ( y,2 ));

1
5. D =
x y
Solution:
D = 1 / sqrt ( x – y ) ;

6. O =  1  1 

  

 

 (x  y)  (x  y) 
Solution:
O = ( 1 / ( x – y )) * ( 1 / ( x + y) ) ;

7. S = xm - xn
Solution:
S = pow ( x , m) – pow ( x , n ) ;

ab
8. P =
a b
Solution:
P = Sqrt ( a + b ) / sqrt ( a - b) ;

(a  x)(a  3)
9. T = |a| +
ax
ax
Solution:
T = abs ( a ) + sqrt (( a + x) * ( a – 3 )) / sqrt (( a + x ) / ( a – x ));

*******************

35 | P a g e
Example Program 3.1
Write a program using escape sequence and print the following lines of text
using single printf() statement.
Love Pakistan
&
Build Pakistan
Work Hard
To
Develop Your
Home Land

Source Code
void main()
{

clrscr();
printf("\n\t\t\t\tLove Pakistan\n\t\t\t\t\t\t&\n\t\t\t\tBuild
Pakistan\n\t\t\t\t\tWork
Hard\n\t\t\t\t\t\tTo\n\t\t\t\tDevelop Your\n\t\t\t\tHome Land");
getch();
}
-*******************
Example Program 3.2
Write a program that reads and prints the data using Escape sequence,
(asking the name, age, height and gender of a student).
Source Code
void main()
{
char gender,name[40];
int age;
float height;
clrscr();
printf("Enter your name: ");
scanf("%s",name);
printf("\nEnter your age: ");
scanf("%d",&age);
printf("\nEnter your height: ");
scanf("%f",&height);
printf("\nEnter your gender(m/f): ");
scanf("%s",&gender);
printf("\n\n\t\t\t==================\n");
printf("\t\t\t YOUR INFORMATION\n");
printf("\t\t\t==================\n");

36 | P a g e
printf("\t\t\tName : %s\n",name);
printf("\t\t\tAge : %d\n",age);
printf("\t\t\tHeight : %.2f\n",height);
printf("\t\t\tGender : %c\n",gender);
getch();
}
*******************

Example Program 3.3


Write a program, which prints a Text of four lines consisting of characters,
integer values and floating point values using printf() statement. Taking
input from the keyboard using scanf() statement.

Source Code
void main()
{
char c,s[25];
int i;
float f;
clrscr();
printf("Enter any character: ");
scanf("%c",&c);
printf("\nEnter any string(max length 25): ");
scanf("%s",s);
printf("\nEnter any integer value : ");
scanf("%d",&i);
printf("\nEnter any floating point value: ");
scanf("%f",&f);
printf("\n\nCharacters : %c\n",c);
printf("String : %s\n",s);
printf("Integer : %d\n",i);
printf("Floating Point : %.2f\n",f);
getch();
}
*******************
Example Program 3.4
Write a program that reads and prints the data using Escape sequence,
(asking the name, age, height and gender of a student).
Source Code
void main()
{
char gender,name[40];
int age;
float height;

37 | P a g e
clrscr();
printf("Enter your name: ");
scanf("%s",name);
printf("\nEnter your age: ");
scanf("%d",&age);
printf("\nEnter your height: ");
scanf("%f",&height);
printf("\nEnter your gender(m/f): ");
scanf("%s",&gender);
printf("\n\n\t\t\t==================\n");
printf("\t\t\t YOUR INFORMATION\n");
printf("\t\t\t==================\n");
printf("\t\t\tName : %s\n",name);
printf("\t\t\tAge : %d\n",age);
printf("\t\t\tHeight : %.2f\n",height);
printf("\t\t\tGender : %c\n",gender);
getch();
}
*******************

Example Program 3.5


Write a program which uses arithmetical operators to calculate the area of a
triangle, volume of a sphere, etc.
Source Code
void main()
{
float a,b,r,T,S;
clrscr();
printf("Enter the value for altitude of a triangle: ");
scanf("%f",&a);
printf("\nEnter the value for base of a triangle: ");
scanf("%f",&b);
printf("\nEnter the value for radius of a sphere: ");
scanf("%f",&r);
T=(1.0/2.0)*(a*b);
S=(4.0/3.0)*(3.142)*(r*r*r);
printf("\n\nArea of triangle = %.2f",T);
printf("\nArea of sphere = %.2f",S);
getch();
}
*******************
Example Program 3.6
Write a program, Take input for the marks of five subjects and calculate
total marks and percentage.

38 | P a g e
Source Code
void main()
{
float eng, urdu, phy, comp, maths, tot, per; //Declaring Variables
clrscr();
//Taking Input for Marks
printf("\n Enter the marks of English.\t: ");
scanf("%f",&eng);
printf("\n Enter the marks of Urdu.\t: ");
scanf("%f",&urdu);
printf("\n Enter the marks of Physics.\t: ");
scanf("%f",&phy);
printf("\n Enter the marks of Computer.\t: ");
scanf("%f",&comp);
printf("\n Enter the marks of Mathematics.\t: ");
scanf("%f",&maths);
tot=eng+urdu+phy+comp+maths; //Calculating Total Marks And
Percentage
per=tot/500*100;
printf("\n The Total Marks Are = %0.2f\t”, tot);
printf("\n The Percentage is = %0.2f \t”, per);
getch();
}
*******************
Example Program 3.7
Write a program, take input for basic salary, house rent allowance, travel
allowance and medical allowance calculate 5% tax on gross pay and
calculate the net salary and print results.
Source Code
void main()
{
float BS, TA, HRA, MA, TAX,GP, NS; //Declaring Variables
clrscr();
printf("\n Enter Value for Basic Salary of Employee :\t ");
scanf("%f",&BS);
printf("\n Enter Value for House Rent Allowance :\t ");
scanf("%f",&HRA);
printf("\n Enter Value for Travel Allowance :\t ");
scanf("%f",&TA);
printf("\n Enter Value for Medical Allowance :\t ");
scanf("%f",&MA);
GP=BS+TA+HRA+MA;
TAX=5*GP/100;
NS=GP-TAX;

39 | P a g e
printf("\n ======Printing Salary Details======= \t”);
printf("\n The Basic Salary of Employee Is =%0.2f \t”, BS);
printf("\n The Tax Due on Employee Is =%0.2f \t”, TAX);
printf("\n The Net Salary of Employee Is =%0.2f \t”, NS);
getch();
}
*******************
Example Program 3.8
Write a program to solve the following mathematical equation.
K=a2+2ab+b2
Source Code
void main()
{
int a, b, K;
clrscr();
printf("\n Enter Value a:\t ");
scanf("%d",&a);
printf("\n Enter Value for b:\t ");
scanf("%d",&b);
K=a*a+2*a*b+b*b;
printf("\n ======Printing Result======= \t”);
printf("\n The Result of the Equation Is =%d \t”, K);
getch();
}
*******************

Example Program 3.9


Write a program to solve the following mathematical equation.
Z=a3+3a2b+3ab2+b3
Source Code
void main()
{
int a, b, Z;
clrscr();
printf("\n Enter Value a:\t ");
scanf("%d",&a);
printf("\n Enter Value for b:\t ");
scanf("%d",&b);
Z=a*a+2*a*a*b+2*a*b*b+b*b;
printf("\n ======Printing Result======= \t”);
printf("\n The Result of the Equation Is =%d \t”, Z);
getch();
}
*******************

40 | P a g e
CHAPTER FOUR

OPERATORS
4
AND EXPERSSIONS

OBJECTIVE:
When you have completed this chapter, you will be able
to know about the

Short Answer Questions


Q1. What is an operator? How many types of operators are there in C?
Q2. Explain operands with example.
Q3. Define and explain expression.
Q4. Explain operator precedence in C
Q5. What is a modulus operator? Why it is used?

Long Answer Questions


Q1. Explain all types of operators used in C.

Problems
Example problems with source codes

41 | P a g e
Chapter # 4
OPERATORS AND EXPRESSIONS

============Short Questions and Answers=============


Q1. What is an operator? How many types of operators are there in
C.
Operator
An operator in defined as the programming ingredient which mathematically
or logically evaluates the values of variable, constants or other identifiers.
Explanation
In programming the evaluations are performed and decisions are taken
because of the utilization of different type of operators.
Example

Operator Operation Example


Arithmetic For mathematical operations like +,. - , / , *
Addition, Subtraction, Division etc

Assignment To store some value in the +=,*=, /=


variables
Relational For comparison of data values <,<=, >=
Logical To take logical decisions &&, ||

Classification of Operators
Operators fall into two basic classes:
 Unary Operators
 Binary Operators
Unary Operators
The operator which requires only one operand is called unary operator
Example
++ Increment Operator
-- Decrement Operator
Binary Operators
The operator which requires at least two operands for evaluation is called
binary operator.
Example
+, -, /, *

Q2. Explain operands with example.


Operands
The operands are defined as the variables, constants or identifiers on which
the operators are applied.

42 | P a g e
Explanation
Operators are always supposed to be performed on some value which may
be in form of a variable or constants. There may be multiple operands in a C
statement to evaluate.
Example

Operator C Statement Operands


+ c=a+b; a, b and c
- d=a-b. a, b and d

Q3. Define and explain expression.


Expression
An expression is a collection of one or more operands and operators that can
be evaluated to a single value.
Explanation
An expression is constructed by the combination of operators, operands or
any other C language identifier So an operand is a constant, a variable or
may be another expression.
Example:
C = a +b;
x ++;
y = (2+5+x)/2;

Q4. Explain operator precedence in C


Operator Precedence
The operator precedence defines that in which order multiple arithmetic
operators are going to be applied in an expression. The normal order of
arithmetic operations is are as follows.

Operator Operation Order


*, /,% Multiplication, Division, Remainder Higher
+, - Addition, Subtraction Lower
Role of Parentheses in Operator Precedence
The parentheses can also play an important role while defining the order of
precedence. The natural order of precedence as mentioned can be changed
using parentheses.

Q5. What is a modulus operator? Why it is used?


Modulus Operator
The modulus operator is a mathematical operator which returns the
remainder after dividing a numeric value by another.

43 | P a g e
Explanation
The modulus operator which is denoted by % is also called remainder
operator. The values on which the operator is being applied may be constant
values or in the form of variables.
Example
C=7%2;
The variable C contains the remainder 1 which is leftover after dividing 7 by
2.

=============Long Questions and Answers=============


Q1. Explain all types of operators used in C.
Operators and its Types In C
There are the following operators in C.
 Arithmetic operators
 Assignment operators
 Relational operators
 Logical / Boolean operators
 Increment / Decrement operators
1. Arithmetic Operators
These operators are used to perform mathematical operation. An arithmetic
expression is made up of variable constants or both.
OPERATOR OPERATION EXAMPLE
+ Addition a+b
- Subtraction a -b
* Multiplication a#b
/ Division a/b
% Modulus a%b

2. Assignment Operators
Assignment operator is denoted by (=) is it use to assign / to store the value
of an expression to an identifier.

Expression Meanings
a = 5; 5 is assigned in „a‟
Total = 74.75; 74.75 has been stored in total
Area = Length x breath; The product of length and breath
will be started in area.

The assignment operator is also used with the combination of arithmetic


operators.

44 | P a g e
Operator Operation Example Explanation
+= Add-assign a + =b same as a = a + b
-= Subtract-assign a – =b same as a = a – b
*= Multiply-assign a * =b same as a = a * b
/= Divide-assign a / =b same as a = a / b
% = Remainder-assign a %=b same as a = a % b

3. Relational Operators
The relational operators are used for the comparison of two operands. The
operands may be variables or constant or expressions that ultimately results
in a numeric value. Character values can also be compared as these can be

Operator Operation Example


< Less than a<b
> Greater than c> d
<= Less than or equal a <= d
to
>= Greater than or c> = d
equal to
== Equals to B == c
!= Not equal to x!=y

represented by their ASCII codes.


4. Logical / Boolean Operator
These operators are used to take decisions on the basis of some conditions.
The Boolean operators were described by Irish Mathematician George Bole
(1915- 1964).
An instruction having logical operators may have unary or binary operators.
The operands may be constants, variables or expressions.

Operator Operation Example


&& Logical AND 1 if a == b && c==d; else 0
|| Logical OR 1 if a==b || c > d; else 0
! Logical NOT 1 if (a==b) ! c < d; else 0

5. Increment and Decrement Operator


These are the two important unary operators which are very useful in
programming. If a variable x has to be incremented by 1 then the increment
operator ++ can be used rather than the expression x = x + 1; Similarly the
decrement operator – – is used to decrease the value of a variable by 1.
Example
int x;

45 | P a g e
x = 5;
x = x + 1; //x is incremented
x++; // x is incremented by 1 using incremented operators.
x-- ; // x is decremented by 1 using decremented operators.

Operator Operation Example Explanation


+ + Prefix ++a Increment by 1 then
increment use the new value of a
in the expression in
which a resides.
++ Subtract- a++ Use the current value of
assign a in the expression in
which a resides then
increment a by 1.
* Multiply-assign --a Decrement a by 1 then
use the new value of a
in the expression in
which a resides.
/ Divide-assign a-- Use the current value of
a in the expression in
which a resides, then
decrement a by 1.

smaxgor PmlpmaxE
Example Program 4.1
Write a program to solve the  following mathematical equation.
M=  1  1 

 (x  y)  (x  y) 
 

   
Source Code
void main()
{
int x, y, M;
clrscr();
printf("\n Enter Value x:\t ");
scanf("%f",&x);
printf("\n Enter Value for y:\t ");
scanf("%f",&y);
M = ( 1 / ( x – y )) * ( 1 / ( x + y) ) ;
printf("\n ======Printing Result======= \t”);
printf("\n The Result of the Equation Is =%0.0f \t”, M);
getch();
}
*******************

46 | P a g e
Example Program 4.2
Write a program to solve the following mathematical equation.
ab
P=
a b

Source Code
#include <math.h>
void main()
{
int a, b, P;
clrscr();
printf("\n Enter Value a:\t ");
scanf("%d",&a);
printf("\n Enter Value for b:\t ");
scanf("%d",&b);
P = sqrt ( a + b ) / sqrt ( a - b) ;
printf("\n ======Printing Result======= \t”);
printf("\n The Result of the Equation Is =%d \t”,P );
getch();
}
*******************

Example Program 4.3


Write a program take input for the year of birth and the current year.
Calculate the age of the person and print result.
Source Code
void main()
{
int yob, cy, age;
clrscr();
printf("\nEnter Your Year of Birth :\t ");
scanf("%d",&yob);
printf("\nEnter Current Year:\t ");
scanf("%d",&cy);
age= cy-yob;
printf("\n Your age is \t%d”,age);
getch();
}
*******************
Example Program 4.4
Write a program to solve the following mathematical equation. Z=(a+b)(a-b)
Source Code
void main()
{

47 | P a g e
int a, b, Z;
clrscr();
printf("\n Enter Value a:\t ");
scanf("%d",&a);
printf("\n Enter Value for b:\t ");
scanf("%d",&b);
Z=(a+b)*(a-b);
printf("\n ======Printing Result======= \t”);
printf("\n The Result of the Equation Is =%d \t”, Z);
getch();
}
*******************

Problem 4.5
Write a program which uses arithmetical operators to calculate the area of a
triangle, volume of a sphere.
Source Code
void main()
{
float a,b,r,T,S;
clrscr();
printf("Enter the value for altitude of a triangle: ");
scanf("%f",&a);
printf("\nEnter the value for base of a triangle: ");
scanf("%f",&b);
printf("\nEnter the value for radius of a sphere: ");
scanf("%f",&r);
T=(1.0/2.0)*(a*b);
S=(4.0/3.0)*(3.142)*(r*r*r);
printf("\n\nArea of triangle = %.2f",T);
printf("\nArea of sphere = %.2f",S);
getch();
}

*******************

48 | P a g e
CHAPTER FIVE

CONDITIONAL
5
STATEMENTS

OBJECTIVE:
When you have completed this chapter, you will be able
to know about the

Short Answer Questions


Q1. What are control structures used in C
Q2. Explain the control structure sequence or sequential flow.
Q3. Explain the control structure selection or conditional flow.
Q4. Explain the control structure iteration or repetitive flow.

Long Answer Questions


Q1. Explain If statement with syntax and example program also draw flow
chart.
Q2. Define and explain switch statement with syntax and example program.
Q3. Why nested if statement is used? explain your answer with example
program.
Q4. Differentiate Switch Statement & if statement

Problems
Example problems with source codes

49 | P a g e
Chapter # 5
CONDITIONAL STATEMENTS

============Short Questions and Answers=============


Q1. What are control structures used in C
Control Structure
In a program control structure controls the flow of execution of program
instructions or functions. Structured programming uses a limited number of
control structures to minimize the complexity of the program.
Control Structures Used In 'C'
There are three basic control structures in structured programming.
 Sequence of sequential flow.
 Selection or conditional flow.
 Iteration or repetitive flow.

Q2. Explain the control structure sequence or sequential flow.


Sequence or Sequential Flow
The sequence structure defines that all the statements are executed in the
same order in which these are mentioned in the program.
Explanation
Although the C language IDE does not provide any facility to mention the
line number but all the lines written in a program are executed in the same
order as these are written in the program.
Example
The program instructions will be performed one by one in the same order.
void main()
{
int a,b;
a=5;
clrscr();
printf("\n The value of A is %d", a);
getch();
}

Q3. Explain the control structure selection or conditional flow.


Selection or Conditional Flow
The selection control structure defines the flow of the program by choosing
different alternatives on the basis of some condition.
Explanation
The selection control structure is used for the decision making while
programming for a particular problem. So the execution of program
conditionally may or may not be in sequence.
Example:
If statement, Switch statement and Conditional operator.

50 | P a g e
Q4. Explain the control structure iteration or repetitive flow.

Iteration or Repetitive Flow


The repetitive control structure defines the flow of program in a way when a
statement or multiple statements are supposed to be carried out for a
number of times on the basis of some condition.
Explanation
The program statements are performed for number times without writing
them again and again in this way program complexity is reduced, less
memory is occupied and speed increases.
Example
1. For loop
2. While loop
3. Do While loop

=============Long Questions and Answers=============


Q1. Explain If statement with syntax and example program also
draw flow chart.

Definition
The “if” statement is a conditional control structure. In programming "if"
statement is used when an action is supposed to be taken on the basis of
some condition.
Explanation
In programming, sometimes it happens when the programmer has to take
some action by checking some condition. The action can be taken not only
when the condition is true but also when the condition is false. The if
statement has mainly two parts
1) Condition
2) Action
The following are some general example
1. If tomorrow it is holiday, we will go for the picnic.
2. If I pass intermediate exam, I will apply in NED University.
3. If tomorrow it is raining. I will go for the picnic otherwise I will go to
the college.
Syntax
if (condition)
{
Action 1
Action 2

51 | P a g e
else
{
Action 1
Action 2

Flowchart

Example Program
#include <stdio.h>
#include <conio.h>
void main()
{
float bs, hra, ns; // declared variables
clrscr(); //cleared the screen.
printf(“\n Enter Basic Salary of Employee\t”)
scanf(“%f”, &bs);
/* Take input in the basic salary of employee. Now we will calculate the
house rent allowance on the basis of a condition */

if (bs >=5000) // condition


{
hra = bs * 10/100; // Action when true
ns = bs + hra;
}
else
{
hra = bs * 5/100; // Action when false
ns = bs + hra;
}
print f(“\n The Net Salary of employee is \t%f”ns);
getch();
}

Program Demonstration
In the above program we have taken input basic salary of an employee and
then mentioned a condition if the basic salary is greater then equal to 5000
we have calculated house rent allowance 10% of the basic salary and if the
condition is false then we have calculated the house rent allowance 5% of
the basic salary then the result has been printed.

*******************

52 | P a g e
Q2. Define and explain switch statement with syntax and example
program.

Definition
The switch statement is selection control which is used to select an option
from different alternatives.

Explanation
As compared to the if, the switch statement is used to check only for
equality. Normally the condition is checked by a variable called controlling
variable. The value of this may be type of integer or character but not any
other.

Syntax
switch (variable)
{
case 1:
Statement (s);
Break;
case 2:
statement (s);
break;
}

Flow Chart

Example Program
#include <stdio.h>
#include <conio.h>
void main()
{
int I;

53 | P a g e
clrscr();
print f (“ In Enter a number from 1 to 4\t”);
scan f(“%d”,& i);
switch (i)
{
case 1:
print f(“You are in case 1 \n”);
break;
case 2:
print f(“You are in case 2 \n”);
break;
case 3
print f(“You are in case 3\n”);
break;
default:
print f(“\n invalid input”);
}
getch();
}
Program Demonstration
In this example program we have taken input in a integer variable we have
mentioned that the value must be from 1 to 4. The reserved word case
checks the condition for equality for the alternate operations. The action is
performed under the concerned case. There may be one or more statement
under any case.
Purpose of Break
When the option is found in any of the case the statement(s) under the case
is performed and the break statement specifies that no more case should be
checked now.
Purpose of Default
The statements under the default are performed if the user input is not from
the given alternatives.

Q3. Why nested if statement is used? explain your answer with


example program.
Definition
In programming nesting refers to the statement inside the same statement.
Here nested if statement refers to the condition under a condition.
Explanation:
Some time we have to deal with the situation, when a condition is true but in
the action block or body of the "if" statement, we have to check for another
condition and if the nested condition is also true then we take the action. It
could also be done under the else block of the first condition.

54 | P a g e
Syntax
if (condition)
{
if (condition)
{
Action 1
Action 2

}
}
Example Program
An organization provides 10% house rent allowance if the employee is male.
Not only this but also if his basic salary is greater than Rs. 5000
void main()
{
float bs,hra,ns;
char gender;
clrscr();
printf(“\n Enter basic salary of employee\t”);
scanf(“%f”,&gender);
if(gender=='M')
{
if (bs>5000)
{
hra=bs*10/100;
ns=bs+hra;
}
}
else
{
printf("\n No house rent allowance can be granted");
ns=bs;
}
printf(“\n The net salary of employee is %f\t”,ns);
getch();
}
Demonstration of the program
In the above program we have taken input for basic salary (bs) and gender
of an employee then we have checked the condition if the employee is male
then we have checked another condition that the basic salary is greater then
equal to 5000. We have calculated the house rent allowance as 10% of the
basic salary. Then we have printed the results.

55 | P a g e
Q4. Differentiate Switch Statement & if statement

Switch Statement IF Statement


Keywords Keywords
1) The switch statement uses 1) The „if statement‟ uses the
identifiers and key words like terms or keywords like if, else,
switch case, default and break. etc.
Condition Type Condition Type
2) The switch statement checks 2) In if statement the condition
the condition only for equality can be checked using all the
without using any equality relational & logical operators.
operator.
Mergence of Conditions Mergence of Conditions
3) In switch statements two or 3) The if statement can make the
more condition cannot be merged combination for two or more
using logical operators. condition using logical operators.
Nesting in Switch Nesting in if
4) The switch statement is 4) Nested if is a powerful feature
normally not coded as nested of the if statement.
switch.
Data Type Data Type
5) The condition can be checked 5) The condition can be checked
only for int and char variables, for any data type.

Solve the following problems by conditional statements


Problem 5.1
Take two integer numbers having same value and check them for equality.
Source Code
void main()
{
int a,b;
a=5;
b=5;
clrscr();
if (a==b)
{
printf("\n a and b are equal");
}
getch();
}
*******************

56 | P a g e
Problem 5.2
Take Input for three numbers and find the greatest among them
Source Code
void main()
{
int a, b, c; //Declaring Variables
clrscr();
printf("\n Enter First Number:\t ");
scanf("%d",&a);
printf("\n Enter Second Number:\t ");
scanf("%d",&b);
printf("\n Enter Third Number:\t ");
scanf("%d",&c);
if(a>b && a>c)
printf("\n The First Number is Greatest that is\t%d”a);
else if (b>a && b>c)
printf("\n The First Number is Greatest that is\t%d”b);
else if (c>a && c>b)
printf("\n The First Number is Greatest that is\t%d”c);
getch();

}
*******************
Problem 5.3
Take input for two numbers x and y, Compare the numbers by if() and print
the message whether these are equal or not.
Source Code
void main()
{
int x,y;
clrscr();
printf("\n Enter the value for x:\t");
scanf("%d",&x);
printf("\n Enter the value for y:\t ");
scanf("%d, &y);
if (num1 == num2)
{
printf("\n you are in true action block.");
printf("\n No.1 and No.2 are equal." );
}
else
{
printf("\n You are in false action block");
printf("\n No.1 and No.2 are not equal.");

57 | P a g e
}
getch();
}
*******************
Problem 5.4
Take input for an employee's basic salary. If basic salary is greater then
5000 then give 10% house rent and calculate net salary otherwise 5% house
rent allowance and calculate net salary. Print net salary.
Source Code
void main()
{
float BS, HRA, NS; // declared variables
clrscr();
printf("\n Enter the employee's Basic Salary \t");
sanf("%f",&BS);
if (BS>5000)
{
HRA = BS*10/100;
NS = BS+HRA;
}
else
{
HRA = BS*5/100;
NS = BS + HRA;
}
pinttf("\n The net salary of the employee is\t %0.2f",NS);
getch();
}
*******************
Problem 5.5
Take input for gender and final percentage marks, if the gender is female
and marks are greater then 70% then student can apply for admission other
wise cannot apply for the admission.
Source Code
void main()
{
float per;
char gender;
clrscr();
printf("\n Enter value for gender 'm/f'\t");
scanf("%c",&gender);
printf("\n Enter value for percentage\t");
scanf("%f",&per);
if (gender=='f' && per >= 70)

58 | P a g e
{
printf("\n\n You can apply for the admission.");
}
else
{
printf("\n You can not apply for the admission.");
}
getch();
}

*******************
Problem 5.6
A company insures a person if he is male and having age less than 35 years.
Write a program to check whether a person is insured or not.
Source Code
void main()
{
//Declaring Variables
float BS, TA, HRA, GP, TAX, NS;
char GEN;
clrscr();
printf("\n Enter Gender of the Person :\t ");
scanf("%c",&gender);
printf("\n Enter Age of the Person :\t ");
scanf("%f",&AGE);

if(gender==‟m‟&&AGE<=35)
printf("\n The Person Is Insured\t”);
else
printf("\n The Person Is Not Insured\t”);

getch();
}
*******************
Problem 5.7
A company pays 10% house rent allowance and 8% travel allowance if the
basic pay of the employee is greater than 10000 otherwise the company
pays 7% house rent allowance and 5% travel allowance. Calculate the gross
pay.
Source Code
void main()
{
//Declaring Variables
float BS, TA, HRA, GP;

59 | P a g e
clrscr();
printf("\n Enter Value for Basic Salary of Employee :\t ");
scanf("%f",&BS);
if(BS>=10000)
{
HRA=7*BS/100;
TA=5*BS/100;
}
else
{
HRA=10*BS/100;
TA=8*BS/100;
}

GP=BS+TA+HRA;
printf("\n ======Printing Salary Details======= \t”);
printf("\n The Basic Salary of Employee Is =%0.2f \t”, BS);
printf("\n The House Rent Allowance For Employee Is =%0.2f \t”, HRA);
printf("\n The Travel Allowance For Employee Is =%0.2f \t”, TA);
printf("\n The Gross Pay of Employee Is =%0.2f \t”, GP);
getch();
}
*******************

Problem 5.8
A company pays 15% house rent allowance and 7% travel allowance if the
basic pay of the employee is greater than 12000 otherwise the company
pays 12% house rent allowance and 6% travel allowance. The employee has
to pay 5% tax on basic pay. Calculate the gross pay and net pay.
Source Code
void main()
{
//Declaring Variables
float BS, TA, HRA, GP, TAX, NS;
clrscr();
printf("\n Enter Value for Basic Salary of Employee :\t ");
scanf("%f",&BS);
if(BS>=12000)
{
HRA=15*BS/100;
TA=7*BS/100;
}
else
{

60 | P a g e
HRA=12*BS/100;
TA=6*BS/100;
}
TAX=5*BS/100;
GP=BS+TA+HRA;
NS=GP-TAX;
printf("\n ======Printing Salary Details======= \t”);
printf("\n The Basic Salary of Employee Is =%0.2f \t”, BS);
printf("\n The House Rent Allowance For Employee Is =%0.2f \t”, HRA);
printf("\n The Travel Allowance For Employee Is =%0.2f \t”, TA);
printf("\n The Gross Pay of Employee Is =%0.2f \t”, GP);
printf("\n The Tax Due on of Employee Is =%0.2f \t”, TAX);
printf("\n The Net Pay of Employee Is =%0.2f \t”, NS);
getch();
}
*******************
Problem 5.9
Write a program to make a simple calculator in C using switch statement.
Source Code
void main()
{
int a, b, ans=0;
char op;
clrscr();
printf("\n Enter Number1=\t");
scanf("%d",&a); //taking input for the two numbers
printf("\n Enter Number2=\t");
scanf("%d",&b);
printf("\n Enter Operator=\t");
scanf("%c",&op);
switch(op) // checking operator using switch
{
case „+‟:
ans=a+b;
break;
case „-‟:
ans=a-b;
break;
case „/‟:
ans=a/b;
break;
case „*‟:
ans=a*b;
break;

61 | P a g e
default:
printf("\n\n Invalid Operator Try Again");
}
printf("\n The answer is =%f\t",ans); // printing answer.
getch();
}
*******************
Problem 5.10
Develop a simple program of call center in C.
Source Code
void main()
{
int sc, a, ans=0;
char op;
clrscr();
printf("\n =======Welcome To Call Center=======\n",;
printf("\n Dial Service Code=\t");
scanf("%d",&sc); //taking input for the two numbers
printf("\n Press 1 To Check Balance\n Press 1 To Check
Balance\n Press 2 To Recharge\n Press 3 For Net Services\n
Press 4 To Call Operator\n \t");
scanf("%d",&a);
printf("\n Enter Operator=\t");
scanf("%c",&op);
switch() // checking operator using switch
{
case 1:
printf("\n Your Current Balance Is ---------- \t");
case 2:
printf("\n You Balance Can Be Loaded Using Card\t");
case 4:
printf("\n Your Current Balance Is ---------- \t");
case 5:
printf("\n Your Current Balance Is ---------- \t");
default:
printf("\n\n Invalid Operator Try Again");
}
printf("\n The answer is =\t",ans); // printing answer.
getch();
}
*******************

62 | P a g e
CHAPTER SIX

INPUT
6
OUTPUT FUNCTIONS

OBJECTIVE:
When you have completed this chapter, you will be able
to know about the

Short Answer Questions


Q1. How many types of IO functions are used in C language?
Q2. Describe the following with syntax and example program.

Long Answer Questions


No long questions in this chapter

63 | P a g e
INPUT OUTPUT FUNCTIONS

============Short Questions and Answers=============

Q1. How many types of IO functions are used in C language?

C language provides two types of I/O functions


 Formatted IO functions
 Unformatted I/O functions

IO function

Formatted Unformatted

Single Character Multiple Character

Single Character Input Single Character Output


getch();getche();getchar(); putch();putchar();

Input Output
scanf(); printf();
Multiple Character Input Multiple Character Output
gets(); puts();

Formatted IO functions
Formatted IO function are the C language predefined functions which have a
particular syntax for writing its code. It is necessary to follow the proper
syntax while using them in a program.
Example
printf(); is an example of formatted output function.
And scanf(); is an example of formatted input function.
Syntax
Here is the syntax of scanf(); function.
Function Name Format Specifier Double quotes Address Operator

scanf(“%d”, &a);

Parentheses Comma Variable Name Semicolon

64 | P a g e
Here is the syntax of printf(); function.

65 | P a g e
Function Name Format Specifier Double quotes

printf(“The value of a is %d”, a);

Parentheses Comma Variable Name Semicolon

Unformatted IO functions
The formatted IO functions are the C language function which do not have a
specified syntax in parentheses.
Example
The following are the C lanuage formatted IO functions.
getch();
getche();
getchar();
gets();
puts();
putch();
putchar();

Q2. Describe the following with syntax and example program.


getch();
It is a single character unformatted input function used to take input of one
character but that is not displayed on the screen while entering using
keyboard.
Here is an example.
char x;
x=getch();
getche();
It is a single character unformatted input function used to take input of one
character but that is displayed on the screen.
Here is an example.
char y;
y=getche();
getchar();
It is a single character unformatted input function, used to take input for
only one character data value.
Here is an example.
getchar(x);
putch();
It is a single character unformatted output function, which can display on
character.
Here is an example.
putch(x);

66 | P a g e
putchar();
It is a single character unformatted output function, which can display on
character.
Here is an example.
putchar();
gets();
This function is used to take input for multiple character values.
Here is an example.
x=gets(“Enter Your County Name”);
puts();
This function is used to give output for multiple characters
Here is an example.
puts(x);

*******************

67 | P a g e
CHAPTER SEVEN

ITERATION
7
AND ITS TYPES

OBJECTIVE:
When you have completed this chapter, you will be able
to know about the

Short Answer Questions


Q1. Define the term iteration.
Q2. Differentiate while and do while loop.
Q3. Explain For loop with syntax and example program.
Q4. Explain while loop with syntax and example program.
Q5. Explain do while loop with syntax and example program.

Long Answer Questions


Q1. Describe nested looping with example program.

Problems
Example problems with source codes

68 | P a g e
CHAPTER # 7
ITERATION AND ITS TYPES

============Short Questions and Answers=============

Q1. Define the term iteration.


Iteration
The term iteration refers to repetition. In programming when a statement or
number of statements are supposed to be repeated for a specified number of
times. It is done by the iterative control structure.
There are three iterative control structures used in C language
1. For Loop 2. While Loop 3. Do While Loop
All the three types of loops provided in C language has their own
significance.

Q2. Differentiate while and do while loop.

While Loop Do While Loop


1 Testing Mode
While loop uses pre testing. do while loop uses post testing.
2 Base of Condition
No action is taken if the Action is taken one time even if
condition is false in the very the condition is false in the very
first step. first step.
3 Block of the Loop
Block of the loop is written Block of the loop is written before
after the condition. the condition checking
4 Reserved Words
Reserved word while is used. Reserved word do while loop is
used.

For Loop While Loop


1 Loop Type
For loop is a counter loop. While loop is a conditional loop.
2 No of Iterations
No of repetition is already Most of the time the No. of
known in this loop. repetition is not already known in
this loop.
3 No of Expressions
It has got three expressions in It has only test expression in the
parenthesis. parenthesis.
4 Reserved Word
Reserved word “for” is used. Reserved word “while” is used.

69 | P a g e
Q3. Explain For loop with syntax and example program.
For Loop
In C- language the most commonly used iterative control structure is „for
Loop‟ which is used to repeat a statement or block of statements for a
specific number of times.
Syntax
for (Initialize Exp; Test Exp; Increment/Decrement Exp)
{
statement(s);
}
Explanation
The „for loop‟ includes three expressions in the parenthesis. The initialize
expression tells the compiler the starting value from where the Loop is going
to be started. The test expression specifies the Last limit until the iteration
has to be performed. The increment or decrement brings the started value
across the test expression. After the parenthesis the bracks {} include a
statement or a block of statements to be repeated.

Example Program
void main()
{
int a ;
clrscr(); //Counter Variable
for (a=1;a<=10;a++)
{ // Block of Loop
printf(“ \n Welcome”);
} // Repetation
getch();
}
Program Demonstration
The program uses a counter variable „a‟ of type integer. The loop starts from
1 and is repeated up to 10 times by increment of 1. So the message
„Welcome‟ will be printed 10 times.

*******************

70 | P a g e
Q4. Explain while loop with syntax and example program.
While Loop
While loop is a iterative control structure of C. It is a conditional loop which
is used to repeat a statement or block of statements for a number of times
depending on a condition.

Syntax
while(condition)
{
statement(s);
}
Explanation
While loop is used in a particular programming situation when a statement
or multiple statement are to be repeated on the bases of some mentioned
condition.

Example Program
void main()
{
int a=0;
clrscr();
while(a<10)
{

printf(“Enter any number less than 10\t”);


scanf(“%d”,&a);
printf(“\n You have entered\t%d”,a);
}

getch();
}

71 | P a g e
Demonstration of the Program
In the above program the programmer has asked to enter a value less than
10. The loop continues until the user does not enter any value which is
greater than or equal to 10. Hence in this situation the numbers of iterations
are not specified, it is dependent on the entered value.

Q5. Explain do while loop with syntax and example program.


Do while loop
It is the third important iteration control of C language. It is a post testing
conditional loop which performs a statement of block of statements at least
once even if the condition is false.
Syntax
do
{
statement(s);
}
while(condition);

Explanation
The do while loop is used in a programming situation when the action block
is supposed to be performed at least once even if the condition is false.
Hence in the do while loop the condition comes after the action block.
Flow Chart

72 | P a g e
Example Program
void main()
{
char ans=‟N‟;
clrscr();
do
{
printf(“\nCollege of Emerging Technologies”);
printf(“ \nDo you want to print the college name again\tY\N”);
scanf(“%c”,&ans);

}
while(ans==‟Y‟);
getch();
}
Demonstration of the Program
In the above program we have printed the college name on screen and then
it has been asked if the user want to print more. Although the condition is
false in the very first step but the message is printed one time.

============Long Questions and Answers=============

Q1. Describe nested looping with example program.

Nested Looping
Nested looping is defined as the loop inside the loop. It is a cyclic execution
of a statement or block of statement for specified number of times.
Syntax
for (initialize Exp; text Exp; Increment/Decrement Exp)
{
for (initialize Exp; text Exp; Increment/Decrement Exp)
{
statement(s);
}
}

73 | P a g e
Muhammad Uwais BIT-MCS (KU)
Computer Science XII 2015- 2016

Flow Chart

Explanation
Loop is an iterative control structure which is used to repeat statement(s) for
a number of times on the bases of some condition. Nested looping refers to
the loop inside a loop for the repetition of some program instructions.
Nested looping can be applied on any of the loop type like for, while and do
while loops. The inner loop repeats the statement(s) for a specific number of
times and the outer loop repeats the inner loop for a specified number of
times.
Example Program
Example Program
void main()
{
int a,b;
clrscr();
for(a=1;a<=5;a++)
{
for(b=1;b<=10;b++)
printf(“\t%d”,b);

}
getch();
}

Page 74 V: 03
Muhammad Uwais BIT-MCS (KU)
Computer Science XII 2015-2016

Output
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10

Demonstration of Example Program


In this program the inner loop prints numbers from 1 to 10 and the outer
loop repeats this iteration for five times. It shows logic working with the
nested looping.

Example Programs
Example Program 7.1
Write a program using for loop to print usual printing characters
corresponding to 32 to 127 ASCII code.
Source Code
void main()
{
int a;
clrscr();
for(a=32;a<=127;a++)
{
printf("%3d=%c\t",a,a);
}
getch();
}

Output
32= 33=! 34=" 35=# 36=$ 37=% 38=& 39=' 40=(
41=)
42=* 43=+ 44=, 45=- 46=. 47=/ 48=0 49=1 50=2
51=3
52=4 53=5 54=6 55=7 56=8 57=9 58=: 59=; 60=<
61==
62=> 63=? 64=@ 65=A 66=B 67=C 68=D 69=E 70=F
71=G
72=H 73=I 74=J 75=K 76=L 77=M 78=N 79=O 80=P
81=Q
82=R 83=S 84=T 85=U 86=V 87=W 88=X 89=Y 90=Z
91=[
92=\ 93=] 94=^ 95=_ 96=` 97=a 98=b 99=c 100=d
101=e

Page 75 V: 03
Muhammad Uwais BIT-MCS (KU)
Computer Science XII 2015-2016

102=f 103=g 104=h 105=i 106=j 107=k 108=l 109=m


110=n 111=o
112=p 113=q 114=r 115=s 116=t 117=u 118=v 119=w
120=x 121=y
122=z 123={ 124=| 125=} 126=~ 127=⌂

*******************

Example Program 7.2


Write a program that calculate power of base without using power function
by taking input both.

Source Code
void main()
{
double pow=1;
int i,num,p;
clrscr();
printf("Enter number : ");
scanf("%d",&num);
printf("\nEnter power : ");
scanf("%d",&p);
for(i=1;i<=p;i++)
{
pow*=num;
}
printf("\nAnswer is %.2f",pow);
getch();
}
Output
Enter number : 6
Enter base : 3

Answer is 216.00
*******************
Example Program 7.3
Write a program using nested for loop to print to print the following.
*
***
*****
*******
*********

Page 76 V: 03
Muhammad Uwais BIT-MCS (KU)
Computer Science XII 2015-2016

Source Code
void main()
{
int a,x,y,m=4,n=1;
clrscr();
for(y=0;y<=4;y++)
{
for(x=1;x<=m;x++)
{
printf(" ");
}
for(a=1;a<=n;a++)
printf("*");

n=n+2;
m--;
printf("\n");
}
getch();
}
Output
*
***
*****
*******
*********
*******************

Example Program 7.4


Write a program to generate the table of N.
Source Code
void main()
{
int a,N;
clrscr();
printf("\nEnter value to print its table\t");
scanf("%d"&a);
for(a=1;a<=10;a++)
{
printf("\n%dx%d=%d",N,a,N*a);
}
getch();
}

Page 77 V: 03
Muhammad Uwais BIT-MCS (KU)
Computer Science XII 2015-2016

Output
Enter value to print its table 7
7x1=7
7x2=14
7x3=21
7x4=28
7x5=35
7x6=42
7x7=49
7x8=56
7x9=63
7x10=70
*******************

Example Program 7.5


Find the factorial of N, use scanf() to read the value of N
Source Code
void main()
{
double f=1;
int num,n;
clrscr();
printf("Enter the no. greater than 0 to find its factorial: ");
scanf("%d",&num);
while(num<0)
{
printf("\nError! number is less than 0.\n");
printf("Please enter number greater than 0: ");
scanf("%d",&num);
}
for(n=1;n<=num;n++)
{
f*=n;
}
printf("\nThe factorial of %d is %f",num,f);
getch();
}
Output
Enter the no. greater than 0 to find its factorial: -3

Error! number is less than 0.


Please enter number greater than 0: -5

Page 78 V: 03
Muhammad Uwais BIT-MCS (KU)
Computer Science XII 2015-2016

Error! number is less than 0.


Please enter number greater than 0: 16

The factorial of 16 is 20922789888000.000000

*******************

Page 79 V: 03
Muhammad Uwais BIT-MCS (KU)
Computer Science XII 2015-2016

CHAPTER EIGHT

FUNCTIONS
8
OBJECTIVE:
When you have completed this chapter, you will be able
to know about the

Short Answer Questions


Q1. Define function and its types.
Q2. Describe predefined or built in functions.
Q3. Describe programmer defined functions used in C.
Q4. Write advantages of user defined function.

Long Answer Questions


Q1. Write procedure of creating a user defined function

Problems
Example problems with source codes

Page 80 V: 03
Muhammad Uwais BIT-MCS (KU)
Computer Science XII 2015-2016

CHAPTER # 8
FUNCTIONS

=============Short Questions and Answers============

Q1. Define function and its types.


Function
In C language a function is a statement or block of statements to perform a
specific task.
Explanation
A function is one of the fundamental idea in structured programming. The
idea defines the development of independent modules which separately
solve the sub problems. Every C program contains at least one function that
is main( ).
Example
clrscr(), printf(),getch() etc.
Types of functions in C language
In C language there are mainly two types of functions.
 Pre-defined / Built In / library function.
 Programmer defined/ User Defined function

Q2. Describe predefined or built in functions.


Pre-defined or library functions
These are the functions which are created by the developers of the
programming language C. These functions are present in these concerned
library files of C, that‟s why these are also called library functions.
Explanation
Every function has a predefined task that it can perform in the program. The
programmer has to include the concerned library file (Header File) while
using a pre-defined function according to the requirement. These functions
are also called built-in function.
Examples
The following are the functions of math.h file.

Function Purpose / example Argument Result


(s)
abs (x) Return the absolute value of its int int
integer argument:if x is -5 ,abs (x)is 5
abs(x) Return the absolute value of its type double double
double argument:if x is -8.432, fabs
(x) is 8.432
log(x) Returns the natural algorithm of x for double double
x>0.0:if x is 2.71828,log(x) is 1.0

Page 81 V: 03
Muhammad Uwais BIT-MCS (KU)
Computer Science XII 2015-2016

pow(x,y) Returns x^y. if x is negative, y must double double


be a whole number:if x is 0.16 and y
is 0.5, pow(x,y) is 0.4
sin(x) Return the sine of angle x: if x is double double
1.5708, sin (x) is 1.0 (radian)
sqrt(x) Return the non-negative square root double double
of x [sqrt(x)] forx>=0.0:if x is
2.25,sqrt(x) is 1.5

Q3. Describe programmer defined functions used in C.


Programmer Define Function
According to the requirement in a software project, the programmer can also
create his own function to solve a specific problem. This type of function is
called a user defined or programmer defined function.
Explanation
In programming sometime the programmer needs to perform specific task
again and again so it can be done by the user define function.
Examples
For instance the programmer want to send three arguments to add three
integer numbers than this type of function is not present in the C library files
so the programmer is supposed to define a user defined function.
Sum.C
main()
{
float ans;
clrscr();
ans=sum(21,42);
printf(“\n the sum is \t %0.2f”,ans);
ans=sum(43,65);
printf(“\n the sum is \t %0.2f”,ans);
getch();
}
float sum(int x,int y)
{
float z;
z=x+y
return z;
}

Page 82 V: 03
Muhammad Uwais BIT-MCS (KU)
Computer Science XII 2015-2016

Q4. Write advantages of user defined function.


The following are some advantages of using functions
 Complexity can be reduced
The complexity of the entire program can be divided into simple subtask
& functions, sub-programs can be written for each subtask.
 No repetition of code required
Function helps to avoid unnecessary repetition of code using functions a
single section of code can be used many times in the program.
 Easy processing
Function can have inputs & outputs & can process information easily.
 Easy to understand
The function or programs are short carries to write, understand & debug.
 Sharing
A functions can be shared by other programs by compiling it separately &
loading them together.
 Autonomous structure
Function are mostly independents of each other just as one program is
independent of another program. Most of the activities in a function are
hidden from the rest of the program.
 Recursions
In turbo c++, a function can call itself again and again. It is called
recursive ness. Many calculations can be done easily using recursive
process such as calculation of factorial of a number etc.
=============Long Questions and Answers=============

Q1. Write procedure of creating a user defined function

Need of a User-Define Function


Sometimes a user needs such type of function which is not already available
in any library file. The user-defined function is an important feature of C
language.
Main Components and Structure
The structure of a user-define function look like a main() function. The
following are the three main function.
 Function declaration / Function Prototype.
 Function definition.
 Function call.
1. Function Declaration
While using a function, a compiler needs to be told that what type of
function is going to be defined in the program, it is done by the function
declaration code. The function declaration contains three parts.
 Returning Data Type
 Function Name
 Argument

Page 83 V: 03
Muhammad Uwais BIT-MCS (KU)
Computer Science XII 2015-2016

The returning data type defines the data type of returning value from the
function definition. If the function does not return any value, the returning
data type is void. The function name is an identifier with the sign of
parentheses. The arguments are separated by commas and mentioned in the
parentheses. If no argument are their then the term “void” is written.
Syntax
The syntax of function prototype is as follows
Returning_data_type function_name (type of arg1, type of arg2 ….);
Example
A function for addition of three numbers
int sum ( int ,int,int);
2. Function Definition
The function definition defines the task of the function which is to be done
when the function is called. The function definition has two parts.
 Function Header.
 Body of the Function
The function header looks like a function declaration but it also includes the
variable names with the data types in the arguments. The function definition
is not terminated by semi-colon rather it has a block having the instructions
about the task of the function. It is called the body of the function. The body
of the function is enclosed by curly brackets.
Syntax
Returning_data_type function_name (type arg1, types arg2 ............. )
{
Statement(s);
}
Example
int sum(int x, int y, int z);
{
z=x+y+z;
return z;
}
3. Function call
The definition function can be called from the main function or from any
other function. If any value is being returned from the function definition, so
it necessary to hold the value in a variable.
Syntax
Variable_Name= Function_Name(arg1,arg2................);
Example
Ans = sum(21,22,34);
Example Program
float pi (void); // Function Déclaration
void main ()
{

Page 84 V: 03
Muhammad Uwais BIT-MCS (KU)
Computer Science XII 2015-2016

float ans;
clrscr ();
ans = pi (); // Function Call
printf(“\n the value of pi is \t %f”, ans);
getch ();
}
float pi (void) // Function Definition
{
float x;
x = 3.142;
return x;
}

Example Problems
Example Program 8.1
Write a program, define a function print a message of "Pakistan
Zindabad. Now call this function from main() five times.
Source Code
void msg(void);
void main()
{
clrscr();
msg();
msg();
msg();
msg();
msg();
getch();
}
void msg()
{
printf("\n Pakistan Zindabad");
}
*******************
Example Program 8.2
Write a program, define a function which can add two integers. Then call
the function at least two times from main() function.
Source Code
int sum(int, int);
void main()
{
int ans;
clrscr();
ans=sum(21,42);

Page 85 V: 03
Muhammad Uwais BIT-MCS (KU)
Computer Science XII 2015-2016

printf(“\n the sum is \t %d”,ans);


ans=sum(43,65);
printf(“\n the sum is \t %d”,ans);
getch();
}
int sum(int x,int y)
{
int z;
z=x+y;
return z;
}
*******************

Example Program 8.3


Write a program, create a user defined function, which receives marks of
five subjects of a student and returns the final percentage.
Source Code
float marks(int, int, int, int, int);
void main ()
{
float per;
clrscr ();
per = marks(46, 68, 79, 54, 88); // function call
printf =(“\n The percentage is \t %0.2f, per);
per = marks(64, 59, 49, 79, 46);
printf =(“\n the percentage is \t %0.2f, per);
per = marks(46, 65, 74, 57, 84);
printf =(“\n the percentage is \t %0.2f, per);
getch ();
}
float marks (int a, int b, int c, int d, int e);
{
float x;
x = (a+b+c+d+e); /500*100;
return x;
}
*******************

Page 86 V: 03
Muhammad Uwais BIT-MCS (KU)
Computer Science XII 2015-2016

Example Program 8.4


Create a user defined function which takes basic salary, house rent
allowance and tax as arguments and calculates the net salary.

Source Code
void sal(float, float, float);
void main ()
{
clrscr ();
sal (10000, 3500, 300);
sal (10000, 3500, 300);
sal (5000, 2200, 150);
getch ();
}
void sal(float BS, float HRA, float TA);
{
float NS;
NS = BS + HRA – TAX;
printf(“\n the net salary of employee is \t % 0.2f”, NS);
}
*******************

Example Program 8.5


Write a program which returns a value but doest not take any argument.
Source Code
float pi (void);
void main ()
{
float ans;
clrscr ();
ans = pi();
printf(“\n the value of pi is \t %f”, ans);
getch ();
}
float pi (void)
{
float x;
x = 3.142;
return x;}
*******************

Page 87 V: 03
Muhammad Uwais BIT-MCS (KU)
Computer Science XII 2015-2016

CHAPTER NINE

DATABASE
9
MANAGEMENT SYSTEM
CONCEPTS

OBJECTIVE:
When you have completed this chapter, you will be able
to know about the

Short Answer Questions


Q1. Define the various database terminologies and give examples
Q2. What is a database model?
Q3. Explain relational database model in detail.

Long Answer Questions


Q1. What are the features of a data base management system?
Q2. Describe advantages of A DBMS
Q3. Describe hierarchal database model in detail.
Q4. Describe network database model
Q5. Explain relational database model in detail.
Q6. Explain different components of a database system.
Q7. Describe key Fields and their types used in a database table
Q8. Differentiate the database terminologies.

Page 88 V: 03
Muhammad Uwais BIT-MCS (KU)
Computer Science XII 2015-2016

CHAPTER # 9
DATA BASE MANAGEMENT SYSTEM CONCEPTS

============Short Questions and Answers=============

Q1. Define the following terminologies and give examples


Data
Data are the row facts and figures about the different entities of any type of
enterprise. Process data is called information.
Example
Ahmed Javed Son of Javed Ali
House No R-222 Block 3 F.B Area.
*******************
Database
The database is a collection of related files in an organization. The database
is a particular arrangement of data. In this arrangement data is stored in
tabular form.
Example
A database of students in a school
A database of books in a library
*******************
Database Management System (DBMS)
The database management system is special purpose software. It provides
all the facilities for the management of a database.
Explanation
The database management system makes it possible to develop a database
for an organization and provides techniques to perform all types of database
operations like creation, insertion, deletion, updating.
Example
Oracle, MS SQL Server, Dbase, MS-Access
*******************
Relational Database Management system
A relational database model is based on the laws of relational algebra which
allows the programmer to work on one or more relations.
Explanation
The theory behind the relational database model is called relational algebra,
which contains rules and regulations and mathematical methods for
relational database. The relational algebra was forwarded by Dr. Edgar F,
Codd, a famous mathematician.
Example
Oracle, SQL Server etc
*******************

Page 89 V: 03
Muhammad Uwais BIT-MCS (KU)
Computer Science XII 2015-2016

Entities
An entity is defined as any physical or logical thing which has some
characteristics of some value.
Example
Person: - Employee, student, patient, customer
Place: - State, Country, Region
Physical Object: - Machine, building
Logical Thing: - Account, company
Event: - Deposit amount, purchase.
*******************
Entity Set / Table
An entity set / table is a collection of different instances of the same entity
with there attributes.
Explanation
Collection of rows and columns relating to the same type of entity is called
the table. In relational database management system a table is termed as
the relational variable.
Example
Student
SID Name Address CellNo DOB

23324 Ahmed Ali R-234 Block 2 0345-3456783 14-07-1990


Tariq Road
23325 Zeeshan H-344 Block 3 0300-2345654 26-03-1991
Khan Korangi
23326 Fareed Shah C-19 Block 5 0333-2334334 02-05-1989
DHA
23327 Kashif Hasan R-45 Block 4 0304-3456765 07-09-1990
F.B Area
******************* -
Field / Column / Attribute
An attribute is a property or characteristic of an entity having some value. In
a table a field is represented by a column having values of the related
attributes.
Example: -
Student: SID, Name, Address, CellNo, DOB etc.
Account: ACC#, Title, Opening Data, Account type, Balance etc.
Employee: Employee ID, Name, Father Name, Designation, Rank, Basic
Salary etc.
*******************
Record / Row
A record is a collection of related fields for a particular entity. In a table a
record is represented by a row.
Example

Page 90 V: 03
Muhammad Uwais BIT-MCS (KU)
Computer Science XII 2015-2016

In the table of student: SID, Name, Address, CellNo, DOB are the attributes
and values under these properties make a complete record.

SID Name Address CellNo DOB

23324 Ahmed Ali R-234 Block 2 0345-3456783 14-07-1990


Tariq Road
*******************
Key Field
There may be a number of fields present in a table, but a field which
uniquely identifies all the records is called a key field.
Explanation
The key field is unique in nature. There cannot be any duplication in a key
field. Similarly it cannot have a null value. The key field may be of the
following types.
 Candidate Key
 Primary Key
 Secondary Key
 Foreign
Example
Employee: NIC, NTN, Password #, EID etc
*******************

Q2. What is a database model?


Data Base Model
The database model is defined as the various waves in which the data can
be structured in a database. All database systems are characterized by the
way they structure, organized and manipulate data item and by the
relationship among the data items
The following are the most popular database models
 Hierarchal Database Model
 Network Database Model
 Relational Database Model

Q3. Explain relational database model in detail.


Relational Database Management system
A DBMS is said to be a Relational DBMS or RDBMS if the database
relationships are treated in the form of a table. A statical table that is
composed of rows and columns is used to organize the database and its
structure and is actually a two dimension array in the computer memory.

Page 91 V: 03
Muhammad Uwais BIT-MCS (KU)
Computer Science XII 2015-2016

Explanation
The theory behind the relational database model is called relational
algebra, which contain rules and regulations and mathematical methods
for relational database. The relational algebra was forwarded by Dr. Edgar
F, cod, a famous mathematician.
Example
A number of RDBMS are available however the most popular are Oracle,
Sybase, Ingress, Informix, Microsoft SQL Server, Microsoft Access, MySql
and so on.
============Long Questions and Answers==============

Q1. What are the features of a data base management system?

Important Features of DBMS


There are a number of DBMS available in the market. While choosing a
database we should be aware of some important characteristics exhibited by
a particular database.
Efficient use of Resources
The database must be able to use the current hardware efficiently without
requiring any new hardware and without wasting the storage space.
Maximum performance should be exhibited.
Speed
In a DBMS a query must be responded very fast within acceptable time
frame. It means that a database must have an extra ordinary speed.
Compatibility
Compatibility refers that how much a DBMS can be conveniently installed on
a computer system. Compatibility is also needed between the DBMS and
operating system.
Efficient Use of Data
The DBMS must allow for the quick and efficient, addition and deletion of
data. It must also be flexible to handle changes or re-arrangement of data
within the database.
Accessibility
A DBMS must provide easy to use methods for the users to access data. This
task is done via easy to learn query languages or by form layouts.
Data Integrity
A DBMS must have safeguard for data integrity. In case user committed
mistakes, power failures, accidental deletion of data, The DBMS should have
backup measures to insure that valuable data remain intact.
Privacy & Security
A major objective of any DBMS is to prevent the database from unauthorized
users, medical records, bank record, military information are a few examples
of sensitive and confidential material kept in database. So the DBMS must
provide high security

Page 92 V: 03
Muhammad Uwais BIT-MCS (KU)
Computer Science XII 2015-2016

Q2. Describe advantages of A DBMS


The advantages of database and DBMS software are as follows:
Reduction of Data Redundancy
Instead of the same data fields being repeated in different files, in a
database the information appears just once. The single biggest advantage of
a database is that the same information is available to different users. More
over, reduced redundancy lowers the expense of storage media and
hardware, because more data can be stored on the media.
Improvement of Data Integrity
Since data is centralized, the data update at only one place reflects
throughout the system automatically. There by avoiding the error that is
often introduced when the same update has to be made manually in several
independent files.
More Program Independence
With a database management system, the program and file formats are the
same, so that one programmer or even several programmers can spend less
time to maintain files.
Increased User Productivity
Database management systems are fairly easy to use, so that users can get
their requests for information answered without having to resort to technical
manipulations. In addition, users do not have to wait for computer
professionals to provide what they need.
Increased Security
Although various departments may share data in common access to specific
information can be limited to selected users. Thus, through the use of
passwords, a student‟s financial, medical, and grade information in a
university database is made available only to those who have a legitimate
need to know.

Q3. Describe hierarchal database model in detail.


Hierarchical Database Model
The hierarchical database model contains organization of data into related
groups just like a family tree.
Explanation
A DBMS is said to be hierarchical if the relationships among data in the
database are established in such a way that one data item is present as the
subordinate of another one. Here subordinate means that items have
'parent-child' relationships among them. Direct relationships exist between
any two records that are stored consecutively. The data structure "tree" is
followed by the DBMS to structure the database. No backward movement is
possible in the hierarchical database. Most of the older DBMS such as Dbase,
FoxPro etc are hierarchical in nature. These databases are rarely used
nowadays. Hierarchical databases were difficult to handle because rolling of
operations was highly tedious.

Page 93 V: 03
Muhammad Uwais BIT-MCS (KU)
Computer Science XII 2015-2016

Important Aspects of Hierarchical Database Model:

The following are the important points and characteristics of hierarchical


data base model:
1. Data is organized into related groups creating a tree like structure.
2. A lower level record is called a child, and higher level record is called a
parent.
3. A parent record is also called a root record.
4. Data is accessed in the Hierarchical order means sequentially.
5. This model has fast accessing of data and very fast searching mechanism
because of the hierarchical structure.

Q4. Describe network database model


Network database Model
Network database model contain organization of data into related groups
but having multiple parents groups for a child.
Explanation
A DBMS is said to be a Network DBMS if the relationships among data in
the database are of type many-to-many. The relationships among many-

Page 94 V: 03
Muhammad Uwais BIT-MCS (KU)
Computer Science XII 2015-2016

to-many appears in the form of a network. Thus the structure of a


network database is extremely complicated because of these many-to-
many relationships in which one record can be used as a key of the entire
database. A network database is structured in the form of a graph that is
also a data structure. Though the structure of such a DBMS is highly
complicated however it has two basic elements i.e. records and sets to
designate many-to-many relationships. Mainly high-level languages such
as Pascal, COBOL and FORTRAN etc. were used to implement the records
and set structures. But it's very difficult to understand.

Important Features of Network Database Model


The following are the important point and characteristics of a network
database model.
1. The network database model is similar to a hierarchal DBMS.
2. Each child record can have more than one parent record.
3. In a network database model the relationship between the entities can
be either many to one (simple network or many to many complex
network).

Page 95 V: 03
Muhammad Uwais BIT-MCS (KU)
Computer Science XII 2015-2016

4. The network database has more accessing speed.


5. A disadvantage of the network database model is the requirement of
re-definition of the database for any new record.

Q5. Explain relational database model in detail.

Relational Database Management system


A DBMS is said to be a Relational DBMS or RDBMS if the database
relationships are treated in the form of a table. A statical table that is
composed of rows and columns is used to organize the database and its
structure and is actually a two dimension array in the computer memory.
Explanation
The theory behind the relational database model is called relational
algebra, which contain rules and regulations and mathematical methods
for relational database. The relational algebra was forwarded by Dr. Edgar
F, cod, a famous mathematician.
Example
A number of RDBMS are available however the most popular are Oracle,
Sybase, Ingress, Informix, Microsoft SQL Server, Microsoft Access, MySql
and so on.
Introduction to Edgar Frank Codd
Edgar Frank Codd (August 23, 1923 – April 18, 2003) was a British
computer scientist who, while working for IBM, invented the relational
model for database management, the theoretical basis for relational
databases. He made other valuable contributions to computer science,
but the relational model, a very influential general theory of data
management, remains his most mentioned achievement.
Rules Given by Edgar Frank Codd
Edgar Frank "Ted" Codd twelve rules are a set of thirteen rules
(numbered zero to twelve) proposed by Edgar F. Codd, a pioneer of the
relational model for databases, designed to define what is required from a
database management system in order for it to be considered relational,
i.e., a relational database management system (RDBMS). They are
referred to as "Codd's Twelve Rules".

Rule 0: Basic Rule:

The system must qualify as relational, as a database, and as a


management system. For a system to qualify as a relational database
management system (RDBMS), that system must use its relational
facilities (exclusively) to manage the database.

Page 96 V: 03
Muhammad Uwais BIT-MCS (KU)
Computer Science XII 2015-2016

Rule 1: The information rule:

All information in the database is to be represented in only one way,


namely by values in column positions within rows of tables.

Rule 2: The guaranteed access rule:

All data must be accessible. This rule is essentially a restatement of the


fundamental requirement for primary keys. It says that every individual
scalar value in the database must be logically addressable by specifying
the name of the containing table, the name of the containing column and
the primary key value of the containing row.

Rule 3: Systematic treatment of null values:

The DBMS must allow each field to remain null (or empty). Specifically, it
must support a representation of "missing information and inapplicable
information" that is systematic, distinct from all regular values (for
example, "distinct from zero or any other number", in the case of numeric
values), and independent of data type. It is also implied that such
representations must be manipulated by the DBMS in a systematic way.

Rule 4: Active online catalog based on the relational model:

The system must support an online, inline, relational catalog that is


accessible to authorized users by means of their regular query language.
That is, users must be able to access the database's structure (catalog)
using the same query language that they use to access the database's
data.

Rule 5: The comprehensive data sublanguage rule:

The system must support at least one relational language that

 Has a linear syntax


 Can be used both interactively and within application programs.
 Supports data definition operations (including view definitions),
data manipulation operations (update as well as retrieval),
security and integrity constraints, and transaction management
operations (begin, commit, and rollback).

Rule 6: The view updating rule:

All views that are theoretically updatable must be updatable by the


system.

Page 97 V: 03
Muhammad Uwais BIT-MCS (KU)
Computer Science XII 2015-2016

Rule 7: High-level insert, update, and delete:

The system must support set-at-a-time insert, update, and delete


operators. This means that data can be retrieved from a relational
database in sets constructed of data from multiple rows and/or
multiple tables. This rule states that insert, update, and delete
operations should be supported for any retrievable set rather than just
for a single row in a single table.

Rule 8: Physical data independence:

Changes to the physical level (how the data is stored, whether in


arrays or linked lists etc.) must not require a change to an application
based on the structure.

Rule 9: Logical data independence:

Changes to the logical level (tables, columns, rows, and so on) must
not require a change to an application based on the structure. Logical
data independence is more difficult to achieve than physical data
independence.

Rule 10: Integrity independence:

Integrity constraints must be specified separately from application


programs and stored in the catalog. It must be possible to change
such constraints as and when appropriate without unnecessarily
affecting existing applications.

Rule 11: Distribution independence:

The distribution of portions of the database to various locations should


be invisible to users of the database. Existing applications should
continue to operate successfully :

 when a distributed version of the DBMS is first introduced; and


 when existing distributed data are redistributed around the system.

Rule 12: The non subversion rule:

If the system provides a low-level (record-at-a-time) interface, then


that interface cannot be used to subvert the system, for example,
bypassing a relational security or integrity constraint.

Page 98 V: 03
Muhammad Uwais BIT-MCS (KU)
Computer Science XII 2015-2016

Example
Oracle, SQL Server etc

Important Features of Relational Database Management System

1. The theory behind the relation database model is called relational


algebra, which contain rules and regulations and mathematical
methods for relation database.
2. The relational algebra was forwarded by Dr. Edgar F, cod, a famous
mathematician.
3. A relation database model is the most commonly use type of database
model for all levels of main frame.
4. A relational database relates or database files through a key field.
5. A database query language is a helpful tool that acts as an interface
between user and a relational database management system.
6. One of the major advantage of relational database is that there are no
parents or child

Page 99 V: 03
Muhammad Uwais BIT-MCS (KU)
Computer Science XII 2015-2016

Q6. Explain different components of a database system.


Components of a Database Management System
The database management system may have a number of components
including:-
 Query Language
 Data Dictionary
 Utilities
 Report Generator
 Security Manager
 Data Recovery Manager
Now we discuss all these components one by one
1. Query Language
An easy to use language to communicate with the DBMS in order to perform
the database operation (insertion, deletion, updating) called a Query
Language.
Example 1
SQL is the most popular Query Language it is known as structured
query language DDL & DML are the types of SQL .DDL stands for (Data
Definition Language), DML stands for (Data Manipulation Language)
Example 2
QBE stands for (Query by example) is also a query language which
unable a user to construct database queries without remembering
language code.
2. Data Dictionary
Some DBMS contain the component of data dictionary which stores the data
definition of the structure of the data being use with the DBMS.
Example

Field Data Type Field Size Constraints

SID Number 10 Not Null


Name Text 30 Not Null
Date of birth Data/Time - Not Null
Cell # Number 15 Not Null

3. Utilities
The utilities are the sub-programs which facilities the user for the maintains
of the database.
 Data dictionary maintenance
 Monitoring Performance
 Data Prevention

Page 100 V: 03
Muhammad Uwais BIT-MCS (KU)
Computer Science XII 2015-2016

4. Report Generator
The report generator is a DBMS component which can produce on-screen
and print out report according to the requirement. The user is able to specify
the format of the report.
Example
Oracle Report Builder
Seagate crystal Reports
5. Security Manager
The security manager is the important component of the DBMS which
enables the DBA (Database administrator) to specify different access
privileges for different user of DBMS. The purpose of the security feature is
of course to protect data from unauthorized user.
Example
Oracle Rights Manager

6. Data Recovery Manager


This component the enable the DBA to recovery contents of the hardware of
software failure. The DBA takes back ups for the data time by time.
Example
Oracle Data Recovery Manager

Q7. Describe key fields and their types used in a database table.
Key Field
There may be a number of fields present in a table, but a field which
uniquely identifies all the records is called key field.
Explanation
The key field is unique in nature. There cannot be any duplication in a key
field. Similarly it cannot have a null value. The key field may be of the
following types.
 Candidate Key
 Primary Key
 Secondary Key
 Foreign
Example
Employee: NIC, NTN, Password #, EID etc
1. Candidate Key
All unique keys present in a table behave as candidate keys. It means that
these are candidate to be selected as a primary key.
Example
Employee: NIC, NTN, Passport #, EID etc.
Here the entire given field are candidate keys

Page 101 V: 03
Muhammad Uwais BIT-MCS (KU)
Computer Science XII 2015-2016
2. Primary Key
From the candidate keys, a key
which is selected as to uniquely
identify all the record is called a
primary key.
Normally in ERDs the primary key is
Employee
underline in a table. Here EID is a
primary key EID
NTC
3. Secondary Key Name
Once a primary key has been Address
selected the remaining candidate NTN
keys are called secondary keys Phone #
Here NIC and NTN are secondary
keys.

4. Foreign Key
In the database when a table is suppose to be linked with another table a
key field is required in both the tables which is called foreign key.
Two tables cannot be linked without a foreign key. A primary key can also be
used as foreign key.
Here SID is primary key in the table of “student” and it is foreign key in the
table of “Marks”.

Page 102 V: 03
Muhammad Uwais BIT-MCS (KU)
Computer Science XII 2015-2016

Q8. Differentiate the following database terminologies.

DBMS RDBMS
1 The database management A relational database is a
system is special purpose particular DBMS based on
software to manage data base relational algebra.
2 It is based on the rules of It is based on relational algebra
DBMS
3 The database management The theory behind the relation
system makes it possible to database model is called relational
develop a database for an algebra, which contain rules and
organization and provides regulations and mathematical
techniques to perform all methods for relation database.
types of database operation The relational algebra was
like creation, insertion, forwarded by Dr. Edgar F, cod, a
deletion, updating. famous mathematician.
4 The DBMS foundations were The relational algebra was
developed by different forwarded by Dr. Edgar F, cod, a
computer science and famous mathematician.
mathematics scientists.
5 Example: Fox Pro Example : Oracle, SQL Server MS-
Access etc

Primary Key Foreign Key


1 The primary key is used to The foreign key is used to link one
uniquely identify all the table to another for data integrity.
records in a table
2 It is necessary to have a Foreign key is required wherever
primary key in a table. there is a need to link two or more
tables.

Page 103 V: 03
Muhammad Uwais BIT-MCS (KU)
Computer Science XII 2015-2016

CHAPTER TEN

10
MICROSOFT
ACCESS

OBJECTIVE:
When you have completed this chapter, you will be able
to know about the

Short Answer Questions


Q1. What do you know about MS-Access?
Q2. What are MS-Access Data Types? Explain any one.

Long Answer Questions


Q1. Write a note on MS-Access database.
Q2. What are MS-Access objects explain any five.
Q3. What are MS-Access Data Types? Explain any five.

Page 104 V: 03
Muhammad Uwais BIT-MCS (KU)
Computer Science XII 2015-2016

CHAPTER # 10
MICROSOFT ACCESS

============Short Questions and Answers=============

Q1. What do you know about MS-Access?


Microsoft Office Access, previously known as Microsoft Access, is a relational
database management system from Microsoft that combines the relational
Microsoft Jet Database Engine with a graphical user interface and software-
development tools.
Explanation
It is a member of the Microsoft Office suite of applications, included in the
Professional and higher editions or sold separately. In mid-May 2010, the
current version of Microsoft Access 2010 was released by Microsoft in Office
2010; Microsoft Office Access 2007 was the prior version. Access stores data
in its own format based on the Access Jet Database Engine. It can also
import or link directly to data stored in other applications and databases.

Q2. What are MS-Access Data Types? Explain any one.


While creating a column in table the database designer needs to define the
type of the data which is going to be stored in that column. The Microsoft
Access provides a number of data types which can be used according to the
requirement. The data types used in MS-Access are as follows.
 Text
 Number
 Date and Time
 Yes/No
 OLE Object
 Auto Number
 Memo
 Currency
 Hyperlink

Text
Character data can be stored using this data type. Maximum 255 characters
can be stored while using this data type.
Explanation
(Default) Text or combinations of text and numbers, as well as numbers that
don't require calculations, such as phone numbers can be stored using this
data type. The field size may be up to 255 characters or the length set by
the Field Size property. Microsoft Access does not reserve space for unused
portions of a text field
Example

Page 105 V: 03
Muhammad Uwais BIT-MCS (KU)
Computer Science XII 2015-2016

Name, Address, Qualification etc are some examples of the fields for which
text data type can be stored.

=============Long Questions and Answers=============

Q1. Write a note on MS-Access database.


Microsoft Office Access, previously known as Microsoft Access, is a relational
database management system from Microsoft that combines the relational
Microsoft Jet Database Engine with a graphical user interface and software-
development tools.
Explanation
It is a member of the Microsoft Office suite of applications, included in the
Professional and higher editions or sold separately. In mid-May 2010, the
current version of Microsoft Access 2010 was released by Microsoft in Office
2010; Microsoft Office Access 2007 was the prior version. Access stores data
in its own format based on the Access Jet Database Engine. It can also
import or link directly to data stored in other applications and databases.
Historical Background
With Office 95, Microsoft Access 7.0 ("Access 95") became part of the
Microsoft Office Professional Suite, joining Microsoft Excel, Word, and
PowerPoint and transitioning from Access Basic to Visual Basic for
Applications (VBA). Since then, Microsoft has released new versions of
Microsoft Access with each release of Microsoft Office. This includes Access
97 (version 8.0), Access 2000 (version 9.0), Access 2002 (version 10.0),
Access 2003 (version 11.5), Access 2007 (version 12.0), and Access 2010
(version 14.0).
Uses and Features
Software developers and data architects can use Microsoft Access to develop
application software, and "power users" can use it to build simple
applications. Like other Office applications, Access is supported by Visual
Basic for Applications, an object-oriented programming language that can
reference a variety of objects including DAO (Data Access Objects), ActiveX
Data Objects, and many other ActiveX components. Visual objects used in
forms and reports expose their methods and properties in the VBA
programming environment, and VBA code modules may declare and call
Windows operating-system functions.

Q2. What are MS-Access objects explain any five.


MS – ACCESS OBJECTS
MS-Access is a relational database management system. Its main
components which are used for the development of a database are called
MS-Access Objects. Each object has its own functionality. The following are
the MS-Access objects.

Page 106 V: 03
Muhammad Uwais BIT-MCS (KU)
Computer Science XII 2015-2016

 Table
 Form
 Query
 Reports
 Pages
 Macros etc
Now we will discuss these objects in detail
1. Table/Relational Variable
In a relational database a Table is also called relational variable. A table is a
collection of rows and columns, where row represents a complete record and
a column represents related fields.

Example
Student
SID Name Class Address Phone
Code
0300 Mahrukh G2M1 Tipu Sultan R. 4371298
0301 Javeria G2M2 Tariq Road. 4572370
0302 Zeeshan P2M2 Khadda Mrk. 4209211

2. Form
A form is defined as a GUI or windows like object which facilitates a user to
perform database operations (insertion, deletion, updating, searching) in an
easy to se way.

Example

Page 107 V: 03
Muhammad Uwais BIT-MCS (KU)
Computer Science XII 2015-2016

3. Query
A query is a view of selected columns taken from a single or multiple tables.
A query is not an actual table it shows the data of existing tables.
Sometimes user needs to have the data of different columns from different
tables, in this situation a query is defined as a view level table.
Example: - Table: Student

4. Report
A report is an important MS-ACCESS
object it facilitates the database
designer to generate on screen as well
as print out reports for the Users
according to the requirement. The data
is taken from the concerned tables.
Report can be formatted according to
the requirement having logos, Company

Page 108 V: 03
Muhammad Uwais BIT-MCS (KU)
Computer Science XII 2015-2016

title, header and footer and other graphics.


Example

5. Pages
MS-ACCESS object which enables a database designer to create web pages
linked with the database. The data will be accessed from the concerned
tables while using the website.

Q3. What are MS-Access Data Types? Explain any five.


While creating a column in table the database designer needs to define the
type of the data which is going to be stored in that column. The Microsoft
Access provides a number of data types which can be used according to the
requirement. The data types used in MS-Access are as follows.
 Text
 Number
 Date and Time
 Yes/No
 OLE Object
 Auto Number
 Memo
 Currency
 Hyperlink
1. Text
Character data can be stored using this data type. Maximum 255
characters can be stored while using this data type.
Explanation
(Default) Text or combinations of text and numbers, as well as
numbers that don't require calculations, such as phone numbers can
be stored using this data type. The field size may be up to 255
characters or the length set by the Field Size property. Microsoft
Access does not reserve space for unused portions of a text field
Example
Name, Address, Qualification etc are some examples of the fields for
which text data type can be stored.
2. Number
This data type is used for the fields which carry numeric data. The
number data type supports different sizes of numerical figures.
Explanation
Numeric data used in mathematical calculations. It occupies 1, 2, 4, or
8 bytes (16 bytes if the Field Size property is set to Replication ID).
Example
Basic Salary, House Rent Allowance, Cell No Etc

Page 109 V: 03
Muhammad Uwais BIT-MCS (KU)
Computer Science XII 2015-2016

3. Date & time


Besides using the text data type, Access provides a separate data type in
order to store date and time. This data type supports a number of
formats to mention data and time.
Explanation
Date and time values for the years 100 through 9999 can be stored. It
occupies eight bytes in memory.
Example
In the table of Employee the joining data is column which belongs to
this data type.
4. Yes/No
This data type contains only two values for a particular column. These
values are true or false. Sometimes an entity can have a property which
can have a value in the form of yes or no.
Explanation
Yes and No values and fields that contain only one of two values
(Yes/No, True/False, or On/Off). 1 bit
Example
In the table of employee marital status is the field which can have only
when value that is true or false.
5. OLE Object
Besides the text or numeric data, there may be any requirement to store
data of any other type. Pictures, Audios, videos and animation files are
special types of data which are stored in MS-Access database using the
data type OLE Object.
Explanation
An object (such as a Microsoft Excel spreadsheet, a Microsoft Word
document, graphics, sounds, or other binary data) linked to or
embedded in a Microsoft Access table.
Example
In the table of employee Emp-Photo, Voice-Password are the example
of OLE Object.
6. Auto Number
It is a numeric data type which is normally used for primary or foreign
key. For every new record MS-Access increases the next value itself
without taking the input from the user.
Explanation
A unique sequential (incremented by 1) number or random number
assigned by Microsoft Access can be declared whenever a new record
is added to a table. AutoNumber fields can't be updated. It occupies 4
bytes (16 bytes if the Field Size property is set to Replication ID).
Example
In the table of employee the Emp-ID can be settled with the data type
of auto number.

Page 110 V: 03
Muhammad Uwais BIT-MCS (KU)
Computer Science XII 2015-2016

CHAPTER ELEVEN

PRACTICAL PROGRAMMING
11
PROBLEMS IN C
OBJECTIVE:
When you have completed this chapter, you will be able
to know about the
Problems With Algorithm and Source Code
1. Write a program that generate 1 to 10 numbers, calculate and print
average of these numbers.
2. Write a program that reads marks of five subjects, calculate the total
marks, percentage, and state whether the student is passed or fail.
3. Write a program to generate the table of N.
4. Find the factorial of N, use scanf() to read the value of N.
5. Write a program that finds out the largest number among three input
numbers.
6. Write a program which uses arithmetical operators to calculate the area of
a triangle, volume of a sphere, etc.
7. Write a program to print square and cube of first ten prime numbers.
8. Write a program, to calculate the roots of a quadratic equation
ax2+bx+c=0.
9. Write a program using for loop to print usual printing characters
corresponding to 32 to 127 ASCII code.
10. Write a program, which uses a switch and break statements.
11. Write a program that calculate power of base without using power
function by taking input both.
12. Write a program to calculate pay roll of an employee. Read the basic pay
from keyboard; calculate medical allowance as 15% of basic pay,
conveyance allowance as 20%, and house rent allowance as 45% of basic
pay. Calculate gross pay and net pay and print all.
13. Write a program using nested for loop to print pyramid of stars.
14. Write a program using function that accepts two numbers as its
arguments and returns summation of these two numbers.

Page 111 V: 03
Muhammad Uwais BIT-MCS (KU)
Computer Science XII 2015-2016

PRACTICAL PROGRAMMING PROBLEMS IN C

Experiment No 1
Write a program that generate 1 to 10 numbers, calculate and print average
of these numbers.
Algorithm
Step 1 START
SET sum= 0
Step 2 REPEAT a=1 TO 10
i.WRITE a
ii.SET sum=sum+a
Step 3 END REPEAT
Step 4 SET avg=sum/10
Step 5 END

Source Code
void main()
{
int a,sum=0;
float avg;
clrscr();
for(a=1;a<=10;a++)
{
printf("\t%d",a);
sum+=a;
}
avg=sum/10;
printf(“\n The sum of first ten numbers is=\t%d”,sum);
printf(“\n And the average of first ten numbers is=\t%0.2f”,avg);
getch();
}
Output
1 2 3 4 5 6 7 8 9 10
The sum of first ten numbers is= 55
And the average of first ten numbers is= 5.5

*******************
Experiment No 2
Write a program that reads marks of five subjects, calculate the total marks,
percentage, and state whether the student is passed or fail.
Algorithm
Step 1 START
Step 2 READ eng
Step 3 READ urdu

Page 112 V: 03
Muhammad Uwais BIT-MCS (KU)
Computer Science XII 2015-2016

Step 4 READ phy


Step 5 READ comp
Step 6 READ math
Step 7 SET total =eng+urdu+phy+comp+math
Step 8 SET per=total*100/500
Step 10 WRITE total
Step 11 WRITE per
Step 12 IF per>33 THEN
WRITE “pass”
ELSE
WRITH “fail”
END IF
Step 10 END
Source Code
void main()
{
int eng,urdu,phy,comp,math,total;
float per;
printf("\nEnter marks for English\t");
scanf("%d",&eng);
printf("\nEnter marks for Urdu\t");
scanf("%d",&urdu);
printf("\nEnter marks for Physics\t");
scanf("%d",&phy);
printf("\nEnter marks for Computer\t");
scanf("%d",&comp);
printf("\nEnter marks for Mathematics\t");
scanf("%d",&math);
total=eng+urdu+phy+comp+math;
per=total*100/500;
printf("\nYour total marks are\t%d",total);
printf("\nYour Percentage is \t%0.2f"per);
if(per>=33)
printf("\nYou are Pass");
else
printf("\nYou are Fail");
getch();
}
Output
Enter marks for English 45
Enter marks for Urdu 77
Enter marks for Physics 63
Enter marks for Computer 48
Enter marks for Mathematics 78

Page 113 V: 03
Muhammad Uwais BIT-MCS (KU)
Computer Science XII 2015-2016

Your total marks are 311


Your Percentage is 62.2
You are Pass
*******************
Experiment No 3
Write a program to generate the table of N.
Algorithm
Step 1 START
Step 2 READ N
Step 3 REPEAT a=1 TO 10
WRITE N,a,N*a
END REPEAT
Step 4 END

Source Code
void main()
{
int a,N;
clrscr();
printf("\nEnter value to print its table\t");
scanf("%d"&a);
for(a=1;a<=10;a++)
{
printf("\n%dx%d=%d",N,a,N*a);
}
getch();
}
Output
Enter value to print its table 7
7x1=7
7x2=14
7x3=21
7x4=28
7x5=35
7x6=42
7x7=49
7x8=56
7x9=63
7x10=70
*******************

Page 114 V: 03
Muhammad Uwais BIT-MCS (KU)
Computer Science XII 2015-2016

Experiment No 4
Find the factorial of N, use scanf() to read the value of N.
Algorithm
Step1. Start.
Step2. Set f = 1, i = 0
Step3. Read num
Step4. Repeat WHILE num <= 0.
c. “Write Error! You have enter no. less than 0”
d. Read num
[End of outer WHILE loop]
Step5. Repeat FOR n = 1 to num
a. Set f = f * 1
[End of FOR Loop]
Step6. Write f
Step7. Exit
Source Code
void main()
{
double f=1;
int num,n;
clrscr();
printf("Enter the no. greater than 0 to find its factorial: ");
scanf("%d",&num);
while(num<0)
{
printf("\nError! number is less than 0.\n");
printf("Please enter number greater than 0: ");
scanf("%d",&num);
}
for(n=1;n<=num;n++)
{
f*=n;
}
printf("\nThe factorial of %d is %f",num,f);
getch();
}
Output
Enter the no. greater than 0 to find its factorial: -3

Error! number is less than 0.


Please enter number greater than 0: -5

Error! number is less than 0.


Please enter number greater than 0: 16

Page 115 V: 03
Muhammad Uwais BIT-MCS (KU)
Computer Science XII 2015-2016

The factorial of 16 is 20922789888000.000000

*******************

Experiment No 5
Write a program that finds out the largest number among three input
numbers.
Algorithm
Step 1 START
Step 2 READ a
Step 3 READ b
Step 4 READ c
Step 5 IF a>b AND a>c THEN
WRITE “a is largest”
ELSE IF b>c AND b>a THEN
WRITE “ b is largest”
ELSE
WRITE “ c is largest”
END IF
Step 6 END

Source Code
void main()
{
int a,b,c;
clrscr();
printf("\nEnter First Number\t");
scanf("%d",&a);
printf("\nEnter Second Number\t");
scanf("%d",&b);
printf("\nEnter Third Number\t");
scanf("%d",&c);
if(a>b&&a>c)
printf("\n First number is largest that is %d",a);
else if(b>a&&b>c)
printf("\n Second number is largest that is %d",b);
else
printf("\n Second number is largest that is %d",c);
getch();
}

Output
Enter First Number 45
Enter Second Number 72

Page 116 V: 03
Muhammad Uwais BIT-MCS (KU)
Computer Science XII 2015-2016

Enter Third Number 34


Second number is largest that is 72
*******************
Experiment No 6
Write a program which uses arithmetical operators to calculate the area of a
triangle, volume of a sphere, etc.
Algorithm
Step1. Start
Step2. Read a, b, r, T, S
Step3. Set T = (1.0/2.0)*(a*b)
S = (4.0/3.0)*(3.142)*(r*r*r)
Step4. Write T, S
Step5. Exit
Source Code
void main()
{
float a,b,r,T,S;
clrscr();
printf("Enter the value for altitude of a triangle: ");
scanf("%f",&a);
printf("\nEnter the value for base of a triangle: ");
scanf("%f",&b);
printf("\nEnter the value for radius of a sphere: ");
scanf("%f",&r);
T=(1.0/2.0)*(a*b);
S=(4.0/3.0)*(3.142)*(r*r*r);
printf("\n\nArea of triangle = %.2f",T);
printf("\nArea of sphere = %.2f",S);
getch();
}
Output
Enter the value for altitude of a triangle: 3.65
Enter the value for base of a triangle: 4.98
Enter the value for radius of a sphere: 9.29

Area of triangle = 9.09


Area of sphere = 3358.86
*******************

Page 117 V: 03
Muhammad Uwais BIT-MCS (KU)
Computer Science XII 2015-2016

Experiment No
Write
118 a program to print square and cube of first ten prime numbers.
Algorithm
Step1. Start.
Step2. Repeat FOR p = 1 to 30
a. Set isPrime = 1
b. Repeat FOR d = 2 to p
a. IF p % d is equal to 0 then
b. Set isPrime = 0
c. IF isPrime is not equal to 0 then
d. Write p,pxp,pxpxp
[End of FOR Loop]
[End of FOR Loop]
Step3. Exit
Source Code
void main ()
{
int p, d, isPrime;
clrscr();
for(p=1;p<=30;++p)
{
isPrime=1;
for(d=2;d<p;++d)
if(p%d==0)
isPrime=0;
if (isPrime!=0)
printf ("\n%d\t%d\t%d ", p,p*p,p*p*p);
}
getch();
}
Output
2 3 5 7 11 13 17 19 23 29
2 4 8
3 9 27
5 25 125
7 49 343
11 121 1331
13 169 2179
17 289 4913
19 361 6859
23 529 12167
29 841 24389
*******************

Page 118 V: 03
Muhammad Uwais BIT-MCS (KU)
Computer Science XII 2015-2016

Experiment No 8
Write a program, to calculate the roots of a quadratic equation ax2+bx+c=0.
Algorithm
Step1. Start.
Step2. Read a, b, c
Step3. Set xp = (-b)+(sqrt(pow(b,2.0)-(4.0*a*c)))/(2.0*a)
xn = (-b)-(sqrt(pow(b,2.0)-(4.0*a*c)))/(2.0*a)
Step4. Write xp, xn
Step5. Exit
Source Code
#include<math.h>
void main()
{
int a,b,c;
float xp,xn;
clrscr();
printf("\nEnter the value for a : \t");
scanf("%d",&a);
printf("\nEnter the value for b : \t");
scanf("%d",&b);
printf("\nEnter the value for c : \t");
scanf("%d",&c);
xp = (-b)+(sqrt(pow(b,2.0)-(4.0*a*c)))/(2.0*a);
xn = (-b)-(sqrt(pow(b,2.0)-(4.0*a*c)))/(2.0*a);
printf("\nThe roots of given equation are (%.2f,%.2f)",xp,xn);
getch();
}
Out Put
Enter the value for a : 5
Enter the value for b : 10
Enter the value for c : 25

The roots of given equation are (-22.94,-27.09)

*******************
Experiment No 9
Write a program using for loop to print usual printing characters
corresponding to 32 to 127 ASCII code.
Algorithm
Step1. Start.
Step2. Repeat FOR a = 32 to 127
Write a, a
[End of FOR Loop]
Step3. Exit

Page 119 V: 03
Muhammad Uwais BIT-MCS (KU)
Computer Science XII 2015-2016

Source Code
void main()
{
int a;
clrscr();
for(a=32;a<=127;a++)
{
printf("%3d=%c\t",a,a);
}
getch();
}
Output
32= 33=! 34=" 35=# 36=$ 37=% 38=& 39=' 40=(
41=)
42=* 43=+ 44=, 45=- 46=. 47=/ 48=0 49=1 50=2
51=3
52=4 53=5 54=6 55=7 56=8 57=9 58=: 59=; 60=<
61==
62=> 63=? 64=@ 65=A 66=B 67=C 68=D 69=E 70=F
71=G
72=H 73=I 74=J 75=K 76=L 77=M 78=N 79=O 80=P
81=Q
82=R 83=S 84=T 85=U 86=V 87=W 88=X 89=Y 90=Z
91=[
92=\ 93=] 94=^ 95=_ 96=` 97=a 98=b 99=c 100=d
101=e
102=f 103=g 104=h 105=i 106=j 107=k 108=l 109=m 110=n
111=o
112=p 113=q 114=r 115=s 116=t 117=u 118=v 119=w 120=x
121=y
122=z 123={ 124=| 125=} 126=~ 127=⌂

******************

Experiment No 10
Write a program, which uses a switch and break statements.
Algorithm
Step1. Start.
Step2. Read num1, num2
Step3. Read switch op
Step4. IF switch op = „+‟
Write num1 + num2
IF switch op = „-‟
Write num1-num2

Page 120 V: 03
Muhammad Uwais BIT-MCS (KU)
Computer Science XII 2015-2016

IF switch op = „*‟
Write num1 * num2
IF switch op = „/‟
Write num1 / num2
Step5. ELSE
Write Unknown operator
Step6. Exit
Source Code
void main()
{
float num1=1.0,num2=1.0;
char op, c;
clrscr();
A:
printf("Type number, operator, number : ");
scanf("%f %c %f", &num1, &op, &num2);
switch(op)
{
case'+':
printf(" = %.2f",num1+num2);
break;
case'-':
printf(" = %.2f",num1-num2);
break;
case'*':
printf(" = %.2f",num1*num2);
break;
case'/':
printf(" = %.2f",num1/num2);
break;
default:
printf("\nUnknown operator");
}

printf(“\n Do you want to perform again y/n\t”);


scanf(“%c”,&q);
if(q==‟y‟)
goto A;
getch();
}

Page 121 V: 03
Muhammad Uwais BIT-MCS (KU)
Computer Science XII 2015-2016

Output
Type number, operator, number : 12 + 7
= 19.00
Do you want to perform again y/n y
Type number, operator, number : 2 * 4
= 8.00
Do you want to perform again y/n y
Type number, operator, number : 8 - 7
= 1.00
Do you want to perform again y/n y
Type number, operator, number : 16 / 3
= 5.33
Do you want to perform again y/n n

*******************
Experiment No 11
Write a program that calculate power of base without using power function
by taking input both.
Algorithm
Step1. Start.
Step2. Read num, p
Step3. Repeat FOR i = 1 to p
a. Set pow = pow * num
[End of FOR Loop]
Step4. Write pow
Step5. Exit
Source Code
void main()
{
double pow=1;
int i,num,p;
clrscr();
printf("Enter number : ");
scanf("%d",&num);
printf("\nEnter power : ");
scanf("%d",&p);
for(i=1;i<=p;i++)
{
pow*=num;
}
printf("\nAnswer is %.2f",pow);
getch();
}

Page 122 V: 03
Muhammad Uwais BIT-MCS (KU)
Computer Science XII 2015-2016

Output
Enter number : 6
Enter base : 3
Answer is 216.00
*******************
Experiment No 12
Write a program to calculate pay roll of an employee. Read the basic pay
from keyboard; calculate medical allowance as 15% of basic pay,
conveyance allowance as 20%, and house rent allowance as 45% of basic
pay. Calculate gross pay and net pay and print all.
Source Code
void main()
{
float BS,MA,CA,HRA,GPAY,NPAY,TAX=0;
clrscr();
printf("\nEnter the basic pay of employee\t");
scanf("%f",&BS);
MA=15*BS/100;
CA=20*BS/100;
HRA=45*BS/100;
GPAY=BS+MA+CA+HRA;
NPAY=GPAY-TAX;
printf("\nEmployee\'s basic salary is \t%0.2f",BS);
printf("\nEmployee\'s medical allowance is\t %0.2f",MA);
printf("\nEmployee\'s conveyance allowance is\t %0.2f",CA);
printf("\nEmployee\'s house rent allowance is\t %0.2f",HRA);
printf("\nEmployee\'s gross pay is \t%0.2f",GPAY);
printf("\nEmployee\'s net pay is \t %0.2f",NPAY);
getch();
}
Algorithm
Step 1 START
Step 2 READ BS
Step 3 SET TAX=0
Step 4 SET MA=15*BS/100
Step 5 SET CA=20*BS/100
Step 6 SET HRA=45*BS/100
Step 7 SET GPAY=BS+MA+CA+HRA
Step 8 SET NPAY=GPAY-TAX;
Step 9 WRITE BS
Step 10 WRITE MA
Step 11 WRITE HRA
Step 12 WRITE GPAY
Step 13 WRITE NPAY

Page 123 V: 03
Muhammad Uwais BIT-MCS (KU)
Computer Science XII 2015-2016

Step14 END

Output
Enter the basic pay of employee 5000
Employee‟s basic salary is 5000
Employee‟s medical allowance is 750
Employee‟s conveyance allowance 1000
Employee‟s house rent allowance is 2250
Employee‟s gross pay is 9000
Employee‟s net pay is 9000
*******************

Experiment No 13
Write a program using nested for loop to print to print the following.
*
***
*****
*******
*********
Algorithm
Step1. START
Step2. SET m=4
Step3. SET n=1
Step4. Repeat FOR y =1 to 4
a. REPEAT FOR x = 1 to m
b. WRITE space
END REPEAT
c. REPEAT FOR a = 1 to n
d. WRITE *
END REPEAT
e. SET n=n-2
f. WRITE new line
END REPEAT
Step5. END
Source Code
void main()
{
int a,x,y,m=4,n=1;
clrscr();
for(y=0;y<=4;y++)
{
for(x=1;x<=m;x++)
{
printf(" ");

Page 124 V: 03
Muhammad Uwais BIT-MCS (KU)
Computer Science XII 2015-2016

}
for(a=1;a<=n;a++)
printf("*");

n=n+2;
m--;
printf("\n");
}
getch();
}

Output
*
***
*****
*******
*********

*******************

Experiment No 14
Write a program using function that accepts two numbers as its arguments
and returns summation of these two numbers.
Algorithm
Step 1 START
Step 2 READ a
Step 3 READ b
Step 4 SET ans=sum(a,b)
Step 5 RETURN x+y
Step 6 WRITE ans
Step 7 END

Source Code
int sum(int,int);
void main()
{
int a,b,ans;
clrscr();
printf("\nEnter first number\t");
scanf("%d",&a);
printf("\nEnter second number\t");
scanf("%d",&b);
ans=sum(a,b);

Page 125 V: 03
Muhammad Uwais BIT-MCS (KU)
Computer Science XII 2015-2016

printf("\nThe sum of the two numbers is \t%d",ans);


getch()

int sum(int x,int y)


{
return(x+y);
}

Output

Enter first number 35


Enter second number 25
The sum of the two numbers is 60

*******************

Page 126 V: 03
Muhammad Uwais BIT-MCS (KU)
Computer Science XII 2015-2016

CHAPTER TWELVE

12
MIRCROSOFT ACESS
PRACTICALS

OBJECTIVE:
When you have completed this chapter, you will be able
to perform the following practicals

Microsoft Access Practicals


1. Create a database in MS-Access of Bank Accounts.
2. Create a database in MS-Access of Student Attendance.
3. Create a database in MS-Access of Student Information.
4. Create a database in Library
5. Create a payroll table in MS access.
6. Create an Inventory control database in MS Access.
7. Create a Hospital Record database in MS Access.
8. Create Student Result database in MS Access

Page 127 V: 03
Muhammad Uwais BIT-MCS (KU)
Computer Science XII 2015-2016

PRACTICAL NO.1

Objectives:

Create a database in MS-Access of Bank Accounts.


 Create two tables and create relationship b/w tables Acct_ID
,Acct_Name, Acct_Address, Acct_Phone, Acct_Email
 Required fields of 2nd table are Acct_ID, Acct_Status
 Search the Desired Acct_ID, Delete the Desired Acct_ID
 Also update desired Acct-ID.

Procedure:
1- First we click on the start then move to the programs and then open
Microsoft Access Click on the blank database option to create a New
Database (Bank Account)
2- Click create Table in Design View t Create a New Table Account Info and
enter fields name which are Acct_ID, Acct_Name, Acct_Address,
Acct_Phone, Acct_Email.
3- Create 2nd Table in Design View (Account Status)
4- Create relationship b/w Account Info. Acct_ID and Account Status,
Acct_ID
5- Create a Query that will retrieve desired Acct_ID
SELECT*
FROM Account Info
WHERE Account Info. Acct_ID= [Account Identification No. is];
6- Create 2nd Query which will give desired result
DELET*
FROM Account Info
WHERE Account Info, Acct_ID =[ Account Identification No. is];
7- Create 2nd Query which will give desired result
UPDATE Account Info
SET Acct_Name= [Account Holder Name],
Acct_Address= [Account Holder Address],
Acct_Phone= [Account Holder Phone],
Acct_Email= [Account Holder Email]
WHERE Acct_ID= [Account Holder Identification];

Page 128 V: 03
Muhammad Uwais BIT-MCS (KU)
Computer Science XII 2015-2016

Output:
1st Table:

2nd Table:

Page 129 V: 03
Muhammad Uwais BIT-MCS (KU)
Computer Science XII 2015-2016

Search Desired Acct_ID:

Page 130 V: 03
Muhammad Uwais BIT-MCS (KU)
Computer Science XII 2015-2016

PRACTICAL NO. 2
Objective:

Create a database in MS-Access of Student Attendance. Create two tables


and relationship b/w tables
 Required fields of 1st table are:
stud_ID, stud_Name, stud_Address, stud_Phone,stud_Email
 Required field of 2nd table are:
stud_ID, stud_Attendance
 Search the Desired stud_ID,delete the desired Stud_ID
 Also Update desired Stud_ID

Procedure:
1. First we click on start then move to programs and then open
Microsoft Access .click on blank data baseoption to create a New
Database (Student attendance).
2. Click Create Table in Design View to Create a New table Student
Info and enter fields name which are
Stud_ID,Stud_Name,Stud_Address,Stud_Phone,
Stud_Email.
3. Create 2nd Table in design View Student Attendence and enter
fields names are (Stud_ID,Stud_Attendance)
4. Create relationship b/w Student info.Stud_ID & Student
Attendence.Acct_ID
5. Create a Query that will retreive desired Stud_ID.
SELECT*
FROM [student info].
WHERE Stud_ID=[Student identification number
Is];
6. Create 2nd Query which will give desired result
DELETE*
FROM [Student info]
WHERE Stud_ID= [Student identification number is];
7. Create 2nd Query which will give desired result
UPDATE [Student info]
SET Stud_Name = [Student Name],
Stud_Adress = [Student Address],
Stud_Phone = [Student Phone],
WHERE Stud_ID[Student Identification No].

Page 131 V: 03
Muhammad Uwais BIT-MCS (KU)
Computer Science XII 2015-2016
Output:
1st Table:

2nd Table:

Table Relationship:

Page 132 V: 03
Muhammad Uwais BIT-MCS (KU)
Computer Science XII 2015-2016

Search Desired Acct_ID:

Page 133 V: 03
Muhammad Uwais BIT-MCS (KU)
Computer Science XII 2015-2016

PRACTICAL NO.3

Objective:

Create a database in MS_Access of Student Information (Std_ID, Name,


Class, Group and Gender).
 Create Std_ID as Primary key.
 Input 10 records.
 Find the list of female student.
 Find the list of student having Pre_Engineering group.

Procedure:

1. Open Microsoft Access and select blank Access database, Click Ok


button to display File New Database dialog window. Type the
database name. Click on the option to finish process.
2. Create a table by using Design View. Enter the required fields into
the cell with their suitable data type. Then select the Std_Id as a
primary key by right click on the field (Std_ID), Then save the table
and give the suitable name.
3. Create a query by using wizard, set criteria to find the female
students.
4. Create a query by using wizard, set criteria to find the
Pre_Engineering group.

Output:

Page 134 V: 03
Muhammad Uwais BIT-MCS (KU)
Computer Science XII 2015-2016

Page 135 V: 03
Muhammad Uwais BIT-MCS (KU)
Computer Science XII 2015-2016

PRACTICAL NO.4

OBJECTIVE:

Create a database in Library (Book_Id, Name, Reference or Lending book,


issued).

 Create a suitable primary key and input 15 records with different


names.
 Display a list of books, which are not for Lending.
 Find the list of book issued.

PROCEDURE:

1. Open Microsoft Access and select blank Access database, Click OK


button to display File New Database dialog window.Type the database
name.Click on the option to finish process.
2. Create a table by using Design View. Enter the required fields into the
cell with their suitable data type. Then create a suitable primary key
by right click on the field (Book_id). Then save the table and give the
suitable name.
3. Create a query by using wizard, set criteria to Display of books, which
are not for Lending.
4. Create a query by using wizard, set criteria to find the list of books
issued.

Page 136 V: 03
Muhammad Uwais BIT-MCS (KU)
Computer Science XII 2015-2016

Output:

Book Table:

Page 137 V: 03
Muhammad Uwais BIT-MCS (KU)
Computer Science XII 2015-2016

Issued Books

Books Not Lending:

Page 138 V: 03
Muhammad Uwais BIT-MCS (KU)
Computer Science XII 2015-2016

RACTICAL No. 5

Objective:

Create a payroll table in MS access.


 Create following tables, input 8 records and create relationship
between them.
 Assign Emp_id as primary key.
 Then calculate gross_pay as Gross_pay = Medical Allownce +
Convience allowance + House Rent Allownce + Basic Pay.
 Then Calculate Tax as 5 % of Gross Pay.
 Then Calculate Net Pay = Gross Pay- Tax.
 Then Create a query by using wizard, set criteria to search Emp_id,
Name and Job whose net pay is greater then 10,000.

Employee

Emp_id Name F_name Address Job Appointmentdate

Salary

Emp_id Medical Convince House Basic Tax Net Pay


Allownce Allownce Rent Pay
Allownce

Procedure
1. Open Microsoft Access and select bland Access database, click Ok
button to display File New Database dialog window. Type the
database name. Click on the option to finish process.
2. Create a table by using Design. Enter the required fields into the
cell with their suitable data type. Then select the (Emp_id) as a
Primary key. Then save the table and give the suitable name
3. Create an Employee table which is given in objective.
4. Create a salary table which is given in objective.
5. Then calculate gross_pay as Gross_pay = Medical Allownce +
Convience allowance + House Rent Allownce + Basic Pay.
6. Then Calculate Tax as 5 % of Gross Pay.
7. Then Calculate Net Pay = Gross Pay- Tax.
All the above criteria can be met by coding the following SQL
query.

Page 139 V: 03
Muhammad Uwais BIT-MCS (KU)
Computer Science XII 2015-2016

SELECT Salary.emp_id, Salary.medical_allow,


Salary.convence_allow, Salary.house_rent_allow, Salary.basic_pay,
Salary.medical_allow+Salary.convence_allow+Salary.house_rent_al
low+Salary.basic_pay AS Gross_pay, 5*gross_pay/100 AS Tax,
gross_pay-tax AS net_payFROM Salary;
8. Then Create a query by using wizard, set criteria to search Emp_id,
Name and Job whose net pay is greater then 10,000.

Output:

Table Employee:

Table Salary:

Page 140 V: 03
Muhammad Uwais BIT-MCS (KU)
Relationships: Computer Science XII 2015-2016

Query: Salary Greater Than 10000:

Page 141 V: 03
Muhammad Uwais BIT-MCS (KU)
Computer Science XII 2015-2016

Query: Calculated Columns According to Requirement:

Page 142 V: 03
Muhammad Uwais BIT-MCS (KU)
Computer Science XII 2015-2016

PRACTICAL NO.6

Objective:

Create an Inventory control database in MS Access.

 Create following tables, input 05 records and create relationship


between them.

Item
Item_Id Item _Name Item _rate

Customer
Customer_Id Name Phone Address

Order
Customer_Id Date Item_Id Quantity Amount

 Search the items which are sold within a given range of Dates.
 Delete the record where Name like”Ahmed”.
 Update the record; set Item_rate to 400 where Item_code like
K101.

Procedure:

 Open Microsoft Access and select blank Access database, Click Ok


button to display File New Database dialog window. Type the database
name. Click on the option to finish process.
 Create the table by using Design View. Enter the required fields into the
cell with their suitable data type. Then create a suitable relationship
between tables by right click on the field (Item_id, Customer_id and
Item_code). Then save the table and give the suitable name.
 Create a query by using wizard, set criteria to search the items which
are sold within a given range of dates.
 Create a query by using wizard, set criteria to Delete the record where
Name like “Ahmed”.
 Create a query by using wizard, set criteria to Update the record; set
item rate to 400 where Item_code like K101.

Page 143 V: 03
Muhammad Uwais BIT-MCS (KU)
Computer Science XII 2015-2016

Output:

Page 144 V: 03
Muhammad Uwais BIT-MCS (KU)
Computer Science XII 2015-2016

Table Item:

Relationship:

Page 145 V: 03
Muhammad Uwais BIT-MCS (KU)
Computer Science XII 2015-2016

PRACTICAL No. 7

Objective:

Create a Hospital Record database in MS Access.


 Create following tables, input 07 records and create relationship
between tables.
 Create Patient_Id as a primary key.

Patient

Patient_Id Name Address Doctor Admit Discharge Charges


Name Date Date

Status

Patient_Id Date Doctor Test Prescription Disease


Name report

 Search all patients under treatment of a particular Doctor named Dr.


Ahmer.
 Delete all records of patient, who are discharged.
 Update the prescription of a particular.

Procedure:
 Open Microsoft Access and select bland Access database, click Ok
button to display File New Database dialog window. Type the database
name. Click on the option to finish process.
 Create a table by using Design. Enter the required fields into the cell
with their suitable data type. Then select the (Patient_ Id) as a
Primary key. Then save the table and give the suitable name.
 Create a Patient table which is given in the objective.
 Create a Status table which is given in the objective.
 Create a query in which show the patients under treatment of a
particular doctor “Dr. Ahmer”.
 Create a query to delete the record of the patient who has been
discharged.
 Create a query using design method to update the prescription of a
particular patient.

Page 146 V: 03
Muhammad Uwais BIT-MCS (KU)
Computer Science XII 2015-2016

Page 147 V: 03
Muhammad Uwais BIT-MCS (KU)
Computer Science XII 2015-2016

Page 148 V: 03
Muhammad Uwais BIT-MCS (KU)
Computer Science XII 2015-2016

Page 149 V: 03
Muhammad Uwais BIT-MCS (KU)
Computer Science XII 2015-2016

PRACTICAL No. 8

Objective:

Create Student Result database in MS Access.

 Create following tables and create relationship between them.


 Assign a suitable primary key
 Input 05 records.

Bio Data

Roll_No Stud_Id Stud_Phone Stud_address Class Year

Marks

Roll_No Physics Chemistry Computer English Total Percentage

 Calculate the percentage up to 2 decimaal places by using expression


builder.
 Calculate the highest marks in all surdents.

Procedure:
1. Open Microsoft Access and select bland Access database, click Ok
button to display File New Database dialog window. Type the database
name. Click on the option to finish process.
2. Create a table by using Design. Enter the required fields into the cell
with their suitable data type. Then select the (Roll_No) as a Primary
key. Then save the table and give the suitable name.
3. Create a Bio Data table which is given in the objective.
4. Create a Marks table which is given in the objective.
5. Input five records in tables.
6. Create a query in which calculate the percentage up to 2 decimal
places.
7. Create a query in which we have to calculate the highest marks.

Page 150 V: 03
Muhammad Uwais BIT-MCS (KU)
Computer Science XII 2015-2016

Output:
Table: Bio data:

Table: Result:

Page 151 V: 03
Muhammad Uwais BIT-MCS (KU)
Computer Science XII 2015-2016

Query Result to Calculate Percentage:

Query: Highest Marks:

Page 152 V: 03
Muhammad Uwais BIT-MCS (KU)
Computer Science XII 2015-2016

CHAPTER THIRTEEN

QUESTIONS
13
AND ANSWERS FOR SELF
PRACTICE

OBJECTIVE:
When you have completed this chapter, you will be able
to know about the
Question from C Language
Exercises 1
Getting Started with C
Exercises 2
The Components of a C Program
Exercises 3
Storing Data: Variables and Constants
Exercises 4
Statements, Expressions, and Operators
Exercises 5
Functions: The Basics
Exercises 6
Basic Program Control
Exercises 7
Fundamentals of Input and Output
Exercises 8
Using Numeric Arrays
Exercises 9
Understanding Variable Scope
The exercises are available on the blog
Biekcomputercience.blogspot.com

Page 153 V: 03
Muhammad Uwais BIT-MCS (KU)
Computer Science XII 2015-2016

CHAPTER FORTEEN

TEST PAPERS
14
FOR PREPARATION

OBJECTIVE:
When you have solved these papers you will be able
appear in the final examination with a remarkable
preparation

Question Papers
Grand Test Paper
Silver Test for MS-Access
Golden Test of C Language

Page 154 V: 03
Muhammad Uwais BIT-MCS (KU)
Computer Science XII 2015-2016

GRAND TEST PAPER


Intermediate College
Computer Science-II

Marks: 70 Time: 3 Hours


Note: Attempt all questions of section „A‟ and form section „B‟ and three
questions from section „C‟. For objective section „A‟, write directly answers
by putting answer no. It is also a guess paper for final exam. Learn all these
question properly.
Section ‘A’(Objective)
Q1.
a) Fill in the blanks with correct answers:
i. The operator increases the value of the variable for
one.
ii. SQL stands for
iii. Foundations of relational algebra were described by
iv. A key field which links two tables is called key.
v. A function can return value(s) at a time.

b) Choose the correct answer for each of the given option:


i. A table is a collection of
a. Files and records
b. Fields and records
c. Relations and records
d. Rows and records
ii. && is a/an operator.
a. Logical
b. Relational
c. Arithmetic
d. Address
iii. Which one is an example of MS-Access data type
a. OLE
b. Hyperlink
c. Currency
d. all
iv. From which part of the loop is the break statement is used to
exit.
a. Beginning
b. Middle
c. End
d. None of them
v. The format specifier of a single char is

Page 155 V: 03
Muhammad Uwais BIT-MCS (KU)
Computer Science XII 2015-2016

a. %d
b. %c
c. %s
d. %cc

c) State whether the following statements are true or false:


i. When a function calls itself the process is called recursion
ii. Function declaration is optional.
iii. The format specifier %f is used for integer numbers
iv. Four variables of the same name can be declared in the single C
statement.
v. If there is only one statement in the block of the if statement,
the braces are optional.

d) Match the columns


Column ‘A’ Column ‘B’
1. Data dictionary Control structure
2. Switch statement Unformatted function
3. getchar Relational algebra
4. Post testing Constraints
5. E.F Cod While loop

Section ‘B’
Q2.
What are MS-Access objects? Explain any five in detail.
05
OR
Write down the steps involved in programming

Q3.
Define any five of the following
05
1. Algorithm
2. Format Specifier
3. Header File
4. Flow Chart
5. Modulus Operator
6. Variable
7. Preprocessor Directive
8. Address Operator
9. Comment
10. Library Function

Page 156 V: 03
Muhammad Uwais BIT-MCS (KU)
Computer Science XII 2015-2016

Q4.
Convert the following equations into C equivalent.
04
i. Z=p2+q2+t2+pq+qt+pt
ii. X=2(a2+b2)
iii. F=pq/p+q

Q5
Explain any three of the following with examples.
06
1. Data types of C
2. Escape Sequence
3. Keywords of C
4. Unformatted I/O functions
5. Control Structures
6. IDE

Section ‘C’
Q6.
(a) Explain diagrammatically the structure of a C program 05
OR
What are MS-Access database? Explain any five in detail.

(b) Write the program take input for a number and calculate the factorial of
that number. 05
OR
Write a program, take input in three numbers and find the greatest among
them

Q7.
(a) How many types of loops are there in C language? Explain each of them
with example codes. 06
OR
Write down the procedure of creating a user defined function in detail.

(b)Write advantages of creating user defined functions.


04
OR
Write advantages of data base management system.

Page 157 V: 03
Muhammad Uwais BIT-MCS (KU)
Computer Science XII 2015-2016

Q8.
(a)How many types of operators are there in C? Describe relational and
logical operators with example codes. 05
OR
Differentiate
j. Switch and if statement
k. DBMS and RDBMS
l. Break and Continue

(b). Write a program using nested for loop that prints the following series.
05
1 1 1 4 3 9 -----------------10 100
OR
Write a program using for loop to print the following output. Also write
comments.
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10

Q9
(a) What is a database model explain relational database model in detail.
05
OR
How many types of relationships can be defined in a data base explain each
with example.

(b) Write a program that takes input for a number in variable M and find the
square, cube and square root of that number and print results. 05
OR
Write a program to solve the quadratic equation using quadratic formula.

Page 158 V: 03
Muhammad Uwais BIT-MCS (KU)
Computer Science XII 2015-2016

SILVER TEST FOR MS-ACCESS


Intermediate College
Computer Science-II

Time: 3Hrs Max Marks: 75


Note: Section A is compulsory. Do not copy all the parts. Only write
correct answers by putting part No.

SECTION ‘A’ (MCQs)

Q1. Choose the correct answer from given options. 12

vi. A key which can uniquely identify each record in a table is called
*Super key *Foreign Key *Candidate Key *None of them
vii. A table is a collection of
*Fields and Records *File and Records
*Fields and Relations *Records and Relation
viii. The collection of rows and columns is called
*File *Table *Record *Database
ix. Which one is an access data type
*char *float *number *long
x. Which one is an MS- Access object?
*Macro *Report *Pages *All
xi. A property or characteristic of an entity having some value is
called
*Column *Attribute *Field *All
xii. Which one is a component of a database management system.
*Data dictionary *Utilities *Query language *All
xiii. ERD stands for
*entity relationship diagram *example relationship diagram
*entity ray diagram *example ray diagram
xiv. Which one is not an example of a database management
system?
*Excel *dbase *SQL server *Access
xv. Rules and regulations which are applied on a table are called
*logics *query language *constraints *none
xvi. Normally how many characters can be stored using text data
type?
*512 *1024 *255 *100
xvii. Which data type is used to for the fields which carry numeric
data?
*Date/Time *Number *Text *OLE

Page 159 V: 03
Muhammad Uwais BIT-MCS (KU)
Computer Science XII 2015-2016

SECTION ‘B’ (Short Question Answers)

Note: Attempt any six questions from this section. The answer must
not exceed 8 to 10 lines. All questions carry equal marks. (36)

Q2. What is a key field? Why it is important in database? 06


Q3. Define relationship. How many types of relationships are their in
MS- Access? 06
Q4. Write a short note on relational database management system. 06
Q5. Define the following terminologies 06
Data, database, field, record
Q5. Define the term database. Write down advantages of using database.
06
Q6. Differentiate between DBMS and RDBMS. 06
Q7. Define the following terms with example 06
Field, Record, Table, DBMS

SECTION ‘C’ (Long Question Answers)


Note: Answer any two questions in detail from this section. All
questions carry equal marks. (32)

Q11.
(a) What are MS-Access objects explain any five in detail. 08
(b) Define and explain the relational database management system. 08

Q12. 08
(a) Explain MS-Access data types in detail.
(b) Describe hierarchical database management system with diagram. 08
Q13. 08
(a) What are the components of a database management system? Describe
in detail.
(b) Write Procedure to create a database in MS-Access of Bank Accounts.
08
1) Create two tables and create relationship b/w tables
Acct_ID ,Acct_Name, Acct_Address, Acct_Phone, Acct_Email
2) Required fields of 2nd table are
Acct_ID, Acct_Status.
3) Search the Desired Acct_ID, Delete the Desired Acct_ID
Also update desired Acct-ID.

Page 160 V: 03
Muhammad Uwais BIT-MCS (KU)
Computer Science XII 2015-2016

GOLDEN TEST OF C LANGUAGE


Intermediate College
Computer Science-II
Time: 3Hrs Max Marks: 75
Note: Section A is compulsory. Do not copy all the parts. Only write
correct answers by putting part No.
SECTION ‘A’ (MCQs)
Q1. Choose the correct answer from given options. 15
1. & is a/an operator.
*Logical *Relational *Arithmetic *Address
2. The format specifier of long double is
*%d *%f *%LF *%lf
3. Which one is not a C language data type
*char *int *float *string
4. Which one is the correct syntax of power function
*power(a,b) *pow(a,b) *pow(x) *power(y)
5. Which one is logical operator
*&& *|| *! *All
6. Which keyword does not belong to switch statement
*default *else *break *case
7. Which expression is the part of for() loop
*Initialize exp *Test exp *Inc/ Dec exp *All
8. Which one is not a valid variable name
*_N1 *2N1 *_N1_ *N2N
9. It is necessary to save a source file with the extension
*.cpp *.obj *.c or .cpp *.c or .cp
10. Which one is equal operator.
*!= *== *= *<>
11. Which sub-directory contains header files
* Bin * Include *Lib *TC
12. The character data type occupies bytes in memory.
*1 *2 *3 *4
13. Which one is an example of assignment in C?
*c=a+b; *c+=b; c=a; *All
14. <= is called operator.
*Assignment *Relational *Logical *Remainder
15. Which of the following statement is incorrect in C?
*Integer a; * float b; *double float x; character c;
16. Which value is valid to store in an integer variable?
*4.55 * 39677 *-22 *none
17. Which function is used to get a single character from the
keyboard?
*gets() *puts() *getche() *printf()

Page 161 V: 03
Muhammad Uwais BIT-MCS (KU)
Computer Science XII 2015-2016

18. A variable which is defined out of main function but not in any
other function is called
*Local Variable *Counter Variable *Global Variable *Operating
Variable
19. The process of writing program instructions is called
*Designing *Coding *Compiling *Running
20. loop uses post testing.
*for() *while() *do while() * None
21. Which of the following is an example of initializing a character
variable?
* int i=‟a‟; *char ch=‟a‟; *ch=‟a‟; char ch=a;
22. Which Header file is used for string functions?
*string.h iostream.h *stdio.h *conio.h
23. In C language the library files are also called
*header files *object files *source files
*Exe files
24. Which one is not a valid variable name?
*const *2ND *my age *All
25. Which escape sequence is used for back space?
*\x *\a *\n *\b
26. The C language was developed by
*Peter Norton * Dennis Ritchie *Robert Lafore *Yashwanth
Kenethkar
27. The step by step process to solve a problem is called
*Flow Chart *Program *Algorithm *Software
28. A C language Source Code File cannot be run without
Function
*main() *clrscr() *getch() *printf()
29. Which one is not a C language data type?
*char *int *float *string
30. A single line C statement is terminated by
*Colon *Semicolon *Comma *Full Stop

SECTION ‘B’ (Short Question Answers)

Note: Attempt any eight questions from this section. The answer
must not exceed 8 to 10 lines. All questions carry equal marks. (32)

Q2. Define the following terms of C with example. 04


(i) Escape Sequence (ii) Pre Processor Directive
Q3. What do you know about relational operators? Describe with example.
04
Q4. Differentiate for loop and while loop. 04
Q5. Define function. Describe predefined functions used in C language. 04

Page 162 V: 03
Muhammad Uwais BIT-MCS (KU)
Computer Science XII 2015-2016

Q6. Describe any three C language data types with their ranges, format
specifier and example program. 04
Q7. Define the following terms of C language. 04
1. User Defined Function 2. Format Specifier 3. Control
Structures Logical Operators
Q8. What do you know about C language? Describe the IDE of C. 04
Q9.Describe the control structures of C language. 04
Q10. Define algorithm. Write its characteristics. 04
Q11. How many types of C language file are there? Describe briefly. 04
Q.12 Convert the following equations in C. (Only Write Equations)
04
H=(abc+a3b2c+2ab)/3xy P=a3+b3+3ab+√xy
D=(a2+b2)/2ab Z= Ax2+Bxy+Sinx

SECTION ‘C’ (Long Question Answers)


Note: Answer any two questions in detail from this section. All
questions carry equal marks. (28)

Q11.
(a) Write a program to calculate pay roll of an employee. Read the basic pay
from keyboard, calculate medical allowance as 15% of basic pay,
conveyance allowance as 20%, and house rent allowance as 45% of basic
pay. Calculate gross pay and net pay and print all. 05
(b) Write a program that calculates power of base without using power
function by taking input both. 05
(c) Write output for the following program. 04
void main()
{
int a,x,y,m=4,n=1;
clrscr();
for(y=0;y<=4;y++)
{
for(x=1;x<=m;x++)
{
printf(" ");
}
for(a=1;a<=n;a++)
printf("*");

n=n+2;
m--;
printf("\n");
}

Page 163 V: 03
Muhammad Uwais BIT-MCS (KU)
Computer Science XII 2015-2016

getch();
}

Q12.
(a) Explain iterative control structures of C in detail. 08
(b) Write a program using nested loop which prints the following output.
06
1 2 3 4 5
1 2 2 4
1 2 3
1 2
1
Q13.
(a) Write a program using for loop to print usual printing characters
corresponding to 32 to 127 ASCII code. 05
(b) Find errors and write the correct program. 05
(c) Write output for the following program. 04

void main ()
{
int p, d, isPrime;
clrscr();
for(p=1;p<=30;++p)
{
isPrime=1;
for(d=2;d<p;++d)
if(p%d==0)
isPrime=0;
if (isPrime!=0)
printf ("\n%d\t%d\t%d ", p,p*p,p*p*p);
}
getch();
}

Page 164 V: 03
Muhammad Uwais BIT-MCS (KU)
Computer Science XII 2015-2016

CHAPTER FIFTEEN

15
MULTIPLE CHOICE
QUESTIONS

OBJECTIVE:
When you have completed this chapter, you will
command to answer the multiple
choice questions

MCQs from Chapter 1 to Chapter 10


Ch 1 Concepts of Computer Programming
Ch 2 Algorithms and Flow Charts
Ch 3 C Language Fundamentals
Ch 4 Operators and Expressions
Ch 5 Conditional Statements
Ch 6 Input and Output Function
Ch 7 Iterations and its Types
Ch 8 Functions
Ch 9 Database Concepts
Ch 10 MS Access

Page 165 V: 03

You might also like