0% found this document useful (0 votes)
86 views

1 List and Describe Various Parts of Computer Hardware. Ans

The document provides answers to various questions related to computer hardware and software components. It defines key hardware components like processors, motherboards, RAM, computer cases, power supplies, hard drives, video cards, network adapters, sound cards and optical drives. It also defines system software and application software, and provides examples. An algorithm to calculate the area of a triangle using Heron's formula is given. Pseudo code to find the largest of three numbers is also defined.

Uploaded by

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

1 List and Describe Various Parts of Computer Hardware. Ans

The document provides answers to various questions related to computer hardware and software components. It defines key hardware components like processors, motherboards, RAM, computer cases, power supplies, hard drives, video cards, network adapters, sound cards and optical drives. It also defines system software and application software, and provides examples. An algorithm to calculate the area of a triangle using Heron's formula is given. Pseudo code to find the largest of three numbers is also defined.

Uploaded by

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

Unit - 1 Assignment Solutions

1 List and describe various parts of computer hardware.


Ans:
Computers have two main parts: hardware and software
Major Hardware components are :
Processors
The processor directly affects overall computer performance, more than other
components such as the sound card or power supply.
When selecting a processor, some important considerations include the number of
cores, the clock speed of those cores, and the amount of cache memory.

Motherboards
The motherboard is the component that unifies the internal hardware. You will need to
ensure that the processor, memory, and other computer parts are compatible with the
motherboard.
Though the motherboard can affect system performance, it can be difficult to quantify
how much of an impact it has. Several important considerations include, the maximum
amount of memory supported, compatible processors, data interface standards, and
expansion card slots.

Random Access Memory (RAM)


Both the amount and speed of memory are quantifiable factors that directly affect
computer performance. Generally, the more memory a computer has, the better it will
be able to multitask. Faster memory can speed up tasks that require data to be
frequently loaded and retrieved.

Computer Cases
There are many different types of computer cases, from small portable ITX cases to
larger E-ATX cases for servers and workstations.
When selecting a case, you should consider how and where the computer will be used.
Also, determine if the case’s internal dimensions are adequate for the components that
you plan to use.
Power Supply Unit (PSU) or SMPS
Computer power supplies are components that connect to an electrical outlet and send
power to the individual computer parts. When selecting a power supply, you will need
to determine if can handle the total power requirement of all the components.
To do that, add up the power loads of all the internal components and ensure that the
PSU can supply at least that much power. It is recommended that you choose a power
supply well above that minimum for more flexibility.

Hard Drives
The hard drive is a data storage device that can be used to store the operating system,
programs, documents, and other important files. When selecting a hard drive, ensure
that it is compatible with the motherboard as well as being large and quick enough for
your needs.
Alternatively, you can use a solid state drive for increased data transfer speeds, lower
noise output, and better energy efficiency.

Video Cards
A video card is a required component, but many motherboards already have one built-
in. However, some tasks may require the use of a dedicated video card even if the
motherboard has onboard video capabilities. Tasks such as 3D rendering and simulation
can sometimes require the use of workstation-grade video cards.

Network Adapters
While not required for the computer to be used, network connectivity is necessary for
internet and local area network (LAN) access. Some motherboards have network
adapters built into them, so separate adapters are not always required.
There are two main types of network adapters, internal and external. Internal network
adapters utilize expansion slots while external variants are usually USB.

Sound Cards
Many desktop motherboards have sound cards built-in, allowing for audio playback
without the need for a dedicated sound card. However, the quality of these built-in
sound cards is generally not on par with high-end dedicated sound cards. For tasks that
require high definition audio playback, dedicated sound cards are usually better than
onboard solutions.

Optical Drives
An optical drive is beneficial for many uses, including backing up data, installing
software, and playing multimedia content. Before shopping for an optical drive however,
you should check what type of data connector the motherboard utilizes and if any are
available for use.

2 List and describe types of computer software.


Ans:

Typically, there are two major classifications of software, namely System Software and
Application Software.

Definition:
1. System Software can be designed as the software in such a way so that it can control and
work with computer hardware. It acts as an interface between the device and the end user.
It also provides the platform for the running of other software
Examples of System software are:
i) Operating systems
ii) Device Drivers
iii) Language compilers and interpreters

i) Operating systems:
Basically, the OS coordinates the different hardware components of a computer.
It performs operations like process management, memory management, I/O
management etc.
There are many OS in the market. There are several operating systems are available.
Ex: Windows, Linux, Unix, Xenix, MacOS, Android etc.

ii) Device Drivers


These are the software which supports the Operating System.
Driver software is a type of system software so that we can use our devices smoothly
without any troubleshooting problem. This type of software enables the components
to perform their tasks as directed by the OS.
There are some examples of devices which requires drivers:
• Mouse
• Keyboard
• Touch pad
• Printer
• Display card
• Network card
• Sound
Some tools are there, whose drivers are already installed on the computer by default
for ex-mouse, keyboard and touchpad.
If the device is new for the operating system like the printer, then we have to install
the drivers so that it get familiar with the OS. We can install them from the websites.

iii) Programming Language Translators


These are convert the high-level language and middle-level language into machine
language as machine understands only its language. The high-level language is the
language through which the user interacts with the computer. Java, C, C++, PHP,
Python all are the examples of high-level language. Machine language is the code
which is understood by the processor only. The average human being cannot be able
to understand it. With these we can create system development software as well.
Some famous translators are Compiler, Interpreter and assembler. They are designed
by the manufacturers of the computer. Translators can completely translate the code
into machine code at once, or they can do it line by line.
2. Application Software:
Application Software: It enables the end users to accomplish certain specific tasks.
Business software, databases and educational software are some forms of application
software. Different word processors, which are dedicated for specialized tasks to be
performed by the user, are other examples of application software.
Application software is broken in to two classes:
i) general-purpose software
ii) application – specific software.

General purpose software is purchased from a software developer and can be used
for more than one application.
Examples of general purpose software include word processors, database
management systems ,and computer aided design systems. They are labeled general
purpose because they can solve a variety of user computing problems.

Application–specific software can be used only for its intended purpose. A general
ledger system used by accountants and a material requirements planning system
used by a manufacturing organization are examples of application-specific software.
They can be used only for the task for which they were designed they cannot be used
for other generalized tasks.

3 Define algorithm and write an algorithm to calculate the area of a triangle.


Ans:

Definition:
An algorithm is a finite set of instructions to accomplish a particular task in a given
problem. In other words, it is a step by step procedure to solve a problem. There are
time and space complexity associated with each algorithm.
Time complexity specifies the amount of time required by an algorithm to perform a
desired task.
The space complexity specifies the amount of memory space required by the
algorithm to perform the desired task.
Important criteria for algorithms are as follows: (Characteristics of Algorithms)
1. Input
2. Output
3. Finiteness
4. Definiteness
5. Solvable

Algorithm for calculating area of a triangle:


Using Heron's Formula
Step 1: Start
Step 2: Read Side1, Side2, Side3
Step 3: Calculate semi perimeter s = (side1 + side2 + side3) / 2
Step 4: Calculate Area = sqrt (s * (s – side1) * (s – side2) * (s – side3))
Step 5: Print Area
Step 6: Stop

4 Define pseudo code and write a pseudo code to find the largest of three numbers.
Ans:
Definition:
Pseudo code is an informal way of programming description that does not require
any strict programming language syntax or underlying technology considerations.
It is similar to algorithm, and can be easily convertible to any programming
language.
Pseudo code can be broken down into five components.
• Variables:
• Assignment:
• Input/output:
• Selection:
• Repetition:
A variable has a name, a data type, and a value. There is a location in memory
associated with each variable. A variable can be called anything or be given any
name. It is considered good practice to use variable names that are relevant to the
task at hand.
Assignment is the physical act of placing a value into a variable. Assignment can be
shown using
set = 5;
set = num + set;
The left side is the variable a value is being stored in and the right side is where the
variable is being accessed. When a variable is assigned a value, the old value is
written over with the new value so the old value is gone. x = 5 does not mean that x
is equal to 5; it means set the variable x to have the value 5. Give x the value 5, make
x equal to 5.

Input / Output both deal with an outside source (can be a user or another program)
receiving or giving information. An example would be assuming a fast food
restaurant is a program. A driver (user) would submit their order for a burger and
fries (input), they would then drive to the side window and pick up their ordered
meal (output.)
• Output – Write / display / print
• Input – Read / get / input
Selection construct allows for a choice between performing an action and skipping it.
It is our conditional statements.
Selection statements are written as such:
if ( conditional statement)
statement list
else
statement list

Repetition is a construct that allows instructions to be executed multiple times (i.e.


repeated).
In a repetition problem
– Count is initialized
– Tested
– incremented
Repetition problems are shown as:
while ( condition statement)
statement list

Pseudo code for finding the largest of three numbers:

READ three numbers and store it in n1,n2,n3


IF n1>n2
IF n1>n3
WRITE "n1 is Maximum"
ELSE
WRITE "n3 is Maximum"
ENDIF
ELSE
IF n2>n3
WRITE "n2 is Maximum"
ELSE
WRITE "n3 is Maximum"
ENDIF

5 Describe a Flowchart? Show the symbols used in a flow chart with an example each.
Ans:
 Flowchart is a graphical representation of an algorithm.
 Flowchart is the diagrammatic representation of an algorithm. It is constructed
with different types of symbols and boxes. The operation to be performed is
written inside the box. All symbols are connected by arrows among themselves to
indicate the flow of information and processing.
 The symbols used in flowcharts have been standardized by the American
National Standards Institute. Arrows are used on the connecting flow lines if the
direction of flow is not clear. A flowchart should have one start and one or more
stop points and should be arranged so that the direction of processing is from
top to bottom and from left to right. Although flowlines can cross, the crossing
flowlines are independent of each other. Whenever possible, crossing of flowlines
should be avoided, since it makes the flowchart difficult to read.

Oval Terminal Start/Stop/Begin/End

Parallellogram Input/Output Making the


data
available(input)

for processing
Rectangle Process Any processing is
performed.
Represents computations
and data manipulations
Diamond Decission Represents the
branching to
alternative paths
based on a test

Circle On-page Connects two or more


Connector flows into one

Off-page Connects flows on


connector different pages

Directional Flow Represent


Arrows direction of
processing

6 Describe the steps involved in program development.


Ans:
Program Development steps/ Execution of C Program Execution of C program
involves the following steps.
1. Creating the program
2. Compiling the program
3. Linking the program
4. Executing the program
Those steps can be pictorially represented with following flow chart.

Creating phase:
i. We can create a C program in any text editor or any any integrated
environment. i.e., the code must be entered into a file.
ii. The created program is called as source code.
iii. Once the editing or creating is over, we have to save the file. For Ex:
“filename.c”
iv. The File must have an extentionof “.c” for every c program file.

Compiling phase:

i. The edited/created program must be compiled with the help of c compiler.


ii. Compiler translates the source code into object code(i.e. machine
understandable code).
iii. If any syntax errors are found the errors will be dispalyed. We have to edit the
program, save again and we have to compile till the syntax errors are
eliminated.
iv. If there are no errors, the compiler generates the object code. Ex:
“filename.obj”

Linking phase:

i. The object file has to be linked with system libraries.


ii. Linking is the process of putting all functins together with object code with
the help of system libraries. For Ex: printf funnction (available in stdio.h
library).
iii. Now the object code is ready for the next phase i.e execution phase. And it
will create a executable file with extention of “.exe” For Ex: “filename.exe”

Execution phase:

i. In this phase the executable object code is loaded into the memory and the
program execution begins.
ii. At the time of execution, we may get some logical errors or run time errors.
iii. If any logical errors are found, we have to re edit the program and proceed to
all pahses again.
iv. If we gave any wrong data as the input, we have to re run (execute) the exe
file to give the coorect data as input to get the correct output.
7 List the different types of computer languages. Describe them briefly.
Ans:

Types of computer Languages:


1940’s Machine level Languages
1950’s Symbolic Languages/Assembly Languages 1960’s High-Level Languages

Machine Language:
At the lowest level computer understands only 0 and 1. Programs expressed in terms
of binary language are called machine language. A computer’s programming
language consists of strings of binary numbers (0’s and 1’s) and is the only one
language computer can understand. This language is the lowest level of computer
language recognized and used by the CPU. An instruction prepared in any machine
language consists of 2 parts. The first part is the command or opcode or operation
code. The second part of the instruction is the operand/s or data and it tells the
processor where to find or store the data or other instructions that are manipulated.
A short sample of machine language to perform addition in the storage location
0166 will look like this
00010000 00000001 01100010
A machine language programmer has to know the binary code for each operation to
be carried out. Machine language programmers must also be familiar with the
internal organization of the computer. A machine language programmer must also
keep track of all the addresser of main memory locations that are referred to in the
program. The machine language format is slow and tedious. We the human beings
work on natural language and not on binary language. Hence writing machine
language program is difficult for the humans.

The off state can be represented by 0 and the on state can be represented by 1. Each
0 or 1 digit is referred to as a bit.
 A bit is a single 0 or 1 in binary code.
 A byte is a sequence of 8 bits. Each byte could also be represented as a decimal
number from 0 to 255.

Advantages:

i) Works very fast


ii) Directly deals with the Processors.

Disadvantages:

i) Different instruction sets are required for different hardware


ii) Machine language is that it is totally confusing and unreadable. Nobody want to
memorize all these sequences of 0’s and 1’s.

Assembly language:
In the 1950’s, the first symbolic languages were created. The idea was to have each
type of instruction represented by some intuitive code word, and to allow data to be
represented as decimal numbers. Here is an excerpt from a symbolic language
program:
LDA 9000
MOV B,A
MOV C,A
HLT
An assembler is a special program used to translate symbolic code into machine
code. Symbolic languages also became known as assembly languages.
Assembler is used to convert assembly language into the machine language.
For example object program or machine language equivalent for the above assembly
language is 01110 0100001100
01110011101
0111110000
1011100000

Advantages:
i. Assembly language programs are commonly used to write programs for electronic
controls using microprocessors e.g., compilers, operating systems, animation in
computer graphics and so on.
ii. Assembly language is relatively easy for the human beings compared to machine
language. Programs writing are faster compared to machine language.
Disadvantages:
1. Assembly language programmer should know details of the architecture of the
machine. Assembly language programs are not portable.
2. Machine, symbolic and high level languages

High Level Language:


Assembly languages are easier to program than machine languages. However, there
is still approximately a one to one correspondence between assembly language
instructions and machine language instructions, and there needs to be a different
assembly language for each type of computer. To avoid these problems, high-level
languages were developed.
Instructions which are written using English language with symbols and digits are
called high level languages. The high level language is closer to our natural
language. The commonly used high level languages are FORTRAN, BASIC, COBOL,
PASCAL, PROLOG, C, C++ etc. The complete instruction set written in one of these
languages is called a high level language program or computer program or source
program.

Three benefits of high-level languages:


1. More powerful instructions; each may translate to several machine language
instructions.
2. Portable to many different computers.
3. Simpler to understand and use.

Procedure Oriented Languages:


High level languages designed to solve general purpose problems and they are called
procedural languages. They are designed to express logic and procedure of a
problem.

Ex: C, Fortran, Pascal, COBOL etc

Problem oriented languages:

They are used to solve specific problems and they are known as fourth generation
languages. Generally these languages uses WYSIWYG( What You See Is What You
Get) environment

For ex: Querry languages like SQL, Visual C++, Visual BASIC etc.,

Natural Languages:

Natural Languages behave like an expert to solve problems and tend to use artificial
intelligence. These languages are called Fifth Generation Languages and still they are
in developmental stage.

Ex: LISP and Prolog are having the characteristics and features of such languages.

8 Describe briefly about how interpreter and compiler work with the help of a neat
block diagram.
Ans:

High Level Language:


Assembly languages are easier to program than machine languages. However, there
is still approximately a one to one correspondence between assembly language
instructions and machine language instructions, and there needs to be a different
assembly language for each type of computer. To avoid these problems, high-level
languages were developed.
Instructions which are written using English language with symbols and digits are
called high level languages. The high level language is closer to our natural
language. The commonly used high level languages are FORTRAN, BASIC, COBOL,
PASCAL, PROLOG, C, C++ etc. The complete instruction set written in one of these
languages is called a high level language program or computer program or source
program.
In order to execute the instructions, the source program is translated into binary
form by a compiler or interpreter. A compiler is also used to translate source
program into an object program. An interpreter is a program which takes the source
program line by line and converts into machine code line by line. .
C language uses a compiler as its translator to translate or compile the complete C
program. It is also necessary to create an executable program to execute the
instructions given in a source program by linking the input and output devices with
your program. A linker (another program) is used to link library routing and generate
an executable program from an object program. Compiler converts source program
into object program in terms of stages called passes. Normally, most of the
compilers use two passes to convert source program into the machine language
program.

Translators used:
Compiler & Interpreter
Compiler:

Compilers convert the program instructions from human understandable form to the
machine understandable form and the translated program instruction is called object
code. Compiler is nothing but a language translator used to translate the entire
program of the high level language into machine language. Every programming
language requires its own compiler to translate the program. For example, the
programming language PASCAL requires PASCAL compiler and C uses C compiler.

Interpreter:
Interpreters also convert the source program to machine language instruction but
execute each line as it is entered. The translation of the source program takes place
for every run and is slower than the compiled code. An interpreter must accompany
the object code to run a program. Programming languages BASIC, Python and LISP
use interpreters.
GW BASIC is an interpreter used to convert basic program into object program.

9 Describe the structure of C program with an example.


Ans:
Documentaion Section /* comments of a program */  multi line comments
// Single line comments  Single line comments
Header Files Section #include <stdio.h> /* #include is a preprocessor directive
through which we can include header
files */
#include <math.h>
….
….
…..
Definition Section # define pi 3.1415 /* Here we can define some symbolic
constants
Global variable int var1, var2 …..varn;
Declaration
Section
main Function Section main()
{ {
Declaration section int x=10;
float a =
5.25;
Executable statements printf(“The value of x is =%d, the value of a= %f”,x,a);
}

}
Sub program add (int x, int y)
Section Or {
User Defined Function --------
Section ---------
}

10 List the different data types along with their sizes in C, also give example for each.
Ans:
 C data types are defined as the data storage format that a variable can store a
data to perform a specific operation.
 Data types are used to define a variable before to use in a program.
 Size of variable, constant and array are determined by data types.
C data types can be classified in to the following categories.
Type Data types
Basic Data Type int, char, float, double
Derived Data Type array, pointer, structure, union
Enumeration Data Type enum, typedef
Void Data Type void

on a 4-byte compiler
Modifier Type Size max-value min-value
(bytes)
signed Char 1 127 (27-1) -128 (-27)
Unsigned char 1 255 (28-1) 0
signed int 4 2147483647 (231-1) -2147483648 (-231)
Unsigned int 4 4294967295 (232-1) 0
signed long 8 9223372036854775807 (263-1)-9223372036854775808 (-
263)
Unsigned long 8 18446744073709551615 (264- 0
1)
float 4 3.4*1038 1.4*10-45
double 8 1.7*10308 4.9*10-324

on a 2-byte compiler
Modifier type Size max-value min-value
(bytes)
signed char 1 127 (27-1) -128 (-27)
unsigned char 1 255 (28-1) 0
signed int 2 32767 (215-1) -32768 (-215)
unsigned int 2 65535 (216-1) 0
signed long 4 2147483647 (231-1) -2147483648 (-231)
unsigned long 4 4294967295 (232-1) 0
float 4 3.4*1038 1.4*10-45
double 8 1.7*10308 4.9*10-324

Data Type Format Specifier


int %d
char %c
float %f
double %lf
short int %hd
unsigned int %u
long int %li
long long int %lli
unsigned long int %lu
unsigned long long int %llu
signed char %c
unsigned char %c
long double %Lf

11 Describe the different types of constants in C with appropriate examples?


Ans:
TYPES OF C CONSTANT:
1. Integer constants
2. Real or Floating point constants
3. Octal & Hexadecimal constants
4. Character constants
5. String constants
6. Backslash character constants
Constant type data type (Example)
Integer constants int (53, 762, -478 etc )
unsigned int (5000u, 1000U etc)
long int, long long int
(483,647 2,147,483,680)
Real or Floating point constants float (10.456789)
doule (600.123456789)
Octal constant int (Example: 013 /*starts with 0 */)
Hexadecimal constant int (Example: 0x90 /*starts with 0x*/)
character constants char (Example: ‘A’, ‘B’, ‘C’)
string constants char (Example: “ABCD”, “Hai”)

RULES FOR CONSTRUCTING C CONSTANT:


1. INTEGER CONSTANTS IN C:
 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.

2. REAL CONSTANTS IN C:
 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.

3. CHARACTER AND STRING CONSTANTS IN C:


 A character constant is a single alphabet, a single digit or a single special symbol
enclosed within single quotes.
 The maximum length of a character constant is 1 character.
 String constants are enclosed within double quotes.

4. BACKSLASH CHARACTER CONSTANTS IN C:


 There are some characters which have special meaning in C language.
 They should be preceded by backslash symbol to make use of special function of
them.
 Given below is the list of special characters and their purpose.

Backslash_character Meaning
\b Backspace
\f Form feed
\n New line
\r Carriage return
\t Horizontal tab
\” Double quote
\’ Single quote
\\ Backslash
\v Vertical tab
\a Alert or bell
\? Question mark
\N Octal constant (N is an octal constant)
\XN Hexadecimal constant (N – hex.dcml cnst)

