You are on page 1of 68

UNIT-1

Q1. What is algorithm? Write down the general characteristics of an algorithm and write an
algorithm to print the digits of a number in reverse order.
Ans. Algorithm: An algorithm is a sequence of finite instructions, often used for calculation and data
processing.
An algorithm is a step-by-step method of solving a problem.
An algorithm is a set of instructions designed to perform a specific task.
Characteristics of the algorithm:
1) Finiteness: - an algorithm terminates after a finite numbers of steps.
2) Definiteness: - each step in algorithm is unambiguous. This means that the action specified by the step
cannot be interpreted (explain the meaning of) in multiple ways & can be performed without any
confusion.
3) Input:- an algorithm accepts zero or more inputs
4) Output:- it produces at least one output.
5) Effectiveness:- it consists of basic instructions that are realizable. This means that the instructions can
be performed by using the given inputs in a finite amount of time.
Algorithm to print the digits of a number in reverse order:
Digitsreverse(num)
1. Start.
2. Please enter number.
3. Read num.
4. While (num>0) repeat steps 5,6 and 7 otherwise go to step 8.
5. Do digit =num%10
6. Print digit;
7. Do num= num/10
8. Stop
Q2. What do you understand by flow chart? Draw a flow chart to find maximum of three numbers.
Ans-
Flow chart:
It is very important tool for developing algorithm and program.
It is pictorial representation of step by step solution of a problem. Programmer often uses it as a program
planning tool for visually organizing step necessary to solve a problem.
It uses boxes of different shapes that denote different type of instruction.
While making a flow chart a programmer needs not to pay attention on the elements of the programming
language, he has to pay attention to the logic of solution to the problem
Q3. Define computer. Explain anatomy of computer in detail.
Ans- Computer: Computer is an electronics device that can perform various arithmetic and logical
operations. It can receive data, process it and produce output. It can store large amount of data.

A computer system consists of mainly four basic units; namely input unit, storage unit, central
processing unit and output unit. Central Processing unit further includes Arithmetic logic unit and
control unit, as shown in the figure:
Input Unit: This unit is used for entering data and programs into the computer system by the user for
processing. Input devices are,Keyboard, Mouse, Trackball, Touchpad, Light Pen, Magnetic ink character
recognition (MICR), Optical mark recognition (OMR), Bar code reader.
Memory Unit: The storage unit is used for storing data and instructions before and after processing.
Computer’s memory can be classified into two types; primary memory and secondary memory.
Primary Memory can be further classified as RAM and ROM.
RAM or Random Access Memory is the unit in a computer system. It is the place in a computer where the
operating system, application programs and the data in current use are kept temporarily so that they can
be accessed by the computer’s processor. It is said to be ‘volatile’ since its contents are accessible only as
long as the computer is on. The contents of RAM are no more available once the computer is turned off.
ROM or Read Only Memory is a special type of memory which can only be read and contents of which
are not lost even when the computer is switched off. It typically contains manufacturer’s instructions.
Among other things, ROM also stores an initial program called the ‘bootstrap loader’ whose function is to
start the operation of computer system once the power is turned on.
Secondary Memory
RAM is volatile memory having a limited storage capacity. Secondary/auxiliary memory is storage other
than the RAM. These include devices that are peripheral and are connected and controlled by the
computer to enable permanent storage of programs and data.
Secondary storage devices are of two types; magnetic and optical. Magnetic devices include hard disks
and optical storage devices are CDs, DVDs, Pen drive, Zip drive etc.
Output Unit: The output unit is used for storing the result as output produced by the computer after
processing. Output devices are monitor, printer etc.
CPU: The Central Processing Unit (CPU) takes data and instructions from the storage unit and makes all
sorts of calculations based on the instructions given and the type of data provided. It is then sent back to
the storage unit. CPU includes Arithmetic logic unit (ALU) and control unit (CU)
• Arithmetic Logic Unit: All calculations and comparisons, based on the instructions provided, are
carried out within the ALU. It performs arithmetic functions like addition, subtraction, multiplication,
division and also logical operations like greater than, less than and equal to etc.

• Control Unit: Controlling of all operations like input, processing and output are performed by control
unit. It takes care of step by step processing of all operations inside the computer.
Q4. What do you mean by operating system? Explain various functions of operating system.
Operating System:
It is a software program that acts as an interface between the user and the computer. It is a software
package which allows the computer to function.
It is a program that controls the execution of application programs.
It is an interface between applications and hardware.
Functions:
1. Program creation
2. Program execution
3. Access to Input/Output devices
4. Controlled access to files
5. System access
6. Error detection and response
7. Interpreting the commands
8. Managing peripherals
9. Memory management
10. Processor management
11. Information management
12. Process communication
Q5: Differentiate CUI and GUI.

Ans:
BASIS CLI/CUI GUI

Graphical User interface


Command line interface
permits a user to interact
enables a user to
Basic with the system by using
communicate with the system
graphics which includes
through commands.
images, icons, etc.

Device used Keyboard Mouse and keyboard

Easy to perform tasks


Hard to perform an operation
Ease of Use and does not require
and require expertise.
expertise.

Memory Low Consumption High Consumption

Custom changes can be


Appearance Can't be changed
employed

Speed Fast Slow

Example of GUI operating system: Windows 98, Windows 7, Windows XP, Windows Vista, Mac OS
etc.
Example of Command Line operating system: DOS, Linux, Unix etc.

Q6. What do you understand by memory hierarchy? Explain each memory in brief.

Register: Registers are located inside the processor. Each register typically holds a word of data (often 32
or 64 bits). CPU instructions instruct the arithmetic and logic unit to perform various calculations or other
operations on this data. Registers are the fastest of all forms of computer data storage.
Cache memory: Cache memory is a very high speed semiconductor memory which can speed up CPU. It
acts as a buffer between the CPU and main memory. It is used to hold those parts of data and program
which are most frequently used by CPU.
Main memory: Primary memory holds only those data and instructions on which computer is currently
working. It has limited capacity and data is lost when power is switched off. It is generally made up of
semiconductor device.. The data and instruction required to be processed reside in main memory. It is
divided into two subcategories RAM and ROM.
Disk cache: A disk cache is a mechanism for improving the time it takes to read from or write to a hard
disk. Today, the disk cache is usually included as part of the hard disk. A disk cache can also be a
specified portion of random access memory (RAM). The disk cache holds data that has recently been read
and, in some cases, adjacent data areas that are likely to be accessed next.
Secondary memory: This type It is slower than main memory. These are used for storing data
permanently. CPU directly does not access these memories instead they are accessed via input-output
routines. Contents of secondary memories are first transferred to main memory, and then CPU can access
it. For example: disk, CD-ROM, DVD etc.

Q7. What is computer? Explain classification of computer in detail.


Ans-- Computer: Computer is an electronics device that can perform various arithmetic and logical
operations. It can receive data, process it and produce output. It can store large amount of data.
Classification of Computer:
Computers differ based on their data processing abilities. They are classified according to purpose, data
handling and functionality.
According to purpose, computers are either general purpose or specific purpose.
General purpose computers are designed to perform a range of tasks.They have the ability to store
numerous programs, but lack in speed and efficiency.
Specific purpose computers are designed to handle a specific problem or to perform a specific task. A set
of instructions is built into the machine.
According to data handling, computers are analog, digital or hybrid.
Analog Computer
An analog computer (spelt analogue in British English) is a form of computer that uses
continuous physical phenomena such as electrical, mechanical, or hydraulic quantities to model the
problem being solved
Digital Computer
A computer that performs calculations and logical operations with quantities represented as digits,
usually in the binary number system
Hybrid Computer (Analog + Digital)
A combination of computers those are capable of inputting and outputting in both digital and analog
signals. A hybrid computer system setup offers a cost effective method of performing complex
simulations.
On the basis of Size
Super Computer
The fastest and most powerful type of computer Supercomputers are very expensive and are employed for
specialized applications that require immense amounts of mathematical calculations. For example,
weather forecasting requires a supercomputer. Other uses of supercomputers include animated graphics,
fluid dynamic calculations, nuclear energy research, and petroleum exploration.
The chief difference between a supercomputer and a mainframe is that a supercomputer channels all its
power into executing a few programs as fast as possible, whereas a mainframe uses its power to execute
many programs concurrently.
Mainframe Computer
A very large and expensive computer capable of supporting hundreds, or even thousands, of users
simultaneously. In the hierarchy that starts with a simple microprocessor (in watches, for example) at the
bottom and moves to supercomputers at the top, mainframes are just below supercomputers. In some
ways, mainframes are more powerful than supercomputers because they support more simultaneous
programs. But supercomputers can execute a single program faster than a mainframe.
Mini Computer
It is midsized computer. In size and power, minicomputers lie between workstations and mainframes. In
the past decade, the distinction between large minicomputers and small mainframes has blurred, however,
as has the distinction between small minicomputers and workstations. But in general, a minicomputer is a
multiprocessing system capable of supporting from 4 to about 200 users simultaneously.
Micro Computer or Personal Computer
Desktop Computer: a personal or micro-mini computer sufficient to fit on a desk.
● Laptop Computer: a portable computer complete with an integrated screen and keyboard. It
is generally smaller in size than a desktop computer and larger than a notebook computer.
● Palmtop Computer/Digital Diary /Notebook /PDAs: a hand-sized computer. Palmtops
have no keyboard but the screen serves both as an input and output device.
Workstations
It is a terminal or desktop computer in a network. In this context, workstation is just a generic term for a
user's machine (client machine) in contrast to a "server" or "mainframe."
Q8. Write short notes on DOS and Android.
Ans-
DOS: Short for Microsoft Disk Operating System, MS-DOS is a non-graphical command line operating
system derived from 86-DOS that was created for IBM compatible computers. MS-DOS originally
written by Tim Paterson and introduced by Microsoft in August 1981 and was last updated in 1994 when
MS-DOS 6.22 was released. MS-DOS allows the user to navigate, open, and otherwise manipulate files
on their computer from a command line instead of a GUI like Windows.
Today, MS-DOS is no longer used; however, the command shell, more commonly known as the
Windows command line is still used by many users. MS-DOS is a command-line and is navigated by
using MS-DOS commands. Some commands are as follows:
1. CLS: this command is used to clean the screen.
2. DIR: this command allows the user to see all files and sub-directory in the current directory. Dir/p
- page by page display of file name and directory names;
Dir/w - width-wise display;
Dir/s - displays all sub directory and files in the sub-directory of current directory.
3. Date it displays two system date and allows the user to change it if desired ; it is displayed in the form
of mm - dd - yy; eg:c:\> date - enter.
4. Time it displays the system type and enables the user to change it; eg: C:\> Time - enter.
5. md(mkdir) it creates a new directory in sub directory in the current directory; eg: C:\> md <New
directory name>
6. Type it displays the content of saved file; eg: C:\> Type> file name.
7. Delete delete a file from current directory; Syntax: C;\> del<file name>
8. Copy it copies the given file or files from the source directory to the largest directory;
Syntax: C:\> copy<source file name> <target file name>.

Android: Android is a mobile operating system developed by Google. It is used by several smart phones ,
such as the Motorola Droid, the Samsung Galaxy, and Google's own Nexus One.
The Android operating system (OS) is based on the open Linux kernel. Android is open source, meaning
developers can modify and customize the OS for each phone. Therefore, different Android-based phones
may have different graphical user interfaces GUIs even though they use the same OS.
Android phones typically come with several built-in applications and also support third-party programs.
Developers can create programs for Android using the free Android SDK (Software Developer Kit).
Android programs are written in Java and run through Google's "Davlik" virtual machine, which is
optimized for mobile devices. Users can download Android "apps" from the online Android Market.

