Xii - Computer Science (Complete)

Download as pdf or txt
Download as pdf or txt
You are on page 1of 65

SESSION 2021-22

CLASS XII
COMPUTER SCIENCE

PREPARED BY: SIR S.M. RIZWAN


CONCEPT OF COMPUTER PROGRAMMING
01

IMPORTANT QUESTIONS:
1) Define program and programming.
2) What are the characteristics of a successful computer program?
3) Explain the steps in programming.
4) What is bug? Describe the types of programming errors with appropriate example.
5) Explain the debugging process in detail.
6) What is Programming Language? Discuss its different types.
7) How many types of programming languages are there regarding structure?
8) Write the differences between procedure oriented language and object oriented language.
9) What is a language translator? Also explain its types.
10) Write the differences between Compiler and Interpreter.
11) Define Source code and Object code.
12) Describe the four general classes of instruction found in all computer languages.
13) Write the differences between source code and object code.

PREPARED BY: S.M.RIZWAN


Q 01: Define program and programming?

Program
A program is a set of instructions that computer must follow in order to process data into
information.

Programming
Programming, also called software engineering, is a multistep process for creating the set of
instruction.

Q 02: What are the characteristics of a successful computer program?


The characteristics of a successful computer program are as follows.
1. It does what it is supposed to do.
2. It is easy to use.
3. It works without failing.
4. It can be easily comprehended.
5. It can be enhanced and updated.
6. It can be modified to supply other information as required.

Q 03: Explain the steps in programming.

1) DEFINING THE PROBLEMS:


It is impossible to develop a solution to a problem if you do not have a clear understanding of the
problem itself. The programmer’s first task is, therefore, to determine just what the problem is and how
to solve it. Defining the problem requires that the programmer specify four mini task. They are:

• The programmer’s objective


• The desired output
• The input data required
• The processing requirements.

2) PLANNING THE SOLUTION:


Once the programmer has determined what the program must do, the next step is to plan a solution,
preferably using structured programming techniques or program design tools. These techniques consist
of the following:

• Top-down program design


• Algorithm
• Flowchart

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 implantation
the programmer comes to know the physical and logical errors which are supposed to be debug. The
program is tested regarding all types of error that are syntax errors, logical errors and run time errors.
The testing phase makes sure that the program fulfills all the objectives which are required for the users.
5) DOCUMENTING THE PROGRAM:
Documentation is a written detailed description of the programming cycle and specific facts about the
program. Typical program documentation materials include the origin and nature of the program, a brief
narrative description of the program, algorithm and flowcharts, data-record descriptions, program
listings, and testing results.

Q 04: What is bug? Describe the types of programming errors with appropriate example.

Programming errors are knows as bugs.

In general, there are three types of errors that occur in a computer program:

i) Syntax error ii) Logic error iii) Run time Error

SYNTAX ERROR:

A syntax error is a violation of the rules whatever language the program is being written. These are
often caused by simple typing mistakes.

For example:

C = (A + B / 2

LOGIC ERROR:

The logical error is an error in planning the program’s logic. In this case, the language processor
successfully translates the source code into machine code. The computer actually does not know that an
error has been made.

For example:

You wanted to do the sum of A and B and put the result in the variable C. this is accomplished by
typing:

C=A+B

But while typing, the programmer has, however typed the following expression:

C=A–B

RUN TIME ERROR:

Runtime errors occur when a program is run on the computer and the results are not achieved due to
some misinterpretation of a particular instruction.

For Example:

Dividing a number by Zero.

Q 05: Explain the 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
programmers 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 found then it is removed
before further testing.

Structured walkthrough:

A structure walkthrough is a process in which three or four programmers, including the creator of the
program, review (walkthrough) the program. They analyze it for completeness, accuracy, and quality of
design and then discus their conclusion.

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.

Q 06: What is Programming Language? Discuss its different types.

PROGRAMMING LANGUAGE

A programming language is a special language programmers use to develop software programs, scripts,
or other sets of instructions for computers to execute.

MACHINE LANGUAGE (LOW LEVEL LANGUAGE)

Every creation of this universe has its own language. Likewise, computer has a language that is called
Machine Language (machine level language) for instructing computer to perform specific task. It is also
called binary language because it is the language of 0s and 1s, means every instruction in Machine
language consists of a series of 0s and 1s (binary code) that a computer can understand and execute
directly.

ASSEMBLY LANGUAGE:
In assembly language, the statements are written in symbolic codes (termed as mnemonics) that are
easier for human to read and write as compared to machine language. Each assembly language
statement corresponds to one machine language statement.

HIGH LEVEL LANGUAGE

High level languages are closer to human languages than low-level language and include statement like
GOTO and PRINT which are regular words. Unlike the assembly language, the program of high level
languages do not have to be written for a particular computer, but it can be execute on any machine that
has a compiler for that language.

Q 07: 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

Procedure Oriented languages require programmers to solve programming problems using traditional
programming logic; that is, programmers write the instructions in the sequence in which they must be
executed to solve the problem.

Object Oriented:

An object oriented language uses classes and objects having specific properties and method for a
comprehensive programming. It is a better approach than a procedure oriented language.

Example:

C++, JAVA etc.

Visual Programming

A visual programming language provides a graphical or windows like environment for programming. It
contains visual objects like text boxes, buttons, combo boxes, lists and forms etc.

Example:

VB6.Net

Q 08: Write the differences between procedure oriented language and object oriented language.

PROCEDURE ORIENTED LANGUAGE OBJECT ORIENTED LANGUAGE

1) Procedure oriented language takes a


Object oriented language follows a top-down
bottom-up approach in designing a
approach.
program.
2) Program is divided into small chunks Program is divided into objects depending on
based on the functions. the problem.

3) Each function contains different data. Each object controls its own data.

4) Operator overloading is not allowed. Operator overloading is allowed.

Q 09: What is a language translator? Also explain its types.


LANGUAGE TRANSLATORS
It translates the computer program into machine understandable form. Language translators are
interpreter, compiler and assembler.

i. Interpreter
Interpreter translates and executes each program statement one at a time, translation is required if
program is run again. Example: GWBASIC

ii. Compiler
Compiler translates the whole program at a time and stores translated program on disk. The original
program is called Source Program and its translated version is called Object Program.

iii. Assembler
Assembler is a program that converts an assembly language program into machine language.

Q 10: Write the differences between Compiler and Interpreter.

COMPILER INTERPRETER

It translates a single line of code or


1) It translates an entire program at a time.
instruction at a time.

It does not produce any intermediate object


2) It generates intermediate object code.
code.
3) The compilation is done before Compilation and execution take place
execution. simultaneously.

4) It is comparatively faster It is slower than compiler.

Q 11: Define Source code and Object code.

SOURCE CODE:
A program written in a high-level language is called source code. Source code is also called source
program. Computer cannot understand the statements of high-level language. The source code cannot
be executed by computer directly. It is converted into object code and then executed.
OBJECT CODE:
A program in machine language is called object code. It is also called object program or machine code.
Computer understands object code directly.

Q 12: Describe the four general classes of instruction found in all computer languages.

The four general classes of instruction found in all computer languages can be categorized as
follows.

INPUT / OUTPUT INSTRUCTIONS

These instructions direct the computer to “read from” or “write to” a peripheral device.

COMPUTATION INSTRUCTIONS

These instructions direct the computer to perform arithmetic operations.

CONTROL INSTRUCTIONS

These instructions can alter the sequence of the program execution or terminate execution.

ASSIGNMENT INSTRUCTION

These instructions transfer data internally from one RAM location to another.

Q 13: Write the differences between source code and object code.

Source code Object code

1) Source code is written in high-level Object code is written in machine


or assembly language. language through compilers.