12 i) Define a variable? List the rules for naming the variables. [4M]
Ans:
Variables
In programming, a variable is a container (storage area) to hold data. To indicate the
storage area, each variable should be given a unique name (identifier). Variable names
are just the symbolic representation of a memory location. A variable can change its
value in the course of a program.
For example:
int age = 25;
char gender = ‘M’;
Rules for naming a variable
The following are the rules for declaring the variables. Rules for constructing variable
names
1. The first character of the variable name must either be alphabet or underscore. It
should not start with the digit
2. No commas and blanks are allowed in the variable name
3. No special symbols other than underscore are allowed in the variable name
4. They can take maximum of length 31 characters.
5. Upper case and lower case variables are different i.e., int a is different from int A.

ii) Give examples for decimal, octal, hexadecimal integer literals. [3M]
Ans:
Literals
Literals are data used for representing fixed values. They can be used directly in the
code. For example: 1, 2.5, 'c' etc.
Here, 1, 2.5 and 'c' are literals. Why? You cannot assign different values to these terms.
Integers
An integer is a numeric literal(associated with numbers) without any fractional or
exponential part. There are three types of integer literals in C programming:
decimal (base 10)
octal (base 8)
hexadecimal (base 16)
For example:
Decimal: 0, -9, 22 etc
Octal: 021, 077, 033 etc
Hexadecimal: 0x7f, 0x2a, 0x521 etc
In C programming, octal starts with a 0, and hexadecimal starts with a 0x.

13 Describe Arthimetic Operators and write a C program to find the roots of quadratic
equation.
Ans:
Arithmetical Operators

In some cases we need to perform addition, subtraction, multiplication, division


and modulo division operations which are called Arithmetical operations. These are
performed by using the arithmetical operators in C.
There are two types of arithmetical operators. They are
 Unary operators
 Binary operators.
Unary operators
An operator manipulates on only one operand is called as Unary operator. The
following are the some of the unary operators in C.
The following are the some of the unary operators in C.
Operator Description Example
- Unary minus x=-2
++ Unary Increment x++ or ++x
-- Unary Minus x—or –x
& Address operator &x
sizeof Gives the size of the sizeof(x)
variable
Binary Operators
An operator which takes minimum of two operands is called as a binary
operator. Syntax: operand1 operator operand2;
Example: a + b;
These operators are commonly used in the most of the programming languages. The
following are the available arithmetical operators in C.
Operator Description Example
+ Addition a+b
- Subtraction a-b
* Multiplication a*b
/ Division a/b
% Modulo Division a%b

Program for roots of quadratic equation:


#include <math.h>
#include <stdio.h>
int main() {
double a, b, c, discriminant, root1, root2, realPart, imagPart;
printf("Enter coefficients a, b and c: ");
scanf("%lf %lf %lf", &a, &b, &c);
discriminant = b * b - 4 * a * c;
// condition for real and different roots
if (discriminant > 0) {
root1 = (-b + sqrt(discriminant)) / (2 * a);
root2 = (-b - sqrt(discriminant)) / (2 * a);
printf("root1 = %.2lf and root2 = %.2lf", root1, root2);
}
// condition for real and equal roots
else if (discriminant == 0) {
root1 = root2 = -b / (2 * a);
printf("root1 = root2 = %.2lf;", root1);
}
// if roots are not real
else {
realPart = -b / (2 * a);
imagPart = sqrt(-discriminant) / (2 * a);
printf("root1 = %.2lf+%.2lfi and root2 = %.2f-%.2fi", realPart, imagPart, realPart,
imagPart);
}
return 0;
}
14 Describe Relational Operators and write a C program to illustrate all the Relational
Operators.
Ans:
Relational operators are used to compare values of two expressions. Relational
operators are binary operators because they require two operands to operate. An
expression which contains the relational operators is called relational expression. If the
relation is true then the result of the relational expression is 1, if the relation is false then
the result of the relational expression is 0.

The following table lists relational operators along with some examples:
Operator Description Example Result
> Greater than 1>2 0
>= Greater than or equal to 3 >= 2 1
< Smaller than 10 < 5 0
<= Smaller than or equal to 6 <= 7 1
== equal to 98==98 1
!= not equal to 10 != 9 1

In C, all non-zero values are considered as true while 0 is considered as false.


The following program demonstrates relational operators in action:
#include<stdio.h>
int main()
{
int x = 12, y = 13;

printf("x = %d\n", x);


printf("y = %d\n\n", y);

// Is x is greater than y?
printf("x > y : %d\n", x > y);

// Is x is greater than or equal to y?


printf("x >= y : %d\n", x >= y);

// Is x is smaller than y?
printf("x < y : %d\n", x < y);

// Is x is smaller than or equal to y?


printf("x <= y : %d\n", x <= y);

// Is x is equal to y?
printf("x == y : %d\n", x == y);

// Is x is not equal to y?
printf("x != y : %d\n", x != y);

// Signal to operating system everything works fine


return 0;
}
Expected Output:
x = 12
y = 13

x>y:0
x >= y : 0
x<y:1
x <= y : 1
x == y : 0
x != y : 1

15 List and describe logical operators in C and write a C program to check whether a
given year is leap year or not.
Ans:
Logical Operators in C
Logical operators are used to evaluate two or more conditions. In General, Logical
operators are used to combine relational expressions, but they are not limited to just
relational expression you can use any kind of expression even constants. If the result of
the logical operator is true then 1 is returned otherwise 0 is returned.
There are three types of logical operators:
Operator Meaning
&& AND operator
|| OR operator
! NOT operator

The AND ( && ) and OR ( || ) are binary operator while NOT ( ! ) is a unary operator.
In C, all non-zero values are considered as true ( 1 ) while 0 is considered as false.
AND(&&) operator
This operator gives the net result of true (i.e 1) if both operands are true, otherwise false
(i.e 0).
Operand 1 Operand Result
2
true true true
true false false
false true false
false false false

examples:
Expression Intermediate Expression Result
Result
(a==4) && (b==2) false && false => false 0 OR(||) operator
(a>100) && (b<10) false && true => false 0 This operator gives the net
a && b true && true => true 1 result of true (i.e 1) if at
a && 0 true && false => false 0 least one operand is true,
otherwise false.
Operand 1 Operand 2 Result
true true true
true false true
false true true
false false false

Expression Intermediate Expression Result


(a==4) || (b==2) false || false => false 0
(a>10) || (b<10) false || true => true 1
a || b true || true => true 1
a || 12.12 true || true => true 1
Note that the parentheses are used in above two expression to improve readability,
certainly the expression (a==4) && (b==2) is more readable than a==4 && b==2.
Notice that in the last statement second operand is of type double which is perfectly
acceptable.
The most important thing about the OR(||) operator is that if the first operand evaluates
to true, then the second operator is not evaluated.
!(NOT) operator
The ! (not) operator negates the value of the condition. If the condition is false then it
becomes true, if it is true then it becomes false. Unlike && (AND) and || (OR) operator,
the ! (NOT) operator is unary.
Operand Result
true false
false true

Example:
Expression Intermediate Result
Expression
!(a==4) !false => true 1
!(a || b) !true => false 0
!(a && b) !true => false 0
!(a > b) !true => false 0

Program for checking the given year is a leap year or not:


#include <stdio.h>
int main()
{
int y;

printf("Enter year: ");


scanf("%d",&y);

if(y % 4 == 0)
{
//Nested if else
if( y % 100 == 0)
{
if ( y % 400 == 0)
printf("%d is a Leap Year", y);
else
printf("%d is not a Leap Year", y);
}
else
printf("%d is a Leap Year", y );
}
else
printf("%d is not a Leap Year", y);

return 0;
}

Output:
Enter year: 1991
1991 is not a Leap Year

16 Explain different variations of increment and decrement operators in C with


examples.
Ans:
Increment and Decrement Operators in C

C has two special unary operators called increment (++) and decrement (--) operators.
These operators increment and decrement value of a variable by 1.
Increment and decrement operators can be used only with variables.
They can’t be used with constants or expressions.

int x = 1, y = 1;
++x; // valid
++5; // invalid - increment operator operating on a constant value
++(x+y); // invalid - increment operating on an expression

Increment/Decrement operators are of two types:


1. Prefix increment/decrement operator.
2. Postfix increment/decrement operator.

Prefix increment/decrement operator

The prefix increment/decrement operator immediately increases or decreases the


current value of the variable. This value is then used in the expression. Let’s take an
example:

y = ++x;
Here first, the current value of x is incremented by 1. The new value of x is then assigned
to y. Similarly, in the statement:
y = --x;
the current value of x is decremented by 1. The new value of x is then assigned to y.
The following program demonstrates prefix increment/decrement operator in action:

#include<stdio.h>

int main()
{
int x = 12, y = 1;

printf("Initial value of x = %d\n", x); // print the initial value of x


printf("Initial value of y = %d\n\n", y); // print the initial value of y

y = ++x; // increment the value of x by 1 then assign this new value to y

printf("After incrementing by 1: x = %d\n", x);


printf("y = %d\n\n", y);

y = --x; // decrement the value of x by 1 then assign this new value to y

printf("After decrementing by 1: x = %d\n", x);


printf("y = %d\n\n", y);

// Signal to operating system everything works fine


return 0;
}

Expected Output:
Initial value of x = 12
Initial value of y = 1

After incrementing by 1: x = 13
y = 13

After decrementing by 1: x = 12
y = 12

Postfix Increment/Decrement operator


The postfix increment/decrement operator causes the current value of the variable to be
used in the expression, then the value is incremented or decremented. For example:
1 y = x++;
Here first, the current value of x is assigned to y then x is incremented.
Similarly, in the statement:
1 y = x--;
the current value of x is assigned to y then x is decremented.
The following program demonstrates postfix increment/decrement operator in action:
#include<stdio.h>

int main()
{
int x = 12, y = 1;

printf("Initial value of x = %d\n", x); // print the initial value of x


printf("Initial value of y = %d\n\n", y); // print the initial value of y

y = x++; // use the current value of x then increment it by 1

printf("After incrementing by 1: x = %d\n", x);


printf("y = %d\n\n", y);

y = x--; // use the current value of x then decrement it by 1

printf("After decrementing by 1: x = %d\n", x);


printf("y = %d\n\n", y);

// Signal to operating system everything works fine


return 0;
}
Expected Output:
Initial value of x = 12
Initial value of y = 1

After incrementing by 1: x = 13
y = 12

After decrementing by 1: x = 12
y = 13

17 Explain about assignment operator and its variations in C with examples.


Ans:
Assignment operators are used to assigning value to a variable. The left side operand of
the assignment operator is a variable and right side operand of the assignment operator
is a value. The value on the right side must be of the same data-type of the variable on
the left side otherwise the compiler will raise an error.

Different types of assignment operators are shown below:

“=”: This is the simplest assignment operator. This operator is used to assign the value
on the right to the variable on the left.

For example:
a = 10;
b = 20;
ch = 'y';

“+=”: This operator is combination of ‘+’ and ‘=’ operators. This operator first adds the
current value of the variable on left to the value on the right and then assigns the result
to the variable on the left.

Example:
(a += b) can be written as (a = a + b)
If initially value stored in a is 5. Then (a += 6) = 11.

“-=”This operator is combination of ‘-‘ and ‘=’ operators. This operator first subtracts
the current value of the variable on left from the value on the right and then assigns the
result to the variable on the left.

Example:
(a -= b) can be written as (a = a - b)
If initially value stored in a is 8. Then (a -= 6) = 2.

“*=”This operator is combination of ‘*’ and ‘=’ operators. This operator first multiplies
the current value of the variable on left to the value on the right and then assigns the
result to the variable on the left.

Example:
(a *= b) can be written as (a = a * b)
If initially value stored in a is 5. Then (a *= 6) = 30.
“/=”This operator is combination of ‘/’ and ‘=’ operators. This operator first divides the
current value of the variable on left by the value on the right and then assigns the result
to the variable on the left.

Example:
(a /= b) can be written as (a = a / b)

If initially value stored in a is 6. Then (a /= 2) = 3.

Below example illustrates the various Assignment Operators:

// C program to demonstrate
// working of Assignment operators

#include <stdio.h>

int main()
{

// Assigning value 10 to a
// using "=" operator
int a = 10;
printf("Value of a is %d\n", a);

// Assigning value by adding 10 to a


// using "+=" operator
a += 10;
printf("Value of a is %d\n", a);

// Assigning value by subtracting 10 from a


// using "-=" operator
a -= 10;
printf("Value of a is %d\n", a);

// Assigning value by multiplying 10 to a


// using "*=" operator
a *= 10;
printf("Value of a is %d\n", a);

// Assigning value by dividing 10 from a


// using "/=" operator
a /= 10;
printf("Value of a is %d\n", a);

return 0;
}

Output:
Value of a is 10
Value of a is 20
Value of a is 10
Value of a is 100
Value of a is 10

18 Explain about conditional operator and write a C Program to find the maximum of
three numbers.
Ans:
The Conditional operator the ternary operator (?:) is just like an if-else statement that
can be with in an expression. This operator is useful in situations, in which two or
more alternatives for an expression. They make the program code more compact.
The Syntax is :
exp1 ? exp2 : exp3

Here expression 1 is evaluated 1st. If it is true, then expression 2 is evaluated and


becomes the result of the expression, otherwise expression3 is evaluated and
becomes the output of the expression.

Ex1: To find the largest of two numbers


large = ( a > b) ? a : b;
Since conditional operator is itself an expression, it can be used as an operand of
another conditional operation. This means you can have nested conditional
expressions.
Ex2: To find the smallest of three numbers
int a = 5, b = 4, c = 7, small;
Small = ( a < b ? ( a < c ? a : c) : (b < c ? b : c) );

Program to find largestof three numbers using ternary operator:


#include<stdio.h>
void main()
{
int a,b,c,large;
printf("enter three numbers:");
scanf("%d %d %d",&a,&b,&c);
large=(a>b)?((a>c)?a:c):((b>c)?b:c);
printf("\n the biggest number is %d\n",large);
}
Execution and Expected Output
$ cc ternary.c
$./a.out
Enter three numbers: 4 5 6
The biggest number is 6

19 Explain the use of printf() and scanf() function in C. Illustrate with an example.
Ans:
 printf() and scanf() functions are inbuilt library functions in C programming
language which are available in C library by default. These functions are declared
and related macros are defined in “stdio.h” which is a header file in C language.
 We have to include “stdio.h” file as shown in below C program to make use of
these printf() and scanf() library functions in C language.
printf() function:
• In C programming language, printf() function is used to print the “character,
string, float, integer, octal and hexadecimal values” onto the output screen.
• We use printf() function with %d format specifier to display the value of an
integer variable.
• Similarly %c is used to display character, %f for float variable, %s for string
variable, %lf for double and %x for hexadecimal variable.
• To generate a newline,we use “\n” in C printf() statement.
Example for printf():
#include <stdio.h>
int main()
{
char ch = 'A';
char str[20] = "fresh2refresh.com";
float flt = 10.234;
int no = 150;
double dbl = 20.123456;
printf("Character is %c \n", ch);
printf("String is %s \n" , str);
printf("Float value is %f \n", flt);
printf("Integer value is %d\n" , no);
printf("Double value is %lf \n", dbl);
printf("Octal value is %o \n", no);
printf("Hexadecimal value is %x \n", no);
return 0;
}
Output:
Character is A
String is fresh2refresh.com
Float value is 10.234000
Integer value is 150
Double value is 20.123456
Octal value is 226
Hexadecimal value is 96

SCANF() FUNCTION IN C LANGUAGE:


 In C programming language, scanf() function is used to read character, string,
numeric data from keyboard
 Consider below example program where user enters a character. This value is
assigned to the variable “ch” and then displayed.
 Then, user enters a string and this value is assigned to the variable “str” and
then displayed.
Example Program for scanf():
#include <stdio.h>
int main()
{
char ch;
char str[100];
printf("Enter any character \n");
scanf("%c", &ch);
printf("Entered character is %c \n", ch);
printf("Enter any string ( upto 100 character ) \n");
scanf("%s", &str);
printf("Entered string is %s \n", str);
}

Output:
Enter any character
a
Entered character is a
Enter any string ( upto 100 character )
hai
Entered string is hai
20 Explain the purpose of #include in a C program and write a C Program to find the
squareroot of a given number.
Ans:
In the C Programming Language, the #include directive tells the preprocessor to
insert the contents of another file into the source code at the point where the
#include directive is found. Include directives are typically used to include the C
header files for C functions that are held outsite of the current source file.

Syntax
The syntax for the #include directive in the C language is:
#include <header_file>
OR
#include "header_file"

header_file
The name of the header file that you wish to include. A header file is a C file that
typically ends in ".h" and contains declarations and macro definitions which can be
shared between several source files.

Note
The difference between these two syntaxes is subtle but important. If a header file is
included within <>, the preprocessor will search a predetermined directory path to
locate the header file. If the header file is enclosed in "", the preprocessor will look
for the header file in the same directory as the source file.

/**
* C program to find square root of a number
*/

#include<stdio.h>
#include<math.h>
int main()
{
int number;
double result;

printf("Enter any integer number: ");


scanf("%d",&number);

result = sqrt(number);
printf("Square root value=%.2lf",result);

return 0;
}

Output:

Enter any integer number: 25


Square root value=5.00

Enter any integer number: 30


Square root value=5.48
Unit 1 3 Marks Questions
1 Write a C program to calculate Compound interest.
2 Write a C program to Swap Two numbers with out using a third variable.
3 Write down the algorithm for exchanging the values of two variables a and b
assigned to them.
4 Write pseudocode for finding the factorial of a given number.
5 Draw a flowchart for finding the factorial of a given number.
6 Draw a flowchart for finding the maximum of three numbers.
7 Write a C program to print the Digit at ones place of a given number.
8 Write a C program to convert the temperature from Fahrenheit to Celsius.
9 Write the access specifiers for short int, long double,unsigned int, hexadeciamal.
10 Can we compile and execute C program without using #include<stdio.h> .Justify
11 Write a C program to find the average of three numbers.
12 Write a C program to perform Addition,Multiplication, and Division of two numbers.
13 Illustrate a C program to swap two integer values without using a third variable.
14 Illustrate a C program to swap two integer values without using bit wise operators.
15 Write the difference between &(address operator) , &&(Logical And operator)
describe their operator precendences and also illustrating with code snippets how
they are used.
16 Evaluate the output for the following:
int main(){
int a=10;
printf("%d%d%d%d",i++,++i,i--,--i);
}
17 Write a C program to convert the given temperature from Celsius to Fahrenheit
18 Write the difference between assignment equals to (=) , comparison equals to (==)
and show with code snippets how they are used.
19 Write a C program to calculate Simple interest.
20 Evaluate the output for the following:
int main(){
int a,b,c;
printf("%d",scanf("%d%d%d",&a,&b,&c));
printf("%d",printf("MVGR"));
}
UNIT 2 Q and A 7 Marks
1. List the bitwise operators available in C and give one example for each
Ans:
Bitwise operators are used to manipulate data at bit level (binary data).
Bitwise operators can be applied only to operands of integer type i.e char,
int, signed, unsigned and long.
C provides six bitwise operators as given below:
Operat Description
or
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
(XOR)
<< Bitwise Left shift
>> Bitwise Right shift
~ One's Complement

Bitwise AND (&) operator:


The syntax for using a Bitwise AND (&) operator is:
operand1 & operand2
where operand1 and operand2 should be of integral type.
It sets a bit to 1 if and only if both the corresponding bits in its operands
are 1, and to 0 if the bits differ or both are 0.
Truth Table for Bitwise AND(&):
A B A&B
0 0 0
0 1 0
1 0 0
1 1 1
For example 1010 & 1100 will result in 1000.
10 ⟹ 1010
&
12 ⟹ 1100
-------
1000 ⟹ 8
-------
Bitwise OR (|) operator:

The syntax for using a Bitwise OR (|) operator is:


operand1 | operand2

where operand1 and operand2 should be of integral type. It sets a bit


to 1 if one or both the bits in its operands are 1, and to 0 if both the bits
are 0.

Truth Table for Bitwise OR (|):


A B A|B
0 0 0
0 1 1
1 0 1
1 1 1

For example, 1010 | 1100 will result in 1110.


10 ⟹ 1010
|
12 ⟹ 1100
-------
1110 ⟹ 14
-------
Bitwise XOR (^) Operator:
The syntax for using a Bitwise XOR (^) operator is:
operand1 ^ operand2
where operand1 and operand2 should be of integral type.
It sets the bit to 1 where the corresponding bits in its operands are different,
and to 0 if they are the same.
Truth Table for Bitwise Exclusive OR (^):
A B A^B
0 0 0
0 1 1
1 0 1
1 1 0
For example 1010 ^ 1100 will result in 0110.
10 ⟹ 1010
^
12 ⟹ 1100
-------
0110 ⟹ 6
-------

bitwise left-shift (<<) operator:


The syntax for using a bitwise left-shift (<<) operator is:
operand1 << operand2
where operand1 should be of integral type and operand2 should also be an
integral number which indicates the number of positions that should be
shifted to the left in operand1.
The value of number << bits to be shifted is number left-shifted by bits to be
shifted bit positions. This is equal to multiplying operand1 by 2.
The two examples given below show the usage of bitwise left-shift operator
(<<) on decimal 3:
Decimal 3 in binary is 11.
Hence, 11 << 1 will result in 110, i.e, 3 << 1 = 3 X 2  = 6.
1

Similarly, 11 << 2 will result in 1100, i.e, 3 << 2 = 3 X 2  = 12.


2

bitwise right-shift (>>) operator:


The syntax for using a bitwise right-shift (>>) operator is:
operand1 >> operand2
where operand1 should be of integral type and operand2 should also be
an integer which indicates the number of bits that should be shifted to
the right in operand1.
The value of number >> bits to be shifted is number right-shifted by bits to
be shifted bit positions while preserving the sign. The resulting value is equal
to the rounded up value of number / 2.
For non-negative values of number, this is equivalent integer division,
i.e. number / 2.
The two examples given below show the usage of bitwise right-shift operator
(>>) on decimal 15:
Decimal 15 in binary is 1111.
Hence, 1111 >> 1 will result in 111, i.e, 15 >> 1 = 15 / 2  = 7.
1

Similarly 1111 >> 2 will result in 11, i.e, 15 >> 2 = 15 / 2  = 3.


2

Bitwise one's complement (~) operator :


The format for usage of one's complement (~) operator is:
~operand
where operand should be of primitive integral type.
This operator works on the binary representation of the given number.
It flips all the 1's to 0's and 0's to 1's respectively.
For example, if the ~ operator is applied to the binary number 110, the
result will be 001.
Truth Table for Bitwise NOT (~):
A ~A
0 1
1 0

2. i) Describe the left shift and right shift operators in C with suitable
examples and usage.
Ans:
The bitwise shift operators are used to move/shift the bit patterns
either to the left or right side. Left and right are two shift operators
provided by 'C' which are represented as follows:
Operand << n (Left Shift)
Operand >> n (Right Shift)
Here, an operand is an integer expression on which we have to
perform the shift operation.
'n' is the total number of bit positions that we have to shift in the
integer expression.
The left shift operation will shift the 'n' number of bits to the left side.
The leftmost bits in the expression will be popped out, and n bits with
the value 0 will be filled on the right side.
It performs multiplication
The right shift operation will shift the 'n' number of bits to the right
side. The rightmost 'n' bits in the expression will be popped out, and
the value 0 will be filled on the left side.
Example: x is an integer expression with data 1111. After performing
shift operation the result will be:
x << 2 (left shift) = 1111<<2 = 1100
x>>2 (right shift) = 1111>>2 = 0011
Shifts operators can be combined then it can be used to extract the
data from the integer expression.
A program to demonstrate the use of bitwise shift operators:
#include <stdio.h>
int main() {
int a = 20; /* 20 = 010100 */
int c = 0;

c = a << 2;/* 80 = 101000 */


printf("Left shift - Value of c is %d\n", c );

c = a >> 2;/*05 = 000101 */


printf("Right shift - Value of c is %d\n", c );
return 0;
}
Output:
Left shift - Value of c is 80
Right shift - Value of c is 5
After performing the left shift operation the value will become 80
whose binary equivalent is 101000.
After performing the right shift operation, the value will become 5
whose binary equivalent is 000101.

ii) Describe bit masks. Illustrate their purpose with an example.


Ans:
Masking is the process or operation to set bit on to off or off to on in a
byte,nibble or word. Mask means to block. Masking is the process by
which ,only required data is retained and the rest is masked (blocked)
Masking can be done using Bitwise Operators. Most Commonly Used
Bitwise Operator is AND(&)
Literary meaning of Mask means to hide, and in programming it does the
same thing. In programming masking is used at bit level. means mostly
data is used in terms of bytes like char holds 1 byte, int hold 2 bytes. 1
byte = 8 bits.
So masking is used at bit level. say we have 8 LED connected through
some circuit. now to control 8 LED ON/OFF we will use bit level
programming, say initially all LEDS were ON, now I want to put OFF first 4
LED, so lets C how this works in C programming.

Say we have variable LED = 0b11111111 ——-> ALL LED ON


now to turn OFF first 4 LED we will mask 4 initial bits. Here bitwise AND
operation will help us, as 0 AND 1 = 0, 1 AND 1 = 1, so lets say we use
this
LED = LED & 0b00001111 ;
LED = 0b00001111 (output) now our result is achieved, first four LED get
turned OFF
Similarly we can use XOR to toggle these LED means if it ON, make it OFF,
and vice a versa.
Lets see how it toggles, Lets say I have LED = 0b01010101
now XOR functions 0 XOR 1 = 0, 1 XOR 1 = 0, 0 XOR 0 = 0, so here we
use LED XOR with all 1’s
It should be 0 XOR 1 = 1
LED = LED XOR 0b11111111 (Remember LED new values)
LED = 0b10101010
#include<stdio.h>
void main()
{
int LED = 0xFF;
printf("The original value before masking = %x\n",LED);
LED = LED & 0xF0;
printf("The value of ter masking = %x\n",LED);

LED = 0x55;
printf("The original value before toggle = %x\n",LED);
LED = LED ^ 0xFF;
printf("Toggle Values after toggle = %x\n",LED);
}
Output:
The original value before masking = ff 11111111
The value of ter masking = f0 11110000
The original value before toggle = 55 01010101
Toggle Values after toggle = aa 10101010

3. Define expression. Illustrate with at-least 3 suitable examples expressions


that include unary, binary and ternary operators.
Ans:
An expression is a combination of variables constants and operators
written according to the syntax of C language. In C every expression
evaluates to a value i.e., every expression results in some value of a
certain type that can be assigned to a variable.

Algebraic Expression C Expression


axb–c a*b–c
(m + n) (x + y) (m + n) * (x + y)
(ab / c) a*b/c
3x2 +2x + 1 3*x*x+2*x+1
(x / y) + c x/y+c

Evaluation of Expressions
Expressions are evaluated using an assignment statement of the form
Variable = expression;
Variable is any valid C variable name. When the statement is
encountered, the expression is evaluated first and then replaces the
previous value of the variable on the left hand side. All variables used in
the expression must be assigned values before evaluation is attempted.
Example of evaluation statements are:
x=a*b–c
y=b/c*a
z = a – b / c + d;
Example of Expression with unary operator:
Unary expression requires only one operand.
For example :
Ex1:
int a = 5;
a++;
here a requires only one operator i.e. ++ and it evaluates as a = a+1;
Ex2:
int a = 10;
~a;
Here also ~ requires only one operand i.e a and it will be evaluated as a=
1010 and it becomes 0101

Example of expression with binary operator:


In this the expression requires minimum two operands to work with
For ex:
int a=5, b=10;
c=a+b;
here + requires two operands a and b
Example of Expression using ternary operator:
int a=10, b=15,big;
big=(a>b)?a:b;
In this expression (?:) ternary operator requires three operands ((a>b), a,
b).
In the above case big will be placed with the value of because the first
expression is evaluated as false
4. Define type casting. Describe implicit and explicit type casting with
examples.
Ans:
Typecasting is converting one data type into another one. It is also called
as data conversion or type conversion. It is one of the important concepts
introduced in 'C' programming.
'C' programming provides two types of type casting operations:
Implicit type casting
Explicit type casting
Implicit Type Conversion
It is also known as ‘automatic type conversion’.
 Done by the compiler on its own, without any external trigger from the
user.
 Generally takes place when in an expression more than one data type
is present. In such condition type conversion (type promotion) takes
place to avoid lose of data.
 All the data types of the variables are upgraded to the data type of the
variable with largest data type.
 char -> short int -> int -> unsigned int -> long -> unsigned -> long
long -> float -> double -> long double
 It is possible for implicit conversions to lose information, signs can be
lost (when signed is implicitly converted to unsigned), and overflow
can occur (when long long is implicitly converted to float).
Example:
#include<stdio.h>
int main()
{
int x = 10; // integer x
char y = 'a'; // character c

// y implicitly converted to int. ASCII


// value of 'a' is 97
x = x + y;

// x is implicitly converted to float


float z = x + 1.0;

printf("x = %d, z = %f", x, z);


return 0;
}
Output:
x = 107, z = 108.000000

Explicit typecasting:
This process is also called type casting and it is user defined. Here the
user can type cast the result to make it of a particular data type.
The syntax in C:
(type) expression
Type indicated the data type to which the final result is converted.
// C program to demonstrate explicit type casting
#include<stdio.h>

int main()
{
double x = 1.2;

// Explicit conversion from double to int


int sum = (int)x + 1;
printf("sum = %d", sum);

return 0;
}
Output:
sum = 2
Advantages of Type Conversion
 This is done to take advantage of certain features of type
hierarchies or type representations.
 It helps us to compute expressions containing variables of different
data types.

5. Define operator precedence and associativity. Using at-least 3 expression


examples having operators with more than one operators, illustrate how
order of evaluation of expressions is dictated by operator precedence and
associativity.
Ans:
Operator precedence and associativity
Each operator in C has a precedence associated with it. The precedence is
used to determine how an expression involving more than one operator is
evaluated. There are distinct levels of precedence and an operator may
belong to one of these levels. The operators of higher precedence are
evaluated first. The operators of same precedence are evaluated from
right to left or from left to right depending on the level. This is known as
associativity property of an operator.
Example 1:
Operator precedence determines which operator is performed first in an
expression with more than one operators with different precedence.
For example: Solve
10 + 20 * 30
10 + 20 * 30 is calculated as 10 + (20 * 30) and not as (10 + 20) * 30
Ex2:
Operators 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”.

Example 3:
For example: Solve
100 + 200 / 10 - 3 * 10

6. List all the operators in C according to their order of precedence.


Ans:
The table given below gives the precedence of each operator.
Orde Category Operat Operation Associativit
r or y
1 Highest ( ) Function call L ? R
precedence [ ] Left to
? Right
: :
.
2 Unary ! Logical negation R -> L
~ (NOT) Right ->
+ Bitwise 1’s Left
- complement
++ Unary plus
- - Unary minus
& Pre or post
* increment
Size of Pre or post
decrement
Address
Indirection
Size of operant in
bytes
3 Member Access .* Dereference L ->R
?* Dereference
4 Multiplication * Multiply L -> R
/ Divide
% Modulus
5 Additive + Binary Plus L -> R
- Binary Minus
6 Shift << Shift Left L -> R
>> Shift Right
7 Relational < Less than L -> R
<= Less than or equal to
> Greater than
>= Greater than or
equal to
8 Equality == Equal to L ->R
!= Not Equal to
9 Bitwise AAND & Bitwise AND L ->R
10 Bitwise XOR ^ Bitwise XOR L ->R
11 Bitwise OR | Bitwise OR L -> R
12 Logical AND && Logical AND L -> R
14 Conditional ?: Ternary Operator R -> L
15 Assignment = Assignment R -> L
*= Assign product
%= Assign reminder
/= Assign quotient
+= Assign sum
-= Assign difference
&= Assign bitwise AND
^= Assign bitwise XOR
|= Assign bitwise OR
<<= Assign left shift
>>= Assign right shift
16 Comma , Evaluate L -> R

7. Explain different types of if statements with examples.


Ans:
In a 'C' program are executed sequentially. This happens when there is no
condition around the statements. If you put some condition for a block of
statements the flow of execution might change based on the result
evaluated by the condition. This process is referred to as decision making
in 'C.' The decision-making statements are also called as control
statements.
In 'C' programming conditional statements are possible with the help of
the following three constructs:
In C, We have the following types of if statements:
i) if
ii) if else
iii) else-if ladder
Note: All of them can be nested
If statement:
It is one of the powerful conditional statement. If statement is
responsible for modifying the flow of execution of a program. If statement
is always used with a condition. The condition is evaluated first before
executing any statement inside the body of If.
The syntax for if statement is as follows:
Statement x;
if (condition)
{
Statement Block;
}
Statement y;
The condition evaluates to either true or false. True is always a non-zero
value, and false is a value that contains zero. Instructions can be a single
instruction or a code block enclosed by curly braces { }.
It is a one way selection statement.
Ex:
int num1=1;
int num2=2;
if(num1<num2) //test-condition
{
printf("num1 is smaller than num2");
}

If else statement:
If else is a two way selection statement.

The syntax for if else statement is:


Statement x;
if (test-expression)
{
True block of statements;
}
else
{
False block of statements;
}
Statement y;
Ex:
int n=5;
if(n%2==0)
printf(“%d is an Even Number\n”,n);
else
printf(“%d is an Odd Number\n”,n);

This is evaluated as false and the output will be:


5 is an Odd number

if-else ladder:
The if else ladder statement in C programming language is used to test
set of conditions in sequence. An if condition is tested only when all
previous if conditions in if-else ladder is false. If any of the conditional
expression evaluates to true, then it will execute the corresponding code
block and exits whole if-else ladder.
Example Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int a;
printf(“Enter a number : “);
scanf(“%d”,&a);
if(a > 0)
{
printf(“\nThe number is positive “);
}
else if(a<0)
{
printf(“\n The number is negative”);
}
else
{
printf(“Number is zero”);
}
}
Output:
Enter a number : 25
The number is positive
8. Explain Nested if with syntax and write a C program to find the largest of
three numbers using nested if.
Ans:
Nesting means using one if-else construct within another one.
If we use if statement in another if statement, we can call it as nested if
statement.
The syntax of nested if statement is :
Statement x;
if( condition-1)
{
if( condition-2)
{
Statement Block 1
}
else
{
Statement Block 2;
}
}
else
{
if(condition-3)
{
Statement Block 3
}
else
{
Statement Block 4;
}
}
Statement y;

//Program for finding the largest of given 3 nos. using nested if


statements:
#include <stdio.h>
void main()
{
int a,b,c,max;
printf("Enter 3 integers : ");
scanf("%d %d %d",&a, &b, &c);
if(a>b)
{
if(a>c)
max=a;
else
max=c;
}
else
{
if(b>c)
max=b;
else
max=c;
}
printf("Largest of three numbers is : %d\n",max);
}
Output:
Enter 3 integers : 6 5 4
Largest of three numbers is : 6
9. Explain the syntax of a switch statement with an example.
Ans:
A switch statement tests the value of a variable and compares it with
multiple cases. Once the case match is found, a block of statements
associated with that particular case is executed.
Each case in a block of a switch has a different name/number which is
referred to as an label or identifier. The value provided by the user is
compared with all the cases inside the switch block until the match is
found.
If a case match is found, then the default statement is executed, and the
control goes out of the switch block.
Syntax:
switch( expression )
{
case value-1:
Block-1;
Break;
case value-2:
Block-2;
Break;
case value-n:
Block-n;
Break;
default:
Block-1;
Break;
}
Statement-x;

Syntax Explanation:
 The expression can be integer expression or a character expression.
 Value-1, 2, n are case labels which are used to identify each case
individually. Remember that case labels should not be same as it
may create a problem
 Case labels always end with a colon ( : ). Each of these cases is
associated with a block.
 A block is nothing but multiple statements which are grouped for a
particular case.
 Whenever the switch is executed, the value of test-expression is
compared with all the cases which we have defined inside the
switch.
 The break keyword in each case indicates the end of a particular
case. If we do not put the break in each case then even though the
specific case is executed, the switch will continue to execute all the
cases until the end or (break) is reached. Break will terminate the
case once it is executed and the control will fall out of the switch.
 The default case is an optional one. Whenever the value of test-
expression is not matched with any of the cases inside the switch,
then the default will be executed.
 Once the switch is executed the control will go to the statement-x,
and the execution of a program will continue.
Program:
#include <stdio.h>
int main()
{
int language = 5;
switch (language)
{
case 1: printf("C#\n"); break;
case 2: printf("C\n"); break;
case 3: printf("C++\n"); break;
default: printf("Other programming language\n");
}
}
Output:
Other programming language
10. Write a C program to read two numbers and an arithmetic operator.
Using switch case perform the required arithmetic operations and display
the results.
Ans:
#include<stdio.h>
void main()
{
int a, b;
char op;
printf("Enter two integer values : ");
scanf("%d %d", &a, &b);
printf("Enter an arithmetic operator : ");
scanf(" %c", &op);
switch (op)
{
case '+': printf("%d + %d = %d\n", a, b, a+b);
break;
case '-': printf("%d - %d = %d\n", a, b, a-b);
break;
case '*': printf("%d * %d = %d\n", a, b, a*b);
break;
case '/': if (b != 0)
printf("%d / %d = %d\n", a, b, a/b);
else
printf("Division is not possible! Divide by zero error\
n");
break;
case '%': if (b != 0)
printf("%d %% %d = %d\n", a, b, a%b);
else
printf("Modulo division is not possible! Divide by zero
error\n");
break;
default: printf("Error! Operator is not correct\n");
}
}
Output:
Enter two integer values : 10 3
Enter an arithmetic operator : %
10 % 3 = 1
11. Explain while loop syntax with an example program.
Ans:
while loop in C:
A while loop statement in C programming language repeatedly executes a
target statement as long as a given condition is true.
Syntax:
The syntax of a while loop in C programming language is:
Statement x;
while( condition)
{
Statement1;
Statement2;
.
. Statement Block
.
Statementn;
Updation;
}
Statement y;
After executing Statement x, Condition will be evaluated first. The
condition may be any expression, and true is any nonzero value. The loop
iterates while the condition is true. Here, statement(s) may be a single
statement or a block of statements. The statement block consists of
updating statement also.
When the condition becomes false, program control passes to the line
immediately following the loop in this case, Statement y;.
Example program:
#include <stdio.h>
void main()
{
int count=1;
while (count <= 4)
{
printf("%d ", count);
count++;
}
}
Output:
1234
step1: The variable count is initialized with value 1 and then it has been
tested for the condition.
step2: If the condition returns true then the statements inside the body of
while loop are executed else control comes out of the loop.
step3: The value of count is incremented using ++ operator then it has
been tested again for the loop condition.
12. Describe while loop and write a C program to find the factorial of a given
number using while loop.
Ans:
C while loops statement allows to repeatedly run the same block of code
until a condition is satisfied. If the condition becomes false, the loop
terminates.
while loop is a most basic loop in C programming. while loop has one
control condition, and executes as long the condition is true. The
condition of the loop is tested before the body of the loop is executed,
hence it is called an entry-controlled loop.
The syntax for while loop is:
statement x;
while (condition)
{
statement(s);
updation;
}
statement y;
Here, statement(s) may be a single statement or a block of statements.
The condition may be any expression,
and true is any nonzero value. The loop iterates while the condition is
true.
When the condition becomes false, program control passes to the line
immediately following the loop.
Flow Diagram:

Here, key point of the while loop is that the loop might not ever run. When
the condition is tested and the result is false, the loop body will be
skipped and the first statement after the while loop will be executed.
C program to find the factorial of a given number:
#include <stdio.h>
void main()
{
int n,i=1,fact=1;
printf("Enter a Number : ");
scanf("%d", &n);
while(i<=n)
{
fact=fact * i;
i = i + 1;
}
printf("Factorial of %d = %d\n",n, fact);
}

Output:
Enter a Number: 6
Factorial of 6 = 720
13. Explain do-while loop syntax with an example program.
Ans:
C do while loops are very similar to the while loops, but it always executes
the code block at least once and furthermore as long as the condition
remains true.
Unlike for and while loops, which test the loop condition at the top of the
loop, the do...while loop in C programming language checks its condition
at the bottom of the loop.
This is an exit-controlled loop.
Syntax of do while loop:
Statement x;
do
{
statement(s);
updation;
} while ( condition );
Statement y;
Notice that the conditional expression appears at the end of the loop, so
the statement(s) in the loop execute once before the condition is tested.
If the condition is true, the flow of control jumps back up to do, and the
statement(s) in the loop execute again. This process repeats until the
given condition becomes false.
Flow Diagram:

Example:
//C Program to find sum of ‘N’ natural numbers:
#include <stdio.h>
void main()
{
int N, i=1, sum=0;
printf("Enter N value: ");
scanf("%d", &N);
do
{
sum+=i;
i++;
} while (i<=N);
printf("Sum of %d Natural Nos = %d\n",N, sum);
}
Output:
Enter N value: 10
Sum of 10 Natural Nos = 55

14. Write a C program to print the sum of all even and odd numbers using
do-while loop.
Ans:
#include <stdio.h>
void main( )
{
int n,oddsum=0,evensum=0,i,x;
printf("Enter No. of elements : ");
scanf("%d", &n);
printf("Enter %d numbers: ", n);
for(i=1;i<=n;i++)
{
scanf("%d",&x);
if(x%2 == 0)
evensum+=x;
else
oddsum+=x;
}
printf("Sum of all Odd Numbers = %d\n",oddsum);
printf("Sum of all Even Numbers = %d\n",evensum);
}
Output:
Enter No. of elements : 6
Enter 6 numbers: 1 2 3 4 5 6
Sum of all Odd Numbers = 9
Sum of all Even Numbers = 12
15. Explain for loop construct with syntax and illustrate its usage with an
example.
Ans:
A for-loop is used to iterate over a range of values using a loop counter,
which is a variable taking a range of values in some orderly sequence (e.g.,
starting at 0 and ending at 5 in increments of 1).
The value stored in a loop counter is changed with each iteration of the loop,
providing a unique value for each individual iteration. The loop counter is
used to decide when to terminate the loop.
A for-loop construct can be termed as an entry controlled loop.
Syntax of a for-loop :
for (initialization; condition; update)
{
statement(s);
}
1. The initialization expression initializes the loop counter; it is executed
once at the start of the loop.
2. The loop continues to execute as long as the condition expression
evaluates to true.
3. The update expression is executed after each iteration through the
loop, to increment, decrement or change the loop counter.
Example with code :
int i;
for (i = 1; i < =5; i++)
{
printf("%d\n",i);
}
Output:
1
2
3
4
5
Explanation:
1. Above for-loop statement initializes an integer variable i (which is the
loop counter) as part of the initialization expression.
2. In the update section, it increments the variable i by 1 using the post-
increment expression i++.
3. The expression in condition is i <=5. The for-loop keeps on executing
the code inside the loop body as long as this condition evaluates to
true. And the loop terminates when the condition evaluates to false.
4. It is a good practice to always keep the loop body (which contains the
code to be executed) within an opening-brace { and a closing-brace }.
Note : No ; at the end of the for statement.
16. Write a C program to print the pyramid with numbers.
Ans:
#include <stdio.h>
void main()
{
int i,j,k,n;
printf(“Enter Number of rows: “);
scanf(“%d”,&n);
for(i=1; i<=n; i++)
{
for(k=1; k<=n-i; k++)
printf(" ");
for(j=1; j<=i; j++)
printf("%2d",i);
printf("\n");
}
}

Output:
Enter Number of rows: 5
1
22
333
4444
55555
17. Describe the purpose of break statement with a suitable program.
Ans:
The break statement terminates the loop immediately when it is
encountered.
In switch statement it will be used to terminate each block.
Its syntax is:
break;
The break statement is almost always used with if...else statement inside the
loop.
The working process of break statement in loops:

Example Program:
#include <stdio.h>

void main()
{
int i,j,k=1,n;
printf("Enter a number to stop: ");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
for(j=1;j<=i;j++)
{
if(k<=n)
printf("%3d",k++);
else
{
i=n;
break;
}
}
printf("\n");
}
}