The version history of the Android mobile operating system began with the release of the Android beta in
November 2007. The first commercial version, Android 1.0, was released in September 2008. The most
recent major Android update is Android 5.0 "Lollipop", which was released on November 3, 2014. Since
April 2009, Android versions have been developed and released in alphabetical order, beginning with
Android 1.5 "Cupcake"; the earlier versions 1.0 and 1.1 were not released under specific code names:

● Cupcake (1.5)
● Donut (1.6)
● Eclair (2.0–2.1)
● Froyo (2.2–2.2.3)
● Gingerbread (2.3–2.3.7)
● Honeycomb (3.0–3.2.6)
● Ice Cream Sandwich (4.0–4.0.4)
● Jelly Bean (4.1–4.3.1)
● KitKat (4.4–4.4.4, 4.4W–4.4W.2)
● Lollipop (5.0–5.1.1)
Q9. What do you mean by translator? Differentiate compiler and interpreter.
Ans- A translator is a computer program that performs the translation of a program written in a given
programming language into a functionally equivalent program in a different computer language, without
losing the functional or logical structure of the original.
Examples of widely used types of computer languages translators include interpreters, compilers, and
assemblers.
Difference between Compiler and Interpreter
No Compiler Interpreter
1 Compiler Takes Entire program as input Interpreter Takes Single instruction as input .
2 Intermediate Object Code is Generated No Intermediate Object Code is Generated
Conditional Control Statements are Executes
3 Conditional Control Statements are Executes slower
faster
Memory Requirement : More (Since Object
4 Memory Requirement is Less
Code is Generated)
Every time higher level program is converted into
5 Program need not be compiled every time
lower level program
Errors are displayed after entire program is Errors are displayed for every instruction
6
checked interpreted (if any)
7 Example : C Compiler Example : BASIC

Q10. Explain assembler, linker and loader in detail.


Assembler: A program which translates an assembly language program into a machine language program
is called an assembler. If an assembler which runs on a computer and produces the machine codes for the
same computer then it is called self assembler .If an assembler that runs on a computer and produces the
machine codes for other computer then it is called Cross Assembler.
Linker: In high level languages, some built in header files or libraries are stored. These libraries are
predefined and these contain basic functions which are essential for executing the program. These
functions are linked to the libraries by a program called Linker. If linker does not find a library of a
function then it informs to compiler and then compiler generates an error. The compiler automatically
invokes the linker as the last step in compiling a program.
Not built in libraries, it also links the user defined functions to the user defined libraries. Usually a longer
program is divided into smaller subprograms called modules. And these modules must be combined to
execute the program. The process of combining the modules is done by the linker.
Linker creates exe file.
Loader: Loader is a program that loads machine codes of a program into the system memory.
In Computing, a loader is the part of an Operating System that is responsible for loading programs. It is
one of the essential stages in the process of starting a program. Because it places programs into memory
and prepares them for execution. Loading a program involves reading the contents of executable file into
memory. Once loading is complete, the operating system starts the program by passing control to the
loaded program code.

Q11. What is programming language? Differentiate high level and low level language.
Ans-
Languages are a means of communication. Communication with computers is carried out through a
language. This language is understood both by user and the machine. Every computer language is bound
by rules known as SYNTAX of that language. The user is bound by that syntax while communicating
with the computer system.

Difference between high level and low level language:


Sr. No. High level language Low level language
1. In high level code instructions use words. In low level code instructions are in binary
code(0,1) and mnemonics.
2. High-level code is designed to be read by low level code is to be read/executed by the
human programmers. computer.
3. High level code can be portable/translated low level code is specific to a particular
for different machines. machine so not portable.
4. System knowledge not required. System knowledge required.
5. Less error prone. More error prone.
6. Execution slow. Execution fast.
Less memory efficient More memory efficient.
7. Translator required. Translator not required in machine code.
(compiler or interpreter) Assembler required for low level code.
8. C , c ++ ,JAVA Machine, assembly

Q12. Differentiate top down and bottom up programming approach in detail.


Ans-Top down approach and bottom up approach are involved in software development. These
approaches are not involved in program execution.

● Structure/procedure oriented programming languages like C programming language follows top


down approach. Whereas object oriented programming languages like C++ and Java
programming language follows bottom up approach.
● Top down approach begins with high level design and ends with low level design or development.
Whereas, bottom up approach begins with low level design or development and ends with high
level design.
● In top down approach, main() function is written first and all sub functions are called from main
function. Then, sub functions are written based on the requirement. Whereas, in bottom up
approach, code is developed for modules and then these modules are integrated with main()
function.
● Now-a-days, both approaches are combined together and followed in modern software design.
● In a top-down implementation, the implementation starts from the top of the hierarchy and
proceeds to the lower levels. First the main module is implemented, then its subordinates are
implemented, and their subordinates, and so on.
● When we proceed top-down, for testing a set of modules at the top of the hierarchy , stubs will
have to be written for the lower level modules that the set of modules under testing invoke. On
the other hand, when we proceed bottom-up, all modules that are lower in the hierarchy have
been developed and driver modules are needed to invoke these modules under testing

Q13.Differentiate the following:


1. Hardware and software
2. Application and system software
3. Windows and android
4. Multi programming, Multi tasking and multi threading OS

Ans-

Basics Hardware Software


Software is a collection of
Devices that are required to
program that enables a
Definition store and execute (or run) the
computer to perform a specific
software.
task
System software,
Input, storage, processing,
Types Programming software, and
control, and output devices.
Application software.
Software does not wear out
Durability Hardware wears out over time.
over time.
Hardware is physical in
Nature Software is logical in nature.
nature.
QuickBooks, Adobe Acrobat,
CD-ROM, monitor, printer,
Examples Google Chrome, Microsoft
video card, scanners
Word, Microsoft Excel

Graphical User interface permits a


Command line interface enables a
user to interact with the system by
Basic user to communicate with the
using graphics which includes
system through commands.
images, icons, etc.

Device used Keyboard Mouse and keyboard

Hard to perform an operation and Easy to perform tasks and does


Ease of Use
require expertise. not require expertise.

Memory Low Consumption High Consumption

Custom changes can be


Appearance Can't be changed
employed

Speed Fast Slow

BASIS SYSTEM SOFTWARE APPLICATION SOFTWARE

System Software manages


Application Software, when
system resources and provides a
Basic run, perform specific tasks, they
platform for application
are designed for.
software to run.
System Software is written in a Application Software is written
Language low-level language, i.e. assembly in a high-level language like
language. Java, C++, .net, VB, etc.
System Software starts running
when the system is turned on, Application Software runs as
Run
and runs till the system is shut and when the user requests.
down.
System Software is Application Software is
Purpose
general-purpose. specific-purpose.
Microsoft Office, Photoshop,
Examples Operating system.
Animation Software, etc.

Multi Programming OS Multi Tasking OS Multi Threading OS


● In a
● Multithreading is an
multiprogramming ● Multitasking refers to
execution model that
system there are one having multiple
allows a single process
or more programs (programs, processes,
to have multiple code
loaded in main tasks, threads) running at
segments (i.e., threads)
memory which are the same time.
run concurrently within
ready to execute. ● This term is used in
the “context” of that
● Only one program at modern operating systems
process.
a time is able to get when multiple tasks share
● You can think of
the CPU for a common processing
threads as child
executing its resource (e.g., CPU and
processes that share the
instructions (i.e., Memory). At any time the
parent process
there is at most one CPU is executing one task
resources but execute
process running on only while other tasks
independently.
the system) while all waiting their turn.
● Multiple threads of a
the others are waiting ● The illusion of parallelism
single process can share
their turn. is achieved when the CPU
the CPU in a single
● The main idea of is reassigned to another
CPU system or (purely)
multiprogramming is task (i.e. process or thread
run in parallel in a
to maximize the use context switching).
multiprocessing system
of CPU time.

Q15. Explain various symbol used in flowchart.


Ans:

Symbol Symbol Name Purpose

Used at the beginning and end of the algorithm


Start/Stop
to show start and end of the program.

Process Indicates processes like mathematical operations.


Input/ Output Used for denoting program inputs and outputs.

Stands for decision statements in a program,


Decision
where answer is usually Yes or No.

use to connect the flow of two of more flow


Connector
charts

Arrow Shows relationships between different shapes.

Q16. Define structured programming and pseudocode.


Ans:
• Structured programming techniques use functions or subroutines to organize the programming
code. The programming purpose is to break the large code into smaller pieces and organized
together using function.
• This technique uses the concept of modularization/top down design approach to provide cleaner
code and simplifies maintaining the program. Each function has its own identity and isolated from
other, thus change in one function doesn’t affect other.
Features of Structured Programming
• Codes are simple to write & understand
• Concise & clear codes, easy to debug
• Effective & Efficient code Execution
• Scalability & reusability of function

Pseudocode is an informal way of programming description that does not require any strict programming
language syntax or underlying technology considerations. It is used for creating an outline or a rough draft
of a program. Pseudocode summarizes a program’s flow, but excludes underlying details. System
designers write pseudocode to ensure that programmers understand a software project's requirements and
align code accordingly.
Advantages of pseudo code:
• Pseudocode is understood by the programmers of all types.
• It enables the programmer to concentrate only on the algorithm part of the code development.
• It cannot be compiled into an executable program.
Example: Average of 10 numbers
Set total = 0
Set I =1
While i is less than or equal to 10
Input the next number
Add the number into the total
I = I +1
Set the average to the total divided by 10
Print the average.
Q17. What is storage class in c? Explain various storage classes in c in detail.
Ans-

A storage class is an attribute that tells us where the variable would be stored, what will be the initial
value of the variable if no value is assigned to that variable, life time of the variable and scope of the
variable.
There are four storage classes in C:
1) Automatic storage class
2) Register storage class
3) Static storage class
4) External storage class
Initial /
Storage Storage
S.No. default Scope Life
Specifier place
value

CPU Garbage Local to the Within the function


1 auto
Memory value block only.

Register Garbage Local to the Within the function


2 register
memory value block only.

Retains the value of


CPU Local to the the variable between
3 static Zero
memory block different function
calls.
CPU Till the end of the
4 extern Zero Global
memory main program.

Q18: Define structure(layout) of c program with example.


Ans: c program contains following:

Documentation section : It consists of a set of comment lines giving the name author date etc. of
program and other details.
Link section: It provides information or instructions to the compiler to link functions from the system
library.
Definition section: It defines all symbolic constants.
Global declaration section: Variables that are declared outside all the functions and are used in more
than one function.
Main function section: This section contains two parts declaration part and execution part.
Subprogram section: It contains all the user defined functions that are called in main functions.
Example:
// Sample of C Program(documentation Section)
#inclufe<stdio.h> // link section
#include<conio.h> // link section
#define pi 3.14 // definition section
int a=10; // global variable declaration
void disp(); // global function declaration
void main() // main function definition
{
float area,r;
printf(“enter radius”);
scanf(“%f”,&r);
area=pi*r*r;
printf(“area=%f”,area);
disp();
getch();
}
void disp() // user defined function definition
{
printf(“hello”);
}

Q19: Define different type of errors in c program.