2) Source code is easy to understand. Object code is difficult to understand.

3) Source code is easy to modify. Object code is difficult to modify.

4) Source code contains fewer Object code contains more statements


statements than object code. than source code.
ALGORITHM AND FLOWCHARTS
02

IMPORTANT QUESTIONS:

1) What is an algorithm?
2) What is Pseudo Code?
3) Define different algorithm notations.
4) What is flowchart? Describe the functions of various flowcharting symbols and give
their pictorial representation.
5) What are the various guidelines to be followed while drawing a flowchart?
6) What are the advantages of flowcharts when they are used to solve a problem?
7) What are the disadvantages of flowchart?

PREPARED BY: S.M.RIZWAN


Q1: What is an algorithm?

ALGORITHM:

The word algorithm is derived from the well known ninth century mathematician of Iran Abu Jafar Ibn
Musa Al-Khwarizmi, who develop method to solve problems using specific instruction step-by-step.

The algorithm can be defined as a finite sequence of unambiguous instructions design to solve a particular
problem and these instructions ultimately terminate if followed.

Q2: What is Pseudo Code?

PSEUDO-CODE:

Pseudo-code is an English-like way of representing the solution to a problem. The prefix pseudo means
fake; pseudo-code, therefore literally mean “fake code”, that is not the code that is actually entered into the
computer.

Q3: Define different algorithm notations.

ALGORITHMIC NOTATIONS:

Following points and terminology used in making algorithm.

1. Algorithm Name: Each algorithm must be given a unique name for identification
2. Step Number: Each statement of the algorithm must be given a unique number for identification.
3. Variable Name: Variable name will use capital letters, as X, Y, SUM.
4. Getting Input from the user: ‘read’ is used to get input from the user (computer asks the user for
value).
5. Assigning Value to a Variable: ‘Set’ is used to assign value to a variable (computer itself sets the
value for variable)
6. Algorithm Termination: ‘Exit’ is used to terminate the algorithm.
7. Comments: ‘[‘and ‘]‘are used for providing comments or marks.
8. Control Transfer: Use ‘Goto Step n’ to transfer control to step n.

Q4: What is flowchart? Describe the functions of various flowcharting symbols and give their
pictorial representation.

FLOWCHARTS:

A flowchart is a pictorial representation of logic used in a computer program. It illustrates the major
program elements and how they are logical integrated.

The symbols used in flowchart are given below:

Terminal Symbol:

The terminal symbol is used to indicate the beginning (START), ending (STOP),
and pauses (HALT) in the program logic flow. It is the first symbol and the last
symbol in the program logic. In addition, if the program logic calls for a pause in
the program, that also is indicated with a terminal symbol.
(Oval)
Input/output Symbol:

The input/output symbol is used to denote any type of input data or output
information. This symbol represents generic input/output functions of all kinds.

(Parallelogram)
Process Symbol:

A process symbol is used in a flowchart to represent an operation involved in


actual processing of data. The process symbol is used for all arithmetic and data
transfer (MOVE) operations.
(Rectangle)

Flow lines:

Flow lines with arrowheads are used to indicate the flow of operation, that is,
the exact sequence in which the instructions are to be executed. The normal
flow of flowchart is from top to bottom and left to right.
(Arrow)

Decision Symbol:

The decision symbol is used in a flowchart to indicate a point at which a decision


has to be made and a branch to one of two or more alternative points is possible.

(Diamond)
On-Page Connector Symbol:

If a flowchart becomes very long, the flowlines start crossing at many places
that causes confusion and reduces understandability of the flowchart. In this
situation it is useful to utilize the connector symbol as a substitute for flowlines.
This symbol represents an entry from, or an exit to another part of the
flowchart. (Circle)

Off-Page Connector Symbol:

This symbol is used to connect parts of the flowchart from one page to another.

Predefined Process Symbol:

This symbol is used to access (“perform” or “call”) a subroutine not detailed at


that particular point but usually define d in a separate micro flowchart. May be
either procedures or functions that are used repeatedly or steps that would
overly complicate the flowchart.
Annotation Symbol:

This symbol holds additional descriptive comments, explanatory


notes, or clarifications; connected by dashed line to the symbol
being commented on. It is used as needed to aid understanding.

Q5: What are the various guidelines to be followed while drawing a flowchart?

FLOWCHARTING RULES:

Some of flowcharting rules and guidelines are as follows:

1. First chart the main line of logic, and then incorporate detail.
2. Maintain a consistent level of detail for a given flowchart.
3. Do not chart every detail or the flowchart will only be a graphic representation, step by step, of the
program. A reader who is interested in greater details can refer to the program itself.
4. Word in the flowchart symbols should be common statements and easy to understand. It is
recommended to use descriptive title written in designer’s own language rather than in machine
oriented language.
5. Be consistent in using names and variables in the flowchart.
6. Go from left to right and top o bottom in constructing flowchart.
7. Keep the flowchart as simple as possible. The crossing of flow-lines should be avoided as far as
practicable.
8. If a new flowcharting page is needed, it is recommended that the flowchart be broken at an input
point. Moreover properly labeled connectors should be used to link the portions of the flowchart
on different pages.

Q6: What are the advantages of flowcharts when they are used to solve a problem?

ADVANTAGES OF FLOWCHARTS:

The following advantages may be obtained when flowcharts are used for the purpose of program planning.

1. Better communication: Since, a flowchart is a pictorial representation of a program; it is easier for


a programmer to explain the logic of a program to some other programmer.

2. Effective Analysis: A macro-flowchart that presents the main lines of logic used in a program
becomes a model of a program/system that can be broken down into detailed parts for study.

3. Proper Program Documentation: Program documentation involves collecting, organizing and


storing a complete historical record of programs and the other documents associated with a system.
The flowchart obviously provides a valuable documentation support.

4. Efficient Coding: Once a flowchart is ready, programmers find it very easy to write the concerned
program. Flowchart act as guide during program writing stage.

5. Systematic Debugging: Even after taking full care in program design, some errors may remain in
the program. It is easier to find out the reason for the error by going through the logic of the
program in flowchart form. A flowchart is very helpful in detecting, locating, and removing errors
(bugs) in a program in a systematic manner.
Q7: What are the disadvantages of flowchart?

DISADVANTAGES OF FLOWCHARTS:

In spite of their many obvious advantages, flowcharts have several disadvantages which are as follows:

1. Time Consuming Process: Flowchart are very time consuming and laborious to draw with proper
symbols especially for large complex programs.

2. Difficult to read and understand: Flowchart tends to take up a lot of space, filling multiple sheets
of paper to capacity. This can make them difficult to read and understand.

3. Hard to Modify: Owing to the symbol-string nature of flowcharting, any changes or modifications
in the program logic will usually require a completely new flowchart.

4. Lack of Standard: There are no standards determining the amount of detail that should be included
in a flowchart.
AN OVERVIEW OF ‘C’ LANGUAGE
03

IMPORTANT QUESTIONS:

1) What do you know about C programming language?


2) What are the general characteristics of C? OR what are the advantages of C?
3) Define IDE and discuss how it is useful in c programming.
4) What is the general structure of a C program?
5) What is a preprocessor directive? What are types of preprocessor directive?
6) What is a Header file?
7) What is the purpose of #include<stdio.h> in a C program?
8) What is a statement terminator?
9) What is the main ( ) function?
10) What are Escape sequences? Mention all Escape sequences.
11) What is the purpose of comments in a C program?

PREPARED BY: S.M.RIZWAN


Q1: What do you know about C programming language?

C is a procedural programming language. It was initially developed by Dennis Ritchie at bell


laboratories of USA in 1972. It was mainly developed as a system programming language to write
operating system. The main features of C language include low-level access to memory, simple set
of keywords, and clean style, these features make C language suitable for system programming like
operating system or compiler development.