Output:
Enter a number to stop: 13
1
2 3
4 5 6
7 8 9 10
11 12 13
In the above program inner for loop will breaks with bellow code
if(k<=n)
printf("%3d",k++);
else
{
i=n;
break;
}
18. Describe the purpose of continue statement with a suitable example.
Ans:
The continue statement skips the current iteration of the loop and
continues with the next iteration.
Its syntax is:
continue;
The continue statement is almost always used with the if...else statement.
The working process of continue in loops:
Example Program for continue:
// Program to calculate the sum of a maximum of 10 numbers
// Negative numbers are skipped from the calculation

# include <stdio.h>
void main()
{
int n, i, sum = 0;
printf(“Enter 10 numbers: “);
for(i=1; i <= 10; ++i)
{
scanf("%d",&n);
if(n < 0)
{
continue;
}
sum += n; // sum = sum + number;
}
printf("Sum = %d\n",sum);
}
Output:
Enter 10 numbers: 2 -3 5 1 20 -10 3 15 -24 -2
Sum = 46.

In the above program continue makes the sum+= n statement omits when
the n is –ve number.
19. Define event controlled loops. Illustrate the same with suitable code
snippet.
Ans:
Event controlled loop
1. Here we don't know how many times loop is going to work
2. An event changes loop expression to be evaluated from true to false.
3. Example: when we read the data loop expression may be evaluated to
true. But, we encounter the end of the input. Loop expression may be
evaluated to false.
4. Sine series, palindrome, finding lcm and gcd are some of the examples
for event control loop programs.
Example Program.
//C program to find the GCD and LCM of two integers using Euclids' algorithm
#include <stdio.h>
void main()
{
int n1, n2, gcd, lcm, rem, numerator, denominator;
printf("Enter two numbers\n");
scanf("%d %d", &n1, &n2);
if (n1 > n2)
{
numerator = n1;
denominator = n2;
}
else
{
numerator = n2;
denominator = n1;
}
rem = numerator % denominator;
while (rem != 0)
{
numerator = denominator;
denominator = rem;
rem = numerator % denominator;
}
gcd = denominator;
lcm = n1 * n2 / gcd;
printf("GCD of %d and %d = %d\n", n1, n2, gcd);
printf("LCM of %d and %d = %d\n", n1, n2, lcm);
}
Output:
Enter two numbers: 24 8
GCD of 24 and 8 = 8
LCM of 24 and 8 = 24
In the above program we don’t know how many times the while loop will be
repeated. It will run until the remainder is not equals to 0 and stops when the
condition is false (which is an event).

20. Define counter controlled loops. Illustrate the same with suitable code
snippet.
Ans:
Counter controlled loop:
1. Here we know how many times loop is going to work.
2. Sum of n natural numbers, Fibonacci series these are examples for
counter controlled loop programs.
Example Program:
// Program to print Fibonacci series up to n terms
#include <stdio.h>
void main()
{
int a, b, c, i, terms;

/* Input number from user */


printf("Enter number of terms: ");
scanf("%d", &terms);

/* Fibonacci magic initialization */


a = 0;
b = 1;
c = 0;
printf("Fibonacci terms: \n");

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


{
printf("%d, ", c);

a = b; // Copy n-1 to no2


b = c; // Copy current to no-1
c = a + b; // New term
}
}

Output:
Enter number of terms: 5
01123

Here We know that the for loop is going to be executed ‘n’ times with the
help of a counter variable ‘i’, hence it is a counter controlled loop.
Unit 3_1 Assignment Question and Answers

1 Explain integer 1D array with suitable example code snippets illustrating


declaring, initializing and accessing of the array.
Ans:
Array is a simple data structure which can store collection of elements of
same data type. All elements are stored in the contiguous memory. An
array is used to store a collection of data, but it is often more useful to
think of an array as a collection of variables of the same type. Instead of
declaring individual variables, such as number0, number1, ..., and
number99, you declare one array variable such as numbers and use
numbers[0], numbers[1], and ..., numbers[99] to represent individual
variables. A specific element in an array is accessed by an index.

All arrays consist of contiguous memory locations. The lowest address


corresponds to the first element and the highest address to the last
element.

Declaring Arrays
To declare an array, a programmer specifies the type of the elements and
the number of elements required by an array as follows:

type arrayName [ arraySize ];

This is called a single-dimensional array. The arraySize must be an integer


constant greater than zero and type can be any valid C data type. For
example, to declare a 10-element array called balance of type double, use
this statement:

double balance[10];

Now balance is a variable array which is sufficient to hold up to 10 double


numbers.

Initializing Arrays
You can initialize array either one by one or using a single statement as
follows:

double balance[5] = {1000.0, 2.0, 3.4, 17.0, 50.0};

The number of values between braces { } cannot be larger than the


number of elements that we declare for the array between square
brackets [ ]. Following is an example to assign a single element of the
array:
If you omit the size of the array, an array just big enough to hold the
initialization is created. Therefore, if you write:

double balance[] = {1000.0, 2.0, 3.4, 17.0, 50.0};


The above statement assigns element number 5th in the array a value of
50.0. Array with 4th index will be 5th ie. last element because all arrays
have 0 as the index of their first element which is also called base index.

Accessing Array Elements


An element is accessed by indexing the array name. This is done by
placing the index of the element within square brackets after the name of
the array. For example:

double salary = balance[9];

The above statement will take 10th element from the array and assign
the value to salary variable.

e.g.

#include <stdio.h>
void main ()
{
int n[5 ]; /* n is an array of 5 integers */
int i,j,x;
printf(“Engter 5 Elements : “);
for ( i = 0; i < 5; i++ )
{
scanf(“%d”,&n[i]);
}
for (j = 0; j < 5; j++ )
{
printf("Element[%d] = %d\n", j, n[j] );
}
}

When the above code is compiled and executed, it produces the following
result:
Enter 5 Elements : 4 5 6 8 9
Element[0] = 4
Element[1] = 5
Element[2] = 6
Element[3] = 8
Element[4] = 9
Element[9] = 109
2 Write a program to read an array of integers (with max size 10) and print
the largest and the smallest of the given numbers.
Ans:

#include<stdio.h>
void main()
{
int a[10], i, n, min, max;
printf("Enter how many values you want to read : ");
scanf("%d", &n);
for(i=0; i<n; i++)
{
printf("Enter the value of a[%d] : ", i);
scanf("%d", &a[i]);
}
min=max=a[0];
for(i=1; i<n; i++)
{
if(a[i]<=min)
min = a[i];
if(a[i]>=max)
max = a[i];
}
printf("The largest element of the array = %d\n",max);
printf("The smallest element of the array = %d\n", min);
}
Output:
Enter how many values you want to read : 5
Enter the value of a[0] : 2
Enter the value of a[1] : 1
Enter the value of a[2] : 3
Enter the value of a[3] : 5
Enter the value of a[4] : 4
The largest element of the array = 5
The smallest element of the array = 1

3 Explain character 1D array with suitable example code snippets


illustrating declaring, initializing and accessing of the array.
Ans:
A character 1D array is nothing but string in C. Strings must have a NULL
or ‘\0’character after the last character to show where the string ends. A
string can be declared as a character 1D array.

Declaration:

The string can be declared as follow:


Syntax:
char string_name [size];

Example:
char name[50];

Initialization:
A One-dimensional character array is initialized as:
char ch[ ] = { 'a', 'e', 'i', 'o', 'u', '\0'};.
Or
char ch[] = “aeiou”;
Or
char ch[5]={ 'a', 'e', 'i', 'o', 'u'};

When compiler assigns string to character array then it automatically


supplies null character ('\0') at the end of string. Thus, size of string =
original length of string + 1. char name[7];
name = "TECHNO";

Accessing 1D Character array:

Method 1:
Accessing all content at once:
 In C for accessing 1D character array we can use %s format
specifier in scanf() and printf() statements.
 Using these statements we can access the whole array content at a
time.
For ex:
char name[20];
printf(“Enter your name: “);
scanf(“%s”, name);
printf(“Hello! \t %s\n”,name);

Output:
Enter your name: Ravi
Hello! Ravi

Method2:
Accessing the content by character by character:
- We have to use %c format specifier in printf() and scanf() statements
- We have to use a counter loop for printing the content character by
character

For ex:
char name[20];
int i=0;
printf(“Enter your name: “);
scanf(“%s”,name);
printf(“The name is : “);
while(name[i]!=\0’)
{
printf(“%c”,name[i]);
i++;
}

Output:
Enter your name: Rahul
The name is : Rahul

4 Write a C program to reverse the given string.


Ans:
#include<string.h>
#include<string.h>
void main(){
char str1[50],str2[50];
printf("Enter a String : ");
scanf("%s",str1);
strcpy(str2,str1);
strrev(str2);
printf("Reverse of the String %s = %s\n",str1, str2);
}

Output:
Enter a String : Hello
Reverse of the String Hello = olleH

Explanation:

First we copied the string1 to string2 using built-in function strcpy()


Then We reversed the string2 with built-in function strrev()
Then we printed the both strings.
Note: For using string handling functions we have to include string.h
header file.

5 Explain integer 2D array with suitable example code snippets illustrating


declaring, initializing and accessing of the array.
Ans:

Two Dimensional Arrays:

An array with two subscripts (indexes) is termed two-dimensional array or


2 – D Array. A 2-D array can be thought of as a group of one or more 1-D
array(s)., all of which share a common name and they are separable with
subscript values. Thus a 2-D array is essentially an array of 1-D arrays.
1-D array can store a row of elements, so a 2-D array enables us to store
multiple rows of elements i.e., a table of elements or a matrix.

Declaration of 2-D Arrays

The general syntax of declaring 2-D array is:

Data-type array-name[row-size]

Data-type - refers to any valid data type supported by C


array –name - should be a valid C identifier
row-size - indicates the maximum number of rows.
Col-size - indicates column size i.e., no of elements in each
row.

Example:

int x[3][3] ;

Here, x is declared to be an array of two dimensions and of int data type.


Row-size and col-size are 3 and 3 respectively. Memory gets allocated to
store the array of x as follows. It is important to note that x is the
common name shared by all the elements of the array.
column numbers
0 1 2
0 X[0][0] X[0][1] X[0][2]
Numb
Row

ers

1 X[1][0] X[1][1] X[1][2]


2 X[2][0] X[2][1] X[2][2]

Initialization of 2-D Arrays

We can initialize a 2-D array also while declaring it like 1-D arrays. There are two
forms of initializing 2-D arrays.

The First method of initializing 2-D array is

The syntax for initializing 2D array is:

Data-type array-name[rowsize][colsize] =
{ initialize-list } ;
Data type refers to any data type supported by C. Array-name refers to
any valid C identifier. Rowsize indicates the no. of rows, colsize indicates
the no. of columns of the array. Initializer-list is a comma separated list of
values.

In the no. of values in initializer-list is equal to product of rows-size and


col-size, the first rowsize values in the initializer-list will be assigned to the
first row, the second row-size values will be assigned to the second row of
the array and so on.

Example:

Int x[2][4] = { 1, 2, 3, 4, 5,6,7,8 } ;

Since col-size is 4, the first 4 values of the initializer list are assigned to
the first row of x and the next 4 value are assigned to the second row of x
as sown bellow

1 2 3 4
5 6 7 8

Note:

If the number of values in the initializer-list is less than the product of


row-size and col-size, only the first few matching locations of the array
would get values from the initializer-list row-wise. The trailing unmatched
locations would get zeros.

Example:

Int x[2][4] = { 1,2,3,4 } ;

The 1st row of x gets filled with the values in the intializer-list. The second
row gets filled with 0’s.

1 2 3 4
0 0 0 0

The second method of Intializing a 2-D array is as follows:

Data-type array-name [row-size][col-size] = { { initialize-list 1 } , { initialize-list 2 } } ;

The values in the initializer-list 1 are assigned to the location in the first
row. The values in the initializer-list 2 are assigned to the locations in the
second row and so on.
Example:

Int x[2][4] = { { 1, 2, 3, 4 } , { 5,6,7,8 } } ;

As a result of this , the array x get filled up as follows:

1 2 3 4
5 6 7 8

Note:
1. If the no. of values specified in any intializer-list is less than col-size of
x, only the 1st location in the corresponding row would get these
values. The remaining locations in that row would get 0.

Example:

int x[2][4] = { { 1,2,3 } , { 5, 6, 7, 8 } } ;

since the 1st initializer-list has only 3 values, x[0][0] is 1, x[0][1] is set to
2, x[0][2] is set to 3 and the 4th location in the first row is automatically
set to 0

1 2 3 0
5 6 7 8

2. If the number of values specified in any array initialization-list is more


than col-size of x, compiler returns an error.

3. Array elements can not intialized selectively.

4. There is no array bound checking mechanism built into C-compiler. It is


the responsibility of the programmer to see to it that the subscript
value does not go beyond size -1. If does the system may hang.

5. A 2-D array is used to store a table of values (matrix)

6. Similar to int data-type we can declare 2-D arrays to any data-type


that supported by C.

Accessing 2D array:

Reading 2-D array:


For reading 2-D arrays we need two indexes or subscripts. This can be
achieved by using two loops. The indexs represents one for rows and the
other for columns.
Example:

int x[2][2];

for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
scanf(“%d”,&x[i][j]
}
}

Printing 2-D array:


For printing 2-D arrays we need two indexes or subscripts. This can be
achieved by using two loops. The indexes represents one for rows and the
other for columns.

int i, x[5] = { {2, 5, 3} , { 6, 4, 1 } } ;

for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
printf(“%d”,x[i][j]
}
Printf(“\n”);
}

6 Write a C program that can take 2 matrices as input, add them and print
the result.
Ans:
#include <stdio.h>
void main() {
int i, j, m, n, p, q, a[5][5], b[5][5], c[5][5];
printf("Enter the row & column sizes of matrix-1 : ");
scanf("%d %d", &m, &n);
printf("Enter matrix-1 %d elements : ", m*n);
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
scanf("%d", &a[i][j]);
}
}
printf("Enter the row & column sizes of matrix-2 : ");
scanf("%d %d", &p, &q);
printf("Enter matrix-2 %d elements : ", p*q);
for (i = 0; i < p; i++) {
for (j = 0; j < q; j++) {
scanf("%d", &b[i][j]);
}
}

printf("The given matrix-1 is\n");


for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
printf("%d ", a[i][j]);
}
printf("\n");
}
printf("The given matrix-2 is\n");
for (i = 0; i < p; i++) {
for (j = 0; j < q; j++) {
printf("%d ", b[i][j]);
}
printf("\n");
}

if((m!=p) || (n!=q))
{
printf("Addition is not possible\n");
}
else
{
printf("Addition of two matrices is\n");
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
c[i][j] = a[i][j] + b[i][j];
printf("%d ", c[i][j]);
}
printf("\n");
}
}
}
Output:
Enter the row & column sizes of matrix-1 : 2 2
Enter matrix-1 4 elements : 1 2 3 4
Enter the row & column sizes of matrix-2 : 2 2
Enter matrix-2 4 elements : 1 2 3 4
The given matrix-1 is
12
34
The given matrix-2 is
12
34
Addition of two matrices is
24
68

7 Write a C program that can take 2 matrices as input, multiply them and
print the result.
Ans:
#include <stdio.h>
void main() {
int i, j, k, m, n, p, q, a[5][5], b[5][5], c[5][5];
printf("Enter the row & column sizes of matrix-1 : ");
scanf("%d %d", &m, &n);
printf("Enter matrix-1 %d elements : ", m*n);
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
scanf("%d", &a[i][j]);
}
}
printf("Enter the row & column sizes of matrix-2 : ");
scanf("%d %d", &p, &q);
printf("Enter matrix-2 %d elements : ", p*q);
for (i = 0; i < p; i++) {
for (j = 0; j < q; j++) {
scanf("%d", &b[i][j]);
}
}
printf("The given matrix-1 is\n");
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
printf("%d ", a[i][j]);
}
printf("\n");
}
printf("The given matrix-2 is\n");
for (i = 0; i < p; i++) {
for (j = 0; j < q; j++) {
printf("%d ", b[i][j]);
}
printf("\n");
}
if (n == p) {
for (i = 0; i < m; i++) {
for (j = 0; j < q; j++) {
c[i][j] = 0;
for (k = 0; k < n; k++) {
c[i][j] = c[i][j] + a[i][k] * b[k][j];
}
}
}
printf("Multiplication of two matrices is\n");
for (i = 0; i < m; i++) {
for (j = 0; j < q; j++) {
printf("%d ", c[i][j]);
}
printf("\n");
}
}
else
{
printf("Multiplication is not possible\n");
}
}
Output:
nter the row & column sizes of matrix-1 : 3 3
Enter matrix-1 9 elements : 1 2 3 4 5 6 7 8 9
Enter the row & column sizes of matrix-2 : 3 3
Enter matrix-2 9 elements : 1 0 0 0 1 0 0 0 1
The given matrix-1 is
123
456
789
The given matrix-2 is
100
010
001
Multiplication of two matrices is
123
456
789

8 Define 2D Integer array and write a C program to find the transpose of a


given matrix 
Ans:
#include <stdio.h>
void main() {
int i, j, rows, cols;
int a[5][5], b[5][5];
printf("Enter the order of matrix : ");
scanf("%d %d", &rows, &cols);
printf("Enter %d elements : ", rows * cols);
for (i = 0; i < rows; i++) {
for (j = 0; j < cols; j++) {
scanf("%d", &a[i][j]);
}
}
printf("The given matrix is\n");
for (i = 0; i < rows; i++) {
for (j = 0; j < cols; j++) {
printf("%d ", a[i][j]);
}
printf("\n");
}
for (i = 0; i < rows; i++) {
for (j = 0; j < cols; j++) {
b[j][i] = a[i][j];
}
}
printf("Transpose of the given matrix is\n");
for (i = 0; i < cols; i++) {
for (j = 0; j < rows; j++) {
printf("%d ", b[i][j]);
}
printf("\n");
}
}

Output:
Enter the order of matrix : 3 2
Enter 6 elements : 1 2 3 4 5 6
The given matrix is
12
34
56
Transpose of the given matrix is
135
246

9 Explain character 2D array with suitable example, illustrating declaring,


initializing and accessing of the array.
Ans:

 A character 2D array represents a collection of strings. We have


array of integers, array of floating point numbers, etc., similarly we
have array of strings also.
 Collection of strings is represented using array of strings.

Declaration:-
char arr[rowsize][colsize];
where,
arr - name of the array
rowsize -represents number of strings
colsize -represents size of each string

Initialization:-

Syntax:
char Array_Name[row][col] = { list of strings };

Example:-
char city[5][10] = { “DELHI”, “CHENNAI”, “BANGALORE”, “HYDERABAD”,
“MUMBAI” };

D E L H I \0
C H E N N A I \0
B A N G A L O R E \0
H Y D E R A B A D \0
M U M B A I \0
In the above storage representation memory is wasted due to the fixed
length for all strings.

Accessing 2D character Array:-0

We can access 2D array elements either row by row or by a particular


column in a particular row wise. For accessing 2D arrays character by
character we require 2 loops. For accessing element (each row) we
require one loop.

For ex:
printf(“%c”,city[0][1]);
- It prints ‘E’ from the above city 2D array

printf(“%s”city[1]);
- It prints “CHENNAI” from the above 2D array.

Example Program for reading and printing names of five students


using 2D array:

#include<stdio.h>
void main() {
char names[5][30];
int i;
printf("Enter 5 Names : \n");
for(i=0;i<5;i++)
scanf("%s", names[i]);
printf("Names in the array are:\n");
for(i=0;i<5;i++)
printf("%s\n", names[i]);
}

Output:
Enter 5 Names :
Kavitha
Jeevan
Hari
Varma
Neelima
Names in the array are:
Kavitha
Jeevan
Hari
Varma
Neelima

10 Write a C program to search a given name in list of strings.


Ans:
#include<stdio.h>
#include<string.h>
void main()
{
char names[10][30], search[30];
int n,i,j,flag=0;
printf("Enter How many Names : ");
scanf("%d", &n);
printf("Enter %d names :\n", n);
for(i=0;i<n;i++)
scanf("%s",names[i]);
printf("Names in the List are :\n");
for(i=0;i<n;i++)
printf("%s\n",names[i]);
printf("Enter a name to search : ");
scanf("%s",search);
for(i=0;i<n;i++)
{
if(strcmp(names[i],search)==0)
{
flag=1;
break;
}
}
if(flag==1)
printf("%s is found in the list at %d location\n", search, i+1);
else
printf("%s is not found in the list\n");
}

Output:
Enter How many Names : 5
Enter 5 names :
Hari
Geetha
David
Harika
Gautham
Names in the List are :
Hari
Geetha
David
Harika
Gautham
Enter a name to search : David
David is found in the list at 3 location

11 Write a C program to concatenate two strings without using library