Ans: There are different types of error in C

1. Syntax error
2. Run Time error
3. Linker error
4. Logical error
5. Semantic error

Syntax error:
• The errors which arises due to violation of any rule or regulation(syntax) of C language during
the development of program those errors are known as Syntax error.
• Syntax errors are also known as the compilation errors as they occurred at the compilation time,.
These errors are mainly occurred due to the mistakes while typing or do not follow the syntax of
the specified programming language.
Examples:-Missing of semicolon or parenthesis (}) or Displaying the value of a variable without its
declaration while writing the code.
1.If we want to declare the variable of type integer,
int a; // this is the correct form
Int a; // this is an incorrect form. .
2. #include <stdio.h>
int main()
{
a = 10; // a is not declared
printf("The value of a is : %d", a);
return 0;
}
3. #include <stdio.h>
int main()
{
int a=2;
if(.) // syntax error we put the (.) instead of condition in 'if', so this generates the syntax error
printf("a is greater than 1");
return 0;
}

Runtime error: The error which occurs during the execution of program those errors are turn termed as
runtime error. The division by zero is the common example of the run-time error. These errors are very
difficult to find, as the compiler does not point to these errors.
Linker error
• Linker errors are mainly generated when the executable file of the program is not created.
• This can be happened either due to the wrong function prototyping or usage of the wrong header
file.
Example1: The most common linker error that occurs is that we use Main() instead of main().
Example2: Using print() instead of printf().
Logical error : The errors which are introduced due to usage of wrong expression formula for logic in
program these errors are called as logical error.
The logical error is an error that leads to an undesired output.
For example using 2 * 3.14 *r as area of circle.
Or by mistake semi colon after for statements.
for(i=0;i<10;i++);
printf(”hello”);
semantic error: This error occurs when a statement is syntactically valid, but does not do
what the programmer intended.
The following can be the cases for the semantic error:
1.Use of a un-initialized variable.
int i;
i=i+2;
2.Type compatibility
int b = "MIET";
3.Errors in expressions
int a, b;
b = a+”hi” ;
4.Array index out of bound
int a[10];
a[10] = 34;

Q20. Define IDE.


Ans: IDE stands for integrated development tool needed for software development. It consists:
Editor is a program much like a word processor that is used to write or edit the source code of any
program.
Preprocessor is a program that process the source code before it passes through The compiler and
convert source code into expanded source code by mean of preprocessor directives.
Compiler: Already done.
Linker is a program which combines various pieces of relocatable object code and data together to form
a single executable code that can be loaded in primary memory.
Loader is a system program or a part of an operating system that is responsible for loading the executable
code into primary memory for its execution.
Q21. Define C tokens in details.
Ans: C tokens are basic fundamental units used in C language. C tokens are keyword, identifier,
operators, special symbols, constant and string.
Keyword are also known as reserved words whose meaning is already defined in C library they all
perform some specific purpose. There are mainly 32 keywords some are : int, char, float, double if , else,
break, continue ,case, void etc.
Identifier: Each program elements in a C program are given a name called identifiers.
Names given to identify Variables, functions and arrays are examples for identifiers.
• Variable: C variable is a named location in a memory where a program can manipulate the data.
This location is used to hold the value of the variable.
• The value of the C variable may get change in the program.
• C variable might be belonging to any of the data type like int, float, char etc.
Rules for naming variable(same rule for all identifier)
• A variable name is any combination of alphabets digits or underscore
• The first character must be always alphabet or underscore
• No comma or blank space is allowed within variable name
• Only underscore is allowed in special symbols
• Examples are ac ,_cc ,c_a
Constant: It is named location in a memory where entity or value that does not change during the
execution of programs.
const key word is used to make constant.
Exp: const int a=10; const float b=2.5;
Type of constant:

Rules for integer constant:


• An integer constant must have at least one digit.
• It must not have a decimal point.
• It can either be positive or negative.
• No commas or blanks are allowed within an integer constant.
• If no sign precedes an integer constant, it is assumed to be positive.
• The allowable range for integer constants is -32768 to 32767.
Example:
5,-7,555 etc

Rule for real constants:


• A real constant must have at least one digit
• It must have a decimal point
• It could be either positive or negative
• If no sign precedes an integer constant, it is assumed to be positive.
• No commas or blanks are allowed within a real constant.
Floating point constants are the numeric constants that has either fractional form or exponent form. For
example:
• -2.0
• 0.0000234
• -0.22e-5 Note:Here, E-5 represents 10-5. Thus, -0.22e-5 = -0.0000022.
Rules for character constant
• It is a single alphanumeric digit.
• The character is enclosed in single quotes.
• Both single inverted comma point towards left.
• The maximum length of a character constant is one.
• Example ‘a’, ‘1’ , ‘@’
Operator are symbols whose meaning is already known to a C compiler there are total 45 operators used
in C language.
String the collection of characters digits or special symbols and closed in double quotes and terminated
by null character is termed as string.

Q21. What is data type in c? Explain basic data type in term of range, format specifier and size?
Ans-Data Type:
A Data Type is a Type of Data.
Data Type is a Data Storage Format that can contain a Specific Type or Range of Values.
When computer programs store data in variables, each variable must be assigned a specific data
type.
C support three classes of data types
1)Primary data type🡪 char, int, float
2) Derived data type🡪 array, pointer
3)User defined data type 🡪 structure, union,enum
Basic data type in C:
Data Type Range Bytes Format
signed char -128 to + 127 1 %c
unsigned char 0 to 255 1 %c
short signed int -32768 to +32767 2 %d
short unsigned int 0 to 65535 2 %u
signed int -32768 to +32767 2 %d
unsigned int 0 to 65535 2 %u
long signed int -2147483648 to 4 %ld
+2147483647
long unsigned int 0 to 4294967295 4 %lu
Float -3.4e38 to +3.4e38 4 %f
double -1.7e308 to +1.7e308 8 %lf
long double -1.7e4932 to +1.7e4932 10 %Lf
Note: The sizes and ranges of int, short and long are compiler dependent. Sizes
in this figure are for 16-bit compiler.

Q22: Define escape sequence character?


Ans:

● It is used at the time of execution.

● Execution character set is also called as non-graphic character (or) Escape


sequence.
● Escape sequence are invisible and cannot be printed (or) displayed on the output
screen.
● Escape sequence are always represented by a back slash(\) followed by a
character

Character Escape Sequence Result


Bell \a Beep Sound
Back Space \b Moves Previous Position
Horizontal Tab \t Moves next horizontal tab
Vertical Tab \v Moves next vertical tab
Newline (line feed) \n Moves next line
Form feed \f Moves initial position next page
Carriage return \r Moves beginning of the line
Single quote \’ Present Apostrophe mark

Double quotes \” Present double quotes


Backslash \\ Present Back slash mark
NULL \0 NULL

Q23.Differentiate formatted and unformatted input/output function.


Ans-Formatted I/O in C :
The formatted Input / Output functions can read and write values of all data types, provided the
appropriate conversion symbol is used to identify the data type.
scanf is used for receiving formatted Input and printf is used for displaying formatted output.
Syntax for scanf :
scanf(“control_string 1, - - , control_string n”,&variable1, - - - - ,&variable n);
Syntax for printf :
printf(“control_string 1, - - , control_string n”,variable1, - - - - , variable n);
Unformatted I/O in C
Unformatted I/O functions works only with character datatype (char).
The unformatted Input functions used in C are getch(), getche(), getchar(), gets().

Syntax for getch () in C :


variable_name = getch();
getch() accepts only single character from keyboard. The character entered through getch() is not
displayed in the screen (monitor).
Syntax for getche() in C :
variable_name = getche();
Like getch(), getche() also accepts only single character, but unlike getch(), getche() displays the entered
character in the screen.
Syntax for getchar() in C :
variable_name = getchar();
getchar() accepts one character type data from the keyboard.
Syntax for gets() in C :
gets(variable_name);
gets() accepts any line of string including spaces from the standard Input device (keyboard). gets() stops
reading character from keyboard only when the enter key is pressed.
The unformatted output statements in C are putch, putchar and puts.
Syntax for putch in C :
putch(variable_name);
putch displays any alphanumeric characters to the standard output device. It displays only one character
at a time.
Syntax for putchar in C :
putchar(variable_name);
putchar displays one character at a time to the Monitor.
Syntax for puts in C :
puts(variable_name);

Extra Important programs:


1. Write a c program to swap two numbers with or without using third variable.
2. Write a program to find area of circle.
3. WAP to find area of triangle using Heron’s formula.
4. WAP to find simple interest.
5. WAP to print ASCII value of entered character.

UNIT-2:

Q1. Define operator. Explain various operators used in c.


An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations.
C language is rich in built-in operators and provides the following types of operators:

Arithmetic Operators:
Operator Description
+ Adds two operands
- Subtracts second operand from the first
* Multiply both operands
/ Divide numerator by denumerator
% Modulus Operator and remainder of after an
integer division
++ Increment operator, increases integer value by
one
-- Decrement operator, decreases integer value
by one

Logical (or Relational) Operators:


Operator Description
== Checks if the value of two operands is equal
or not, if yes then condition becomes true.
!= Checks if the value of two operands is equal
or not, if values are not equal then condition
becomes true.
> Checks if the value of left operand is greater
than the value of right operand, if yes then
condition becomes true.
< Checks if the value of left operand is less than
the value of right operand, if yes then
condition becomes true.
>= Checks if the value of left operand is greater
than or equal to the value of right operand, if
yes then condition becomes true.
<= Checks if the value of left operand is less than
or equal to the value of right operand, if yes
then condition becomes true.
&& Called Logical AND operator. If both the
operands are non zero then then condition
becomes true.
|| Called Logical OR Operator. If any of the two
operands is non zero then then condition
becomes true.
! Called Logical NOT Operator. Use to
reverses the logical state of its operand. If a
condition is true then Logical NOT operator
will make false.

Bitwise Operators:

Bitwise operator works on bits and perform bit by bit operation and used with integer only.
Operator Description
& Binary AND Operator copies a bit to the
result if it exists in both operands.
| Binary OR Operator copies a bit if it exists in
eather operand.
^ Binary XOR Operator copies the bit if it is set
in one operand but not both.
~ Binary Ones Complement Operator is unary
and has the efect of 'flipping' bits.
<< Binary Left Shift Operator. The left operands
value is moved left by the number of bits
specified by the right operand.
>> Binary Right Shift Operator. The left
operands value is moved right by the number
of bits specified by the right operand.

Assignment Operators:
Operator Description
= Simple assignment operator, Assigns
values from right side operands to left
side operand
+= Add AND assignment operator, It adds
right operand to the left operand and
assign the result to left operand
-= Subtract AND assignment operator, It
subtracts right operand from the left
operand and assign the result to left
operand
*= Multiply AND assignment operator, It
multiplies right operand with the left
operand and assign the result to left
operand
/= Divide AND assignment operator, It
divides left operand with the right
operand and assign the result to left
operand
%= Modulus AND assignment operator, It
takes modulus using two operands and
assign the result to left operand
<<= Left shift AND assignment operator
>>= Right shift AND assignment operator
&= Bitwise AND assignment operator
^= bitwise exclusive OR and assignment
operator
|= bitwise inclusive OR and assignment
operator

Misc Operators
Operator Description
sizeof() Returns the size of an variable.
& Returns the address of an variable.
* Pointer to a variable.
?: Conditional Expression

