Xii - Computer Science (Complete)
Xii - Computer Science (Complete)
Xii - Computer Science (Complete)
CLASS XII
COMPUTER SCIENCE
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.
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.
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.
In general, there are three types of errors that occur in a computer program:
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
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:
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.
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.
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.
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.
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.
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 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?
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:
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.
3) Each function contains different data. Each object controls its own data.
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.
COMPILER INTERPRETER
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.
These instructions direct the computer to “read from” or “write to” a peripheral device.
COMPUTATION INSTRUCTIONS
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.
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?
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.
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.
ALGORITHMIC NOTATIONS:
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.
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:
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:
(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)
This symbol is used to connect parts of the flowchart from one page to another.
Q5: What are the various guidelines to be followed while drawing a flowchart?
FLOWCHARTING RULES:
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.
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.
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:
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.
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.
#include<…>
{ } Start of function
Statement 1;
} } 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
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.
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.
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
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.
Single line comment is generally used for short comments. It starts with double forward slashes
‘//’.
Multi line comment is used when the comment will span several lines. It starts with ‘/*’ and ends
with ‘*/’.
C FUNDAMENTALS
04
IMPORTANT QUESTIONS:
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
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:
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.
Typical
Data
Description Memory
Type
Requirements
The int data type represents integer values, meaning any positive or negative number, or zero, without a
decimal point. Examples of valid integers are:
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:
The float data type represents floating-point values, meaning any singed or unsigned number having a
decimal point. Examples of valid float are:
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:
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:
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:
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:
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:
“514-86-112109”
“12-Qasim Rd.”
SYMBOLIC CONSTANTS:
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.
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:
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?
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.
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 :
For example:
2+6 evaluates to 8
4 * 5 evaluates to 20
48/8 evaluates to 6
10 – 3 evaluates to 7
CLASSIFICATION OF OPERATORS
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.
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:
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:
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
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.
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:
*, /, % Multiplication/Division/Remainder Higher
+, - Addition/Subtraction Lower
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
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).
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.
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.
Example:
float f;
int i = 6, j = 4;
f = (float) i / j;
s
INPUT AND OUTPUT STATEMENTS UNIT # 06
IMPORTANT QUESTIONS:
PREPARED BY:S.M.RIZWAN
Q1: How many types of I/O functions are used in C languages?
➢ 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:
Syntax:
UNFORMATTED IO FUNCTIONS
The unformatted IO functions are the C language functions which do not have a specified syntax
in parentheses.
Example:
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.
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( );
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.
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.
puts(name);
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.
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.
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:
STRUCTURED PROGRAMMING
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:
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 employs a number of conditions which lead to a selection of one
out of several alternatives. C provides three types of selection structures.
1. For loop
2. While loop
3. Do while loop
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;
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;
If-else selection structure performs certain action when the condition is true and some different
action when the condition is false.
if(condition)
statement 1;
else
statement 2;
Q7: Define 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 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);
}
SWITCH IF-ELSE
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:
IMPORTANT QUESTIONS:
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.
➢ For loop
➢ While loop
➢ Do while loop
All the three types of loops provided in C language have their own significance.
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:
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:
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:
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
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 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
loop (condition)
if(…)
Break;
Example Program:
#include<stdio.h>
#include<conio.h>
void main(void){
clrscr();
int count;
printf(“”%3d”, count);
if(count == 5)
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;
if (count == 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:
FUNCTION
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:
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:
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);
ans=sum(43,65,7);
getch( );
}
int sum(int x, int y, int z)
int result;
result = x + y + z;
return result;
The complexity of the entire program can be divided into simple subtask & functions, sub-programs
can be written for each subtask.
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.
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.
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: 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:
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 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:
Example:
Example Program
IMPORTANT QUESTIONS:
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:
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.
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.
MODE DESCRIPTION
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:
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);
Putc(ch, fptr)
fputs (sptr,fptr):
fputs() function writes the data to a file or to a printer a string (line) at atime.
fgets() function reads the data form a file string (line) at a time.
IMPORTANT QUESTIONS:
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:
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.
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.
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.
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.
A DBMS often requires a great deal of memory and secondary storage, and accessing records can be time
consuming.
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:
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:
For Example:
A collection of all employee records for one company would be an employee file.
PRIMARY KEY
A primary key is a field in a table which uniquely identifies each row/record in a database table.
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.
Q09: What is Database Model? Explain various types of Database Model with diagram?
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
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.
Table An organized collection of rows and columns used to store field data.
A graphical object that displays data from a table or a query in an easy to use
Form
format.
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.