function.
Ans:
#include <stdio.h>
int main() {
char a[10], b[10], c[20];
int i, j;
printf("Enter the first string : ");
scanf("%s", a);
printf("Enter the second string : ");
scanf("%s", b);
for (i = 0; a[i] != '\0'; i++) {
c[i] = a[i];
}
for (j = 0; b[j] != '\0'; j++,i++) {
c[i] = b[j];
}
c[i] = '\0';
printf("The concatenated string = %s\n", c);
}
Output:
Enter the first string : MVGR
Enter the second string : College
The concatenated string = MVGRCollege

12 Explain the syntax of strcat, strcpy with example programs.


Ans:
strcat():

The function strcat() is used to concatenate two strings into a single


string.

The syntax of strcat() is:

strcat(string1, string2);

Where string1, string2 are two different strings. Here string2 is


concatenated with string1, and the concatenated string is stored in
string1.

In strcat() operation, NULL character of string1 is overwritten by first


character of string2 and NULL character is added at the end of new
string1 which is created after strcat() operation.

Example program:
#include <stdio.h>
#include <string.h>
void main()
{
char str1[10] = "Hello";
char str2[10] = "Students";
strcat(str1,str2);
printf("str1 = %s\n",str1);
printf("str2 = %s\n",str2);
}

Output:
str1 = HelloStudents
str2 = Students

strcpy():
The function strcpy() is used to copy one sting into another string
including the NULL character (terminator char '\0').

The syntax of strcpy( ) is :


strcpy(string1, string2);

Where string1, string2 are two strings and the string2 is copied into
string1. In this case the copied string is available in string1 and both
strings contains the same data.

If the length of string1 is less than the length of string2 then entire string2
value will not be copied into string1.

For example, consider the length of string1 is 20 and the length of string2
is 30. Then, only the first 20 characters from string2 will be copied into
string1, the remaining 10 characters will not be copied and will be
truncated.

Example Program:
#include <stdio.h>
#include <string.h>
void main()
{
char str1[10] = "Hello";
char str2[10] = "Students";
strcpy(str1,str2);
printf("str1 = %s\n",str1);
printf("str2 = %s\n",str2);
}

Output:
str1 = Students
str2 = Students

13 Write a program to reverse a string without using library functions.


Ans:
#include <stdio.h>

void main( )
{
char str1[30],tmp;
int i,j;
printf("Enter a string: ");
scanf("%s",str1);
for(j=0;str1[j]!='\0';j++);
for(i=0,j=j-1;i<=j;i++,j--)
{
tmp=str1[i];
str1[i]=str1[j];
str1[j]=tmp;
}
printf("Reverse of the string : %s\n",str1);
}

Output:
Enter a string: College
Reverse of the string : egelloC

14 Explain the syntax of strlen and strcmp with example programs.


Ans:

strlen():
The function strlen() is used to find the length of the given string. This
function returns only the integer data (or) numeric data.

The function strlen() counts the number of characters in a given string


and returns the integer value.

It stops counting the character when NULL character is found. Because,


NULL character indicates the end of the string in C.

The syntax of strlen() is:


integer_variable = strlen(string);

Here string is a group of characters, strlen() function finds the length of


the string and the integer value will be stored in the integer_variable.

The string.h header file supports all the string functions in C language.

Example Program:
#include <stdio.h>
#include <string.h>
void main() {
char name[20];
printf("Enter a string : ");
scanf("%s", name);
printf("The length of the string %s is : %d\n", name, strlen(name));
}

Output:
Enter a string : Ranarangam
The length of the string Ranarangam is : 10

strcmp():
The function strcmp() is used for comparison of two strings and it always
returns the numeric data.

The syntax of strcmp() is :

variable = strcmp (string1, string2);

Where string1, string2 are two strings and the variable is of the type
integer.

The comparison of two strings is dependant on the alphabets and not on


the size of the strings.
 If the function strcmp() returns zero, both strings are equal.
 If the function returns less than zero, string2 is higher than string1.
 If the function returns greater than zero, string1 is higher than
string2.

Example Program:
#include <stdio.h>
#include <string.h>
void main()
{
char a[20], b[20];
int i, j;
printf("Enter the first string : ");
scanf("%s", a);
printf("Enter the second string : ");
scanf("%s", b);

i=strcmp(a,b);
if (i==0)
printf("The given two strings are equal\n");
else if (i>0)
printf("The string %s is higher than the string %s\n", a, b);
else
printf("The string %s is higher than the string %s\n", b, a);
}

Output:
Enter the first string : Rajani
Enter the second string : Raju
The string Raju is higher than the string Rajani

15 Explain Linear search algorithm and illustrate implementation of the same


with a code snippet in C.
Ans:
Linear search is a searching technique in which it sequentially checks
each element of the list for the target value until a match is found (or)
until all the elements have been searched.

Algorithm for Linear search:

Linear Search ( Array A, Value x)

Step 1: Set i to 1
Step 2: if i > n then go to step 7
Step 3: if A[i] = x then go to step 6
Step 4: Set i to i + 1
Step 5: Go to Step 2
Step 6: Print Element x Found at index i and go to step 8
Step 7: Print element not found
Step 8: Exit

Code Snippet:

flag = 0;
printf("Enter key element : ");
scanf("%d", &key);
for (i=0; i<n; i++ )
{
if (a[i]==key )
{
flag = 1;
pos = i;
break;
}
}
if (flag==1 )
printf("The key element %d is found at the position %d\n", key,
pos);
else
printf("The Key element %d is not found in the array\n", key);

16 Write a program to find an element in a given set of 1d integer array


using linear search.
Ans:
#include<stdio.h>
void main()
{
int n, a[10], i, key, pos;
printf("Enter value of n : ");
scanf("%d", &n);
for(i=0; i< n; i++)
{
printf("Enter element for a[%d] : ", i);
scanf("%d", &a[i]);
}
printf("Enter key element : ");
scanf("%d", &key);

for(i=0;i<n; i++)
{
if(a[i]==key)
{
printf("The key element %d is found at the position %d\n", key,
i);
break;
}
}
if(i==n)
printf("The Key element %d is not found in the array\n", key);
}

Output:
Enter value of n : 5
Enter element for a[0] : 2
Enter element for a[1] : 5
Enter element for a[2] : 6
Enter element for a[3] : 1
Enter element for a[4] : 4
Enter key element : 1
The key element 1 is found at the position 3

17 Describe binary search algorithm and illustrate implementation of the


same with a code snippet in C.
Ans:

Binary search uses divide and conquer technique and it works on the
sorted list either in ascending or descending order.

Binary search compares the key element to the middle element of the
array; if they are unequal, the half in which the key element cannot lie is
eliminated and the search continues on the remaining half until it is
successful.

Binary Search Algorithm


Step 1 - Read the search element from the user.
Step 2 - Find the middle element in the sorted list.
Step 3 - Compare the search element with the middle element in the
sorted list.
Step 4 - If both are matched, then display "Given element is found!!!"
and terminate the function.
Step 5 - If both are not matched, then check whether the search element
is smaller or larger than the middle element.
Step 6 - If the search element is smaller than middle element, repeat
steps 2, 3, 4 and 5 for the left sublist of the middle element.
Step 7 - If the search element is larger than middle element, repeat steps
2, 3, 4 and 5 for the right sublist of the middle element.
Step 8 - Repeat the same process until we find the search element in the
list or until sublist contains only one element.
Step 9 - If that element also doesn't match with the search element, then
display "Element is not found in the list!!!" and terminate the
function.

Binary Search Code Snippet:


printf("Enter key element : ");
scanf("%d", &key);

low = 0;
high = n;

while (low<=high)
{
mid=(low+high)/2 ;
if (key==a[mid] )
{
flag = 1;
break;
}
else if (key>a[mid] )
low = mid+1;
else if (key<a[mid] )
high = mid-1;
}
if (flag==1 )
printf("The key element %d is found at the position %d\n", key,
mid);
else
printf("The Key element %d is not found in the array\n", key);

18 Explain Binary Search technique with suitable example.


Ans:

How Binary Search Works?


For a binary search to work, it is mandatory for the target array to be
sorted. We shall learn the process of binary search with a pictorial
example. The following is our sorted array and let us assume that we
need to search the location of value 31 using binary search.

First, we shall determine half of the array by using this formula −


mid = low + (high - low) / 2
Here it is, 0 + (9 - 0 ) / 2 = 4 (integer value of 4.5). So, 4 is the mid of the
array.

Now we compare the value stored at location 4, with the value being
searched, i.e. 31. We find that the value at location 4 is 27, which is not a
match. As the value is greater than 27 and we have a sorted array, so we
also know that the target value must be in the upper portion of the array.

We change our low to mid + 1 and find the new mid value again.
low = mid + 1
mid = low + (high - low) / 2
Our new mid is 7 now. We compare the value stored at location 7 with
our target value 31.

The value stored at location 7 is not a match, rather it is more than what
we are looking for. So, the value must be in the lower part from this
location.
Hence, we calculate the mid again. This time it is 5.

We compare the value stored at location 5 with our target value. We find
that it is a match.

We conclude that the target value 31 is stored at location 5.