Q2. What do you mean by ternary operator in c? Write a program to find the largest of three
numbers using ternary operator.
Ans- Ternary Operator: In C programming language the operator which takes THREE arguments
(operands) is called as Ternary Operator. The "Conditional Operator" ( ? : ) is called as "Ternary
Operator" in C Language, because this operator takes three operands.
Syntax: condition ? Expression_1 : Expression_2 ;
Here, if the given condition is TRUE then Expression_1 is performed, if the condition is FALSE
then Expression_2 is preformed.
Program to find largest of three using ternary operator :
# include <stdio.h>
# include <conio.h>
void main()
{
int a, b, c, big ;
clrscr() ;
printf("Enter three numbers : ") ;
scanf("%d %d %d", &a, &b, &c) ;
big = (a > b) ? ((a > c) ? a : c) : ((b > c) ? b : c) ;
printf("\nThe biggest number is : %d", big) ;
getch() ;
}
Output of above program
Enter three numbers : 20 30 10
The biggest number is : 30

Q3. Solve the following expression:


(i) c=a++ * ++b where a=3,b=2.
(ii) Given a=2,b=3,x=0 then find the value of x.
x=(++a,b+=a)
Ans(i)-.
So
c=3*3=9

Ans(ii)- operator ++ has highest precedence so ++a will execute first so


a=a+1
a=3 and now
x=(3,b+=a)
operators = and += have same precedence and same associativity(R-L) so += evaluate first.
b=b+a
b=3+3
b=6 and now
x=(3,6)
if many values in parenthesis are separated by comma(,) then assignment operator(=) assign the right
most value to left hand operand. So
x=6

Q4. Explain various bitwise operators with example.


Ans-
Bitwise operators are used to manipulate one or more bits from integral operands like char, int, short,
long.

Operators Meaning of operators

& Bitwise AND

| Bitwise OR

^ Bitwise exclusive OR

~ Bitwise complement
Operators Meaning of operators

<< Shift left

>> Shift right

Bitwise AND operator in C programming.


The output of logical AND is 1 if both the corresponding bits of operand is 1. If either of bit is 0 or both
bits are 0, the output will be 0. Let us suppose the bitwise AND operation of two integers 12 and 25.
12 = 00001100 (In Binary)
25 = 00011001 (In Binary)

Bit Operation of 12 and 25


00001100
& 00011001
________
00001000 = 8 (In decimal)

Bitwise OR operator in C
The output of bitwise OR is 1 if either of the bit is 1 or both the bits are 1. In C Programming, bitwise OR
operator is denoted by |.
12 = 00001100 (In Binary)
25 = 00011001 (In Binary)

Bitwise OR Operation of 12 and 25


00001100
| 00011001
________
00011101 = 29 (In decimal)

C Programming Bitwise XOR(exclusive OR) operator


The output of bitwise XOR operator is 1 if the corresponding bits of two operators are opposite. It is
denoted by ^.
12 = 00001100 (In Binary)
25 = 00011001 (In Binary)
Bitwise XOR Operation of 12 and 25
00001100
^ 00011001
________
00010101 = 21 (In decimal)

Bitwise compliment operator


Bitwise compliment operator is a unary operator (works on one operand only). It changes the
corresponding bit of the operand to opposite bit i.e., 0 to 1 and 1 to 0. It is denoted by ~.
35=00100011 (In Binary)
Bitwise complement Operation of 35
~ 00100011
________
11011100 = 220 (In decimal)
Shift Operator in C programming
There are two shift operators in C programming: Right shift operator and Left shift operator.
Right Shift Operator
Right shift operator moves the all bits towards the right by certain number of bits which can be specified.
It is denoted by >>.
212 = 11010100 (In binary)
212>>2 = 00110101 (In binary) [Right shift by two bits]
Left Shift Operator
Left shift operator moves the all bits towards the left by certain number of bits which can be specified. It
is denoted by <<.
212 = 11010100 (In binary)
212<<2 = 01010000 (In binary) [Left shift by two bit]

Q5. Differentiate Associativity and precedence.


Ans: Difference between associativity and precedence:
Operator precedence determines which operator is performed first in an expression with more than one
operators with different precedence. For example 10 + 20 * 30 is calculated as 10 + (20 * 30) and not as
(10 + 20) * 30.
Associativity is used when two operators of same precedence appear in an expression. Associativity can
be either Left to Right or Right to Left. For example ‘*’ and ‘/’ have same precedence and their
associativity is Left to Right, so the expression 100 / 10 * 10″is treated as (100 / 10) * 10.
Precedence and Associativity are two characteristics of operators that determine the evaluation order of
subexpressions in absence of brackets.

Q6. What do understand by type conversion? Explain implicit and explicit type conversion with
example.
Ans- Type conversion: Conversion of one data type from another data type is called type casting.
Conversion between data types can be done in two ways :
● Implicit conversion
● Explicit conversion g
Implicit conversion:
Implicit conversion doesn't require a casting operator. This casting is normally used when converting data
from smaller integral types to larger or derived types to the basic type. Implicit Type Conversion also
known as Widening.

int x = 123;
double y = x;
In the above statement, the conversion of data from int to double is done implicitly, in other words
programmer don't need to specify any type operators.
Explicit conversion: Explicit conversion requires a casting operator. This conversion is normally used
when converting a double to int or a base type to a derived type. The Explicit type Conversion is also
known as borrowing.

double y = 123;
int x = (int)y;
In the above statement, we have to specify the type operator (int) when converting from double to int
else the compiler will throw an error.
Q7. Define sizeof() operator with example. Differentiate pre and post increment.
Ans- sizeof() operator
1. sizeof() operator is used to calcualte the size of data type or variables.
2. sizeof() operator will return the size in integer format.
3. sizeof() operator syntax looks more like a function but it is considered as an operator in c
programming
Example of sizeof() operator :
#include<stdio.h>
#include<conio.h>
void main()
{
int ivar;
char cvar;
float fvar;
clrscr();
printf("%d", sizeof(ivar));
printf("%d", sizeof(cvar));
printf("%d", sizeof(fvar));
return 0;
}

Differentiate pre and post increment:


Pre Increment Operator
Pre-increment operator is used to increment the value of variable before using in the expression. In the
Pre-Increment value is first incremented and then used inside the expression.
b = ++y;
In this example suppose the value of variable ‘y’ is 5 then value of variable ‘b’ will be 6 because the value
of ‘y’ gets modified before using it in a expression.
Post Increment Operator
Post-increment operator is used to increment the value of variable as soon as after executing expression
completely in which post increment is used. In the Post-Increment value is first used in a expression and
then incremented.
b = x++;
In this example suppose the value of variable ‘x’ is 5 then value of variable ‘b’ will be 5 because old
value of ‘x’ is used.
Q8. What do you understand by decision control statement? Write a program to check whether a
given number is even or odd.
Ans-Whenever we build an application in any programming language, there is a need of including
decision control statements in code. We can include various conditions in our program using these
statements; we can perform different- different tasks based on the conditions. Following are the decision
control statements available in C.
a) if statement
b) if-else & else-if statement
c) switch-case statements
1. If statement: The code inside if body executes only when the condition defined by if statement is
true. If the condition is false then compiler skips the statement enclosed in if’s body. We can have
any number of if statements in a C program.

Syntax:
if (condition)
{
Statements;
}
2. If-else statement: Here, we have two block of statements. If condition results true then if block
gets execution otherwise statements in else block executes. else cannot exist without if statement.
Syntax:
if (condition)
{
Statements;
}
else
{
Statements;
}
3. Switch-case statement: This is very useful when we have several blocks of statements, which
requires execution based on the output of an expression or condition. Switch defines an
expression (or condition) and case has a block of statements, based on the result of expression,
corresponding case gets execution. A switch can have any number of cases; however there should
be only one default handler.
switch (n)
{
case constant1:
code/s to be executed if n equals to constant1;
break;
case constant2:
code/s to be executed if n equals to constant2;
break;
.
.
default:
code/s to be executed if n doesn't match to any cases;
}
#include<stdio.h>
#include<conio.h>
void main()
{
int n;
clrscr();
printf("enter number");
scanf("%d",&n);
if(n%2==0)
printf("%d is EVEN\n",n);
else
printf("%d is ODD ",n);
getch();
}
Q9. What is the importance of switch case in c. Write a menu driven program to add, subtract,
multiply and divide two numbers.
Ans-
Decision making are needed when, the program encounters the situation to choose a particular statement
among many statements. If a programmer has to choose one block of statement among many alternatives,
nested if-else can be used but, this makes programming logic complex. This type of problem can be
handled in C programming using switch statement.
Syntax of switch-case
switch (n)
{
case constant1:
code/s to be executed if n equals to constant1;
break;
case constant2:
code/s to be executed if n equals to constant2;
break;
.
.
.
default:
code/s to be executed if n doesn't match to any cases;
}
The value of n is either an integer or a character in above syntax. If the value of n matches constant
in case, the relevant codes are executed and control moves out of the switch statement. If the ndoesn't
matches any of the constant in case, then the default codes are executed and control moves out
of switch statement.
The break statement at the end of each case cause switch statement to exit. If break statement is not used,
all statements below that case statement are also executed.
/* C Program to create a simple calculator for addition, subtraction,
multiplication and division */
#include<conio.h>
# include <stdio.h>
void main()
{
char o;
float num1,num2;
printf("Select an operator either + or - or * or / \n");
fflush(stdin);
scanf("%c",&o);
printf("Enter two operands: ");
scanf("%f%f",&num1,&num2);
switch(o)
{
case '+':
printf("%f + %f = %f",num1, num2, num1+num2);
break;
case '-':
printf("%f - %f = %f",num1, num2, num1-num2);
break;
case '*':
printf("%f * %f = %f",num1, num2, num1*num2);
break;
case '/':
printf("%f / %f = %f",num1, num2, num1/num2);
break;
default:
/* If operator is other than +, -, * or /, error message is shown */
printf("Error! operator is not correct");
break;
}
getch();
}

Q10. What do you understand by else if ladder? Write a program to find largest of three numbers.
Ans- In C programming language the else if ladder is a way of putting multiple ifs together when
multipath decisions are involved. It is a one of the types of decision making and branching statements. A
multipath decision is a chain of if’s in which the statement associated with each else is an if. The general
form of else if ladder is as follows -
if ( condition 1)
{
statement - 1;
}
else if (condtion 2)
{
statement - 2;
}
else if ( condition n)
{
statement - n;
}
else
{
default statment;
}
statement-x;

This construct is known as the else if ladder. The conditions are evaluated from the top of the ladder to
downwards. As soon as a true condition is found, the statement associated with it is executed and the
control is transferred to the statement-x (skipping the rest of the ladder). When all the n conditions
become false, then the final else containing the default statement will be executed.

#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c;
clrscr();
printf("\n enter three no.");
scanf("%d%d%d",&a,&b,&c);
if(a>=b)
{if(a>=c)
printf("%d is largest",a);
else
printf("%d is largest",a);
}
else
{
if(b>=c)
printf("%d is largest",a);
else
printf("%d is largest",a);
}
getch();
}
Q11. Differentiate conditional operator and if else . Write a program to check whether a given year
is leap year or not.
Ans-
If else Conditional operator

In if else statement else is optional Both expr2 and expr3 are needed.

N statement can be written within if and else 1 statement can be written within exp2 and expr3
block. block.

Simple with nested conditions Complex with nested conditions