Q2: What are the general characteristics of C? OR what are the advantages of C?

CHARACTERISTIC/ADVANTAGES OF C:

C has many advantages over other programming languages among them are
1. It is an efficient language suitable for applications that run on personal computers,
microcomputers, workstations, and other small machines.
2. It is capable of handling a wide variety of systems applications.
3. C is a portable language. A C program written on one computer can be run with little or
no modification on any other computer with a C compiler.
4. It is a block – structured language, in which you can replace elementary units with entire
blocks.
5. It has high execution speed.

Q3: Define IDE and discuss how it is useful in c programming.

IDE
IDE stands for integrated development environment. Different steps are performed to write a
program. For example editing saving compiling linking and loading. Most programming
languages provide an environment to perform these steps. This environment is cal led IDE.
TURBOO C++
Turbo C++ is an IDE for creating C and C++ programs it is used to create, edit and save
programs. It also has powerful debugging features. These help us in finding and removing
errors from a program. All necessary steps for developing a program can be performed with
this IDE.

Q4: What is the general structure of a C program?

THE BASIC STRUCTURE OF A C PROGRAM:

#include<…> Header files

#include<…>

Void main (void)} Function name

{ } Start of function

Statement 1;

Statement 2; Function body


.........

} } End of function
Q5: What is a preprocessor directive? What are types of preprocessor directive?

PREPROCESSOR DIRECTIVE
Preprocessor is a program that modifies a C program before compilation. Preprocessor
directive are instructions for the preprocessor. These instructions are written at the
beginning of the program. There are two types of preprocessor directives include, define
INCLUDE
It is used to include header files in to the program. The syntax of include directive is
# include < name of header file >
OR
# include “name of header file”
Example:
# include <stdio.h>
DEFINE
Define preprocessor directive is used to define a constant macro. The syntax of define
directive is:
# define Macro – Name expression
Example:
#define num10

Q6: What is a Header file?


HEADER FILE
Header file are part of C computer. C language provides many built in programs. Every
program has a unique name. These programs are called built in functions or library functions
every library functions can perform a specific task. We can use these library functions in our
C language program. These functions are divided into groups according to their
functionality. A group of same type of functions is stored in a file. This file is called header
file. There are many header files available in C language. Header file has an extension‘.h’.

Q7: What is the purpose of #include<stdio.h> in a C program?

#include <stdio . h>

This # include directive tells the compiler to use the information in the header file called stdio . h.
The initial stdio stand for standard input/output and h stand for header file. The stdio . h file
contains all the instructions the compiler needs to work with disk files and send information to the
screen. This header file is provided by the Turbo C++ compiler.

Q8: What is a statement terminator?

Terminator (Semicolon):

Every statement must end with semicolon (also known as the statement terminator). You can put
several statements on a line. For clarity’s sake usually one statement is put on a line.

Q9: What is the main ( ) function?

THE MAIN ( ) FUNCTION


Every C language program must contain a main ( ) function. A program without main
function cannot be executed.
Instructions of program are written between the curly braces { } of main ( ) function.
When a C language program is executed it starts working from the first statement of main (
) function. The use of void is optional in main function.
Body of main is enclosed in curly braces { }. These braces are called delimiters. Every
instruction written in C language program is called a statement.

Q 10:What are Escape sequences? Mention all Escape sequences.

ESCAPE SEQUENCES
Escape sequences are the special codes which are used to control the way the cursor moves
on monitor. An escape sequence consists of the escape character and a second character.
Though there are two characters in an escape sequence they are considered as a single
character. Some of them are shown in the following table.

RESULT AT EXECUTING
ESCAPE SEQUENCE MEANING
TIME

Moves the cursor at the


\n New line
beginning of the next line.

Moves the cursor to the next


\t Tab
tab stop.

\a Alert Produces a beep

Moves the active position to


\r Carriage return the initial position of the next
paragraph.

Moves the active position to


\b Backspace previous position on the
current line.

Moves the active position to


Form feed the initial position of the next
\f
logical page

\0 End of string Null


\/ Back slash Presents with a back slash
\’ Single Quote Presents with a single quote
\” Double Quote Presents with a double
\? Questions mark Presents with a question mark

ASCII code in hexa decimal


\xnn Hexa decimal escape sequence notation (each represents a
digit)
ASCII code in octal notation
\ddd Octal escape sequence
(each d represent a digit)

Q11: What is the purpose of comments in a C program?

COMMENTS IN C:

A comment is a message to anyone in the source program. Adding comments make your programs
easier to understand. Comments can appear anywhere in a program. They are ignored by the
compiler and linker.

There are two types of comments in C.

i) Single line comment ii) Multi line comment

Single Line Comment:

Single line comment is generally used for short comments. It starts with double forward slashes
‘//’.

Multi Line Comment:

Multi line comment is used when the comment will span several lines. It starts with ‘/*’ and ends
with ‘*/’.
C FUNDAMENTALS
04

IMPORTANT QUESTIONS:

1) What is character set?


2) What are identifiers? And state the rules which must be observed while constructing
identifiers.
3) What is Data Type? Name and describe the four basic data types in C.
4) What are constants? Describe the different type of constants.
5) What is symbolic constant?
6) What is a variable? What are the rules for constructing variable name?
7) What is an array?

PREPARED BY: S.M.RIZWAN


Q1: What is character set?

THE C CHARACTER SET:

A character denotes any alphabet, digit, or special symbol used to represent information. The valid
alphabets, numbers, and special characters allowed in C are listed below:

Alphabets A, B, C, …, Z

A, b, c, …, z

Digits 0, 1, 2, …, 9

Special characters + - * / = % & # @ $ !? ^ “ ‘ ~ \ |

< > ( ) [ ] { } : ; . , _ blank space

Q2: what are identifiers? And state the rules which must be observed while constructing identifiers.

IDENTIFIERS:

Identifiers are names given to various program elements, such as variables, functions, and arrays.
Following rules must be observed while constructing identifiers:

1. An identifier must start with a letter or (rarely) an underscore (_).


2. An identifier must contain letters, digits, or underscores (_).
3. An identifier cannot contain blanks, commas, or any other special characters.
4. An identifier cannot consist of more than 31 characters.
5. An identifier must conform to case sensitivity (C differentiates between uppercase and lowercase
alphabetical characters). For example, the identifier MAX is not the same as the identifier max.

Q3: What is Data Type? Name and describe the four basic data types in C.

DATA TYPES:

To prevent data values from being manipulated with the wrong operations and to prevent their
representations from being misinterpreted, the data items are classified into data type. Values belonging to
the same type are subjected to the same operations and are represented in the same way.

THE BASIC DATA TYPES

Typical
Data
Description Memory
Type
Requirements

int Integer quantity 2 bytes


char Single character 1 bytes
float Floating-point number (i.e., a number containing a decimal 4 bytes
point and/or an exponent)
Double-precision floating-point number (i.e., more significant
double figures, and an exponent which may be larger in magnitude) 8 bytes
int Data Types:

The int data type represents integer values, meaning any positive or negative number, or zero, without a
decimal point. Examples of valid integers are:

4 -87 +9345 -18239

Char Data Type:

C also recognizes nonnumeric character data. A char represents individual characters. Hence, the char type
will generally require only one byte of memory. Examples of char are:

‘m’ ‘>’ ‘H’ ‘2’ ‘[‘ ‘!’ ‘F’

Float Data type:

The float data type represents floating-point values, meaning any singed or unsigned number having a
decimal point. Examples of valid float are:

2. -78.294 395.20578 +95.0 -493.

Double Data type:

Float can be single or double precision. So, double is used to store decimal numbers (numbers with floating
point value) but with double precision. Examples of double are:

98.74563 2.73e+03 3.14E-3 58.84261

Q4: What are constants? Describe the different type of constants.

CONSTANTS:

Constants are quantities whose values do not change during program execution. In C, however, some
authors refer them as literals or literal constants. In any case, there are four basic types of constants in C.
They are integer constants, floating-point constants, character constants and string constants.

INTEGER CONSTANTS:

An integer constant is an integer-valued number. Thus it consists of a sequence of digits. Some examples
of valid decimal integer constants are:

273 -597 0 3 666

FLOATING-POINT CONSTANTS:

Integers are inadequate for representing very large or very small numbers and fractions. For this you need
floating-point types. Floating-point constants are also called real constants. Some examples of valid
floating-point constants are:

0. 1. -0.5 6070 0.0001 3E-7 3e-7 0.002e+3 .2191129e19

CHARACTER CONSTANTS:

A character constant is a single character, enclosed in apostrophes. They include the letter of alphabet
(lowercase and uppercase), the numerals 0 to 9, punctuation marks such as :, ; and ? , and special characters
such as &, +, -, # and $.
Some examples of valid character constants are:

‘B’ ‘m’ ‘5’ ‘*’ ‘?’ ‘ ‘

STRING CONSTANTS:

A sequence of zero or more characters enclosed by double quotes is called a string constant. This can also
be defined as an array of character constant. Some examples of valid character constants are:

“The quick brown fox jumps over the lazy dog.”

“514-86-112109”

“12-Qasim Rd.”

Q5: What is symbolic constant?

SYMBOLIC CONSTANTS:

A symbolic constant is a programmer-defined identifier that is replaced with a sequence of characters


called text. The replacement text may represent a numeric constant, a character constant, or a string
constant. Thus, a symbolic constant allows an identifier to appear in place of a numeric constant, a
character constant, or a string constant.

Q6: What is a variable? What are the rules for constructing variable name?

VARIABLES:

A variable is a programmer-defined identifier whose value can change during the execution of program.
All variables must have a name and a data type. C supports most of the common data types for variables-
integer, float (real), and character.

RULES FOR CONSTRUCTING VARIABLE NAMES:

1. The first character in the variable name must be alphabet.


2. No commas or blanks are allowed within a variable name.
3. No special symbol other than an underscore (as in tax_rate) can be used in a variable name.

DECLARATION OF VARIABLE:

A declaration associates a group of variables with a specific data type. A declaration consists of a data type,
followed by one or more variable names, ending with a semicolon.

Example of variable names and their data types as they might be declared at the beginning of the function
look like this program statement:

Void main (void)


{
int num;
Float tax_rate;
}
Q7: What is an array?

ARRAY:

An array is an identifier that refers to a collection of data items that all have the same name. the data items
must all be of the same type (e.g. all integers, all characters etc).
OPERATORS AND EXPRESSIONS
05

IMPORTANT QUESTIONS:

1) What is an operator?
2) Define expression.
3) Describe several different types of operators.
4) What is meant by operator precedence?
5) What is meant by associativity? What is the associativity of arithmetic operator?
6) Describe the three logical operators.
7) When should parenthesis be included within an expression? In what order are the
operations carried out within an expression that contains nested parenthesis?
8) What is cast?

PREPARED BY: S.M.RIZWAN


Q1: What is an operator?

OPERATOR

An operator defines what is done with data. Therefore we can say that ‘operators’ are used to perform some
‘operation’ on the ‘operands’. For example:

A= b + c

Here, b and c are operands, and the operation is being performed is ‘addition’ by using ‘+’ operator.

Q2: Define expression.

EXPRESSIONS

An expression is a collection of operands (one or more) and operators (zero or more) that can be evaluated
to a single value. An operand is a constant, variable, or another expression. The most general form is :

Operand-1 operation operand-2

The result is a new value.

For example:

2+6 evaluates to 8

4 * 5 evaluates to 20

48/8 evaluates to 6

10 – 3 evaluates to 7

Q3: Describe several different types of operators.

CLASSIFICATION OF OPERATORS

Operators fall into three classes:

1. Unary Operator: Those that requires one operand.


2. Binary Operator: Those that requires two operands.
3. Ternary Operator: This one is unique. It requires three operands.
Some commonly used operators are:

1. Arithmetic operators
2. Assignment operators
3. Relational operators
4. Logical/Boolean operators
5. Increment and Decrement operators
ARITHMETIC OPERATORS

Arithmetic operators are used to perform mathematical operations. An arithmetic expression is made up of
constants, variable, a combination of both or a function call, connected by arithmetic operators. Following
list provide the detail about arithmetic operators.

OPERATOR OPERATION EXAMPLE


+ Addition a+b
- Subtraction a-b
* Multiplication a*b
/ Division a/b
% Remainder after integer division a%b

ASSIGNMENT OPERATORS

The basic assignment operator is =. This is used to assign value of an expression to an identifier. It has the
general form:

Identifier = expression

In addition to=, there are a number of assignment operators in C. some of them are:

OPERATOR OPERATION EXAMPLE EXPLANATION

+= Add sign a+=b Same as a = a + b

-= Subtract sign a-=b Same as a = a - b

*= Multiply sign a*=b Same as a = a * b

/= Divide sign a/=b Same as a = a / b

%= Remainder sign a%=b Same as a = a % b

RELATIONAL OPERATORS

Relational operators are used to compare two numeric operands. The operands can be variables, constants,
or expressions that ultimately get evaluated to a numerical value. All C relational operators are binary
operators and hence require two operands. The relational operators are summarized as:

OPERATOR OPERATION EXAMPLE


< Less than a<b
< Greater than a>b
<= Less than or equal to a <= b
>= Greater than or equal to a >= b
== Equal to a == b
!= Not equal to a != b

A relational expression is made up of two arithmetic expressions connected by a relational operator. It


returns 0 when the relation is false and 1 when it is true.

LOGICAL/BOOLEAN OPERATORS

A logical operator also called Boolean operator. It combines the result of one or more expressions and the
resultant expression is called the logical expression. After testing the conditions, they return either true
(non-zero value) or false (0) as net result.
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; else 0

INCREMENT AND DECREMENT OPERATOR

The increment operator ++ and decrement operator -- are very useful operators. If a variable ‘a’ is
increment by 1, the increment operator ++ can be used rather that the expression a = a + 1 or a += 1. The
increment operator causes its operand to be increased by 1, whereas the decrement operator causes its
operand to be decreased by 1.

Q4: What is meant by operator precedence?

ORDER OF PRECEDENCE

Order of precedence means the order in which the multiple arithmetic operations take place. The order of
operation of arithmetic operators is as follows:

OPERATOR OPERATION ORDER

*, /, % Multiplication/Division/Remainder Higher

+, - Addition/Subtraction Lower

Q5: What is meant by associativity? What is the associativity of arithmetic operator?

The order in which consecutive operations within the same precedence group are carried out. This is known
as associativity. The associativity is left to right. In other words, consecutive addition and subtraction
operations are carried out from left to right. As are consecutive multiplication, division, and remainder
operations.

Several arithmetic expressions are shown below whose results may have different values if the associativity
is changed.

8–2+3=9

8 * 3 / 2 = 12

9 / 3 + 2 * 4 = 11

Q6: Describe the three logical operators.

LOGICAL AND

Logical AND operator (&&) takes two operands. The result of operation will be true (non-zero) only if
both operands are true (non-zero) otherwise false (zero).
FIRST OPERAND OPERATOR SECOND OPERAND RESULT
False (0) && False (0) 0
True (non-zero) && False (0) 0
False (0) && True (non-zero) 0
True (non-zero) && True (non-zero) 1(non-zero)

LOGICAL OR