Binary search halves the searchable items and thus reduces the count of
comparisons to be made to very less numbers.
`
19 Compare Linear Search and Binary Search with example.
Ans:

S.n Linear search Binary search


o
1 A linear search scans one item at a In contrast, binary search cuts
time, without jumping to any item. down your search to half as soon
as you find the middle of a
sorted list.
2 In linear search, the worst case where binary search making
complexity is O(n), O(log n) comparisons
3 Time taken to search elements But binary search compresses
keep increasing as the number of the searching period by dividing
elements is increased when the whole array into two half.
searching through linear process.
4 Linear search does the sequential whereas Binary search access
access data randomly
5 Input data need not be sorted in Input data needs to be sorted in
Linear Search Binary Search
6 Linear search uses sequential binary search implements divide
approach and conquer approach
7 Linear search is quick and easy to Where binary search algorithm is
use, but there is no need for any tricky, and elements are
ordered elements. necessarily arranged in order.
8 If the amount of data is small, then Binary search is efficient for the
linear search is preferable because larger array
this searching process is fast when
data is small.

Linear search Example:

If an array consists of numbers like "50 20 40 10 80", and the key


element is to find is 10.

Search - 1 :
Compare 10 with value of a[0] i.e., 50, both are not equal so repeat the
same process with a[1].

Search - 2 :
Compare 10 with value of a[1] i.e., 20, both are not equal so repeat the
same process with a[2].

Search - 3 :
Compare 10 with value of a[2] i.e., 40, both are not equal so repeat the
same process with a[3].

Search - 4 :
Compare 10 with value of a[3] i.e., 10, both are equal so stop the
process and print index value where it found, i.e., position 3.

Binary Search Example:

If an array consisting numbers like "50 20 40 10 80", and the key


element is to find is 10.

Search - 1 :
First Sort the given array elements by using any one of the sorting
technique.
After sorting the elements in the array are 10 20 40 50 80 and initially
low = 0, high = 4.

Search - 2 :
Compare 10 with middle element i.e., (low + high) / 2 = (0 + 4) / 2 = 4
/ 2 = 2, a[2] is 40. Here 10 < 40 so search the element in the left half
of the element 40. So low = 0, high = mid - 1 = 2 - 1 = 1.

Search - 3 :
Compare 10 with middle element i.e., (low + high) / 2 = (0 + 1) / 2 = 1
/ 2 = 0, a[0] is 10. Here 10 == 10 so print the index 0 where the
element has found and stop the process

20 Write a C Program to search an element using Binary search


Ans:
#include<stdio.h>
void main()
{
int a[20], i, j, n, key, flag = 0, low, high, mid, temp;
printf("Enter value of n : ");
scanf("%d", &n);

printf("Enter %d Elements in ascending order : ",n);


for (i=0;i<n;i++)
scanf("%d", &a[i]);

printf("Enter key element : ");


scanf("%d", &key);

low = 0;
high = n;

while (low<=high)
{
mid=(low+high)/2 ;
if (key==a[mid] )
{
flag = 1;
break;
}
else if (key>a[mid] )
low = mid+1;
else if (key<a[mid] )
high = mid-1;
}
if (flag==1 )
printf("The key element %d is found at the position %d\n", key,
mid);
else
printf("The Key element %d is not found in the array\n", key);
}

Output:
Enter value of n : 5
Enter 5 Elements in ascending order : 2 4 6 7 8
Enter key element : 7
The key element 7 is found at the position 3
UNIT 3-2 Important Questions for 2nd Mid

1 Explain Bubble sort technique with suitable example.


Ans:

Bubble sort is an internal sorting technique in which adjacent elements are compared and exchanged if
necessary.
The working procedure for bubble sort is as follows:

Consider an array of n elements (i.e., a[n]) to be sorted.

1. Compare the first two elements in the array i.e., a[0] and a[1], if a[1] is less
than a[0] then interchange the two values.
2 Next compare a[1] and a[2], if a[2] is less than a[1] then interchange the values.
3 Continue this process till the last two elements are compared and interchanged.
4 Repeat the above steps for n - 1 passes.

Let us consider an example of array numbers "50 20 40 10 80", and sort the array from lowest
number to greatest number using bubble sort.

In each step, elements written in bold are being compared. Number of elements in the array are 5,
so 4 passes will be required.

Pass - 1 :
( 50 20 40 10 80 ) -> ( 20 50 40 10 80 ) // Compared the first two elements, and swaps since 50 > 20.
( 20 50 40 10 80 ) -> ( 20 40 50 10 80 ) // Swap since 50 > 40.
( 20 40 50 10 80 ) -> ( 20 40 10 50 80 ) // Swap since 50 > 10.
( 20 40 10 50 80 ) -> ( 20 40 10 50 80 ) // Since the elements are already in order (50 < 80), algorithm
does not swap them.
Total number of elements in the given array are 5, so in Pass - 1 total numbers compared are 4. After
completion of Pass - 1 the largest element is moved to the last position of the array.
Now, Pass - 2 can compare the elements of the array from first position to second last position.

Pass - 2 :
( 20 40 10 50 80 ) -> ( 20 40 10 50 80 ) // Since the elements are already in order (20 < 50), algorithm
does not swap them.
( 20 40 10 50 80 ) -> ( 20 10 40 50 80 ) // Swap since 40 > 10.
( 20 10 40 50 80 ) -> ( 20 10 40 50 80 ) // Since the elements are already in order (40 < 50), algorithm
does not swap them.
In Pass - 2 total numbers compared are 3. After completion of Pass - 2 the second largest element is
moved to the second last position of the array.
Now, Pass - 3 can compare the elements of the array from first position to third last position.

Pass - 3 :
( 20 10 40 50 80 ) -> ( 10 20 40 50 80 ) // Swap since 20 > 10.
( 10 20 40 50 80 ) -> ( 10 20 40 50 80 ) // Since these elements are already in order (20 < 40), algorithm
does not swap them.
In Pass - 3 total numbers compared are 2. After completion of Pass - 3 the third largest element is
moved to the third last position of the array.
Now, Pass - 4 can compare the first and second elements of the array.

Pass - 4 :
( 10 2040 50 80 ) -> ( 10 20 40 50 80 ) // Since these elements are already in order (10 < 20), algorithm
does not swap them.
In Pass - 4 total numbers compared are 1. After completion of Pass - 4 all the elements of the array are
sorted. So, the result is 10 20 40 50 80.

Or

Bubble sort
Bubble sort compares the value of first element with the immediate next
element and swaps according to the requirement and goes till the last
element. This iteration repeats for (N - 1) times/steps where N is the
number of elements in the list.

Bubble sort of N elements can take (N - 1) steps and (N -1) iterations in


each steps. Thus resultant is (N - 1)*(N - 1). This sorting algorithm is not
however the best in performance when count of the elements are large.
Time complexities of bubble sort is O(N^2) [Square of N]. This sorting is
well suited for small number of elements and it is easy the implement.

For Ex: If the elements in unsorted list are : 4 9 5 1 0


2. Write a C program to implement Bubble sort algorithm.
Ans:
#include <stdio.h>
void main() {
int i, j, a[10], n, temp;
printf("Enter value of n : ");
scanf("%d", &n);
for (i = 0; i < n; i++) {
printf("Enter element for a[%d] : ", i);
scanf("%d", &a[i]);
}
printf("Before sorting the elements in the array are\n");
for (i = 0; i < n; i++) {
printf("Value of a[%d] = %d\n", i, a[i]);
}
for (i = 0; i < n - 1; i++) {
for (j = 0; j < n - i - 1; j++) {
if (a[j] > a[j+1]) {
temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
}
}
printf("After sorting the elements in the array are\n");
for (i = 0; i < n; i++) {
printf("Value of a[%d] = %d\n", i, a[i]);
}
}
Output:
Enter value of n : 3
Enter element for a[0] : 22
Enter element for a[1] : 33
Enter element for a[2] : 12
Before sorting the elements in the array are
Value of a[0] = 22
Value of a[1] = 33
Value of a[2] = 12
After sorting the elements in the array are
Value of a[0] = 12
Value of a[1] = 22
Value of a[2] = 33

2. Explain Selection sort technique with suitable example.


Ans:

Selection sort process can be done in two ways, one is the largest element method and the other is
smallest element method.

The working procedure for selection sort largest element method is as follows:

Consider an array of n elements (i.e., a[n]) to be sorted.


1 In the first step, the largest element in the list is searched. Once the largest element is found, it is
exchanged with the element which is placed at the last position. This completes the first pass.
2 In the next step, it searches for the second largest element in the list and it is interchanged with
the element placed at second largest position. This is done in second pass.
3 This process is repeated for n - 1 passes to sort all the elements.
4 Let us consider an example of array numbers "80 10 50 20 40", and sort the array from lowest
number to greatest number using selection sort by the largest element.

Pass - 1 :
( 80 10 50 20 40 ) -> ( 40 10 50 20 80 ) // First finds the largest element and it is exchanged with the last
position element.After completion of Pass - 1, the largest element is moved to the end of the array.

Now, Pass - 2 can find the next largest element with out considering the last position element.
Pass - 2 :
( 40 10 50 20 80 ) -> ( 40 10 20 50 80 ) // Largest in 40 10 50 20 is 50 and it is replaced with next last
position of the array.After completion of Pass - 2 the second largest element is moved to the second last
position of the array.
Now, Pass - 3 can find the next largest element with out considering the last two position elements
because they are already sorted.
Pass - 3 :

( 40 10 20 50 80 ) -> ( 20 10 40 50 80 ) // Largest in 40 10 20 is 40 and it is replaced with next last


position of the array. After completion of Pass - 3 the third largest element is moved to the third last
position of the array.

Now, Pass - 4 can find the next largest element with out considering the last three position elements
because they are already sorted.
Pass - 4 :
( 20 10 40 50 80 ) -> ( 10 20 40 50 80 ) // Largest in 20 10 is 20 and it is replaced with next last position of
the array.After completion of Pass - 4 all the elements of the array are sorted. So, the result is 10 20 40
50 80.

3. Write a program to sort set of 1d integer array using Selection sort.


Ans:
#include<stdio.h>
void main() {
int a[20], i, n, j, large, index;
printf("Enter value of n : ");
scanf("%d", &n);

for ( i=0;i<n;i++) {
printf("Enter element for a[%d] : ", i);
scanf("%d", &a[i]);
}
printf("Before sorting the elements in the array are\n");

for (i=0;i<n;i++ ) {
printf("Value of a[%d] = %d\n", i, a[i]);
}

for (i=n-1;i>=1;i-- ) {
index = i;
for (j=i;j>=0;j-- ) {
if (a[j]>a[index] ) {
index = j;
}
}
large = a[index];
a[index] = a[i];
a[i]=large;
}
printf("After sorting the elements in the array are\n");
for (i=0;i<n;i++ ) {
printf("Value of a[%d] = %d\n", i, a[i]);
}
}
Output:
Enter value of n : 3
Enter element for a[0] : 22
Enter element for a[1] : 33
Enter element for a[2] : 12
Before sorting the elements in the array are
Value of a[0] = 22
Value of a[1] = 33
Value of a[2] = 12
After sorting the elements in the array are
Value of a[0] = 12
Value of a[1] = 22
Value of a[2] = 33

4. Explain Insertion sort technique with suitable example.


Ans:

Insertion sort is one that sorts a set of elements by inserting an element into the existing sorted
elements.
The working procedure for insertion sort is as follows:

1 Let us consider an array of n elements (i.e., a[n]) to be sorted.


2 The first element a[0] in the array is itself trivially sorted.
3 The second element a[1] is compared with first element a[0] and it will be inserted either before or
after first element, so that first and second elements are sorted.
4 The third element a[2] is compared with a[0] and a[1] and it will be inserted into its proper place by
checking conditions, so that first three elements are sorted.
5 Repeat the same process for n - 1 passes.

For example of array numbers "50 20 40 10 30", and sort the array from lowest number to greatest
number using insertion sort.
In each step, elements written in color is compared with elements written in bold. Number of elements
in the array are 5, so 4 passes will be required.

Pass - 1 :
( 50 20 40 10 30 ) -> ( 20 50 40 10 30 ) // The second element a[1] is compared with the first element
a[0] and swaps since 50 > 20, so first 2 elements are sorted.
Now, Pass - 2 can compare a[2] with a[0] and a[1].

Pass - 2 :
( 20 5040 10 30 ) -> ( 20 40 50 10 30 ) // Since 40 > 20 and 40 < 50, so 40 is inserted in between 20 and
50.
Now, Pass - a[3] with a[0], a[1] and a[2].

Pass - 3 :
( 20 40 50 10 30 ) -> ( 10 20 40 50 30 ) // Since 10 < 20, so it is inserted before 20.
Now, Pass - 4 can compare a[4] with a[0], a[1], a[2] and a[3].

Pass - 4 :
( 10 20 40 50 30 ) -> ( 10 20 30 40 50 ) // Since 30 > 10, 30 > 20 but 30 < 40, so 30 is inserted in between
20 and 40 .

After completion of Pass - 4 all the elements of the array are sorted. So, the result is 10 20 30 40 50.

6. Write a program to sort set of 1d integer array using Insertion sort.


Ans:
#include<stdio.h>
void main() {
int a[20], i, n, j, temp;
printf("Enter value of n : ");
scanf("%d", &n);

for (i=0;i<n;i++ ) {
printf("Enter element for a[%d] : ", i);
scanf("%d", &a[i]);
}
printf("Before sorting the elements in the array are\n");

for (i=0;i<n;i++ ) {
printf("Value of a[%d] = %d\n", i, a[i]);
}

// code to sort elements


for (i=1;i<n;i++ ) {
temp =a[i] ;
for (j=i;j>0;j-- ) {
if (a[j-1]>temp ) {
a[j]=a[j-1];
a[j-1]=temp;
}
}
}
printf("After sorting the elements in the array are\n");

for (i=0;i<n;i++ ) {
printf("Value of a[%d] = %d\n",i, a[i] );
}
}

Output:
Enter value of n : 3
Enter element for a[0] : 22
Enter element for a[1] : 33
Enter element for a[2] : 12
Before sorting the elements in the array are
Value of a[0] = 22
Value of a[1] = 33
Value of a[2] = 12
After sorting the elements in the array are
Value of a[0] = 12
Value of a[1] = 22
Value of a[2] = 33

7 Compare Bubble sort & Selection sort with suitable example and list their respective time
complexities.
Ans:

1. Bubble Sort
Bubble sort repeatedly compares and swaps(if needed) adjacent elements in every pass. In i-th pass of
Bubble Sort (ascending order), last (i-1) elements are already sorted, and i-th largest element is placed at
(N-i)-th position, i.e. i-th last position.

Algorithm:

BubbleSort (Arr, N) // Arr is an array of size N.


{
For ( I:= 1 to (N-1) ) // N elements => (N-1) pass
{
// Swap adjacent elements of Arr[1:(N-I)]such that
// largest among { Arr[1], Arr[2], ..., Arr[N-I] } reaches to Arr[N-I]
For ( J:= 1 to (N-I) ) // Execute the pass
{
If ( Arr [J] > Arr[J+1] )
Swap( Arr[j], Arr[J+1] );
}
}
}

2. Selection Sort
Selection sort selects i-th smallest element and places at i-th position. This algorithm divides the array
into two parts: sorted (left) and unsorted (right) subarray. It selects the smallest element from
unsorted subarray and places in the first position of that subarray (ascending order). It repeatedly
selects the next smallest element.
Algorithm:

SelectionSort (Arr, N) // Arr is an array of size N.


{
For ( I:= 1 to (N-1) ) // N elements => (N-1) pass
{
// I=N is ignored, Arr[N] is already at proper place.
// Arr[1:(I-1)] is sorted subarray, Arr[I:N] is undorted subarray
// smallest among { Arr[I], Arr[I+1], Arr[I+2], ..., Arr[N] } is at place min_index

min_index = I;
For ( J:= I+1 to N ) // Search Unsorted Subarray (Right lalf)
{
If ( Arr [J] < Arr[min_index] )
min_index = J; // Current minimum
}
Swap ( Arr[I], Arr[min_index] );
// Swap I-th smallest element with current I-th place element
}
}

SORTING ALGORITHM TIME COMPLEXITY


Best Case Average Case Worst Case
Bubble Sort O(N) O(N^2) O(N^2)
Selection Sort O(N^2) O(N^2) O(N^2)

8 Compare Insertion sort & Selection sort with suitable example and list their respective time
complexities.
Ans:
Insertion Sort:
Insertion Sort: Given a list, take the current element and insert it at the appropriate position of the list,
adjusting the list every time you insert. It is similar to arranging the cards in a Card game.
Time Complexity of selection sort is always n(n - 1)/2, whereas insertion sort has better time complexity
as its worst case complexity is n(n - 1)/2. Generally it will take lesser or equal comparisons then n(n - 1)/
2.

Selection Sort:

Selection Sort: Given a list, take the current element and exchange it with the smallest element on the
right hand side of the current element.
SORTING ALGORITHM TIME COMPLEXITY
Best Case Average Case Worst Case
Selection Sort O(N^2) O(N^2) O(N^2)
Insertion Sort O(N) O(N^2) O(N^2)

9 Define Function & outline the structure of a user defined function with example.
Ans:

A function is a block of code that performs a specific task. It has a name and it is reusable .It can be
executed from as many different parts in a program as required, it can also return a value to calling
program.
All executable code resides within a function. It takes input, does something with it, then give the
answer. A C program consists of one or more functions.

A computer program cannot handle all the tasks by itself. It requests other program like entities called
functions in C. We pass information to the function called arguments which specified when the function
is called. A function either can return a value or returns nothing. Function is a subprogram that helps
reduce coding.

The main reasons for using functions are:


• to improve the readability of code.
• improves the re-usability of the code, same function can be used in any program rather than
writing the same code.
• debugging of the code would be easier if you use functions (errors are easy to be traced).
• reduces the size of the code, duplicate set of statements are replaced by function calls.

Structure of a user defined function:

function prototype:

return_type Function_name ( data_type, data_type, ….. data_type);

function call:

function_name(var1, var2, ….varn);

Function Definition

Return_type function_name ( data_type var1, data_type var2 …. data_type varn) {

Local variables;
Local statements;
}

Example of Function in C
#include<stdio.h>
#include <conio.h>

int adition (int, int); //Function Declaration or prototype

int addition (int a, int b) //Function Definition


{
int r; r=a + b;
return (r);
}

int main()
{
int z;
z= addion(10,3); //Function Call
printf ("The Result is %d", z);
return 0;
}

Output: The Result is 13

10 Differentiate Pre-defined and User-defined functions. Write a function to find the factorial of a given
number.
Ans:
A function is a self-contained block of code that carries out some specific and well-defined task.
C functions are classified into two categories
1. Library Functions / Predefined functions
2. User Defined Functions

The user-defined functions are defined by a user as per its own requirement and library functions come
with compiler.

USER DEFINE FUNCTIONS BUILT IN FUNCTIONS


1. The function defined by the user according 1. These are commonly required functions that
to his or her requirement . are not grouped together & are stored in
library.
2. These functions can be modified by the 2. These functions cannot be modifiable.
programmers.
3. They are not predefined. 3. They are predefined.
4. These are written by the programmers. 4. These are not written by the programmers.
5. Not already available hence are created 5. Already available for the programmers to
when required. call.
6. They must be declared before they are 6. Declaration of it is not required.
used.
7. The user can understand the internal 7. It cannot understand the internal working of
working of these functions. these functions.
8.ex.area();etc., 8.ex.cos(x),sqrt(x),etc.,

Program for factorial of a number using function:

#include<stdio.h>
int fact(int);
void main() {
int n, f;
printf(“Enter a number : “);
scanf(‘%d”, &n);
f=fact(n);
printf(“Factorial of %d = %d\n”,n,f);
}
int fact(int n) {
int f=1, i;
for(i=1;i<=n;i++)
f=f*i;
return f;
}

Output:
Enter a number : 5
Factorial of 5 = 120

11 i) Explain about functions with no arguments and no return values with example.[3M]
Ans:
We can create a function with no arguments and no return values.
For Ex:
#include<stdio.h>
void add( void);
void main() {
add();
}
void add() {
int a, b;
printf(“Enter a b values: “);
scanf(“%d %d”, &a, &b);
printf(“%d + %d = %d\n”,a, b, a+b);
}

ii) Explain about functions with arguments and no return values with example.[4M]
Ans:
Similarly we can create a function with arguments and no return values:
For Ex:
#include<stdio.h>
void add( int , int);
void main() {
int a, b;
printf(“Enter a b values: “);
scanf(“%d %d”, &a, &b);
add(a, b);
}
void add(int x , int y) {
int z;
z=x+y;
printf(“%d + %d = %d\n”,x, y, z);
}

12 i) Explain about functions with no arguments and with return values with example.[3M]
Ans:
In this function type the calling function does not have any arguments from the called function.
But the calling function will send argument to the called function.
For Ex:
#include<stdio.h>
int add( void);
void main() {
int x = add();
printf( “Result = %d\n”, x);
}
int add() {
int a=5, b=10;
return (a+b);
}
Output:
Result = 15

ii) Explain about functions with arguments and return values with example.[4M]
Ans:
In this type of function type the calling function will send some arguments to called function and
called function will return a variable or value to calling function.
For Ex:
#include<stdio.h>
int add( int, int);
void main() {
int x=10, y=20, z;
z = add(x,y);
printf( “Result = %d\n”, z);
}
int add(int a, int b) {
return (a+b);
}
Output:
Result = 30

13 How parameters are passed using call by value? Explain with suitable example code snippets.
Ans:
In call by value we send either variables, constants or expressions to the calling function. Here the
values will be passed to the calling function. The called function values are not modified at the
calling function, even though they are modified at the calling function.

For example:
#include<stdio.h>
void add(int , int);
void main() {
int a=10, b=20;
printf(“Before calling add() in main() a = %d, b= %d\n”,a,b);
add(a,b);
printf(“After calling add() in main() a = %d, b= %d\n”,a,b);
}
void add( int a, int b) {
a= a+10;
b=b+10;
printf(“In add() function a = %d, b= %d\n”,a,b);
}
Output:
Before calling add() in main() a = 10, b=20;
In add() function a = 20, b=30
After calling add() in main() a = 10, b=20

14 What is call by value and write a C program for swapping of two numbers using call by value.
Ans:
In call by value the parameters passed to calling function as values. They will be copied to new
variables which are newly created at calling function.
Once the called function is completed its task, it will be destroyed.
The variables which are created, are local to that function only.
They will not create in impact on original variables.
In call by value, we can not send (return) more than one variable to the calling function.

For Example:
#include<stdio.h>
void swap( int, int);
void main() {
int a, b;
printf(“Enter two values : “);
scanf(“%d %d”, &a, &b);
printf(“Before swap in main() a = %d b = %d\n”, a, b);
swap(a,b);
printf(“After swap in main() a = %d b = %d\n”, a,b);
}

void swap ( int x, int y) {


int temp;
printf(“Before swaping in swap function x = %d y = %d\n”,x, y);
temp = x;
x = y;
y = temp;
printf(“After swaping in swap function x = %d y = %d\n”, x, y);
}

Output:

Enter two values : 10 20


Before swap in main() a = 10 b = 20
Before swaping in swap function x = 10 y = 20
After swaping in swap function x = 20 y = 10
After swap in main() a = 10 b = 20

15 Explain automatic, global and register storage classes in detail with examples.
Ans:
See Notes

16 Define storage class and explain extern and static storage classes in detail with examples.
Ans: (See Notes)
Storage classes provide the following information:
• Where the variable would be stored.
• What will be the initial value of the variable; i.e., the default value for the variable.
• What is the scope of the variable; i.e., if the variable is accessible globally or is local to a
function.
• What is the life of the variable; i.e., how long would the variable exist in memory.
Extern Storage class:
• External variables are used with separate compilations. It is common, on large projects, to
decompose the project into many source files.
• The decomposed source files are compiled separately and linked together to form one unit.
• Within file variables outside functions have external storage class, even without the keyword
extern.
• Global variables (defined outside functions) and all functions are of the storage class extern and
storage is permanently assigned to them.
• Files can be compiled separately, even for one program.
• extern is used for global variables that are shared across code in several files.
• a variable declared with a storage class of extent has a file scope; the extent is, static, but
linkage is external.

Declaration:

extern type variable_Name;

An external variable before must be declared before that is used by other source files. The
above syntax is used to external variables from other files.

Initialization

If the variable not initialized, then the first declaration seem by the linkage is considered the
definition and all other declarations reference it. If an initializer is used with a global definition it
is defining declaration.

// extern in multi-file projects


file1.c
  #include <stdio.h>
  int a =1, b = 2, c = 3; /* external variables */
int fun (void);
  int main (void)
{
printf (“%3d\n”, f( ));
printf (“%3d %3d %3d\n”, a, b, c); print 4, 2, 3
return 0;
} a is global and changed by f

 file2.c
int fun (void)
{
extern int a; /* look for it elsewhere */
int b, c;
  a = b = c = 4; b and c are local and don‘t survive
return (a + b + c);
} return 12

Note: The difference between a normal static variable and a extern static variable is that the
static external variable is available only within the file where it is defined while the simple
external variable can be accessed by other files.

Class Scope Extent Linkage Initial Value

auto block automatic internal indeterminate


register block automatic internal indeterminate
static(extern) block static internal Zero
static(linkage) file static internal Zero
extern file static external indeterminate

Static Storage Class:


When a variable is specified as static its value is persisted until the end of program.
A variable can be declared as a static variable by using the keyword static.
Auto variables are created each time they are initialized in a block and are destroyed when they go out
of scope.
However, static variables are initialized only once and they remain in existence till the end of program.
A static variable can either be local (to a function) or global.

The format for specifying static variables is


static data_type variable_1, variable_2,..., variable_n;
The static variables which are declared inside a function are stored in the statically allocated memory
and remains alive through out the execution of the program, but remember that their scope remains
local to the function.

The main difference between auto and static is that the static variables do not disappear when the
function is no longer active (in scope) and their values persist across multiple calls of the same function.

Some of the important points regarding static variables are:


Storage: Memory
Initial value: zero (0)
Keyword: static
Scope: local to the block in which it is defined
Lifetime: throughout the program execution
`Ex:
#include <stdio.h>
void increment(void);
void main() {
increment();
increment();
increment();
}
void increment(void) {
static int x = 3;
int y = 3;
printf("x = %d y = %d\n", x, y);
x++, y++;
}
Output:
x=3y=3
x=4y=3
x=5y=3

here x is static variable hence it retains the value during the function calls, and y is a normal variable
hence it is not retained its value.

17 Define preprocessing. Explain #define , #undef, #include directives with suitable examples.
Ans:
Preprocessing:
The preprocessor is a program which processes the source code before it passes through the
compiler.It operates under the control of preprocessor directive. These are placed in the source
program before the main.
Compilation

Preprocessor programs provide preprocessors directives which tell the compiler to preprocess the
source code before compiling. All of these preprocessor directives begin with a ‘#’ (hash) symbol.

This (‘#’) symbol at the beginning of a statement in a C indicates that it is a pre-processor directive.
We can place these preprocessor directives anywhere in our program. Examples of some
preprocessor directives are: #include, #define, #ifndef etc.

There are 4 main types of preprocessor directives:


1. Macros
2. File Inclusion
3. Conditional Compilation
4. Other directives
• Statements beginning with # are considered preprocessor directives.
• Preprocessor directives indicate certain things to be done to the program code prior to
compilation.
• It includes certain other files when compiling, replace some code by other code.
• Only white space characters before directives on a line.
• Preprocessor commands can be placed anywhere in the program.

#define:

This preprocessor directive can be used to create


a. Symbolic constants
b. Macros

a. Symbolic constants

Macro definition without arguments is referred as a constant. The body of the macro definition can
be any constant value including integer, float, double, character, or string. However, character
constants must be enclosed in single quotes and string constants in double quotes.

Example:

#define PI 3.14159
Here “PI” replaces with "3.14159"

b. Macros

A macro definition command associates a name with a sequence of tokens. The name is called the
macro name and the tokens are referred to as the macro body.

The following syntax is used to define a macro:

#define macro_name(<arg_list>) macro_body

#define is a define directive, macro_name is a valid C identifier.macro_body is used to specify how


the name is replaced in the program before it is compiled.

Example:

#define CIRCLE_AREA( x ) ( PI * ( x ) * ( x ) )
would cause
area = CIRCLE_AREA( 4 );
to become
area = ( 3.14159 * ( 4 ) * ( 4 ) );

#undef :
In the C Programming Language, the #undef directive tells the preprocessor to remove all definitions
for the specified macro. A macro can be redefined after it has been removed by the #undef
directive.

Once a macro is undefined, an #ifdef directive on that macro will evaluate to false.

Undefines a symbol specified by <identifier> which was previously defined with a #define directive.

• #undef Directive is used to undefine any Macro Symbol.


• #undef can undefine only “User Defined” Macro’s.
• #undef cannot undefine “Global Macro Identifiers“.
• #undef is used where we have to redefine any Macro Identifier.
Syntax
#undef macro_definition

macro_definition: The name of the macro which will be removed by the preprocessor.

Example:
/**
* C program to define, undefine and redefine a macro
*/

#include <stdio.h>

// Define PI
#define PI 3.14

int main()
{
printf("Value of PI: %f\n", PI);

// Undefine PI
#ifdef PI
#undef PI
#endif

// Redefine value of PI
#define PI 3.14159

printf("Value of PI after redefinition: %f", PI);

return 0;
}
Output:
Value of PI: 3.140000
Value of PI after redefinition: 3.141590

#include
We use #include directive to include contents of another file (especially header file's) to a program.
We can include a file in two different ways.

#include <file.h>

This variant of including header file, searches header file in the "standard header file directory".
Standard header file directory is the path where all header files are stored.

Syntax:

#include <header.h>

Where header.h is a standard C header file.

Example:

#include <stdio.h>
#include<math.h>

#include "file"

We use this variant of including file when we want to include our own/custom header file. It
searches the file in the current directory and then in the standard header file’s directory.

Syntax:

#include "path_to_header_file";

Where path_to_header_file is relative path to the header file.

Ex:
#include “myheader.c”

18 Explain how pre-processor directives can be used for defining macros with suitable examples.
Ans:

We can use pre processor directive #define to create a macro.

A macro definition command associates a name with a sequence of tokens. The name is called
the macro name and the tokens are referred to as the macro body.

The following syntax is used to define a macro:

#define macro_name(<arg_list>) macro_body

#define is a define directive, macro_name is a valid C identifier. macro_body is used to specify


how the name is replaced in the program before it is compiled.
Example
#define CIRCLE_AREA( x ) ( PI * ( x ) * ( x ) )
would cause
area = CIRCLE_AREA( 4 );
to become
area = ( 3.14159 * ( 4 ) * ( 4 ) );

Use parenthesis for coding macro_body,Without them the macro

#define CIRCLE_AREA( x ) PI * ( x ) * ( x )
would cause
area = CIRCLE_AREA( c + 2 );
to become
area = 3.14159 * c + 2 * c + 2;

19 Define conditional compilation. Explain different conditional compilation directives with examples.
Ans:

CONDITIONAL COMPILATION
In C, a programmer can instruct the preprocessor whether or not to include certain section of the
code. This is accomplished using conditional directives.

C pre-processor offers a feature called conditional compilation that is used to switch on or


off a particular line or group of lines in a program. Compiler skips over part of a source code by
inserting the pre-processing commands #ifdef and #endif, which have the general form as:

#ifdef macro
Stmt1;
Stmt2;
#endif

If macro has been #defined, the block of code will be processed as usual; otherwise not.

These are similar to if statements in syntax and usage. However, unlike if statements which are
executed during runtime, the conditional directives are executed before compilation by the
preprocessor.

These directives are used whenever there is a need to compile a portion of the program
conditionally. It is also known as conditional compilation.
 It allows us to control the compilation process by including or excluding statements.
 Cast expressions, size of, enumeration constants cannot be evaluated in preprocessor
directives.
 Its structure similar to if statement.

Syntax
#if expression1
code to be included for true
#elif expression2
code to be included for true
#else
code to be included false
#endif

The most common conditional directive #ifdef (spelt as if-defined) verifies if a given identifier is
defined or not.
The syntax for its usage is :#ifdef identifier or #if defined (identifier).

The source code following #ifdef will be compiled only if the given identifier is defined either in the
code or if it is provided as a compilation option as -Didentifier_name .

The opposite of #ifdef is #ifndef, which is written as #ifndef identifier or #if !defined (identifier).

Consider the following example:


#if defined (MAX)
#define MIN 20
#else
#define MAX 100
#define MIN 200
#endif
Here, MIN 20 will be defined only if the constant MAX is defined earlier than MIN 20. Else, both MAX
and MIN will be defined with values 100 and 200 respectively.

Example:

#if !defined( NULL )


#define NULL 0
#endif

Determines if symbolic constant NULL has been defined If NULL is defined, defined( NULL ) evaluates
to 1,If NULL is not defined, and this function defines NULL to be 0.
Every #if must end with #endif.
#ifdef short for #if defined( name ).
#ifndef short for #if !defined( name ).

Command Meaning

#if expression When expression is true, the code that follows is


included for compilation.

#endif Terminates the conditional command.

#else Specifies alternate code in two-way decision.


#elif Specifies alternate code in multi-way decision.

#ifdef name Tests for the macro definition.

#ifndef name Tests whether macro is not defined .

20 Explain #ifdef, #ifndef directives with suitable example code snippets.


Ans:

See the above Answers from previous questions


The most common conditional directive #ifdef (spelt as if-defined) verifies if a given identifier is
defined or not.
The syntax for its usage is :#ifdef identifier or #if defined (identifier).

The source code following #ifdef will be compiled only if the given identifier is defined either in the
code or if it is provided as a compilation option as identifier_name .

The opposite of #ifdef is #ifndef, which is written as #ifndef identifier or #if !defined (identifier).

Consider the following example:


1. Write a C program to find ncr for a given n and r values using recursion.

Ans:

#include <stdio.h>
int fact(int num);
void main()
{
int n, r, ncr_var;

printf("Enter the value of n:");


scanf("%d", &n);
printf("\nEnter the value of r:");
scanf("%d", &r);

/* ncr is also represented as C(n,r), the formula is:


* C(n,r) = n! / ( r!(n - r)! ). For 0 <= r <= n.
*/
ncr_var = fact(n) / (fact(r) * fact(n - r));
printf("\nThe value of C(%d,%d) is: %d",n,r,ncr_var);
}

/* This function is used to find the * factorial of given number num */


int fact(int num)
{
int k = 1, i;
// factorial of 0 is 1
if (num == 0)
{
return(k);
}
else
{
for (i = 1; i <= num; i++)
{
k = k * i;
}
}
return(k);
}
Output:

Enter the value of n:


5
Enter the value of r:
2
The value of C(6,2) is: 15
2. Define Recursion and write a C program to print Fibonacci series using recursion.

Definition

Recursion is a process in which a function calls itself as a subroutine. This allows the function to be
repeated several times, since it calls itself during its execution. Functions that incorporate recursion are
called recursive functions.

Recursion is often seen as an efficient method of programming since it requires the least amount of code
to perform the necessary functions. However, recursion must be incorporated carefully, since it can lead
to an infinite loop if no condition is met that will terminate the function.

A recursive function should meet two properties.

i) Base condition
ii) Recursiveness