Slow execution speed. Fast execution speed.

#include<stdio.h>
#include<conio.h>
void main()
{
int n;
clrscr();
printf("enter year");
scanf("%d",&n);
if(n%100==0)
{
if(n%400==0)
printf("%d is LEAP YEAR\n",n);
else
printf("%d is NOT LEAP YEAR ",n);
}
else
{
if(n%4==0)
printf("%d is LEAP YEAR\n",n);
else
printf("%d is NOT LEAP YEAR ",n);
}
getch();
}
Q12. Differentiate switch case and if else.
Ans:
If else switch

works on the basis of true/ false (


work on the basis of equality operator
zero/non-zero)

decision control instruction case control instruction

Less readable More readable

allow all sort of condition Case like (i<5) is not permitted.

No need of break break statement is essential

All data types are permit able in condition Float value is not allowed as case label.

Keyword like “switch”, “case”, “break”,


*keywords like “if” “else” is used.
“default”, are used.

Extra Important Programs for unit-2 :


1. WAP to print grade of students
2. WAP to check whether a entered symbol is digit, small char , upper char or special symbol

Unit:3

Q1. Differentiate break and continue with proper example in detail.


Ans-
Break Statement: In C programming, break is used in terminating the loop and switch case immediately
after it is encountered. The break statement is used with conditional if statement.
Syntax of break statement:
break;
The break statement can be used in terminating all three loops for, while and do while loops.E.g
for(i=1; i<=10; i++)
{
if(i%5==0)
break;
else printf(“%d”, i);
}
OUTPUT: 1 2 3 4
continue Statement: continue is used in loop only.
It is sometimes desirable to skip some statements inside the loop. In such cases, continue statements are
used.
Syntax of continue Statement:
continue;
Just like break, continue is also used with conditional if statement.

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


{
if(i%5==0)
continue;
else
printf(“%d”, i);
}
OUTPUT: 1 2 3 4 6 7 8 9

Q2. Define loop and iteration. Differentiate while and do while.

Ans- Iteration, in the context of computer programming, is a process wherein a set of instructions or
structures are repeated in a sequence a specified number of times or until a condition is met. When the
first set of instructions is executed again, it is called iteration. When a sequence of instructions is executed
in a repeated manner, it is called a loop.
There are following differences between while and do-while:
Sr.N. do while While
1. do -while loop runs at least once even while loop do not run in case the condition given is
though the the condition given is false false
2. In a do-while loop the condition is In a while loop the condition is first tested and if it
tested at the last. returns true then it goes in the loop.
3. do while is exit control loop. While loop is entry control loop
4. Syntax do while loop : Syntax while loop:
do while (condition)
{ {
Statements; Statements;
}while(condition); }
Q3. Explain various loop control structure in detail.
Ans-L oops cause program to execute the certain block of code repeatedly until test condition is false.
Loops are used in performing repetitive task in programming. Consider these scenarios:
● You want to execute some code/s 100 times.
● You want to execute some code/s certain number of times depending upon input from user.
These types of task can be solved in programming using loops. There are 3 types of loops in C
programming:
I. for loop II. while loop III. do...while loop

Basic syntax of for loop is as follows:


for( expression1; expression2; expression3)
{
Single statement
or
Block of statements;
}

In the above syntax:

● expression1 - Initializes variables.


● expression2 - Conditional expression, as long as this condition is true, loop will keep executing.
● expression3 - expression3 is the modifier which may be simple increment of a variable.
Syntax of while loop:
Initialization;
while (test expression)
{
statement/s to be executed;

updating loop variables;


}
The while loop checks whether the test expression is true or not. If it is true, code/s inside the body of
while loop is executed, that is, code/s inside the braces { } are executed. Then again the test expression is
checked whether test expression is true or not. This process continues until the test expression becomes
false.

Syntax of do...while loops

Initialization;

do {
some code/s;

updating loop variables;


}
while (test expression);
At first codes inside body of do is executed. Then, the test expression is checked. If it is true, code/s
inside body of do are executed again and the process continues until test expression becomes false (zero).

Q4. Write a program to print the following pattern:


*
**
***
****
Ans-
Program for printing given pattern:
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j,;
clrscr();
for(i=1;i<=4;i++)
{
for(j=1;j<=i;j++)

{
printf("*");
}
printf("\n");
}
getch();
}

Q5. Write a program to print the following pattern:


1
2 3
4 5 6
7 8 9 10
Ans- Program for printing given pattern:
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j,k,a=1;
clrscr();
for(i=1;i<=4;i++)
{
for(j=1;j<=4-i;j++)
{
printf(" ");
}
for(k=1;k<=i;k++)
{
printf("%d ",a);
a++;
}
printf("\n");
}
getch();
}
Q6. Write a program in c to check whether a number is prime number or not.
Ans-#include<stdio.h>
#include<conio.h>
void main()
{
int n,i;
clrscr();
printf("enter number");
scanf("%d",&n);
for(i=2;i<n;i++)
{
if(n%i==0)
break;
}
If(i<n)
printf("%d is not prime ",n);
else
printf("%d is prime ",n);
getch();
}
Q7. What do you mean by odd loop? Write a program to calculate factorial of a given number.
Ans-Odd loop:
In real life programming, there are many times comes a situation when we don't know how many times
the statements in the loop are to be executed. There is comes concept of odd loop.
Execution of loop an unknown number of times can be done by - while, for and do...while loops.
/*A demonstration of odd loop using do...while*/
#include<stdio.h>
#include<conio.h>
void main()
{
int n;
char answer;
do
{
printf("Enter any number : ");
scanf("%d", &n);
printf("Square of %d is %d",n,n*n);
printf("\nWant to calculate more square y/n: ");
fflush(stdin);
scanf("%c", &answer);
}while(answer=='y');
getch();
}
Program to calculate factorial of a given number:
#include<stdio.h>
#include<conio.h>
void main()
{
int n,i,f=1;
clrscr();
printf("enter number");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
f=f*i;
}
printf("Factorial of %d is %d ",n,f);
getch();
}
Q8. Difference break and exit.Write a program in c to print first n terms of Fibonacci series.
Ans-
break exit()

Break is a keyword While exit() is a library function.

No special header file is required. Process.h header file is required.

It is used to come out of program during its


It is used to come out of loop or switch
execution.

Ex- for(i=1;i<=3;i=i+1) Ex- for(i=1;i<=3;i++)


{ {
if(i==2) If(i==2)
break; exit();
printf(“%d”,i); printf(“%d”,i);
} }
printf(“hello”); printf(“hello”);
Output Output:
1 hello 1

/* Fibonacci Series c language */


#include<stdio.h>
#include<conio.h>
void main()
{
int n, first = -1, second = 1, next, i;
printf("Enter the number of terms\n");
scanf("%d",&n);
printf("First %d terms of Fibonacci series are :-\n",n);
for ( i= 1 ; i <= n ; i++ )
{

next = first + second;


printf("%d\t",next);
first = second;
second = next;
}
getch();
}

Q9. Write a program to find s1 for following series:


S1=12+22+32+42+……………………….+N2
Ans-
// Program to find sum of series S=12+22+32+….+N2.
#include<stdio.h>
#include<conio.h>
void main()
{
int N,i,S=0;
clrscr();
printf("enter the value of N");
scanf("%d",&N);
for(i=1;i<=N;i++)
S=S+i*i;
printf("S=%d",S);
getch();
}

Q10. Write a program in c to find sum of digits of an integer number.


Ans- Program for finding sum of digits of a number:
#include<stdio.h>
#include<conio.h>
void main()
{
long int n;
int sum=0 ;
clrscr();
printf("enter number\n");
scanf("%ld",&n);
while(n>0)
{
sum=sum+n%10;
n=n/10;
}
printf("the sum of digits of number is =%d",sum);
getch();
}

Q11. What do you understand by function? Write a program to calculate ab using function (without
using library function pow()).
Ans-
Function in programming is a segment that groups a number of program statements to perform specific
task. A C program has at least one function main( ). Without main() function, there is technically no C
program.
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,r;
int power(int,int);
clrscr();
printf("enter number and its power\n");
scanf("%d%d",&a,&b);
r=power(a,b);
printf("result=%d\t",r);
getch();
}
int power(int m,int n)
{
int i,p=1;
for(i=1;i<=n;i++)
p=p*m;
return(p);
}

Q12. What do mean by library function. Explain four type of user defined function with example.
Ans- Library function:
● Library functions in C language are inbuilt functions which are grouped together and placed in a
common place called library.
● Each library function in C performs specific operation.
● We can make use of these library functions to get the pre-defined output instead of writing our
own code to get those outputs.
● These library functions are created by the persons who designed and created C compilers.
● All C standard library functions are declared in many header files which are saved as file_name.h.
User defined Function: These function are created by user as per his need.
Type of user defined function:
1. No argument no return value
void add(void);
2. With argument but no return value
void add(int,int);
3. No argument with return value
int add(void);
4. With argument with return value
int add(int,int);

Q13. What is recursive function? Write a program to calculate factorial of a number using
recursion.
Recursive Function: Recursive function is the function which calls itself repeatedly until some condition
is met and then the function stops calling itself and returns to the caller.
A recursive function has two parts:
1- Base case (stopping condition)
2-Recursive case :which must always get closer to base case from one invocation to another.
/*program to calculate factorial using recursive function*/
#include<stdio.h>
int fact(int);
int main(){
int num,f;
printf("\nEnter a number: ");
scanf("%d",&num);
f=fact(num);
printf("\nFactorial of %d is: %d",num,f);
return 0;
}

int fact(int n){


if((n==0)||(n==1)))
return 1;
else
return(n*fact(n-1));
}

Q14. Differentiate iteration and recursion. Write a recursive program to find GCD(greatest
common divisor) of two numbers.
Ans- Difference between Recursion and Iteration
RECURSION ITERATIONS

Recursive function – is a function that is partially Iterative Instructions –are loop based
defined by itself repetitions of a process

Recursion Uses selection structure Iteration uses repetition structure


Infinite recursion occurs if the recursion step does An infinite loop occurs with iteration if the

not reduce the problem in a manner that converges loop-condition test never becomes false

on some condition.(base case)

Recursion terminates when a base case is recognized It terminates when the loop-condition fails

Recursion is usually slower then iteration due to Iteration does not use stack so it's faster than

overhead of maintaining stack recursion

Recursion uses more memory than iteration Iteration consume less memory

Infinite recursion can crash the system infinite looping uses CPU cycles repeatedly

Recursion makes code smaller Iteration makes code longer

#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,r;
int gcd(int,int); //Function prototype
clrscr();
printf("enter two numbers\n");
scanf("%d%d",&a,&b);
if(a>b)
r=gcd(a,b);
else
r=gcd(b,a);
printf("result=%d\t",r);
getch();
}
int gcd(int m,int n)
{
if(n==0)
return(m);
else
return(gcd(n,m%n));
}
Q15. What is function prototyping? Write a recursive program to print n terms of Fibonacci series.
Ans- Function Prototype: All identifiers in C need to be declared before they are used. This is true for
functions as well as variables. For functions the declaration needs to be before the first call of the
function. A full declaration includes the return type and the number and type of the arguments. This is
also called the function prototype.
Recursive program in c to print n Fibonacci terms :
#include<stdio.h>
#include<conio.h>
void main()
{
int n,f,i;
int fib(int); //Function prototype
clrscr();
printf("enter how many terms\n");
scanf("%d",&n);
printf("\n Fibonacce series is as follows:\n");
for(i=0;i<n;i++)
{
f=fib(i);
printf("%d\t",f);
}
getch();
}
int fib(int a)
{
if(a==1||a==0)
return(a);
else
return(fib(a-1)+fib(a-2));
}
Q16- Define argument and also differentiate actual and formal argument.
Ans: It is possible to pass data to the functions as inputs. They are known as arguments. The two
common terms that are related to functions are Actual arguments and Formal arguments.