Logical OR operator (||) also takes two operands. The result of operation will be true (nonzero) if either
operand is true or if both operands are true (nonzero) otherwise false (zero). In other words, the result of a
logical OR operation will be false only if both operands are false (zero).

FIRST OPERAND OPERATOR SECOND OPERAND RESULT


False (0) || False (0) 0
True (nonzero) || False (0) 1(nonzero)
False (0) || True (nonzero) 1(nonzero)
True (nonzero) || True (nonzero) 1(nonzero)

LOGICAL NOT

Logical NOT operator (!) takes only one operand. If the operand is true (nonzero), the result is false (zero);
if the operand is false, the result is true.

OPERAND OPERATOR RESULT

False (0) ! 1(nonzero)

True (nonzero) ! 0

Q7: When should parenthesis be included within an expression? In what order are the operations
carried out within an expression that contains nested parenthesis?

The natural precedence of operations can be altered through the use of parenthesis. Whatever operations
occur in parenthesis is performed first. In the event of nested parenthesis (i.e. parenthesis inside the
parenthesis), the expression enclosed by the innermost parenthesis is performed first. For example, the
expression 1 + ((3 + 1) / (8 - 4) - 5) is evaluated as below:

1 + ( (3 + 1) / (8 - 4) – 5 )

1 + ( 4 / (8 - 4) - 5 )

1 + ( 4 / 4 - 5)

1+(1–5)

1 + -4

-3
Q8: What is cast?

CASTS

Sometimes we are required to convert the value of an expression to a particular data type, to do so, the
expression must be preceded by the name of the desired data type, enclosed in parenthesis i.e.

(data type) expression

This type of construction is known as cast.

Example:

float f;

int i = 6, j = 4;

f = (float) i / j;
s
INPUT AND OUTPUT STATEMENTS UNIT # 06

IMPORTANT QUESTIONS:

1) How many types of I/O functions are used in C languages?


2) What is the difference between formatted and unformatted I/O functions?
3) Describe all unformatted I/O functions with syntax and example.
4) Differentiate between getch ( ) and getche ( ) functions.
5) Describe Scanf( ) and Printf( ).
6) What is the use of “&” operator in scanf( ) function?
7) What is format specifier?

PREPARED BY:S.M.RIZWAN
Q1: How many types of I/O functions are used in C languages?

C language provides two types of I/O functions.

➢ Formatted IO functions
➢ Unformatted IO functions

FORMATTED IO FUNCTIONS

Formatted I/O functions are the C language predefined functions in which we have a particular
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 (“%d”, &a ); function.

Here is the syntax of printf (“The value of a is %d”, a ); function.

UNFORMATTED IO FUNCTIONS

The unformatted IO functions are the C language functions which do not have a specified syntax
in parentheses.

Example:

The following are the C language unformatted I/O functions

Single Character Input:

i) getchar( ); ii) getch( ); iii) getche( );

Single Character Output:

i) putchar( ); ii) putch( );

String Input:

i) gets( );

String Output:

i) puts( );

Q2: What is the difference between formatted and unformatted I/O functions?
The basic difference between formatted and unformatted I/O functions is that the
formatted functions allow the input read from keyboard or the output displayed on the
monitor to be formatted as per out requirements (the f in the scan or print stands for
formatted).
For example:
if values of total marks and percentage marks are to be displayed on the screen, then the
details like where this output would appear on the screen of the monitor, how many spaces
would be present between the two values, the number of places after the decimal points
etc. can be controlled using formatted functions.

Q3: Describe all unformatted I/O functions with syntax and example.

SINGLE CHARACTER INPUT:

getchar( );

It is a single character unformatted input function, used to take input for only one character data
value. When called, the function waits for a key to be pressed.

When the user presses a key, getchar ( ) echoes (displays) the character that yo u typed to
the screen and further it requires Enter key ↲ to be typed following the input character.

Here is an example.

charch = getchar();

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.When we use the function getch ( )
in a program, you must include the header file conio.h.

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 while entering using keyboard. When we use the function getch ( ) in
a program, you must include the header file conio.h.

Here is an example.

char y;

y=getche( );

SINGLE CHARACTER OUTPUT:

putch( );

It is a single character unformatted output function, which can display only one character on the
screen.

Here is an example.

char x;

putch(x);
putchar( );

The function putchar ( ) stands for “put character”. It is a single character unformatted output
function, which can display only one character.The char can be a character variable or the
character itself contained in single quotes. This function is complement of input function
getchar ( ).

Here is an example.

char x;

putchar(x );

STRING INPUT:

gets( );

The function gets ( ) stands for “get string”.It reads a string from the keyboard, adds the
null character ‘/0’ to it, and assigns it to the required variable, which comes as an
argument of the function. The newline character ‘/n’ (created by pressing the enter key)
signals the end of the string.

Here is an example.

Char name [15];

gets(name);

STRING OUTPUT:

puts( );

The function puts ( ) stands for “put string” and displays a string on the monitor. This
function is complement of input function gets ( ).
Turbo C++ perform a new-line command after the outs ( ) function. This means that after
the data is displayed, the cursor will move to the start of the next line.

Here is an example.

char name[7] = “Rizwan”;

puts(name);

Q4: Differentiate between getch ( ) and getche ( ) functions.


The getch ( ) and getche ( ) are two very similar function which serve this purpose. The
“get” means it gets some input and “ch” means it gets a character. The difference between
two functions is that the function getche ( ) echoes (displays) the character that you typed
to the screen (the letter “e” in getche ( ) stands for “echo”) whereas getch ( ) just returns
the character that you typed without echoing it on the screen.

Q5. Describe Scanf( ) and Printf( ).

scanf ( ) Function:

The scanf ( ) is the most versatile input function because it can handle all of the different
variable and control their formatting. Think of scanf ( ) as meaning SCAN Formatted
characters from the keyboard. The function scans (monitors) the keyboard for keystrokes
to be entered, then interprets the input based on the format specifiers. This function can be
used to enter any combination of numeric, character, and string variables all at the same
time.

printf ( ) Function:

The printf ( ) is a more versatile function than puts( ) and putchar( ) because it can display
data of all types and can work with multiple arguments. This function can be used to
output any combination of numerical values, single characters and strings. In addition ,
printf ( ) can format how the data appears.

Q6: What is the use of “&” operator in scanf( ) function?


The “&” (ampersand) operator is the address operator. So to input an integer or character
data (but not the strings), we must use the address operator with the variable and not just
the variable name itself.

Q7: What is format specifier?

Format specifier indicates how the data will be interpreted. Each format specifier starts with the
percent symbol (%) followed by a letter indicating the data type. The format specifier is used by
the input and output statement. Without using a format specifier the data for a variable cannot be
stored or retrieved by a particular memory location.

Following are the format specifiers.

Specifier Meaning
%d Displays an integer number
%u Displays an unsigned integer
%f Displays a float
%e Displays a number in scientific notation (float)
%c Displays a character
%s Displays a string
%o Displays an octal number (unsigned)
%x Displays a hexadecimal number (unsigned)
SELECTION CONTROL STRUCTURES
07

IMPORTANT QUESTIONS:

1) What is structured Programming?


2) What are control structures? Define them.
3) Define if statement in C.
4) How can we perform multiple statements when the condition is true?
5) Define Nested if statement.
6) Define if else select structure.
7) Define Nested if else statements.
8) Define switch case statement with syntax.
9) Differentiate between switch and if-else.
10) Define conditional operator.

PREPARED BY: S.M.RIZWAN


Q1: What is structured Programming?

STRUCTURED PROGRAMMING

Structured Programming is a standardized approach that creates a program as a series of


interrelated sub-program or functions, it also makes programs easier, to write, check, read and
modify.

Q2: What are control structures? Define them.

CONTROL STRUCTURE