#include<stdio.h>
#include<conio.h>
void main()
{
int f,f1,f2,n,i,res;
printf("enter the limit:");
scanf("%d",&n);
printf("The fibonacci series is:");
for(i=0;i<n;i++)
{
res=fib(i);
printf("%d\t",res);
}
}

int fib(int i)
{
if(i==0)
return 0; // Base condition
else if(i==1)
return 1;
else
return(fib(i-1)+fib(i-2)); //Recursiveness
} /

2. Write a C program to implement Ackermann function using recursion.


Ans:

#include <stdio.h>
#include <math.h>
void main() {
long int m, n;
printf("Enter two numbers : ");
scanf("%li %li", &m, &n);
printf("A(%li, %li) = %lli\n", m, n, ackermannFun(m, n));
}

long int ackermannFun(long int m, long int n) {


if (m == 0)
return n + 1;
else if ((n == 0) && (m > 0))
return ackermannFun(m - 1, 1);
else
return ackermannFun(m - 1, ackermannFun(m, n - 1));
}
Output:
Enter two numbers : 2 2
A(2, 2) = 7

2nd Method:
#include <stdio.h>
long long int ackermann(long long int m, long long int n)
{
if (!m) return n + 1;
if (!n) return ackermann(m - 1, 1);
return ackermann(m - 1, ackermann(m, n - 1));
}

int main()
{
long long int m, n;
for (m = 0; m <= 4; m++)
for (n = 0; n < 6 - m; n++)
printf("A(%lld, %lld) = %lld\n", m, n, ackermann(m, n));

return 0;
}

Output:
A(0, 0) = 1
A(0, 1) = 2
A(0, 2) = 3
A(0, 3) = 4
A(0, 4) = 5
A(0, 5) = 6
A(1, 0) = 2
A(1, 1) = 3
A(1, 2) = 4
A(1, 3) = 5
A(1, 4) = 6
A(2, 0) = 3
A(2, 1) = 5
A(2, 2) = 7
A(2, 3) = 9
A(3, 0) = 5
A(3, 1) = 13
A(3, 2) = 29
A(4, 0) = 13

3. Explain Towers of Hanoi problem with example.


Ans:
Tower of Hanoi is a mathematical puzzle where we have three rods and n disks. The objective of the
puzzle is to move the entire stack to another rod, obeying the following simple rules:
1) Only one disk can be moved at a time.
2) Each move consists of taking the upper disk from one of the stacks and placing it on top of another
stack i.e. a disk can only be moved if it is the uppermost disk on a stack.
3) No disk may be placed on top of a smaller disk.

Approach:
Input : 2
Output : Disk 1 moved from A to B
Disk 2 moved from A to C
Disk 1 moved from B to C

Input : 3
Output : Disk 1 moved from A to C
Disk 2 moved from A to B
Disk 1 moved from C to B
Disk 3 moved from A to C
Disk 1 moved from B to A
Disk 2 moved from B to C
Disk 1 moved from A to C
A recursive algorithm for Tower of Hanoi :

START
Procedure Hanoi(disk, source, dest, aux)

IF disk == 1, THEN
move disk from source to dest
ELSE
Hanoi(disk - 1, source, aux, dest) // Step 1
move disk from source to dest // Step 2
Hanoi(disk - 1, aux, dest, source) // Step 3
END IF

END Procedure
STOP

4. Write an algorithm for quick sort


Ans:

5. Write a C program to implement Quick sort


Ans:

#include<stdio.h>
void quicksort(int number[25],int first,int last){
int i, j, pivot, temp;
if(first<last){
pivot=first;
i=first;
j=last;
while(i<j){
while(number[i]<=number[pivot]&&i<last)
i++;
while(number[j]>number[pivot])
j--;
if(i<j){
temp=number[i];
number[i]=number[j];
number[j]=temp;
}
}
temp=number[pivot];
number[pivot]=number[j];
number[j]=temp;
quicksort(number,first,j-1);
quicksort(number,j+1,last);
}
}

int main(){
int i, count, number[25];
printf("Enter some elements (Max. - 25): ");
scanf("%d",&count);
printf("Enter %d elements: ", count);
for(i=0;i<count;i++)
scanf("%d",&number[i]);
quicksort(number,0,count-1);
printf("The Sorted Order is: ");
for(i=0;i<count;i++)
printf(" %d",number[i]);
return 0;
}
Output:
Enter some elements (Max. - 25): 5
Enter 5 elements: 2 1 5 4 3
The Sorted Order is: 1 2 3 4 5

6. What is pointer? Illustrate with a sample code. What are its merits and demerits?
Ans:

A pointer is a variable which contains the address in memory of another variable. We can have a
pointer to any variable type. The ampersand operator & gives the “address of a variable”. The
indirection or dereference operator * gives the “contents of an object pointed to by a pointer”.

A pointer is declared as follows:

int *ptr;
where *ptr is a pointer of int type.

A Program to display the value of an int variable through pointer is listed below
#include<stdo.h>
void main()
{
int k;
int *ptr;

k=10;
ptr=&k;
printf("\n Value of k is %d\n\n",k);
printf("%d is stored at addr %u\n",k,&k);
printf("%d is stored at addr %u\n",*ptr,ptr);
*ptr=25;
printf("\n Now k = %d\n",k);
}
Output of the program is:
Value of k is 10
10 is stored at addr 65524
10 is stored at addr 65524
Now k=25.

Merits of using pointers are:-


1. Pointers are more efficient in handling arrays and data tables.
2. Pointers can be used to return multiple values from a function via function arguments.
3. The use of pointer arrays to character strings results in saving of data storage space in memory.
4. Pointers allow C to support dynamic memory management.
5. Pointers provide an efficient tool for manipulating dynamic data structures such as structures ,
linked lists , queues , stacks and trees.
6. Pointers reduce length and complexity of programs.
7. They increase the execution speed and thus reduce the program execution time.

Demerits of Pointers:
1. If sufficient memory is not available during runtime for the storage of pointers, the program may
crash.
2. If the programmer is not careful and consistent with the use of pointers, the program may crash.
3. Direct access to memory means you can do things that perhaps you should not. Sometimes
unintentionally (or intentionally) access to memory that is not yours, you could overwrite critical
memory, modify the code of a running application, or cause your application or another
application to behave or exit unexpectedly.

8. With suitable code snippets, explain the different arithmetic operations that can be
performed with pointers in C.

(See Notes)
 Like normal variables, pointer variables can be used in
expressions. Ex: x= (*p1) + (*p2);

 C language allows us to add integers to pointers and to subtract integers from pointers
Ex: If p1, p2 are two pointer variables then operations such as p1+4, p2 - 2, p1 - p2
can be performed.

 Pointers can also be compared using relational operators.


Ex: p1>p2, p1==p2, p1! =p2 are valid operations.

 We should not use pointer constants in division or multiplication. Also, two


pointers cannot be added. p1/p2, p1*p2, p1/3, p1+p2 are invalid operations.

 Pointer increments and scale factor:-

Let us assume the address of p1 is 1002. After using p1=p1+1, the value becomes
1004 but not 1003.

Thus when we increment a pointer, its values is increased by length of data type that
points to. This length is called scale factor.

9. How parameters are passed using call by reference? Explain with suitable example code
snippets.
Ans:

Pass by reference or sending the addresses of the arguments- the addresses of actual arguments in the
calling function are copied into formal arguments of the called function.
Using these addresses we are actually working on actual argument so changes will be reflected in the
calling function. This technique of passing arguments is called pass by reference, illustrated by following
example.

#include<stdio.h>
void main()
{
int i=10,j=20;
printf("The values before swap is i: %d, j:%d\n",i,j);
swapr(&i,&j);
printf("The values after swap is i: %d, j:%d\n",i,j);
}
swapr(int *x, int *y)
{
int temp;
temp=*x;
*x=*y;
*y=temp;
}

Tthe result of calling swapr(), call by reference is i=20 and j=10.

11. Describe in detail the different dynamic memory handling functions with example.

Ans:
malloc( ): It is a memory allocation function that allocates requested size of bytes and returns a pointer to
the first byte of the allocated space. The malloc function returns a pointer of type void so we can assign it
to any type of pointer. It takes the the following form:

ptr= (cast type *) malloc(byte-size);

where ptr is a pointer of type cast-type. For example, the statement

x=(int *) malloc(10 *sizeof(int)) means that a memory space equivalent to 10 times the size of an int byte
is reserved and the address of the first byte of memory allocated is assigned to the pointer x of int type.

The malloc function can also allocate space for complex data types such as structures. For example:

ptr= (struct student*) malloc(sizeof (struct student)); where ptr is a pointer of type struct student.

calloc( ): It is another memory allocation function that allocates space for an array of elements, initializes
them to zero and then returns a pointer to the memory. This function is normally used for requesting
memory space at run time. It takes the following form:

ptr= (cast type *) calloc(n, element-size);

This statement allocates contiguous space for n blocks, each of size element-size bytes.

realloc( ): realloc is a memory allocation function that modifies the size of previously allocated space.
Sometime it may happen that the allocated memory space is larger than what is required or it is less than
what is required. In both cases, we can change the memory size already allocated with the help of the
realloc function known as reallocation of memory. For example, if the original allocation is done by
statement

ptr= malloc(size);

then reallocation is done by the statement

ptr=realloc(ptr,newsize); which will allocate a new memory space of size newsize to the pointer variable
ptr and returns a pointer to the first byte of the new memory block.

13. Explain the process of representing 1D arrays using pointers using suitable code snippets.

Ans:

14.
15. Explain the process of represeting 2D arrays using array of pointers through appropriate code
snippets.
Ans:

16. Write a program to find the sum of elements of 1D integer array by using Dynamic Memory
Allocation.

Ans:
#include<stdio.h>
#include<stdlib.h>
void main() {
int *p, n, i, sum=0;
printf("Enter No.of array elements : ");
scanf("%d", &n);
p=(int *) malloc(n * sizeof(int));
printf("Enter %d Elements : ",n);
for(i=0;i<n;i++)
scanf("%d",(p+i));
printf("The elements in the array are : ");
for(i=0;i<n;i++){
printf("%d ",*(p+i));
sum+=*(p+i);
}
printf("\nSum of the Array elements is : %d\n", sum);
}

Output:

Enter No.of array elements : 3


Enter 3 Elements : 3 1 9
The elements in the array are : 3 1 9
Sum of the Array elements is : 13
17. Explain about NULL and VOID pointers with example.
Ans:

NULL Pointer

NULL Pointer is a pointer which is pointing to nothing. In case, if we don’t have address to be assigned
to a pointer, then we can simply use NULL.

#include <stdio.h>
int main()
{
// Null Pointer
int *ptr = NULL;

printf("The value of ptr is %p", ptr);


return 0;
}
Output :
The value of ptr is (nil)

Important Points

 NULL vs Uninitialized pointer – An uninitialized pointer stores an undefined value. A null


pointer stores a defined value, but one that is defined by the environment to not be a valid address
for any member or object.
 NULL vs Void Pointer – Null pointer is a value, while void pointer is a type
Void pointer

Void pointer is a specific pointer type – void * – a pointer that points to some data location in storage,
which doesn’t have any specific type. Void refers to the type. Basically the type of data that it points to is
can be any. If we assign address of char data type to void pointer it will become char Pointer, if int data
type then int pointer and so on. Any pointer type is convertible to a void pointer hence it can point to any
value.

Important Points

 void pointers cannot be dereferenced. It can however be done using typecasting the void pointer.
 Pointer arithmetic is not possible on pointers of void due to lack of concrete value and thus size.

Example:

#include<stdlib.h>
int main()
{
int x = 4;
float y = 5.5;

//A void pointer


void *ptr;
ptr = &x;

// (int*)ptr - does type casting of void


// *((int*)ptr) dereferences the typecasted void pointer variable.

printf("Integer variable is = %d", *( (int*) ptr) );

// void pointer is now float


ptr = &y;
printf("\nFloat variable is= %f", *( (float*) ptr) );

return 0;
}

Output:

Integer variable is = 4
Float variable is= 5.500000

18. Explain about CONSTANT POINTER & POINTER TO CONSTANT VARIBLE with example.

Ans:

1) Constant Pointers :
These type of pointers are the one which cannot change address they are pointing to. This means suppose
there is a pointer which points to a variable (or stores the address of that variable). Now if we try to point
the pointer to some other variable (or try to make the pointer store address of some other variable), then
constant pointers are incapable of this.

A constant pointer is declared as :

int *const ptr; ( the location of 'const' make the pointer 'ptr' as constant pointer)

Example
Constant Pointer
#include<stdio.h>

int main(void)
{
int a[] = {10,11};
int* const ptr = a;

*ptr = 11;

printf("\n value at ptr is : [%d]\n",*ptr);


printf("\n Address pointed by ptr : [%p]\n",(unsigned int*)ptr);

ptr++;
printf("\n Address pointed by ptr : [%p]\n",(unsigned int*)ptr);

return 0;
}

Now, when we compile the above code, compiler complains :