Actual Parameters Formal Parameters

The Actual parameters are the The Formal Parameters are the variables defined by
values that are passed to the the function that receives actual values when the
function when it is invoked. function is called.

The actual parameters are


The formal parameters are in the called function.
passed by the calling function.
In actual parameters, there is no
In formal parameters, the data types of the
mentioning of data types. Only
receiving values should be included.
the value is mentioned.

main()
int add(int d,int e)//d,e are formal parameter
{
{
add(a,b); //a and b are actual
return(d+e);
parameter
}
}

Q17. Differentiate call by value and call by reference with example.


Difference between call by value and call by reference in c:
No. Call by value Call by reference

1 A copy of value is passed to the function An address of value is passed to the function

2 Changes made inside the function is not Changes made inside the function is reflected
reflected on other functions outside the function also

3 Actual and formal arguments will be created Actual and formal arguments will be created
in different memory location in same memory location

4. Pointers not required. Pointers required.

5. void swap(int,int);// function declaration void swap(int *,int *);// function declaration
swap(a,b);// function calling swap(&a,&b);// function calling
//function definition //function definition
void swap(int c,int d) void swap(int *c,int *d)
{ {
int t; int t;
t=c; t=*c;
c=d; *c=*d;
d=t; *d=t;
} }

Q18. What is pointer? Write a program to swap two numbers using call by reference.
Ans-
Pointer-A pointer is a variable whose value is the address of another variable, i.e., direct address of the
memory location. Like any variable or constant, you must declare a pointer before you can use it to store
any variable address.
The general form of a pointer variable declaration is:
type *var-name;
example- int *p; here p is a pointer which stores the address of an integer variable.
// WAP to to swap two numbers using call by reference
#include<stdio.h>
#include<conio.h>
void main()
{

int a,b;
void swap(int *,int *);
clrscr();
printf("enter first no.");
scanf("%d",&a);
printf("enter second no.");
scanf("%d",&b);
printf("before swapping =%d b=%d\n",a,b);
swap(&a,&b);
printf("\nafter swapping in main a=%d b=%d ",a,b);
getch();
}
void swap(int *p,int *q)
{
int c;
c=*p;
*p=*q;
*q=c;
printf("after swapping in swap a=%d b=%d ",*p,*q);
}
Q19. What is double pointer? Write a program to calculate area and perimeter of a circle using
pointer.
Ans-
Pointer Stores the address of the Variable. Double Pointer Stores the address of the Pointer Variable.
Double (**) is used to denote the double Pointer.
Exp:
int num = 45 , *ptr , **ptr2 ;
ptr = &num;
ptr2 = &ptr;
Statement What will be the Output ?
*ptr 45
**ptr2 45
Ptr &num
ptr2 &ptr
// WAP to calculate area and perimeter of a circle using pointer.
#include<stdio.h>
#include<conio.h>
void main()
{
int r;
float area,peri;
void cal(int *,float *,float *);
clrscr();
printf("enter radius of circle");
scanf("%d",&r);
cal(r,&area,&peri);
printf("\narea of circle=%f and perimeter=%f",area,peri);
getch();
}
void cal(int *a,float *b,float *c)
{
*b=3.14*(*a)*(*a);
*c=2*3.14*(*a);
}
Extra Important programs:
1. WAP to check entered number is palindrome or not.
2. WAP to print all prime number between 100 to 500
3. WAP using recursion to find ab.
UNIT-4
Q1. Define array. Write a program to search an element in array.
Ans- Array:

● An array is a collection of similar data type elements stored in contiguous memory locations.

● An array is also termed as subscript variable. Here first element is stored as 0th location.
● Till the array is not initialized it contains garbage value while if partially initialized it contains
zero.
● One of the limitation of array is, it does not provide bound checking.
● Array name is base address of array (base address is the address of first element of array). And
You cannot change the base address of array.
Application of Array
Searching- It is the process of finding the location of specific element in an array of n elements. e.g.
linear search, binary search
Sorting- It is the process of arranging the elements in specific order in an array of n elements. e.g. bubble
sort
Example for C Arrays:
● int a[10]; // integer array
● char b[10]; // character array
// WAP to search an element in one dimensional array
#include<stdio.h>
#include<conio.h>
void main()
{
int a[100];
int i,num,pos,c=0,n;
clrscr();
printf("enter size of array");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("enter value");
scanf("%d",&a[i]);
}
printf("enter number which you want to search");
scanf("%d",&num);
for(i=0;i<n;i++)
{
if(num==a[i])
{
printf("%d is found at a[%d]\n",num,i);
c++;
}
}
if(c==0)
printf("%d in not present in array");
else
printf("%d is fount %d times in array",num,c);
getch();
}
Q2. How will you declare 3D array? Write a program to find largest element of 1D array.
Ans- Declaration of 3D array is follow:
int a[3][4][3];
// WAP to find largest element in one dimensional array
#include<stdio.h>
#include<conio.h>
void main()
{
int a[100];
int i,lar,n;
clrscr();
printf("enter size of array");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("enter value");
scanf("%d",&a[i]);
}
lar=a[0];
for(i=0;i<n;i++)
{
if(a[i]>lar)
lar=a[i]
}
printf("%d is largest",lar);
getch();
}
Q3. What is 2D array? Write a program to find sum of all elements of 2D array.
Ans- Two dimensional array in C:
● Two dimensional array is nothing but array of array.
● syntax : data_type array_name[num_of_rows][num_of_column]
S.no Array declaration Array initialization Accessing array
Syntax: data_type arr_name data_type arr_name[2][2] =
1 arr_name[index];
[num_of_rows][num_of_column]; {{0,0},{0,1},{1,0},{1,1}};
arr [0] [0] = 1; arr [0]
]1] = 2;arr [1][0] = 3;
2 Example:int arr[2][2]; int arr[2][2] = {1,2, 3, 4};

arr [1] [1] = 4;

#include<stdio.h>
#include<conio.h>
void main()
{
int a[5][5],i,j,m,n,s=0;
clrscr();
printf("enter the order of matrix");
scanf("%d%d",&m,&n);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf("enter matrix");
scanf("%d",&a[i][j]);
s=s+a[i][j];
}
}
printf("\nsum=%d",s);
getch();
}
Q4. Write a program to multiply two matrices.
Ans-
// WAP to multiply two matrices
#include<stdio.h>
#include<conio.h>
void main()
{
int a[5][5],b[5][5],c[5][5],i,j,k,m,n,p,q;
clrscr();
printf("enter the order of First matrix");
scanf("%d%d",&m,&n);
printf("enter the order of Second matrix");
scanf("%d%d",&p,&q);
if(n!=p)
{
printf("Multiplication Not possible");
}
else {
for(i=0;i<m;i++)
for(j=0;j<n;j++)
{
printf("enter First matrix");
scanf("%d",&a[i][j]);
}
for(i=0;i<p;i++)
for(j=0;j<q;j++)
{
printf("\nenter Second matrix");
scanf("%d",&b[i][j]);
}
for(i=0;i<m;i++)
for(j=0;j<n;j++)
{ c[i][j]=0;
for(k=0;k<n;k++)
c[i][j]=c[i][j]+a[i][k]*b[k][j];
}
for(i=0;i<m;i++)
{
for(j=0;j<q;j++)
{
printf("%d\t",c[i][j]);
}
printf("\n");
}
}
getch();
}
Q5. What is sorting? Write a program to sort n numbers.
Ans- Sorting: Sorting is a process through which the data is arranged in ascending or descending order.
Sorting can be classified in two types;
Internal Sorts:- This method uses only the primary memory during sorting process. All data items are
held in main memory and no secondary memory is required this sorting process.
Example: Selection sort Heap Sort, Insertion sort, Bubble Sort , Quick sort
External Sorts:- Sorting large amount of data requires external or secondary memory. This process uses
external memory such as HDD, to store the data which is not fit into the main memory.
Example:- Merge Sort
// program to sort n numbers.
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j,t,a[25],n;
clrscr();
printf("how many elements");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("enter value");
scanf("%d",&a[i]);
}
for(i=0;i<n-1;i++)
{
for(j=0;j<n-1-i;j++)
{
if(a[j]>a[j+1])
{
t=a[j];
a[j]=a[j+1];
a[j+1]=t;
}
}
}
printf("\nsorted array is \n");
for(i=0;i<n;i++)
printf("%d\t",a[i]);
getch();
}

Q6. Write a program to add two matrices of order of 3*3.


Ans-
#include<conio.h>
#include<stdio.h>
void main()
{
int a[3][3],b[3][3],c[3][3],i,j;
clrscr();
printf("Enter the First matrix->");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf("enter value");
scanf("%d",&a[i][j]);
}
}
printf("\nEnter the Second matrix->");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf("enter value");
scanf("%d",&b[i][j]);
c[i][j]=a[i][j]+b[i][j];
}
}
printf("\nThe Addition of two matrix is\n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{ printf("%d\t",c[i][j]);
}
printf("\n");
}
getch();
}

Q7. Write a program to find transpose of a matrix.


Ans-
#include<stdio.h>
#include<conio.h>
void main()
{
int a[5][5],b[5][5],i,j,m,n;
clrscr();
printf("enter the order of First matrix");
scanf("%d%d",&m,&n);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf("enter First matrix");
scanf("%d",&a[i][j]);
b[j][i]=a[i][j];
}
}
printf("\ntranspose of matrix is:\n");
for(i=0;i<n;i++)
{
for(j=0;j<m;j++)
{
printf("%d\t",b[i][j]);
}
printf("\n");
}
getch();
}

Q8. What is structure? Differentiate structure and union in detail.


Ans- Structure is the collection of variables of different types under a single name for better handling.
Keyword struct is used for creating a structure.
Syntax of structure
struct structure_name
{
data_type member1;
data_type member2;
.
.
data_type memeber;
};

Structure Union
1.The keyword struct is used to define a structure 1. The keyword union is used to define a union.
2. When a variable is associated with a structure, 2. When a variable is associated with a union, the
the compiler allocates the memory for each compiler allocates the memory by considering the
member. The size of structure is greater than or size of the largest memory. So, size of union is
equal to the sum of sizes of its members. The equal to the size of largest member.
smaller members may end with unused slack bytes.
3. Each member within a structure is assigned 3. Memory allocated is shared by individual
unique storage area of location. members of union.
4. The address of each member will be in 4. The address is same for all the members of a
ascending order This indicates that memory for union. This indicates that every member begins at
each member will start at different offset values. the same offset value.
5 Altering the value of a member will not affect 5. Altering the value of any of the member will
other members of the structure. alter other member values.
6. Individual member can be accessed at a time 6. Only one member can be accessed at a time.
7. Several members of a structure can initialize at 7. Only the first member of a union can be
once. initialized.