Control Structures control the flow of execution in a program or function. Structure programming
uses a limited number of control structures. There are three basic control structures in structure
programming:

1. Sequence, or sequential flow


2. Selection, or conditional flow
3. Iteration, or repetitive flow
THE SEQUENCE CONTROL STRUCTURE

The sequence control structure is the straightforward: the statements are executed in the same
order in which they appear within the program.

THE SELECTIONS CONTROL STRUCTURE

The selections control structure employs a number of conditions which lead to a selection of one
out of several alternatives. C provides three types of selection structures.

1. The if selection structure


2. If/else selection structure
3. The Switch selection structure
THE ITERATIVE CONTROL STRUCTURES

The word 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 structures.

There are three iterative control structures used in C language.

1. For loop
2. While loop
3. Do while loop

Q3: Define if statement in C.

THE IF SELECTION STRUCTURE

The if statement tests a particular condition. Whenever that condition evaluates as true, an action
is performed—but if it is not true, then the action is skipped and control transfers to the next step
of the program.
The general structure of the command is:

if(condition)

Statement;

Q4: How can we perform multiple statements when the condition is true?

MULTIPLE STATEMENTS

The basic if command performs one statement. If you want to perform more than one statement
when the condition is true, you must use a second level of branches. The braces mark the
beginning and end of a block of statements performed when the condition is true:

if(condition)

statement 1;

statement 2;

statement 3;

Q5: Define Nested if statement.

NESTED IF STATEMENTS

An if condition can be written as deeply as you need within the body of another if statement. This
is called nesting of if’s. For example an action is performed if two conditions are true. The
condition 1 is tested and then condition 2 is tested.

if(condition)

if(condition2)

statement;

Q6: Define if else select structure.

THE IF-ELSE SELECTIONS STRUCTURE

If-else selection structure performs certain action when the condition is true and some different
action when the condition is false.

The general structure of the command is:

if(condition)

statement 1;

else

statement 2;
Q7: Define Nested if else statements.

NESTED IF-ELSE STATEMENTS

Nested if-else statements test for multiple conditions by placing if-else statements inside if-else
statements. When a condition is evaluated as true, the corresponding statements are executed and
the rest of structure is skipped. This structure is referred to as the if-else-if ladder.

Example Program:

#include<stdio.h>
#include<conio.h>
void main(void)
{
clrscr();
int month;
printf(“Input month number: ”);
scanf(“%d”, &month );

if(month == 1)
printf(“January”);
else if(month == 2)
printf(“February”);
else if(month == 3)
printf(“March”);
else if(month == 4)
printf(“April”);
else if(month == 5)
printf(“May”);
else if(month == 6)
printf(“June”);
else if(month == 7)
printf(“July”);
else if(month == 8)
printf(“August”);
else if(month == 9)
printf(“September”);
else if(month == 10)
printf(“October”);
else if(month == 11)
printf(“November”);
else if(month == 12)
printf(“December”);
else
printf(“error in month number!!!!”);
getch();
}
Q8: Define switch case statement with syntax.

THE SWITCH STATEMENT

The switch statement is used to select one of the several alternatives, such as menu options. The
Switch statement is especially useful when the selection is based on the value of a single variable
(called controlling variable) or of a simple expression (called the controlling expression). The
value of this variable may be of type int or char, but not of type float, the switch statement also
differs form if, in that switch can only test for equality, whereas the if conditional expression can
be of any type. The general form of the switch statement is:

Syntax:

switch(variable)
{
case constant 1:
statement(s);
break;
case constant 2:
statement(s);
break;
case constant 3:
statement(s);
break;
default:
statement(s);
}

Q9: Differentiate between switch and if-else.

SWITCH IF-ELSE

Which statement will be executed depend


1) Which statement will be executed is
upon the output of the expression inside if
decided by user.
statement.
2) switch statement test only for
if-else statement test for equality as well as
equality.
for logical expression.

if statement evaluates integer, character,


3) Switch statement evaluates only
pointer or floating-point type or Boolean
character or integer value.
type.

4) It requires break statement to avoid It does not require break statement because
execution the block just below the only one of the blocks of the code is
current executing block. executed.
Q10: Define conditional operator.

The conditional operator is also known as the ternary operator. This operator consists of three
operands and is used to evaluate Boolean expressions. Conditional operator returns one value if
condition is true and returns another value if condition is false. The goal of the operator is to
decide; which value should be assigned to the variable.

Syntax:

variable x = (expression)? value if true: value if false


1

ITERATION CONTROL STRUCTURES UNIT # 08

IMPORTANT QUESTIONS:

1) Define the term iteration.


2) Differentiate between while and do while loop.
3) Differentiate between for loop and while loop.
4) Explain for loop with syntax and example program.
5) Explain while loop with syntax and example program.
6) Explain do while loop with syntax and example program.
7) Describe nested looping with example program.
8) Define Break and continue statements with their syntax and example program.

PREPARED BY: S.M.RIZWAN


Q1: Define the term iteration.

ITERATION

The word 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
structures.

There are three iterative control structures used in C language.

➢ For loop
➢ While loop
➢ Do while loop

All the three types of loops provided in C language have their own significance.

Q2: Differentiate between 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 condition is Action is taken one time even the condition
false in the very first step. is false in the very first step.
3 Block of the Loop
Block of the loop is written after the Block of the loop is written before the
condition. condition checking.
4 Reserved Words
Reserved word “while” is used. Reserved words “do while” loop is used.

Q3: Differentiate between for loop and while loop.

For Loop While Loop


1
Loop type
For loop is a counter loop. While loop is a conditional loop.

2
No. of iterations
Most of the time the number of repetition
Number of repetition is already
is not already known in this loop.
known in this loop

3 No of expression
It has only test expression in the
It has got three expressions in
parenthesis.
parenthesis
4 Reserved word
Reserved word “while” is used.
Reserved word “for” is used.
Q4: 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 expression; test expression; increment/decrement expression)
{
Statements(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 expressions
specifiesthe 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 brackets { } include a
statement or a block of statements to be repeated.

Example:

void main( )
{
int a; //Counter Variable
clrscr( );
for (a=1;a<=10;a++)
{ // Block of loop
printf(“Welcome \n”);
}
getch( );
}

Flowchart:

FLOWCHART FORMAT OF FOR LOOP


Q5: Explain while loop with syntax and example program.

WHILE LOOP

While loop is an 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 acondition.

Syntax

While (condition)
{
Statements(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( );

Flowchart:

FLOWCHART FORMAT OF WHILE LOOP


Q6: 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 or 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.

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( );

Flowchart:

FLOWCHART FORMAT OF DO-WHILE LOOP


Q7: Describe nested looping with example program.

NESTED LOOPING

Nested looping is defined as the loop inside the loop. It is a cycle 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);
}

Explanation:

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:

void main( )

int a,b;

clrscr( );

for(a=1;a<=5;a++)

for (b=1;b<=10;b++)

Printf(“\t%d”,b);

getch( );

Q8: Define Break and continue statements with their syntax and example program.

THE BREAK STATEMENT:

The break statement allows you to exit a loop or a switch from any point within its body, bypassing
its normal termination expression. It can be used within any C control structure e.g. for, while, do-
while or switch statement.
Syntax

The general form of the break statement is:

loop (condition)

if(…)

Break;

Example Program:

#include<stdio.h>

#include<conio.h>

void main(void){

clrscr();

int count;

for(count = 1; count <= 10; count++){

printf(“”%3d”, count);

if(count == 5)

break; //exit the loop

getch();

The above program demonstrates the break statement in a for loop. When the if structure detects
that count has become 5, break is executed. This terminates the for statement and loop only
executes 5 times.
THE CONTINUE STATEMENT:

The continue statement is just the opposite of the break statement. It takes the control to the
beginning of the loop, by pressing the statements inside the loop which have not yet been executed.
Syntax:
The general form of the continue statement is:
loop(condition){
….
if(…)
continue;

}

Example Program:

#include<stdio.h>

#include<conio.h>

void main(void){

clrscr();

int count;

for(count = 1; count <= 10; count++){

if (count == 5)

continue; //skip remaining code in loop if x == 5

printf(“%3d”, count);

getch();

The above program demonstrates the continue statement in a for loop. The program used continue
to skip printing the value 5.
s
FUNCTIONS UNIT #
09

IMPORTANT QUESTIONS:

1) Define function and write its type.

2) Describe pre-defined or library functions.

3) Describe programmer defined functions used in C.

4) What are the advantages of using function?

5) Write the procedure of creating a user defined function.

6) How do you pass a value to a function?