practice # gcc constant_pointer.c -o constant_pointer
constant_pointer.c: In function ‘main’:
constant_pointer.c:13: error: increment of read-only variable ‘ptr’
Hence we see very clearly above that compiler complains that we cannot changes the address held by a
constant pointer.
2) Pointer to Constant : These type of pointers are the one which cannot change the value they are
pointing to. This means they cannot change the value of the variable whose address they are holding.
A pointer to a constant is declared as : const int *ptr (the location of 'const' makes the pointer 'ptr' as a
pointer to constant.
#include<stdio.h>

int main(void)
{
int a = 10;
const int* ptr = &a;

printf("\n value at ptr is : [%d]\n",*ptr);


printf("\n Address pointed by ptr : [%u]\n",(unsigned int*)ptr);

*ptr = 11;
return 0;
}
Now, when the above code is compiled, the compiler complains :

practice # gcc pointer_to_constant.c -o pointer_to_constant


pointer_to_constant.c: In function ‘main’:
pointer_to_constant.c:12: error: assignment of read-only location ‘*ptr’
Hence here too we see that compiler does not allow the pointer to a constant to change the value of the
variable being pointed.

19. Describe Dangling Pointer problem with suitable example.


Ans:
Dangling pointer

A pointer pointing to a memory location that has been deleted (or freed) is called dangling pointer. There
are three different ways where Pointer acts as dangling pointer.
1. De-allocation of memory

// Deallocating a memory pointed by ptr causes dangling pointer

#include <stdlib.h>
#include <stdio.h>
int main()
{
int *ptr = (int *)malloc(sizeof(int));

// After below free call, ptr becomes a


// dangling pointer
free(ptr);

// No more a dangling pointer


ptr = NULL;
}

2. Function Call

// The pointer pointing to local variable becomes dangling when local variable is not static.

#include<stdio.h>

int *fun()
{
// x is local variable and goes out of scope after an execution of fun() is over.
int x = 5;

return &x;
}

// Driver Code
int main()
{
int *p = fun();
fflush(stdin);

// p points to something which is not valid anymore


printf("%d", *p);
return 0;
}

Output:
A garbage Address

The above problem doesn’t appear (or p doesn’t become dangling) if x is a static variable.

3. Variable goes out of scope


void main()
{
int *ptr;
.....
.....
{
int ch;
ptr = &ch;
}
.....
// Here ptr is dangling pointer
}

20. Explain unreferenced memoy problem, memory leak with suitable examples.
Ans:

Unreferenced memory problem:

The main challenges while using pointers are:


 Dangling pointers
 Memory leakages

Dangling pointer is a pointer which points to a memory that has been freed or deallocated. Such a pointer
still points to the memory location of the deallocated memory, accessing such memory might cause
segmentation fault error.

In simple terms, a pointer pointing to a non-existing memory location is called a dangling pointer.

example:
void main() {
int *p = (int *) malloc(sizeof(int)); // allocating heap memory
....
free(p); // after deallocating the heap memory, *p now becomes a dangling pointer
*p = 12; // trying to access non-existing memory location can result in error
}
Example 2:
void main() {
int *q;
int *p = (int *) malloc(sizeof(int)); // allocating heap memory
q = p; // store the address containing in p to q i.e., p and q are referring the same heap memory
free(q); // after deallocating the heap memory through q
*p = 12;
// trying to access non-existing memory location through p which is also a dangling pointer, can result in
an error
}

Memory Leaks
Memory leak occurs when programmers create a memory in heap and forget to delete it. Memory leaks
are particularly serious issues for programs like daemons and servers which by definition never terminate.

A memory leak reduces the performance of the computer by reducing the amount of available memory.

A memory leak is that memory which hasn't been freed and there is usually no way to free it anymore.
This can result when a pointer which was the only reference to a memory location (that was dynamically
allocated and not freed) now points somewhere else.

example:
void main() {
int *p = (int *) malloc(sizeof(int)); // allocating heap memory
*p = 12;
printf("The given value = %d\n",*p);
*p = (int *) malloc( 3 * sizeof(int));
// allocating a new memory, the previously allocated memory results in a memory leak
}
1 Illustrate how to define and initialize structure datatype. Also illustrate how to access structure
elements.
Ans:

We can define a structure with struct key word. It can be defined in two ways.

The syntax for defining structure is :

Method 1:
struct structure-tag {
data_type structure member_1;
data_type structure member_2;
data_type structure member_3;
….
….
data_type structure member_n;
};
struct structure-tag structure_variable1, structure_variable2, ….structure_variablen;

Method 2:
struct structure-tag {
data_type structure member_1;
data_type structure member_2;
data_type structure member_3;
….
….
data_type structure member_n;
} structure_variable_1, structure_variable_2, ….structure_variable_n;

Example 1:
struct student {
int no;
char name[30];
float fee;
} s1;

We can access the structure elements by using dot (.) operator. If the member (element) is a pointer
type, then we have to use arrow (->)operator.

Example for above s1 structure variable is initialized at the time of declaration like bellow:
struct student {
int no;
char name[30];
float fee;
} s1={101, “Raju”,25000};

We can access those elements in the following manner.


printf(“Student No = %d\n”,s1.no);
printf(“Student name = %s\n”,s1.name);
printf(“student Fee = %.2f\n”, s1.fee);

2 Write a program to compare two structure varaibles of same data type.


Ans:

We cannot compare two structure variables directly bu using equality (==) operator. We have
compare each element in both the structure variables even though they are of same type.

Example Program:
struct employee{
int number;
int sal;
};
#include<stdio.h>
void main()
{
int x;

struct employee e1 = {111,4500};


struct employee e2 = {222,4350};

x = ((e1.number == e2.number) && (e1.sal == e2.sal)) ? 1 : 0;

if(x == 1)
{
printf("\nEmployee1 and employee2 are same\n\n");
printf("%d %d\n", e1.number,e2.sal);
}
else
printf("\nEmployee1 and Employee2 are different\n\n");

Output
Employee1 and Employee2 are different

3 Define nested structure? Write a C program to print the details of college(College ID, College
Name) and student(Student No, Name, Marks) by embedding student structure in college
structure.
Ans:

Nested structure in C is nothing but structure within structure. One structure can be declared inside
other structure as we declare structure members inside a structure.

Ex:
struct student {
int sno;
char sname[30];
struct date {
int day;
int month;
int year;
} doa;
};

Otherwise we can declare two structures separately and we can insert other structure as a member of
the current structure.
Ex:

struct date {
int day;
int month;
int year;
};

struct student {
int sno;
char sname[30];
struct date doa;
};

The structure variables can be a normal structure variable or a pointer variable to access the data.
 Structure within structure in C using normal variable
 Structure within structure in C using pointer variable

Program:
#include <stdio.h>
#include <string.h>

struct college
{
int cid;
char cname[30];
struct student
{
int sid;
char sname[20];
int smarks;
}s;
};

void main()
{
struct college c = {33, "MVGRCE", {501,"Ravi",450}};
printf("College Id is: %d\n", c.cid);
printf("College Name is: %s\n\n", c.cname);
printf("Student Id is: %d\n\n", c.s.sid);
printf("Student Name : %s\n",c.s.sname);
printf("Student Marks: %d\n",c.s.smarks);
}
output:
College Id is: 33
College Name is: MVGRCE

Student Id is: 501


Student Name : Ravi
Student Marks: 450

4 Write a C program which reads n students data and print the details of the students who are
passed.
Ans:
#include<stdio.h>
struct student {
int no;
char name[30];
int marks;
char res;
}s[10];
void main() {
int n,i;
printf("Enter No. of students : ");
scanf("%d", &n);
printf("Enter %d student details : \n",n);
for(i=0;i<n;i++){
printf("Enter Student no, name and marks : ");
scanf("%d %s %d",&s[i].no, s[i].name, &s[i].marks);
if(s[i].marks<40)
s[i].res='F';
else
s[i].res='P';
}
printf("Student Details are : \n");
printf("Sno\tSname\tMarks\tResult\n");
for(i=0;i<n;i++)
printf("%d\t%s\t%d\t%c\n",s[i].no,s[i].name,s[i].marks,s[i].res);
}

Output:
Enter No. of students : 2
Enter 2 student details :
Enter Student no, name and marks : 101 rahul 45
Enter Student no, name and marks : 102 renuka 33
Student Details are :
Sno Sname Marks Result
101 rahul 45 P
102 renuka 33 F

5 Explain how the structure variable passed as a parameter to a function with example
Ans:

Structure variables can be passed to passed to any function like array variables, i.e., we can pass
the structures to functions in two ways.
 Passing structure to a function by value
 Passing structure to a function by address(reference)
 No need to pass a structure – Declare structure variable as global

Example:
Either 1st method or 2nd method 5 Marks

Example Program:

#include <stdio.h>
#include <string.h>

struct student
{
int id;
char name[20];
float percentage;
};

void func(struct student record);

int main()
{
struct student record;

record.id=1;
strcpy(record.name, "Raju");
record.percentage = 86.5;

func(record);
return 0;
}

void func(struct student record)


{
printf(" Id is: %d \n", record.id);
printf(" Name is: %s \n", record.name);
printf(" Percentage is: %f \n", record.percentage);
}
6 Explain pointer to structure variable with suitable example.
Ans:

Like a pointer variable of any primitive data type, a pointer can also be declared as a structure variable
using the following syntax:

struct tag_name *variable_name;

A structure pointer variable is capable of storing address of a structure variable. Once a pointer is
declared to a structure, members of that structure are accessed in two ways.
 Using -> operator
 Using *. Operator

Below is an example of a pointer to the structure:

#include <stdio.h>
struct account {
char name[20];
int acc_no;
float balance;
};
void main() {
struct account acc, *p;
p = &acc;
printf("Enter the name of account holder : ");
scanf("%s", p->name);
printf("Enter the account number : ");
scanf("%d", &p->acc_no);
printf("Enter the balance : ");
scanf("%f", &p->balance);
printf("The given account details are...\n");
printf("Name: %s\nAccount number: %d\nBalance: %f\n", (*p).name, (*p).acc_no, p->balance);
}

Output:
Enter the name of account holder : ravi
Enter the account number : 101
Enter the balance : 1000
The given account details are...
Name: ravi
Account number: 101
Balance: 1000.000000
7 Describe a self-referential structure and explain through code example in what context a self-
referential structure is necessary.
Ans:

A structure definition which includes at least one member as a pointer to the same structure is
known as self-referential structure.
It can be linked together to form useful data structures such as lists, queues, stacks and
trees. It is terminated with a NULL pointer .

The syntax for using the self referential structure is as follows:

struct tag_name
{
Type1 member1;
Type2 member2;
……….
struct tag_name *next;
};

Ex:-

struct node
{
int data;
struct node *next;
} n1, n2;

Example code
#include <stdio.h>
struct node {
int data;
struct node *next;
};
void main() {
struct node n1, n2;
printf("Enter an integer for first structure variable : ");
scanf("%d", &n1.data);
printf("Enter an integer for second structure variable : ");
scanf("%d", &n2.data);
n1.next = &n2;
n2.next = NULL;
printf(" %d --> %d\n", n1.data, n1.next->data);
}

Output:
Enter an integer for first structure variable : 10
Enter an integer for second structure variable : 20
10 --> 20

8 Write a short notes on typedef and show its usage in structure data type with a program.
Ans:
By using typedef keyword, we can define an alias of the structure.

Structure declaration with typedef Syntax:

typedef struct{
members_declarations;
}structure_tag;

Structure variable declaration with typedef Syntax:

structure_tag structure_name;

Here there is no need to use struct keyword while declaring its variable.

Structure declaration with typedef Example:

//structur declaration with typedef

typedef struct {
char name[30];
int age;
}employee_str;

Structure declaration with typedef Example:

//declare structure variable for employee_str


employee_str emp;
#include <stdio.h>
#include <string.h>

//structur declaration with typedef


typedef struct {
char name[30];
int age;
}employee;

int main()
{
employee emp;
strcpy(emp.name, "Rahul B");
emp.age = 25;

printf("Employee detail:\n");
printf("Name: %s\n",emp.name);
printf("Age: %d\n",emp.age);

return 0;
}
Output:
Employee detail:
Name: Rahul B
Age: 25

9 Define Union? How to declare and initialize unions? Discuss.


Ans:

Union definition:

Union is similar to structure, but the memory allocation is different to structure. The structure size is
collection all structure members size. But for union the largest element of union member’s size is
allocated to the union variable.

Declaring structure / union

struct student {
int a;
float b;
char ch;
} s; // size of the s is 9 bytes

union student {
int a;
float b;
char ch;
} u; // size of the u is 4 bytes

We can initialize and access union members member by member Where as in structure we can initialize
and access all the variables at once.

Initializing Unions:

Union enables us to treat the same space in memory as a number of different variables. We can
define a union member as union item item1;
We cannot assign different values to the different union elements at the same time.
We can do u.a=5;
or
u.b=5.5;
or
u.ch=’A’;

10 Write a C program to read and print a date using dd/mm/yyyy format using bit-fields and
differentiate the same without using bit-fields
Ans:

#include<stdio.h>
struct date1{
unsigned int day;
unsigned int month;
unsigned int year;
}doj={24,10,2019};

struct date2{
unsigned int day:5;
unsigned int month:5;
unsigned int year:22;
}doa={10,12,1998};

void main() {

printf("Date of Join = %d-%d-%d\n",doj.day,doj.month,doj.year);


printf("Date of admission = %d-%d-%d\n",doa.day,doa.month,doa.year);

printf("Size of the date1 using Structure without bitfields = %d\n",sizeof(doj));


printf("Size of the date2 using Structure with bitfields = %d\n",sizeof(doa));
}

Output:
Date of Join = 24-10-2019
Date of admission = 10-12-1998
Size of the date1 using Structure without bitfields = 12
Size of the date2 using Structure with bitfields = 4

We can observe that the structure with bit fields take less space compare to normal structure.

11 Describe in detail about any 3 file handling functions in C.


Ans:

C provides several file handling functions through stdio.h

Basic operations on file:


1. Naming a file
2. Opening a file
3. Reading data from file
4. Writing data into file
5. Closing a File

In order to perform the basic file operations C supports a number of functions .Some of the
important file handling functions available in the C library are as follows :

FUNCTION NAME OPERATION


fopen() Creates a new file for use
Opens an existing file for use

fclose() Closes a file which has been opened for use


fcloseall() Closes all files which are opened
getc()/fgetc() Reads a character from a file
putc()/fputc() Writes a character to a file
fprintf() Writes a set of data values to files
fscanf() Reads a set of data values from files
getw() Reads an integer from file
putw() Writes an integer to a file
gets() Reads a string from a file
puts() Writes a string to a file
fseek() Sets the position to a desired point in afile
ftell() Gives the current position in the file
rewind() Sets the position to the beginning of the file

***Note you have to write any 3 functions elaborately

fopen():

Syntax for opening a file is :

FILE *<file pointer>;


<file pointer> = fopen(“<file Name>”, “mode”);

Ex:
FILE *fp;
fp=fopen(“a.txt”,”r”);

Available modes are: r, w, a, r+,w+, a+ for text files and rb, wb, ab, rb+,wb+, ab+ for binary
files.

fclose() :

The file (both text and binary) should be closed after reading/writing.
Closing a file is performed using library function fclose().

fclose(fptr); //fptr is the file pointer associated with file to be closed.


When the reading or writing of a file is finished, the file should be closed properly using
fclose() function. The fclose() function does the followling tasks:

 Flushes any unwritten data from memory.


 Discards any unread buffered input.
 Frees any automatically allocated buffer
 Finally, close the file.

12 Explain getc(),putw() ,fcloseall() file handling functions with examples.


Ans:
getc()
We can read haracters using getc() from files.
The functions getc() and fgetc() are used to read a character from the file which is opened for reading
purpose. Both functions have same syntax and their working is also same.
The general syntax of getc() is:
int getc(FILE *fp);
The getc() function returns the ASCII equivalent of the character that is being read. If an error occurs in
reading,then it returns EOF.

example:
FILE *fp;
fp = fopen("sample.txt", "r");
ch= getc(fp);

Here, a single character is read from the file with logical name fp. That character is assigned to character
variable ch.

putw()
We can write integers using putw().
The function putw() is used to write an integer value to the file pointed by the file pointer.
The syntax of putw() is:
putw(int number, FILE *fp);

The putw() function takes two arguments, first is an integer value to be written to the file and second is
the file pointer where the number will be written.

Example:
FILE *fp;
int number;
fp = fopen("sample-numbers1.txt","w");
printf("Enter numbers up to 0 : ");
scanf("%d",&number);
while (number != 0) {
putw(number,fp);
scanf("%d",&number);
}
putw(number,fp);
fclose(fp);
fp = fopen("sample-numbers1.txt", "r");
printf("The given numbers are : ");
while ((number = getw(fp)) != 0) {
printf("%d ",number);
}
fclose(fp);

fcloseall()
Sometimes we open multiple files for processing then it is tedious task to close all the open streams one
by one after usage. C provides powerful feature to close all the open streams using single method.
fcloseall() : Does not closed following Streams
1 stdin Standard Input Stream

2 stdout Standard Output Stream

3 stdprn Standard Printer Stream

4 stderr Standard Error Stream


Declaration :
int fcloseall(void);
Remark : Explanation
Remark Point Explanation

Return Value on Success No of Streams Closed by Function

Return Value on Failure EOF

Usage Closing all the open streams


Example
#include<stdio.h>
{
int streams_closed;

fopen("ONE.txt","w");
fopen("TWO.txt","w");

streams_closed = fcloseall();

if (streams_closed == EOF)
printf("Error");
else
printf("%d Streams Were Closed", streams_closed);

return 0;
}
Output :
2 Streams Were Closed

13 Define File? How do you declare a file? Explain different modes of operations on files with
examples.
Ans:
In C programming, file is a place on your physical disk where information is stored.
We have to declare a file pointer with FILE data structure.

For ex: If we want to open a file with name a.txt,

Syntax for opening a file is :

FILE *<file pointer>;


<file pointer> = fopen(“<file Name>”, “mode”);

Ex:
FILE *fp;
fp=fopen(“a.txt”,”r”);

We can open a file with different modes. They are:

Mode Meaning of Mode Remarks

If the file does not exist, fopen() returns


r Open for reading.
NULL.

If the file does not exist, fopen() returns


rb Open for reading in binary mode.
NULL.

If the file exists, its contents are overwritten.


w Open for writing.
If the file does not exist, it will be created.

wb Open for writing in binary mode. If the file exists, its contents are overwritten.
If the file does not exist, it will be created.

Open for append. i.e, Data is added


a If the file does not exists, it will be created.
to end of file.

Open for append in binary mode.


ab If the file does not exists, it will be created.
i.e, Data is added to end of file.

If the file does not exist, fopen() returns


r+ Open for both reading and writing.
NULL.

Open for both reading and writing in If the file does not exist, fopen() returns
rb+
binary mode. NULL.

If the file exists, its contents are overwritten.


w+ Open for both reading and writing.
If the file does not exist, it will be created.

Open for both reading and writing in If the file exists, its contents are overwritten.
wb+
binary mode. If the file does not exist, it will be created.

Open for both reading and


a+ If the file does not exists, it will be created.
appending.

Open for both reading and


ab+ If the file does not exists, it will be created.
appending in binary mode.

14 Write a C program to copy contents of one file into another file.


Ans:
#include<stdio.h>
#include<stdlib.h>
void main()
{
FILE *fp; /* file pointer*/
char fname[20], ch;
printf("\nEnter file name to create :");
scanf("%s",fname);
fp=fopen(fname,"w"); // creating (open) a file
/*check file created or not*/
if(fp==NULL)
{
printf("File does not created!!!");
exit(0); /*exit from program*/
}
printf("File created successfully.");
/*writting into file*/
printf("\nEnter text to write (press ‘@’ to quit):\n");
while( (ch=getchar())!=’@’) {
putc(ch,fp); /*write charactr into file*/
}
fclose(fp);
printf("\nData written successfully.");

/*again open file to read data*/


fp=fopen(fname,"r");
if(fp==NULL) {
printf("\nCan't open file!!!");
exit(0);
}

printf("\nContents of file is :\n");


/*read text until, end of file is not detected*/
while( (ch=getc(fp))!=EOF ) {
printf("%c",ch); /*print character on screen*/
}

fclose(fp);
}

15 Compare and contrast between text files and binary files


Ans:
1. Text files

Text files are the normal .txt files that you can easily create using Notepad or any simple text editors.
When you open those files, you'll see all the contents within the file as plain text. You can easily edit or
delete the contents.
They take minimum effort to maintain, are easily readable, and provide least security and takes bigger
storage space.
2. Binary files
Binary files are mostly the .bin files in your computer.
Instead of storing data in plain text, they store it in the binary form (0's and 1's).
They can hold higher amount of data, are not readable easily and provides a better security than text
files.
Text File Binary File

Bits represent character. Bits represent a custom data.

Less prone to get corrupt as changes reflect


as soon as the file is opened and can easily Can easily get corrupted, even a single bit
be undone. change may corrupt the file.

Can store different types of data (image,


Can store only plain text in a file. audio, text) in a single file.

Developed especially for an application and


Widely used file format and can be opened may not be understood by other
using any simple text editor. applications.

Mostly .txt and .rtf are used as extensions to


text files. Can have any application defined extension.

We can open text file : We can open binary file :


fp=fopen(“a.txt”,”r”); fp=fopen(“a.txt”,”rb”);

In text file 500 takes as 3 bytes as it having 3 In binary file 500 taken as integer and takes
characters only 2 bytes

Occupies large storage space Occupies less storage space

Operation is fast as no conversion is


required. Information is stored in the form of
Slow in operation as conversion takes place binary

Newline is the end of the line or line ending In a binary file, no such conversions take
or line break. It is usually a special character place.
which signifies the end of the line. A newline
character in a text file is first converted into
a carriage return-linefeed combination and
then written to the disk.

For (EOF), In the text mode, a special This is not the case in binary mode. In the
character with the ASCII code 26 is inserted binary mode, we do not have any special
at the end of the file. This character when character to signify the EOF. It keeps track
encountered returns the EOF signal to the with the help of the number of characters
program. present in the directory entry of the file.
16 What is binary file and explain operations performed on binary files.
Ans:

Reading and Writing from Binary Files


Binary files are very similar to arrays except for the fact that arrays are temporary storage in
the memory but binary files are permanent storage in the disks. The most important difference
between binary files and a text file is that in a binary file, you can seek, write, or read from any
position inside the file and insert structures directly into the files. You must be wondering - why
do we need binary files when we already know how to handle plaintexts and text files? Here are
the reasons why binary files are necessary:
1. I/O operations are much faster with binary data.
Usually, large text files contain millions of numbers. It takes a lot of time to convert 32-bit
integers to readable characters. This conversion is not required in the case of binary files as
data can be directly stored in the form of bits.

2. Binary files are much smaller in size than text files.


For data that is in the form of images, audio or video, this is very important. Small size means less storage
space and faster transmission. For example, a storage device can store a large amount of binary data as
compared to data in character format.

3. Some data cannot be converted to character formats.


For example, Java compilers generate bytecodes after compilation.
Having said that, let's move on to handling I/O operations in a binary file in C. The basic parameters that the
read and write functions of binary files accept are:

 the memory address of the value to be written or read


 the number of bytes to read per block
 the total number of blocks to read
 the file pointer

There are functions provided by C libraries to seek, read, and write to binary files. Let's explain this by reading
and writing a structure called rec in a binary file. The structure is defined like this:

1. /* The structure to be inserted in the binary file */


2. struct record
3. { 
4.  int a,b,c;
5. };
The fread() function is used to read a specific number of bytes from the file. An example of fread() looks like 
this:

1. fread(&myRecord, sizeof(struct record), 1, ptr);

This statement reads 'a' bytes (in this case, it's the size of the structure) from the file into the memory
address &myRecord. Here the number 1 denotes the number of blocks of 'a' bytes to be read. If we change it
to 10, then it denotes 10 blocks of 'a' bytes will be read and stored into &myRecord. ptr is the pointer to the 
location of the file that is being read.
Now the fwrite() function is used to write to a binary file, like so:

1. fwrite(&myRecord, sizeof(struct record), 1, ptr);

In this example, the value inside the address &myRecord which is of the size of the structure record is written 
into the file with the help of the file pointer ptr.

Examples using fread() & frwrite()


Now that you know how to read and write binary files, let's discuss this with the help of examples, starting
with an example of using fread().

1. #include<stdio.h>
2. /* Our structure */
3. struct record
4. { 
5.   int a,b,c;
6. };
7. int main()
8. { 
9.  int count;
10.  FILE *ptr;
11.  struct record myRecord;
12.  ptr=fopen("test.bin","rb");
13.  if (!ptr)
14.  { 
15.     printf("Unable to open file!");     return 1;
16.  }
17.  for ( count=1; count <= 10; count++)
18.  { 
19.   fread(&myRecord,sizeof(struct record),1,ptr);   printf("%d\n",myRecord.a);
20.  }  fclose(ptr);
21.  return 0;
22. }

In this example, we tried to read each structure from the binary file using the fread() function. This reads the
structure one byte at a time and stores it inside the address myRecord. Let's now look at an example using
fwrite().

17 Explain random accessing files with suitable example


Ans:
We can randomly move the file pointer to any location in a file. This is very essential when a file consists
of several records in a file. If we go sequentially to move to record it may take time need increased
processing time. C Provides random access i/o functions like fseek(), ftell() and rewind().

For ex: in a.text file the following data is present.


Hello this is a sample text.

If we open the file with a file pointer fp, the pointer points to beginning character of the file i.e ‘H’

If we want to go to 10th character of the file we can issue


fseek(fp,10,SEEK_SET);
If wee want to go to end of the file
fseek(fp,0,SEEK_END);
No the file pointer points to End of the file.

ftell(fp) gives the position from the beginning of the file pointer.

rewind(fp); will moves the file pointer to beginning of the file.

Similarly fread() and fwrite() are also useful in to read and write block of data from files i.e., we can
access record by record.

18 Write a C Program to print the last n characters in a given file.


Ans:
#include<stdio.h>
#include<stdlib.h>
void main() {
FILE *fp;
char ch;
int n,length;
fp=fopen("a.txt","w");
printf("Enter text to store '@' to end..");
while((ch=getchar())!='@') {
fputc(ch,fp);
}
fclose(fp);
fp=fopen("a.txt","r");
printf("Enter how many last charcters to be printed : ");
scanf("%d", &n);
fseek(fp,-n,SEEK_END);
printf("Last %d characters in the file are : ", n);
while((ch=getc(fp))!=EOF) {
putchar(ch);
}
fclose(fp);
}

Output:
Enter text to store '@' to end..abcdefghij12345@
Enter how many last charcters to be printed : 5
Last 5 characters in the file are : 12345

19 Show with example and explain in detail the concept of command-line arguments and how and
when they can be used.
Ans:

Command line arguments:

We can also give command-line arguments in C. Command-line arguments are given after the name of
the program in command-line shell of Operating Systems.

To pass command line arguments, we typically define main() with two arguments : first argument is the
number of command line arguments and second is list of command-line arguments.

int main(int argc, char *argv[]) { /* ... */ }

or

int main(int argc, char **argv) { /* ... */ }

argc (Argument Count) is int and stores number of command-line arguments passed by the user
including the name of the program. So if we pass a value to a program, value of argc would be 2 (one for
argument and one for program name)

 The value of argc should be non negative.


 argv(Argument Vector) is array of character pointers listing all the arguments.
 If argc is greater than zero,the array elements from argv[0] to argv[argc-1] will contain pointers
to strings.
 Argv[0] is the name of the program , After that till argv[argc-1] every element is command -line
arguments.

#include <stdio.h>
#include<math.h>
int main(int argc, char *argv[]) {
if (argc != 5) {
printf("Arguments passed through command line are not equal to 4\n");
return 1;
}
printf("Student name : %s\n", argv[1]);
printf("Subject-1 marks : %s\n", argv[2]);
printf("Subject-2 marks : %s\n", argv[3]);
printf("Subject-3 marks : %s\n", argv[4]);
int sum;
sum = atoi(argv[2]) + atoi(argv[3]) + atoi(argv[4]);
printf("Total marks : %d\n", sum);
return 0;
}

Execution process of Command line argument program:


$ gcc marks.c –o marks.out

$ ./marks.out Anil 45 40 45 // here the arguments are passed to main() function

Output:
Student name : Anil
Subject-1 marks : 45
Subject-2 marks : 40
Subject-3 marks : 45
Total marks : 130

20 Write a C program to copy the contents of one file into another file using command line
arguments.
Ans:

#include<stdio.h>
int main(int argc,char *argv[])
{
FILE *fs,*ft;
int ch;
if(argc!=3)
{
printf("Invalide numbers of arguments.");
exit(1);
}
fs=fopen(argv[1],"r");
if(fs==NULL)
{
printf("Can't find the source file.");
exit(1);
}
ft=fopen(argv[2],"w");
if(ft==NULL)
{
printf("Can't open target file.");
fclose(fs);
exit(1);
}

while((ch=getc(fs))!=EOF)
{
fputc(ch,ft);
}
fclose(fs);
fclose(ft);
return 0;
}

You might also like