Q9. What is union? Write a program to print the record of student having maximum marks.
Structure student has following fields: Integer roll number, string student name, string class name,
integer marks.
Ans- A union is a special data type available in C that enables you to store different data types in the
same memory location. You can define a union with many members, but only one member can contain a
value at any given time. Unions provide an efficient way of using the same memory location for
multi-purpose.
Defining a Union: To define a union, you must use the union statement. Here is the way you would
define a union type named Data which has the three members i, f, and str. The format of the union
statement is as follows:
union Data
{
int i;
float f;
char str[20];
} data;
Now, a variable of Data type can store an integer, a floating-point number, or a string of characters. The
memory occupied by a union will be large enough to hold the largest member of the union. For example,
in above example Data type will occupy 20 bytes of memory space because this is the maximum space
which can be occupied by character string.

Accessing Union Members


To access any member of a union, we use the member access operator (.). The member access operator
is coded as a period between the union variable name and the union member that we wish to access.
data.i=10.
Program for displaying the record of student having maximum marks:
#include<stdio.h>
#include<conio.h>
void main()
{
struct student
{
int rn;
char name[20];
char clas[20];
int marks;
}s[10];
int i,pos=0,max;
clrscr();
for(i=0;i<10;i++)
{
printf("Enter roll number,name,class and marks\n");
scanf("%d%s%s%d",&s[i].rn,&s[i].name,&s[i].clas,&s[i].marks);
}
max=s[0].marks;
for(i=1;i<10;i++)
{
if(s[i].marks>max)
{
max=s[i].marks;
pos=i;
}
}
printf("\nRecord of student having maximum marks\n");
printf("\n%d\t%s\t%s\t%d",s[pos].rn,s[pos].name,s[pos].clas,s[pos].marks);
getch();
}

Q10. Differentiate array and structure. Write a program to print the names of player whose batting
average is greater than 50.Fields of structure (cricket) is name of player, name of country and
batting average of player.
Ans-

Difference between Array and Structure:

Array Structure

i. Data Collection

Array is a collection of homogeneous data. Structure is a collection of heterogeneous data.

ii. Element Reference

Array elements are referred by subscript. Structure elements are referred by its unique name.

iii. Access Method

Array elements are accessed by it's position or Structure elements are accessed by its object as '.'
subscript. operator.

iv. Data type

Array is a derived data type. Structure is user defined data type.

v. Syntax
struct struct_name
{
structure element 1;
structure element 2;
<data_type> array_name[size];
----------
----------
structure element n;
}struct_var_nm;

vi. Example

struct student
{
int abc[5]; int rollno;
char name[50];
}it;

// program to print name of player having batting average more than 50.
#include<stdio.h>
#include<conio.h>
struct cricket
{
float batting_average;
char player_name[20];
char country_name[20];
};
void main()
{
struct cricket c[50];
int i;
clrscr();
for(i=0;i<50;i++)
{
printf("enter batting average,name of player and name of country");
scanf("%f%s%s",&c[i].batting_average,&c[i].player_name,&c[i].country_name);
}
printf("\n Name of players who have batting average more than 50\n");
printf("\nPlayer Name\n");
for(i=0;i<50;i++)
{
if((c[i].batting_average)>50)
printf("\n%s",c[i].player_name);
}
getch();
}
Q11. Write sort notes on enum.
Ans-
An enumeration is a user-defined data type consists of integral constants and each integral constant is
given a name. Keyword enum is used to define enumerated data type.
enum type_name{ value1, value2,..., valueN };
Here, type_name is the name of enumerated data type or tag. And value1, value2,....,valueN are values of
type type_name.
By default, value1 will be equal to 0, value2 will be 1 and so on but, the programmer can change the
default value as below:
enum suit
{
club=0;
diamonds=10;
hearts=20;
spades=3;
};

Declaration of enumerated variable:


Above code defines the type of the data but, no variable is created. Variable of type enum can be created
as:
enum Boolean
{
false;
true;
};
enum boolean check;
Here, a variable check is declared which is of type enum boolean.
Example of enumerated type
#include <stdio.h>
enum week{ sunday, monday, tuesday, wednesday, thursday, friday, saturday};
int main()
{
enum week today;
today=wednesday;
printf("%d day",today+1);
return 0;
}
Output
4 day
Q12. What is string? Write a program to reverse a string using pointer.
Ans- String:- Strings in C are represented by arrays of characters. The end of the string is marked with a
special character, the (‘\0’ ) null character, which is simply the character with the value 0. .
For example, the following defines a string of 50 characters:
char name[50];
Program to reverse a string using pointer:
#include<stdio.h>
#include<conio.h>
void main()
{
char name[100];
void strrev1(char *);
int l;
clrscr();
printf("enter a string \n");
gets(name);
strrev1(name);
printf("After reverse string is :\n");
puts(name);
getch();
}

void strrev1(char *s)


{
int i=0;
char *l,t;
l=s;
while(*l!='\0')
{
i++;
l++;
}
l--;
i=i/2;
while(i>0)
{
t=*s;
*s=*l;
*l=t;
s++;
l--;
i--;
}

Q13. What is the importance of ‘\0’ in string? Write a program to concatenate two strings.
Ans-
In C, a string is a one-dimensional array of characters terminated a null character(‘\0’). The terminating
null character is important. In fact, a string not terminated by ‘\0’ is not really a string, but merely a
collection of characters.
Program for concatenate two strings using pointers:
#include<conio.h>
#include<stdio.h>
void main()
{
char str1[50],str2[20];
void strcon(char [],char []);
clrscr();
puts("enter string");
gets(str1);
printf("enter second string");
gets(str2);
strcon(str1,str2);
printf("after concatenate string is\n");
puts(str1);
getch();
}
void strcon(char *p,char *q)
{
while(*p!='\0')
p++;

while(*q!='\0')
{
*p=*q;
p++;
q++;
}
*p='\0';
}

Q14. Differentiate following:


4. gets( ) and scanf().
5. puts() and printf()
Ans-

Sr.No. scanf() gets()


1. It can be used for all data type like It is used only for string.
int, char, float, string
2. Multi word string can not be enter. Multi word string can be enter.
3. Many string can be enter at a time. Only one string can be enter at a time.
4. Formatted input function. Unformatted input function

Sr.No. printf() puts()


1. It can be used for all data type like It is used only for string.
int, char, float, string
2. After printing cursor remains on After printing cursor goes on next line
same line
3. Many string can be enter at a time. Only one string can be enter at a time.
4. Formatted input function. Unformatted input function

Q15: Explain any three string library function.


Ans:
1.strlen()- In the C Programming Language, the strlen() function returns the length of the string. It does
not include the null character in the length calculation.
Syntax:
The syntax for the strlen function in the C Language is:
size_t strlen (const char *s);
Parameters or Arguments
s The string whose length you want to calculate.
Returns
The strlen function returns the length of the string pointed to by s. It does not include the null character in
the length calculation.
Required Header: string.h
2. strcpy()-strcpy function copies the string pointed to by s2 into the object pointed to by s1. It returns a
pointer to the destination.
Syntax
The syntax for the strcpy function in the C Language is:
char *strcpy(char *s1, const char *s2);
Parameters or Arguments
s1 An array where s2 will be copied to.
s2 The string to be copied.
Returns
The strcpy function returns s1.
Required Header: string.h
3. strcat()- strcat function appends a copy of the string pointed to by s2 to the end of the string pointed
to by s1. It returns a pointer to s1 where the resulting concatenated string resides.
Syntax
The syntax for the strcat function in the C Language is:
char *strcat(char *s1, const char *s2);
Parameters or Arguments
s1 A pointer to a string that will be modified. s2 will be copied to the end of s1.
s2 A pointer to a string that will be appended to the end of s1.
Returns
The strcat function returns a pointer to s1 (where the resulting concatenated string resides).
Required Header: string.h

UNIT-5

Q1. What do you understand by dynamic memory allocation? Explain in detail.


Ans- Dynamic memory allocation-
The exact size of array is unknown until the compile time, i.e., time when a compiler compiles code
written in a programming language into a executable form. The size of array you have declared initially
can be sometimes insufficient and sometimes more than required. Dynamic memory allocation allows a
program to obtain more memory space, while running or to release space when no space is required.
There are 4 library functions under "stdlib.h" for dynamic memory allocation.
Function Use of Function

Allocates requested size of bytes and returns a pointer first byte of allocated
malloc()
space

Allocates space for an array elements, initializes to zero and then returns a
calloc()
pointer to memory

free() dellocate the previously allocated space

realloc() Change the size of previously allocated space

malloc()
The name malloc stands for "memory allocation". The function malloc() reserves a block of memory of
specified size and return a pointer of type void which can be casted into pointer of any form.
Syntax of malloc()
ptr=(cast-type*)malloc(byte-size)
Here, ptr is pointer of cast-type. The malloc() function returns a pointer to an area of memory with size of
byte size. If the space is insufficient, allocation fails and returns NULL pointer.
ptr=(int*)malloc(100*sizeof(int));
This statement will allocate either 200 or 400 according to size of int 2 or 4 bytes respectively and the
pointer points to the address of first byte of memory.
calloc()
The name calloc stands for "contiguous allocation". The only difference between malloc() and calloc() is
that, malloc() allocates single block of memory whereas calloc() allocates multiple blocks of memory
each of same size and sets all bytes to zero.
Syntax of calloc()
ptr=(cast-type*)calloc(n,element-size);
This statement will allocate contiguous space in memory for an array of n elements. For example:
ptr=(float*)calloc(25,sizeof(float));
This statement allocates contiguous space in memory for an array of 25 elements each of size of float, i.e,
4 bytes.
free()
Dynamically allocated memory with either calloc() or malloc() does not get return on its own. The
programmer must use free() explicitly to release space.
syntax of free()
free(ptr);
This statement cause the space in memory pointer by ptr to be deallocated.
realloc()
If the previously allocated memory is insufficient or more than sufficient. Then, you can change memory
size previously allocated using realloc().
Syntax of realloc()
ptr=realloc(ptr,newsize);
Here, ptr is reallocated with size of newsize.
Q2. Differentiate calloc() and malloc().Write a program to find sum of n integer numbers using
dynamic memory allocation.
Ans
malloc calloc

The name malloc stands for memory allocation. The name calloc stands for contiguous
allocation.
malloc() takes one argument that is, number of calloc() take two arguments those are: number
bytes. of blocks and size of each block.

syntax of malloc(): syntax of calloc():


void *malloc(size_t n); void *calloc(size_t n, size_t size);
Allocates n bytes of memory. If the allocation Allocates a contiguous block of memory large
succeeds, a void pointer to the allocated enough to hold n elements of size bytes each.
memory is returned. Otherwise NULL is The allocated region is initialized to zero.
returned.

malloc is faster than calloc. calloc takes little longer than mallocbecause of
the extra step of initializing the allocated
memory by zero.

#include <stdio.h>
#include <stdlib.h>
#include<conio.h>
void main()
{
int n,i,*ptr,sum=0;
printf("Enter number of elements: ");
scanf("%d",&n);
ptr=(int*)calloc(n,sizeof(int));// ptr=(int*)malloc(n*sizeof(int));
if(ptr==NULL)
{
printf("Error! memory not allocated.");
exit(0);
}
printf("Enter elements of array: ");
for(i=0;i<n;++i)
{
scanf("%d",ptr+i);
sum=sum + *(ptr+i);
}
printf("Sum=%d",sum);
free(ptr);
getch();
}
Q3. What do you understand by file handling? Write a program to copy contents of one file to
another file.
Ans- 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. FILE is inbuilt structure in c.
In C language, we use a structure pointer of FILE type to declare a file.

FILE *fp;
C provides a number of functions that helps to perform basic file operations like create, delete,
open, close, modify etc. Following are some functions:

Function description
fopen() create a new file or open a existing file
fclose() closes a file
getc() reads a character from a file
putc() writes a character to a file

#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp1,*fp2;
char ch,fname1[20],fname2[20];
printf("\n enter sourse file name");
gets(fname1);
printf("\n enter sourse file name");
gets(fname2);
fp1=fopen(fname1,"r");
fp2=fopen(fname2,"w");
if(fp1==NULL||fp2==NULL)
{
printf("unable to open");
exit(0);
}
do
{
ch=fgetc(fp1);
fputc(ch,fp2);
}
while(ch!=EOF);
fclose(fp1);
fclose(fp2);
getch();
}
Q4. What is file? Explain any five functions used in file handling.
Ans- File: A file is a collection of bytes stored on a secondary storage device, which is generally a disk of
some kind. The collection of bytes may be interpreted, for example, as characters, words, lines,
paragraphs and pages from a textual document; fields and records belonging to a database; or pixels from
a graphical image. The meaning attached to a particular file is determined entirely by the data structures
and operations used by a program to process the file.
FILE is inbuilt structure in c.