7) How can you return a value from the function?

PREPARED BY: S.M.RIZWAN


Q1: Define function and write its type.

FUNCTION

In C language, a function is a statement or block or statements to perform a specific task.

Explanation:

A function is one of the fundamental ideas 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 pre-defined or library 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 pre-defined 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(s) Result

Return the absolute


value of its integer
abs(x) int int
argument: if x is -5,
abs (x) is 5
Return the smallest
whole number that is
ceil(x) double double
not less than x:if x is
45.23, ceil(x) is 46.0
Returns the natural
algorithm of x for x>
log(x) double double
0.0:if x is 2.71828,
log(x) is 1.0
Returns xy. if x is
negative, y must be a
pow(x,y) whole number: if x double double
is 0.16 and y is 0.5,
pow(x,y) is 0.4
Return the sine of
angle x: if x is
sin(x) double double
1.5708, sin(x) is 1.0
(radian)

Return the non-


negative square root
sqrt(x) of x [sqrt(x)] for x double double
≥0.0: if x is 2.25,
sqrt(x) is 1.5

Q3: Describe programmer defined functions used in C.

PROGRAMMER DEFINED FUNCTION /USER DEFINED FUNCTION

According to the requirements 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.

Example:

For instance the programmer want to send three arguments to add three integer numbers then 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( )

int ans;

clrscr( );

ans=sum(21,42, 7);

printf(“\n the sum is \t %.2f”, ans );

ans=sum(43,65,7);

printf(“\n the sum is \t %.2f” ,ans);

getch( );

}
int sum(int x, int y, int z)

int result;

result = x + y + z;

return result;

Q4: What are the advantages of using 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

Functions 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 carriers to write, understand and debug.

SHARING

A functions can be shared by others programs by compiling it separately & loading them together.

AUTONOMOUS STRUCTURE

Functions 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 recursiveness. Many calculations
can be done easily using recursive process such as calculation of factorial of a number etc.

Q5: Write the procedure of creating a user defined function.

NEED OF A USER-DEFINED FUNCTION

Sometimes a user needs such types 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-defined function look like a main( ) function. The following are the three main
components functions.

➢ Function declaration/function Prototype/ function signature


➢ Function definition
➢ Function call

Function Declaration/ function Prototype/ function signature

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
➢ Arguments

Returning Data Type: The returning data type defines the data type of returning value from the
function definition. If the function does not return value, the returning data type is void.

Function Name: The function name is identifier with the sign of parenthesis.

Arguments: The arguments come inside the parentheses, preceded by their types and separated by
commas. If the function does not use any arguments, the word void is used inside the parentheses.

Syntax:

The syntax of function prototype is as follows:

Returning_data_type function_name (type of arg1, type of arg2,…..);

Example:

A function declaration for addition of three numbers int sum (int, int, int);

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

Function header: The function header looks like a function declaration but it also includes the
variables name with the data types in the arguments. The function definition is not terminated by semi-
colon (;).

Body of the function: It is the main body of the function. All the statements are written in this part of
the program. The statements in the body of the function are written to perform a specific task.

Syntax:
Returning_data_type function_name (type arg1 types of arg2………)

{
Statement(s);

Example:

int sum(int x, int y, int z)

int result;

result = x + y + z;

return result;

Function Call

A user defined function can be called from the main program simply by using its name, including the
parentheses which follow the name.

Syntax:

Variable_Name = Function_Name(arg1, arg2…………..);

Example:

ans = sum(21, 22, 34);

Example Program

float pi (void); // Function Declaration


void main ( )
{
float ans;
clrscr ( );
ans = pi ( ); // Function Call
printf(“\n th value of pi is /t %f”, ans);
getch ( );
}
float pi (void) // Function Definition
{
float x;
x = 3.142;
return x;
}
Q6: How do you pass a value to a function?
You can pass a value (argument) to your own functions. Any data you want to send to the function
must be in the parentheses. You can pass more than one argument, as long the number of arguments in
the function call, and their data types, match those expected by the function.
Q7: How can you return a value from the function?
A function can receive value and return them as well. To return a value from a function, write the
keyword return ( ) followed by the value you want to return.
DATA FILES UNIT # 10

IMPORTANT QUESTIONS:

1) What is a file? Write the name of its type.


2) What is a text file?
3) What is a binary file?
4) Define file opening modes.
5) Define fopen( ) and fclose( ) function.
6) Describe file I/O Functions.

PREPARED BY: S.M.RIZWAN


Q1: What is a file? Write the name of its type.

A file represents a sequence of bytes on the disk where a group of related data is stored. File is
created for permanent storage of data. It is a readymade structure.
In C language, we use a structure pointer of file type to declare a file.
TYPES OF FILE IN C:

There are two kinds of files in a system. They are,

1) Text files (ASCII)


2) Binary files

Q2: What is a text file?

A text file is a computer file that only contains text and has no special formatting such as bold
text, italic text, images, etc. With Microsoft Windows computers text files are identified with the
.txt files extension.

Q3: What is a binary file?

A binary file is a file stored in binary format. Binary file is computer-readable but not human-
readable. All executable programs are stored in binary files as are most numeric data files. In
contrast, text files are stored in a form (usually ASCII) that is human-readable.

Q4: Define file opening modes.

MODE DESCRIPTION

r Opens an existing text file for reading purpose.


Opens a text file for writing. If it does not exist, then a new file is created.
w Here your program will start writing content from the beginning of the
file.
Opens a text file for writing in appending mode. If it does not exist, then
a a new file is created. Here your program will start appending content in
the existing file content.
r+ Opens a text file in both reading and writing mode.

w+ Create a text file in both reading and writing mode.

a+ Create or append a text file in both reading and writing mode.

Q5: Define fopen() and fclose() function.

FOPEN() FUNCTION:

fopen() function is used to open a file to perform operations such as reading, writing etc. In a C
program, we declare a file pointer and use fopen(). fopen() function creates a new file if the
mentioned file name does not exist.
Syntax:

Pointer = fopen (“filename”, “mode”);

Example:

FILE *fp;
fp=fopen (“myfile.txt”, ”‘w”);

FCLOSE() FUNCTION:

fclose() function closes the file that is being pointed by file pointer.

Syntax:

fclose(file_pointer);

Example:

fclose(fp);

Q6: Describe file I/O Functions.

FILE I/O FUNCTIONS:

Putc(ch, fptr)

Putc() function writes data to a file or to a printer a character at a time.

getc (ch,fptr) or fgetch (ch,fptr):

getc() function reads data from a file a character at a time.

fputs (sptr,fptr):

fputs() function writes the data to a file or to a printer a string (line) at atime.

fgets (sptr, len, fptr):

fgets() function reads the data form a file string (line) at a time.

fprintf (fptr, "cs", list):

fprintf ()writes formatted characters, strings, and numbers.

fscanf (fptr, "cs", *list):

fscanf() function reads formatted characters, strings, and numbers.


DATABASE MANAGEMENT SYSTEM
11

IMPORTANT QUESTIONS:

1) What is a Database? Give some examples.


2) Define Database Management System (DBMS).
3) Describe the advantages of DBMS.
4) Describe the disadvantages of DBMS.
5) Define the following terms:
1) Entity 2) Field/ Attribute 3) Record 4) File
6) Define Primary Key with its characteristics.
7) Define Secondary Key.
8) Who is a Data Base Administrator (DBA)? Enlist his three responsibilities.
9) What is Database Model? Explain various types of Database Model with diagram?
10) Discuss the various data types used in MS Access.
11) Discuss the objects of MS Access.

PREPARED BY: S.M.RIZWAN


Q1: What is a database? Give some examples.

DATABASE:

A database is simply an organized collection of related data, typically stored on disk accessible by possibly
many concurrent users. Databases are generally separated into application areas.

For Example:

• Human Resource (employee and pay roll) data


• Sales data
• Accounting data

Q2: Define Database Management System (DBMS).

DATABASE MANAGEMENT SYSTEM (DBMS)

A database managements system (DBMS) is a software package that allows users to create, maintain, and
manipulate a database to produce useful information. The DBMS software represents the interface between the
user and the computer's operating system and database. Oracle, MS Access and MySQL are examples of
database management systems.

Q3: Describe the advantages of DBMS.

The advantages of databases and DBMS software are as follow:

REDUCTION OF DATA REDUNDANCY

Instead of the same data fields being repeated in different files, in a database is that the same information just
appears just once. The single biggest advantage of a database is that the same information is available to
different users.

IMPROVEMENT OF DATA INTEGRITY

Since data are centralized, the data update only one place reflects throughout the system automatically –
thereby avoiding the error that is often introduced then 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 SECURITY:

Although various departments may share data in common access to specific information can be limited to
selected users.
Q4: Describe the disadvantages of DBMS.

Although there are clear advantages to having database, there are still some disadvantages.

COST ISSUE:

Installing and maintaining a database is expensive, particularly in a large organization. In addition, there are
costs associated with training people to use it correctly.

SECURITY ISSUES:

Although databases can be structured to restrict access, it's always possible that unauthorized users will get
past the safeguards. And when they do, they may have access to all the files, not just a few.

PRIVACY ISSUES:

Databases may hold information they should not and be used for unintended purposes, perhaps intruding on
people's privacy.

NEW HARDWARE REQUIRED:

A DBMS often requires a great deal of memory and secondary storage, and accessing records can be time
consuming.

Q5: Define the following terms:

1) Entity 2) Field/ Attribute 3) Record 4) File

1) ENTITY:

Any object or event about which someone chooses to collect data is an entity. Entity may be person, place,
event, object, or concept in a real world that we wish to present in database.
For example of each of these types of entities follow:

Person: employee, student, patient, customer.


Place: state, region, country.
Object: machine, building, country.
Event: machine breakdown, electricity failure.

2) FIELD / ATTRIBUTE:

A field / attribute is an item consisting of one or more logically related characters. It is some characteristic or
quality of an entity that is treated as a single unit in data processing.

For Example:
If we are processing employees’ data of a company, we may have an employee id field, an employee name
field, an employee pay field etc.

3) RECORD:

A record is a collection of related fields. An employee record would be a collection of fields of one employee.
For Example:
These fields would include the employee code field, employee name field, employee pay field and so forth.

4) FILE:

A file is a collection of related records that are treated as a unit.

For Example:
A collection of all employee records for one company would be an employee file.

Q6: Define Primary Key with its characteristics.

PRIMARY KEY

A primary key is a field in a table which uniquely identifies each row/record in a database table.

Characteristics of Primary Key:

i. Primary keys must contain unique values.


ii. A primary key column cannot have NULL values.

Q7: Define Secondary Key.

SECONDARY KEY

An entity may have one or more choices for the primary key. Collectively these are known as candidate keys.
One is selected as the primary key. Those not selected are known as secondary keys.

For example:
An employee has an employee number, a National Insurance (NI) number and an email address. If the
employee number is chosen as the primary key then the NI number and email address are secondary keys.

Q8: Who is a Data Base Administrator (DBA)? Enlist his three responsibilities.

Data Base Administrator (DBA) is a person or group in-charge for implementing DBMS in an organization.

The main responsibilities of DBA are:

• Make decisions concerning the content of the database.


• Plans storage Structures and access strategies.
• Provides support to users.

Q09: What is Database Model? Explain various types of Database Model with diagram?

THE BASIC DATABASE MODEL

A Database model defines the logical design and structure of a database and defines how data will be stored,
accessed and updated in a database management system. While the Relational Model is the most widely used
database model.
Three most popular models of organizations are:
1) Hierarchical database model
2) Network database model
3) Relational database model

THE HIERARCHICAL DATABASE MODEL


This database model organizes data into a tree-like-structure, with a single root, to which all the other data is
linked. The hierarchy starts from the Root data, and expands like a tree, adding child nodes to the parent nodes.
In this model, a child node will only have a single parent node.

THE NETWORK DATABASE MODEL


This is an extension of the Hierarchical model. In this model data is organized more like a graph, and are
allowed to have more than one parent node. In this database model data is more related as more relationships
are established in this database model. Also, as the data is more related, hence accessing the data is also easier
and fast. This database model was used to map many-to-many data relationships.
THE RELATIONAL DATABASE MODEL
In this model, data is organized in two-dimensional tables and the relationship is maintained by storing a
common field. This model was introduced by E.F Codd in 1970, and since then it has been the most widely
used database model. The basic structure of data in the relational model is tables. All the information related to
a particular type is stored in rows of that table. Hence, tables are also known as relations in relational model.

Q10: Discuss the various data types used in MS Access.


DATA TYPE DESCRIPTION
An AutoNumber field creates unique values automatically when Access creates a new
AutoNumber
record. The AutoNumber field is primarily used for Primary Keys in Access.
A Text field can contain values that are text, numeric or a combination of both. A text
Text
field can contain a maximum length of 255 characters.
A much larger version of the text field, allowing storage of up to 64 KB of data in a
Memo
random format.
Number The Number field can store numeric values. Numeric data can be used in calculations.

Date/Time The Date/Time field allows storage of date and time information.

The Currency data type stores values in a monetary format. This can be used with
Currency
financial data as 8-byte numbers with precision to four decimal places.
Yes/No It is used for Boolean data storage of true/false values.
The OLE Object field stores images, documents, graphs etc. from Office and Windows
OLE Object
based programs.
Hyperlink The Hyperlink field type is used to store web addresses.

Lookup wizard A field that allows you to choose a value from another table or from a list of values.
Q11: Discuss the objects of MS Access.

OBJECT CLASS PURPOSE

Table An organized collection of rows and columns used to store field data.

An object that is used to view, change, or organized data.


Query

A graphical object that displays data from a table or a query in an easy to use
Form
format.

Report An object used to present data in a printed form

Data access pages are HTML files designed in access and formatted to display
Pages
in a web browser.

A set of one or more actions that are used to automate common tasks such as
Macro
opening a form or printing a report.

A collection of visual basic for application programming components that are


Module
stored together as a unit.
IMPORTANT ABBREVIATIONS ACCORDING TO SYLLABUS

WORDS FULL FORM

DBMS Database Management System

RDBMS Relational Database Management System

DBA Database Administrator

SQL Structured Query Language

DDL Data Definition Language

DML Data Manipulation Language

DCL Data Control Language

DRL Data Retrieval Language

OLE Object Linking and Embedding

IDE Integrated Development Environment

CPP C Plus Plus

Stdio Standard Input/Output

Conio Console Input/Output

You might also like