1. fopen()
FILE *fopen(const char *path, const char *mode);
The fopen() function is used to open a file and associates an I/O stream with it. This function takes two
arguments. The first argument is a pointer to a string containing name of the file to be opened while the
second argument is the mode in which the file is to be opened.
2.fread()
size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);
The function fread is used for reading data from the file opened by fopen function. This function accepts
three arguments.
3.fwrite()
size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream);
The function fwrite is used for writing data to the file opened by fopen function. This function accepts
three arguments.
4.fseek()
int fseek(FILE *stream, long offset, int whence);
The fseek() function is used to set the file position indicator for the stream to a new position. This
function accepts three arguments.
5.fclose()
int fclose(FILE *fp);
The fclose() function first flushes the stream opened by fopen() and then closes the underlying descriptor.

Q5.Write a program to read positive integer number from one file DATA.txt and copy even number
in second file EVEN.txt and copy odd number in third file ODD.txt.
Ans-
/*program to read integers numbers from data.txt file and write even number in even.txt and odd number
in odd.txt.*/
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp,*fo,*fe;
int n;
clrscr();
fp=fopen("DATA.TXT","r");
fo=fopen("ODD.TXT","w");
fe=fopen("EVEN.TXT","w");
if(fp==NULL||fo==NULL||fe==NULL)
{
printf("file can not open");
exit(0);
}
while((n=getw(fp))!=EOF)
{
if(n%2==0)
putw(n,fe);
else
putw(n,fo);
}
fclose(fp);
fclose(fo);
fclose(fe);
getch();
}

Q6. What is preprocessor? Explain various preprocessor directives.


Ans-
The preprocessor is a program that processes the source code before it passes through the compiler.
Before, the source code passes through the compiler .It is examined by the processor for any preprocessor
directives.Preprocessor directives follow special syntax rules. They all begin with the symbol # and do not
require a semicolon.

These directives can be divided into 3 categories:


1) Macro Substitution directive
2) File Inclusion Directive
3) Compiler Control Directive

MACRO SUBSTITUTION DIRECTIVE Function(Work)

#define Defines a macro substitution

#undef Undefines a macro

FILE INCLUSION DIRECTIVE Function(Work)


#include Specifies the file to be included

COMPILER CONTROL Function(Work)


DIRECTIVE
#if Test a compile time condition
#else Specifies alternatives when #if test fails
#endif Specifies the end of #if
#elif Chain of else if
#ifdef Tests whether the macro is defined
#ifndef Tests whether the macro is not defined

Q7. What do you mean by macro? Differentiate macro and function.


Ans-
Macro: A macro is a name given to a block of C statements as a pre-processor directive. Being a
pre-processor, the block of code is communicated to the compiler before entering into the actual coding
(main () function). A macro is defined with the preprocessor directive, #define.
A macro is a name given to a block of the code which can be substituted where the code snippet is to be
used for more than once.

Difference between macro and function


No Macro Function
1 Macro is Preprocessed Function is Compiled
2 No Type Checking Type Checking is Done
3 Code Length Increases Code Length remains Same
4 Speed of Execution is Faster Speed of Execution is Slower
5 Before Compilation macro name is replaced by During function call , Transfer of Control takes
macro value place
6 Useful where small code appears many time Useful where large code appears many time
7 Macro does not Check Compile Errors Function Checks Compile Errors

Q8. What do you understand by conditional compilation? Explain in detail.


Ans-Six directives are available to control conditional compilation. They delimit blocks of program text
that are compiled only if a specified condition is true. These directives can be nested. The program text
within the blocks is arbitrary and may consist of preprocessor directives, C statements, and so on. The
beginning of the block of program text is marked by one of three directives:

● #if
● #ifdef
● #ifndef

Optionally, an alternative block of text can be set aside with one of two directives:

● #else
● #elif

The end of the block or alternative block is marked by the #endif directive.

If the condition checked by #if , #ifdef , or #ifndef is true (nonzero), then all lines between the matching
#else (or #elif ) and an #endif directive, if present, are ignored.

If the condition is false (0), then the lines between the #if , #ifdef , or #ifndef and an #else , #elif , or
#endif directive are ignored.

Example1:

Lines of source code that may be sometimes desired in the program and other times not, are surrounded
by #ifdef, #endif directive pairs as follows:
#ifdef DEBUG
printf("debug:x = %d, y = %f\n", x, y);
...
#endif
The #ifdef directive specifies that if DEBUG exists as a defined macro, i.e. is defined by means of a
#define directive, then the statements between the #ifdef directive and the #endif directive are retained in
the source file passed to the compiler. If DEBUG does not exist as a macro, then these statements are not
passed on to the compiler.

Thus to ``turn on'' debugging statements, we simply include a definition:


#define DEBUG

Example2:

We can also use #if to test for the presence of a device, for example, so that if it is present, we can include
an appropriate header file.
#if DEVICE == MOUSE
#include mouse.h
#endif
Here, both DEVICE and MOUSE are assumed to be constant identifiers.

Thus to ``turn on'' debugging statements, we simply include a definition:


#define DEVICE MOUSE

Example3:

The #elif provides a multiway branching in conditional compilation analogous to else ... if in C. Suppose,
we wish to write a program that must work with any one of a variety of printers. We need to include in the
program a header file to support the use of a specific printer. Let us assume that the specific printer used
in an installation is defined by a macro DEVICE. We can then write conditional compilation directives to
include the appropriate header file.
#if DEVICE == IBM
#include ibmdrv.h
#elif DEVICE == HP
#include hpdrv.h
#else
#include gendrv.h
#endif
Only constant expressions are allowed in conditional compilation directives. Therefore, in the above code,
DEVICE, IBM, and HP must be defined constants.

Q9. What do you understand by header file in c program? Differentiate two file inclusion methods
#include<filename> and #include” file name “ .
Ans-A header file is a file with extension .h which contains all the constants, macros, system
wide global variables, and function prototypes and to be shared between several source files.
There are two types of header files: the files that the programmer writes and the files that
come with your compiler.
You request the use of a header file in your program by including it, with the C preprocessing directive
#include.
Difference between #include<filename> and #include” file name” :
Both user and system header files are included using the preprocessing directive #include.
It has following two forms:
(1) #include<file>
This form is used for system header files. It searches for a file named file in a standard list of system
directories. You can prepend directories to this list with the -I option while compiling your source code.

(2) #include”file”
This form is used for header files of your own program. It searches for a file named file in the directory
containing the current file. You can prepend directories to this list with the -I option while compiling your source
code.

Q10. Write short notes on following:


(i) typedef
(ii) Text v/s Binary files in file handling
(iii) Various modes in fopen() function.
Ans(i)- In C typedef is a keyword.
Keyword typedef stands for type definition.
It is used for create an alias name of existing data type. typedef is used by writing the keyword typedef,
followed by the existing data type and then the new name.
Syntax:
typedef existing_daya_type new_name ;
Example:
typedef char ch;
In above example, i has defined ch as char, so now i could perfectly use ch as declarations of any other
valid types:
ch yourchar;
ch mychar,*str;
Ans(ii)- Difference between Text File and Binary Files:
There are three main differences between Text files and binary file from the programmers point of view:
1. Handling of newlines: In text mode a newline character is converted into the carriage
return-linefeed combination before being written to the disk. However if the file is opened in
binary mode, no such conversion takes place.
2. Representation of end of files: in Text mode a special character EOF whose ASCII value is
26, is inserted after the last character in the file to marks the end of file. As against this there
is no such special character present in the binary mode. The binary file keep track of the end
of the file from the number of character present in the directory enrty of the file.
3. Storage of numbers: Storage of numbers in text file is inefficient as numbers are stored as
string of characters in Text mode.
Ans(iii)- There are 6 main types of file opening mode for text file:
"r"-Open file for reading and file must exist;
"w"- Open file for writing. If file does not exist it is created or if life already exist it's content is erased.
"a"-Open file for appending. It adds all information at the end of the file leaving old data untouched. If
file does not exist it is created.
"r+"- Open file for reading and writing and file must exist.
"w+"- Open file for writing and reading. If file does not exist it is created or if life already exist it's
content is erased.
"a+"- Open file for appending and reading. Again all new data is written at the end of the file old data
leaving untouched. If file does not exist it is created.
Note: for binary file same six mode with b.
Example ”rb”,”wb”,”ab”,”r+b”,”w+b”,”a+b”

Q11. Define command line argument.WAP to find sum of n integer numbers given as command line
argument.
Ans: Command line argument is a parameter supplied to the program when it is invoked.

Command line arguments are passed to the main() method.

Syntax:
int main(int argc, char *argv[])
Here argc counts the number of arguments on the command line and argv[ ] is a pointer array
which holds pointers of type char which points to the arguments passed to the program.
#include <stdlib.h>
#include <stdio.h>
# include <conio.h>
int main(int argc, char *argv[])
{ int a,b,sum=0;
int i; //for loop counter
for(i=1; i<argc; i++)
{
sum = sum+atoi (argv[i]);
}
printf("SUM =: %d\n",sum);
getch();
}

Q12: Explain linked list and self reference structure.

Ans: A linked list is a list of elements, which are connected together via links.

Linked list can be visualized as a chain of nodes, where every node points to the next node.

Linked List contains a head node have address of first node.


Each node carries a data field(s) and a link field called next.
Each node is linked with its next node using its next link.
Last node carries a link as null to mark the end of the list.
Code for node:
struct node
{
int info;
struct node *next;
};
Self Referential structures are those structures that have one or more pointers which point to the same
type of structure, as their member.
In other words, structures pointing to the same type of structures are self-referential in nature.
Example:
struct node
{
int data1;
char data2;
struct node *next;
};
In the above example ‘next’ is a pointer to a structure of type ‘node’. Hence, the structure ‘node’ is a
self-referential structure with ‘next’ as the referencing pointer.

Q13: WAP to find cube of number using macro.


#include<stdio.h>
#include<conio.h>
#define cube(n) (n*n*n)
void main()
{
int a,r;
clrscr();
printf(”enter number”);
scanf(”%d”,&a);
r=cube(a);
printf(”cube = %d”,r);
getch();
}

You might also like