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

C PROGRAMMING Solution(1)(1)

A programming language is a system used for communication between humans and computers, with high-level languages being machine-independent and easier to understand compared to low-level languages, which are machine-dependent and more complex. The document also discusses data types for various data, the compilation process of C programming, and the significance of algorithms and flowcharts in programming. Additionally, it covers the rules for naming identifiers, the purpose of header files, and the differences between local and global variables.

Uploaded by

mrrandom9867
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)
4 views

C PROGRAMMING Solution(1)(1)

A programming language is a system used for communication between humans and computers, with high-level languages being machine-independent and easier to understand compared to low-level languages, which are machine-dependent and more complex. The document also discusses data types for various data, the compilation process of C programming, and the significance of algorithms and flowcharts in programming. Additionally, it covers the rules for naming identifiers, the purpose of header files, and the differences between local and global variables.

Uploaded by

mrrandom9867
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/ 86

1(a) Define programming language.

Differentiate between high level programming language and low


level programming language.(2013fall,2015spring,2016spring,2017spring)

The language that is acceptable to computer system and is used to communicate between computer and
human is known as programming language.

A programming language is a platform that provides the environment to write program. Actually programming
languages have their own set of grammatical rule used to write program.for eg: c,c++ etc.

Low level language High level language


It is a machine dependent language. It is machine independent language.
It is difficult to understand. It is easy to understand.
It require more time to write the program. It requires less time to write the program.
It’s debugging is more complex. It’s debugging is easier.
It uses assembler to generate object code. It uses complier or interprets to generate object
code.
This language used in 1st and 2nd generation. It is used in 3rd, 4th and 5th generation.

2013 fall, 2018 spring 2(a),1(b) mention the appropriate data type for storing following data. Also justify
your answer in brief.

i) Distance jumped by frog

The distance jumped by frog can be represented by the float data type because the distance
jumped is in fractional number. It occupies 4 bytes of memory space and range – 1.2e -38 to 1.2e 38.

ii) A prime number between 5 and 55


A prime number between 5 and 55 can be represented by the int data type because the prime
number between 5 and 55 is the whole number. It occupies 2 bytes of memory space. It is
represented by keyword int and symbol is %d with range between -32768 to 32767

iii) Weight of your body temperature

The weight of the body can be represented by data type float because the weight may be in
fractional number. it is represented by keyword float, denoted by symbol %f, it occupies 4bytes of memory
space with range between -1.2e38 to 1.2e38.

iv) The examination symbol number of a student


The examination symbol number of a student can be represented by the data long integer
(long int) because it has large number of integer number.
2013spring, 2014fall, 2017fall, 2016spring, 1(a) What do you mean by programming language? Explain
different types of programming languages?

- The language that is acceptable to computer system and help to communicate between computer
and human is known as programming languages.
Programming language is a platform which provide environment to write a program.
Actually programming languages have their own set of grammatical rule to write a program like
c, c++ etc. there are mainly two types of programming languages.
a) Low level language
- Machine language
- Assembly language
b) High level language
a) Low level language
Low level language is machine dependent language. It require more time to write a program and also
difficult to understand and debug. But this language is directly accepted by machine.
This can be further divided into following two types:
• Machine language:

Machine level language is a language that computers actually understand the least possible level at
which we can program a computer is in its own native machine code. Machine language is a
sequence of instruction written in the form of binary numbers. The main advantage of machine
languages is that they executed fast as the computer understand them and doesn’t need translation
into other forms. However machine language is difficult to write eg 11= 0001101.

• Assembly language:
Assembly language used alphanumeric codes, instead of numeric codes for instruction in
instruction set. For eg ADD,SUM etc. Since CPUdoesnt understand the assembly language. It needs
conversion, which is done by assembler.
The assembler is a software which translates an assembly language program into equivalent
machine code.
They are easier to understand and use. But they are machine dependent.
Assembly language is symbolic representation of machine code. The assembly language program
must be translated into machine code by a separate program called an assembler.
• High level language:
Both machine and assembly language are often referred to as low level programming
languages. High level languages were designed to overcome their limitation.using high level
language any one without computer science and engineering background can be programmer. They
are easy to work and learn, but while executing they have to translate into assembly language and
then to machine language so it is slow execution eg c, c++ etc.

2013spring , 2018fall 2(a),1(b) What is the purpose of qualifiers register and volatile? Describe four basic
data types. How could you extend the range of values they represent?

Register means to store some data permanently while volatile means to store data while running a program.
Data on volatile (RAM) are automatically erased after completion of program.
Different data types used in c are follows:

a) Integer type:

Integers are whole numbers with a range of values. Range of values are machine dependent.
Generally an integer occupies 2 bytes of memory space and its value range limited to -32768 to +32767. A
signed integer used one bit for storing sign and rest 15 bit for number.

Syntax : int variable name ;


b) Floating point types:

The float data type is used to store fractional number and occupies 4bytes of memory
space with 6digit of precision. Float data are denoted by keyword float. When the accuracy of floating
point number is insufficient we can use the double to define the number. the double is same but occupies
double space than the float i.e. 8bytes. To extend the precision further we can use long double which
occupies 10 bytes of memory space.
Syntax : float variable name;
-1.2e38 to 1.2e 38

c) Character type:

Character data can store single character. They may be signed and unsigned character.
Unsigned character have value range between 0_ 255 and signed character have value range between -128 to
127.

Syntax : char variable name

c) Void type :
The void type represents no any specific or all type, therefore we cannot declare it as a
variable when we are not sure about the value type to be used. It is normally used in function for not
returning any value.

2013spring, 2014fall;2(a) What do you mean by algorithm and flowchart? Explain the c compilation
process in brief. (significance of algorithms flowchart)

The process of changing high level language into machine level language is known as compilation. It is done by
compiler. There are four Steps of C compilation: preprocessing, compiling, assembly, linking.

Preprocessing:

Preprocessing is the first step. The preprocessor obeys commands that begin with # (known as directives) by:

• removing comments

• expanding macros

• expanding included files


If you included a header file such as #include <stdio.h>, it will look for the stdio.h file and copy the header file
into the source code file.

The preprocessor also generates macro code and replaces symbolic constants defined using #define with their
values.

Compiling:

Compiling is the second step. It takes the output of the preprocessor and generates assembly language, an
intermediate human readable language, specific to the target processor.

Assembly:

Assembly is the third step of compilation. The assembler will convert the assembly code into pure binary code or
machine code (zeros and ones). This code is also known as object code.

Linking:

Linking is the final step of compilation. The linker merges all the object code from multiple modules into a
single one. If we are using a function from libraries, linker will link our code with that library function code.

In static linking, the linker makes a copy of all used library functions to the executable file. In dynamic linking,
the code is not copied, it is done by just placing the name of the library in the binary file.

- An algorithm is a stepwise description to solve a problem in a definite number of steps written in


simple english language.

Significance of algorithm:

- It gives step by step description of method to solve a problem.


- It maintains sequences of computer instruction required to solve the problem.
- It gives decision after execution of instruction.
- It gives repetition which can be implemented by using loop.

A flowchart is a pictorial representation of an algorithm using geometrical


symbols with their own meaning.

Significance of flowchart:

- Flowchart helps in communication which clearly and quickly provides the logic, ideas and
description of algorithm.
- Flowchart helps in proper documentation which provides a permanent recording of program
logic.
- Flowchart helps the programmer for the efficient coding.
- Flowchart makes easy while debugging the program and maintenance of operating program.

Draw a flowchart for finding greatest digit for the supplied number by the user.

Step 1: Start

Step 2: Input N

Step 2: GtDigit = 0

Step 3: While (N != 0)

Rem = N % 10;

If(Gtdigit<Rem) then assign Rem in GtDigit

N = N / 10;

Step 4: Print GtDigit

Flowchart:-
2014spring,2016fall,2018spring ,1(a) With the help of block diagram of digital computer explain the
function of control unit and memory unit.

i) Input/output unit:
Input output units contains input and output devices. Input devices are those electronic
devices through which data and instructions are entered into the computer which is furthered
processed by CPU. Some input devices are as keyword, mouse, scanner etc.
After processing the output is produced to the user on output device in the form of hard copy or
softcopy. Some output devices are monitor, printer, projector etc.
ii) CPU:
CPU stands for central processing unit. Under it there are three parts ALU, control unit and
register. After the input of data, instruction or program , the processing takes place in CPU.
ALU stands for arithmetic and logical unit. The ALU can perform four kinds of arithmetic operation
: addition, subtraction, multiplication and division and three logical operations they are equal to, less
than and greater than .
CU stands for control unit which controls and manages whole computer system operations and
program/instruction. So that data received from input devices and send to output devices at right
time. It sends input, output and control signals at a speed that is measured in MHZ and GHZ.
Register is another part of CPU. Register are special temporary storage location inside cpu. They
quickly accept,store and transfer data and instruction that are currently being used.
iii) Memory :
There are two types of memory Primary (main) memory and secondary memory.
Memory is a storage location where data and instructions are stored either temporarily or
permanently. Primary memory stores the data and program while the program is being executed.
They are volatile in nature for example RAM . Secondary memory stores the data for long periods
of time. They are non volatile for example pen drive, hard disk etc. they are used to store
documents, program files, software, games, songs, films etc.
Diagram(Block) of digital computer

2014 SPRING,1(b) What are the rule for naming identifier? Why we need different data types in
programming? Different between local and global variables with suitable examples?
- Every word used in c programming to identify the name of variable, functions, array pointers and
symbolic constants are known as identifiers. They are name given by the user and consists of
sequence of letters and digits.
The rules for naming identifiers are:
- keywords can’t be used.
- Only 31 characters are significant.
- It must be combination of letter and digits and must begin with letter.
- Underscore is permitted between two words but white space is not allowed.
- It is case sensitive.

There are various types of data type available in c like int, float, char etc. The variety of data type
available which allow the programmer to select the type needed by the application. Each data type
has its own scope to represent the data value. So we need different data type in programming.

Difference between local and global variable

Local variable Global variable

Local variable only exist within the Global variable exists in entire scope of
function or block. the program.
Local variable are re-created each time Global variable aren’t re-created each
when function is called or executed. time a particular function is called.
These variable are not accessible to other Program typically used global variable to
function or to main program. store data is processed by many different
functions.
#include <stdio.h> #include <stdio.h>
int main( ) int a=5; (global variable)
{ int a=5; (local to main() function) int main ()
…….. return o;
} }

2015fall, 2015spring 1(B),1(a) what is flowchart? Write an algorithm and draw a flowchart to display
weather a number is prime or not.

- Flowchart is a pictorial representation of algorithm. Flowchart makes easy to debug and maintain
the program. Different symbol are used in flowchart. Some of them are

Cylinder used to represent start/Stop Rectangle used to represent Arith. Calculation

Parallelogram to represent I/O Diamond to represent logical operation

Arrows to Represent Flow control. etc


Algorithm :

1) Start
2) Initialize a variable I= 2
3) Read a number which is to be checked
4) Compare I with num
a) I < num
b) Rem= num% I
c) Is rem== 0
d) I = I+ 1
5) If a is true than proceed b and c, if c is false proceed step d otherwise display not prime.
6) If a step is false, and compare I with num. if I is equal to num display prime no.
7) End
2015 fall,1(b) why headers file in c is included in program? Give reasons. List out different header files
you know. Illustrate the program showing the use of header file.

- A header file is a file containing c declaration and macro definition to be shared between several
source files. The use of a header files in a program by including it, with the c preprocessing
directive #include header files serve in two purposes.
System header files declare the interfaces to parts of the operating system. We can include and
declare which is needed to invoke system calls and libraries.
Some header files are listed below.
- <stdio.h>
- <conio.h>
- math.h
- stdlib.h
- string.h etc
E.g.
#include <stdio.h>
#include <conio.h>
void main ( )
{
int a,b,c;
sum=a+b+c;
clrscr();
print f (“The sum of a,b,c is %d”,sum);
getch ( )
}
In the above program void, int printf(), are used which are declared in stdio.h and clrscr() is
declared in conio.h header files. Without including these header file the program can not be
compiled and executed.

2016 fall, 2018 spring,1(b) Define the role of flow chart in efficient program maintenance with it’s
characteristics. Also develop a flow chart to print the even numbers between 150 to 500.
- Flowchart is a pictorial representation of algorithm. Using the flow chart the c program can be
written step wise as in flow chart. It also helps to debug the program whenever any modification
or correction is needed.
Significance of flowchart:-
- Flowchart helps in communication which clearly and quickly provides the logic idea and
description of algorithm.
- Flowchart helps in proper documentation which provide permanent recording of program logic.
- Flowchart helps the programmer for the efficient coding.
- Flowchart helps in easy debugging process and maintenance of operating program.

Figure 1 even number between 1 to 150

(Note:- i=150 and in diamond i<=500 consider to find even numbers between 150 to 500)
2016 spring ,1(b) What is the significance of algorithm and flowchart in programming? Write an
algorithm and draw a neat flowchart to input a number and check it is palindrome number or not.

[Note: Palindrome number remains same even after it’s reverse such as 989]

2017 fall,1(b) Define algorithm and flowchart. Draw a flowchart to read 3 numbers from the user and
find the biggest/smallest one.

Algorithm :-

An algorithm (pronounced AL-go-rith-um) is a procedure or formula for solving a problem, based


on conducting a sequence of specified actions. A computer program can be viewed as an elaborate algorithm. In
mathematics and computer science, an algorithm usually means a small procedure that solves a recurrent
problem.
Flowchart:-

Flowchart is a diagrammatic representation of an algorithm. Flowchart are very helpful in writing program and
explaining program to others.

Symbols Used In Flowchart

Different symbols are used for different states in flowchart, For example: Input/Output and decision making has
different symbols. The table below describes all the symbols that are used in making flowchart

Symbol Purpose Description

Flow line Used to indicate the flow of logic by connecting symbols.

Terminal(Stop/Start) Used to represent start and end of flowchart.

Input/Output Used for input and output operation.


Symbol Purpose Description

Processing Used for airthmetic operations and data-manipulations.

Decision Used to represent the operation in which there are two alt

On-page Connector Used to join different flowline

Off-page Connector Used to connect flowchart portion on different page.

Predefined Process/Function Used to represent a group of statements per

(Note:- to find smallest just change the symbol > to


<).
2018 fall,1(a) What is computer software? Explain different types of software used in today’s life.

Software is defined as a collection of programs, documentation and operating procedures. The Institute of
Electrical and Electronic Engineers (IEEE) defines software as a 'collection of computer programs,
procedures, rules and associated documentation and data.' It possesses no mass, no volume, and no colour,
which makes it a non-degradable entity over a long period. Software does not wear out or get tired.
Software controls, integrates, and manages the hardware components of a computer system. It also instructs the
computer what needs to be done to perform a specific task and how it is to be done. For example, software
instructs the hardware how to print a document, take input from the user, and display the output.
Computer works only in response to instructions provided externally. Usually, the instructions to perform some
intended tasks are organized into a program using a programming language like C, C++, Java, etc., and
submitted to computer. Computer interprets and executes these instructions and provides response to the user
accordingly. A set of programs intended to provide users with a set of interrelated functionalities is known as
a software package. For example, an accounting software package such as Tally provides users the
functionality to perform accounting-related activities.

Classification Of Software

The following diagram shows the way we classify software.

System Software
We use the term System Software for software which is primarily used to operate the hardware.
Operating Systems
The operating system is the software that allows you to operate the hardware. The programs that we want to
execute, the applications that we want to use all require a platform on which to execute. That platform is
provided by the operating system.
One role of the operating system is to provide a virtual machine. This refers to the way that, by clicking on
icons and menus, or by typing in commands at a prompt, we get to interact with the computer hardware without
having to understand its complexity. By hiding the true complexity of the system from the user, the operating
system makes it easier for ordinary people to make computers perform useful tasks.
Utility Programs
Some utility programs are bundled in with operating system software these days. Others you buy or source in
some other way.
Utility programs tend to perform specific tasks related to the management of hardware. Examples of utility
programs include compression programs, formatters, defragmenters and other disk management tools.
Library Programs
Library programs are compiled libraries of commonly-used routines. On a Windows system they usually carry
the file extension dll and are often referred to as run-time libraries. The libraries are run-time because they are
called upon by running programs when they are needed. When you program using a run-time library, you
typically add a reference to it either in your code or through the IDE in which you are programming.
Some library programs are provided within operating systems like Windows or along with development tools
like Visual Studio. For example, it is possible to download and use a library of routines that can be used with
Windows Media Player. This includes things like making playlists, functions and procedures for accessing and
manipulating the music library (which is a binary file) and playback routines.
Using library programs saves time when programming. It also allows the programmer to interact with
proprietary software without having access to its source code.
Language Translators
Whatever language or type of language we use to write our programs, they need to be in machine code in order
to be executed by the computer. There are 3 main categories of translator used,
Assembler
An assembler is a program that translates the mnemonic codes used in assembly language into the bit patterns
that represent machine operations. Assembly language has a one-to-one equivalence with machine code, each
assembly statement can be converted into a single machine operation.
Compiler
A compiler turns the source code that you write in a high-level language into object code (machine code) that
can be executed by the computer.
The compiler is a more complex beast than the assembler. It may require several machine operations to
represent a single high-level language statement. As a result, compiling may well be a lengthy process with very
large programs.
Interpreter
Interpreters translate the source code at run-time. The interpreter translates statements one-at-a-time as the
program is executed.
Interpreters are often used to execute high-level language programs whilst they are being developed since this
can be quicker than compiling the entire program. The program would be compiled when it is complete and
ready to be released.
Interpreters are also used with high-level scripting languages like PHP, Javascript and many more. These
instructions are not compiled and have to be interpreted either by the browser (in the case of Javascript) or by
interpreters on the server (in the case of PHP).
Some programming languages make use of both compilers and interpreters. If you were to write a Java program
in a text editor, when you came to compile it with the Java compiler, you would actually be creating something
called bytecode. Bytecode can be thought of as an intermediate stage between source code and object code.
When a computer executes a Java program, library programs on that machine interpret the bytecode. This
allows Java to be platform-independent - a user needs the correct run-time libraries for Java on their machine in
order to execute the programs.
Application Software
Application software tends be used for the tasks that have some relationship to the world outside of the
computer. For example, you might use a word processor to write a letter or an essay. Although you use the
computer to perform the task, the task itself might reasonably be considered to be a non-computer task.
General-Purpose Software
Software is general-purpose if it can be used for lots of different tasks. You can use a word processor to write
letters, memos, essays, instructions, notes, faxes, invoices and lots more.
These days we tend to use integrate suites of office software where a range of general-purpose software is
provided, usually with the facility to combine elements from each application in a single file.
Special-Purpose Software
This software performs a single specific task. This task might be complex like payroll calculation, stock control
etc. but will be based on a single task.
As with many abstract concepts, you can stretch these definitions until they blur a little. These days, web
browsers can contain a lot of features. They are still primarily focused on a single task, rendering web pages and
so the web browser is special-purpose. Being able to access an application using a browser does not change the
main purpose of the browser software itself.
Bespoke Software
Bespoke software is written for a single client. Large organisations have a need for well-developed applications
suited to their specific needs. Such software is often expensive to develop since the development costs are not
shared among a large number of people purchasing the software.
What are the Generations Of Programming Languages ? Briefly explain them
First Generation Languages
Here we are talking about machine code (Binary digit code). This is the only form of code that can be executed
by the computer directly.
Second Generation Languages
Assembly language was developed to make it easier for programmers to write instructions than it would be
using machine code. Mnemonics are used instead of bit patterns (which are harder to remember).
First and Second-Generation languages are low level and machine-oriented. This refers to the way that they
are based on the machine operations that are available for a given processor.
Third Generation Languages
Third generation languages are high level, platform-independent and problem oriented. When source code is
interpreted/compiled, there is a one-to-many equivalence of high level language statements to machine code
statements. Third generation programs can be run on any platform for which an appropriate compiler or
interpreter exists.
High level languages are developed to solve particular types of problem. The FORTRAN language was
designed with Mathematics, Science and Engineering in mind, it contains lots of scientific functions that the
average programmer may not need. The COBOL language was developed with business logic in mind, PHP
was developed for server-side scripting and so on.
All of the languages in the first 3 generations are called imperative languages because the program's statements
are executed in the order specified by the programmer.
Fourth Generation Languages
Fourth generation languages are declarative. This means that the programmer will write facts or rules rather
than statements. The interpreter for the language produces the result using whichever standard algorithms it has
been given for doing so.
SQL and Prolog are both examples of declarative languages. Both are described in the programming section of
this site and are relatively easy to try out. A quick half-hour blast at each would give you a feel for how they
work and help you to understand how they differ from the other types of language.

2018 fall ,1(b) write al;gorithm and draw flowchart to generate Fibonacci sequence of eight terms.
2018 spring ,Develop a flowchart to print the Armstrong numbers between 150 to 500.

Start
2014 fall,2(a)Define the following terms with suitable examples.

i) Statement (printf(), scanf() etc.)


ii) Token (General name for keyword, identifies, variable, data type.)
iii) Format specifier (%d,%s,%f,%c)

i) Statement:-
A statement is a command given to the computer that instructs the computer to take a specific
action, such as display to the screen or collect input. A computer program is made up of series of
statements.
Labeled statements, compound statements , expression statements , selection statements, iteration
statements , jump statements.
ii) Token :-
The basic elements recognized by the c.compiler are the “ tokens”. A token is source program text
that the compiler does not break down into component element. The keywords, identifiers, constants,
string literals operators, the special symbols: brackets( [ ] ), braces ( { } ), parentheses ( ( ) ) and
commas( ,) are examples of tokens.
iii) Format specifiers:-
In C programming we need lots of format specifier to work with various data type. Formatted
specifier define the type of data to be printed on standard output. Whether to print formatted input we
need format specifiers. Format specifiers are also called as format string.

Format specifier Description Supported data type


%c Character char
unsigned char
%d Signed integer short
unsigned short
int,long
%f Floating point float
%s String char*
%p Address of pointer to void void* void*
%n Print nothing
%% Print% character

2014 fall, 2016 fall 2(b) 2nd part , 2018 fall ,2018 spring
2(b) Explain break and continue statements with examples.

Continue statement Break statement


The loop is continue when the condition The loop is terminated when the
becomes true. condition isn true.
The output are printed onoly when the The output are printed until the condition
condition becomes false. becomes true.
Continue can appear only in loop (for, A break can appear in both switch and
while, do) statements. loop (for, while, do) statements.
Code.
Code. For(i=0;i<=5;i++)
For(i=0;I<=5; i++) {if (i= =4)
{if (i= =4) Break;
Continue; Print f (“\t%d”,i);
Print f (“\t%d”,i); }
} Output :0 1 2 3 4
Output :0 1 2 3 5
2014 spring,2(a) What is the importance of documentation in programming? Write an algorithm and
draw a flowchart to find and output all the roots of a quadratic equations for non-zero coefficients. In
case of errors program should report suitable message.

- Program documentation is the description of program and it’s logic written to support
understanding of the program. Documentation of program helps to those who use maintain and
extend the program in future. A program may be difficult to understand even to the programmer
who wrote the code after some days. If a program coded by one person is to be maintained and
extend by other person, there will be more difficult to understand it. Properly documented
program is necessary which will be useful and efficient in debugging, testing, maintenance and
redesign process.
2015 fall, 2016 fall, 2016 spring, 2017 fall,2(a) Define operator in C. List out different types of operators
used in C. Exp[lain three of them with example.

- The any symbols, punctuation marks and mathematical symbols which are used to calculate
mathematical and logical and relational calculation are known as operator. The different type of
operator used in C programming are:-
- Arithmetic operator:-
Basic and commonly used to arithmetic operators are as given below. considering A=6
and B=5, The output of operators are given in the table with arithmetic operators

Operator Meaning Example Output


+ Addition A+B 11
- Subtraction A-B 1
* Multiplication A*B 30
/ Division A/B 1
% Module(reminder) A%B 1

- Relational operator:-
They compare two operands, depending on their relation and take action.
A<B
In this case A is left hand side and B is right hand side operands. The less than operator will
compare both operand and if the relation is true then the value of relational operator will be 1 ( if
condition is true) or 0 (if condition is false). It can be further understood by the table below; for
A=4 and B=7.
Operator Meaning Example Output
< Less than A<B 1
> Greater then A>B 0
<= Less than or equal A<=B 1
=> Greater than or equal A=>B 0
!= Not equal A!=B 1
== Equal A = =B 0

- Logical operator:-
They are used to evaluate logical or relational expreesion. Like relational operator
They give value 0 or 1. The example to demonstrate logical operator are as follows:

A B A && B(And A||B (or !A (NOT !B


operator) operator) operator)
0 1 0 1 1 0
0 0 0 0 1 1
1 1 1 1 0 0
1 0 0 1 0 1

Here, &&, || is binary operator and ! is unary operator.


- Conditional operator (? : ) : -
They are also called ternary operator since they take three argument. They form a kind of
short hand of if( ) else.

Syntax
Test Expression 1? True Expression2 : False Expression 3. It means if expression 1 is true: then
the value return will be expression 2, otherwise the value return will be expression 3.

- Assignment operator:-
They are used to assign the value of expression or any constant or variable to another
variable.
A=B+4, A+=B, *=, /=, %=

- Increment and decrement operator:-


Increment operator (++) increase the value of an operand by 1, and decrement operator(- -)
decrease the value of operand by 1. This operand are used as prefix (++q) and postfix (q++) with
the variable. When prefix the value of variable is first increased or decreased then assigned to the
variable. When postfix the value is assigned to the variable and increased or decreased.
Based on the number of operands types of operator are:-
1) Unary operator:-
The operator which required only one operand are known as unary operators.
E.g. ++, - - etc.
2) Binary operator:-
The operator which require two operand are known as binary operators. E.g. +, -, *, /,
<,>etc.
3) Ternary operator:-
The operator that require three operand are known as ternary operators. E.g. the operator
pair “ ?: ” conditional operator is ternary operator.

2015 fall, 2015 spring,2(b) An electricity board charges according to the following rates.

For first 100 units Rs 40 per unit

For next 200 units Rs 50 per unit

For the beyond 300 units Rs 60 per unit

All users are also charge meter charge which is equal to Rs 50. Write a program to read number of units
consumed and print out the total charges.

- # include<stdio.>

# include<conio.h>

# define metercharge 50

void main ( ) {

int amount =0, unit;

printf (“\n enter total unit consumed”);

scanf (“%d,” & unit);

if (unit <=100)

amount = metercharge + unit*40;

elseif( unit <=300)

amount= metercharge + 100*40 + (unit-100)*50;

else

amount = metercharge + 100*40 + 200*50 + (unit-300)*60;

printf (“\n your total amount is %d,” amount);

getch ( );
}.

2016 spring ,2(b) Differentiate between while loop and do while loop. Write a program to print the sum of
the digits of a number.

WHILE DO-WHILE

Condition is checked first then statement(s) is Statement(s) is executed atleast once, thereafter

executed. condition is checked.

It might occur statement(s) is executed zero times, If

condition is false. At least once the statement(s) is executed.

No semicolon at the end of while. Semicolon at the end of while.

while(condition) while(condition);

If there is a single statement, brackets are not

required. Brackets are always required.

Variable in condition is initialized before the

execution of loop. variable may be initialized before or within the loop.

while loop is entry controlled loop. do-while loop is exit controlled loop.

while(condition) do { statement(s); }

{ statement(s); } while(condition);

- #include<stdio.h>
#include<conio.h>
void main ( )
{
int n,t, sum =0, remainder;
printf (“ Enter an integer \n”);
scanf (“%d,” &n);
t=n;
while (t!=0)
{
reminder = t%10;
sum = sum + remainder;
t=t/10;
}
printf (“sum of digits is %d\n”,sum);
getch ( );
}

2017 spring, 2014 fall, 3(b),2(b) What is an array? Write a C program using array to find largest and
smallest number from a list of 100 given numbers.

- Array is a collection of similar data types. The advantage of array is that we can declare many
value at once, rather than declaring them many times.
e.g.
#include<stdio.h>
#include<conio.h>
void main ( )
{
int i, A[3] = {2, 3, 4};
for ( i=0; i<3;i++)
printf (“ The values are %d”, A[i]);
getch ( );
}

2013 spring, 2013 fall7©, 2014 spring 7(b), 2016 fall 3(b), 2017 fall 7(b), 2017 spring 7(c), 2018 fall 4(b)

3(a) List different string handling functions in C. Write a program to check whether the given string is
palindrome or not. (Palindrome is a word which reads same from left to right and right to left. For e.g.
LIRIL)

- String is an array of characters i.e. (characters are arranged one after another in memory) in other
words character array is also known as a string.
Some functions related to string are as follows:-
1) strlen( );
This function counts and returns the number of character in a particular string. The length
always doesn’t include a null character.
The syntax for strlen() is as follows;
N=strlen(string);
Where n is integer variable which receives the value of length of string
2) strcmp();
In C you cannot directly compare the value of 2 strings in a condition like
if(string1==string2).Most libraries however contain the function called strcmp(); which
return a zero if two string are equal or a non-zero number.if two string are not the same the
syntax for strcmp() is given below.
strcmp(string1,string2)
3) strcpy();
To assign the characters to a string C doesnot allow you directly as in the statement
name=Robert, instead use the strcpy() function found in most compilers the syntax for
function is illustrated below.
strcpy(string1,string2)
4) strrev();

This function reverses the characters in a particular string. The syntax of the function is
illustrated below.
strrev(string);
5) strcat();
This function concatenates two strings.ie,it appeds one string at the end of another.This
function accepts two strings as parameters and stores the contents of the second string at end
of the first. It’s syntax is
strcat(string1,string2);
Program to test string is palindrome or not

#include <stdio.h>
int main()
{
char text[100];
int begin, middle, end, length = 0;

gets(text);

while (text[length] != '\0')


length++;

end = length - 1;
middle = length/2;

for (begin = 0; begin < middle; begin++)


{
if (text[begin] != text[end])
{
printf("Not a palindrome.\n");
break;
}
end--;
}
if (begin == middle)
printf("Palindrome.\n");

return 0;
}
2013 spring3(b)What is an array? Why do we use array in programmimg language?write a program to
find sum of all elements of a 3*3 matrix.

#include<stdio.h>
#include<conio.h>
void menu()
{
int i,j,mat[10][10],row,col;
int sum=0;
printf(“enter the no of rows”);
scanf(“%d”,&row);
printf(“enter the no of columns”);
scanf(“%d”,&col);
for (i=0;i<row;i++) {
for(j=0;j<col;j++) {
printf(“enter the element mat[%d][%d]”,row,col);
scanf(“%d”,&mat[i][j]);
}}
for(i=0;i<row;i++){
for(j=0;j<col;jj++){
sum=sum+mat[i][j];
}}
printf(“sum of all element in matrix is %d’,sum);
getch();
}

2014 fall,2014 spring 3(b)What is string?write a rogram to sort n students name in alphabetical order

A string is nothing but a collection of characters in a linear sequence. 'C' always treats a string a single data
even though it contains whitespaces. A single character is defined using single quote representation. A string is
represented using double quote marks.

Example, "Welcome to the world of programming!".

Program To sort Strings.( N numbers of names in Alphabetical order)


#include <stdio.h>
#include <string.h>
void main()
{

char name[10][8], tname[10][8], temp[8];


int i, j, n;
printf("Enter the value of n \n");
scanf("%d", &n);
printf("Enter %d names n \n", n);

for (i = 0; i < n; i++)


{
scanf("%s", name[i]);
strcpy(tname[i], name[i]);
}

for (i = 0; i < n - 1 ; i++)


{
for (j = i + 1; j < n; j++)
{
if (strcmp(name[i], name[j]) > 0)
{
strcpy(temp, name[i]);
strcpy(name[i], name[j]);
strcpy(name[j], temp);
}
}
}

printf("\n----------------------------------------\n");
printf("Input Names\tSorted names\n");
printf("------------------------------------------\n");

for (i = 0; i < n; i++)


{
printf("%s\t\t%s\n", tname[i], name[i]);
}

printf("------------------------------------------\n");

2014 fall 3(b,)Write a program to read n number from keyboard and find the smallest and largest
number using array

#include<stdio.h>
#include<conio.h>
void main()
{
int num[50],max,min,I,n;
printf(“enter how many numbers \n”);
scanf(%d”,&n);
printf(“enter %d numbers”,n);
for(i=0; i<n;i++)
{
scanf(“%d”,&num[i]);
}
max=num[0];
min=num[0];
for(i=0; i<n;i++)
{
if (max<num[i])
max=num[i];
if (min>num[i])
min=num[i];
}
printf(“the maximum no is %d”,max);
printf(“the maximum no is %d”,min);
getch();
}

2014 spring, 2015 spring, 2016 spring, 5(a), 2018 fall 5(a)

3(a) Why array is important in programming? How can you initialize different types of array? Explain 2
dimensional array in C.

- Array is important in programming because we can declare many element of similar data type at
the same time. We can initialize different types of array in different way:

Initialization of 1-D array:-


Till the array elements are not given any specifies values, they are supposed to contain
garbage values. The value can be assigned to element at the time of array declaration which is
called array initialization. Since an array has multiple elements, braces are used to separate the
individual values assign to the elements in the array initialization statements. The syntax for
initialization is
Storage – class- data-type array-name [size]=[value 1, value2,_ _ _ value n]
Where value 1 is value of first element, value 2 is value of second element.
The array initialization may be of three types, as below:-
a) int a[5] = {1,2,3,5,8}
Where a is integer type array which has 5 elements. Their values are assigned as 1, 2,
3,5,8 (i.e. a[0]=1, a[1]=2, a[2]= 3, a[3]=5, a[4]=8). The array elements are store sequently in
separate memory locations.
b) int b[ ]={2,5,7}
Here size of an array is not given. The complier automatically set it size according to
the number of values given. The size of array b is 3 in this array initialization as three values
2,5 and 7 are assigned at time of initialization. Thus writing int b[ ]={2,5,7} is equivalent to
writing int b[3]={2,5,7}.
c) int c[10]={45,89,54,89}
In this array the size of array c has been set 10 but only 5 elements are assigned at the
time of initialization. In this situation all individual elements that are not assigned explicity
contains zero as initial values. Thus the value of c[5], c[6], c[7], c[8] and c[9] is zero in this
example.
Multidimensional arrays:-
Multidimensional arrays are those which have more than one dimensions.
Multidimensional arrays are deined in much the same manner as one dimensional array,
except that a separate pair of square brackets is required for each subscript or dimension or
index. Thus two dimensional array required two pair of square brackets, three dimensional
array required three pair of square brackets and so on. The two dimensional array is also
called matrix. Multidimensional array can be defined as following.
Storage-class data-type array-name[dim 1] [dim 2]_ _ _ _[dim n]
Here dim 1, dim 2, _ _ _ dim n are +ve value integer expressions that indicates the
number of array element associated with each subscript.
Declaration of two dimensional array:-
Like one dimensional array two dimensional arrays must be declared before using it.
Syntax for declaration is.
[Storage-class] data – type array- name [row] [column]
Example:-
int matrix [2] [3];
matrix is 2-D array which has 2 rows and 3 columns i.e. it contains 6 elements.
Float m[10] [20]
Char students [10] [15];

Initialization of multidimensional array:-


Like one dimensional array multidimensional arrays can be initialized at the time of
array definition. Some examples of 2-D array initialization are:-
1) int marks [2] [3]= {{2,4,6}, {8,10,12}} is equivalent to following assignment. marks[0]
[0]=2, marks [0] [1]=4, marks[0] [2]=6, marks[1] [0]=8, marks[1] [1]=10, marks[1]
[2]=12.
2) int marks[ ] [3]={{2,4,6},{8,10,12}}; is equivalent to marks [0] [0]=2; marks[0] [1]=4;
marks[0] [2]=6; marks [1] [0]=8; marks [1] [1]=10; marks [1] [2]=12;
First dimension of 2-D array may be empty while initializing 2-D array.
3) int marks [2] [3]={2,4,6,8,10,12};
marks [0] [0]=2; marks [0] [1]=4; marks [0] [2]=6; marks [1] [0]=8 marks [1] [1]=10;
marks [1] [2]=12;
4) int marks [ ] [3] = {2,4,6,8,10,12}; is equivalent to 1,2 or 3.
5) int marks [ ] [3]={2,4,6,8,10}; is equivalent to
marks[0] [0]=2; marks [0] [1]=4; marks [0] [2]=6; marks [1] [0]=8; marks [1] [1] =10;
marks [1] [2]=0
if number of value provided while initialization is less than size of array zero is assigned
to the remaining elements.
6) int marks [3] [ ]= {2,4,6,8,10,12};/*error*/
7) int marks [ ] [ ]= {2,4,6,8,10,12};/*error!!!*/
2015 fall, 2016 fall,3(a) Write a program to read a matrix and find the sum of all the digits in it’s main
diagonal. Why array is called static data type?

- #include<stdio.h>
#include<conio.h>
void main ( )
{
int matrix [10] [10],I, j, p, q sum=0;
Print f (“Enter order of a square matrix (less than 10*10)\t:”);
Scan f (“%d %d”, &p, &q);
If (p>10 11 q>10)
{
Print f (“\n the order is out of range\n”);
Getch ( );
Exit ( );
}
Print f (“Enter matrix of order %d * %d\n”, p, q);
For (i=0: i<p; i++)
For (j=0: j<q; j++)
{
Print f (“matrix[%d] [%d] = “, i,j);
Scan f (“%d”,& matrix [i] [j]);
If (i= =j)
Sum=matrix [i] [j] +sum;
}
Print f (“your matrix is:\n”);
For (i=0; i<p; i++)
{for (j=0; j<q; j++)
Print f(“%d\t’,matrix [i] [j]);
Print f (“\n”);
}
Print f (“The sum is %d,”sum);
Getch ( );
}

An array could be called as static because it is generally not changed structurally once it is
created, meaning that we do not add, delete or swap the nodes themselves through we will likely
modify the data contained by the nodes.

2015 fall,3(b) Define function prototype. Write a program to read an integer number and find the sum of
it’s digits using recursive function.
Function prototype

A function prototype is simply the declaration of a function that specifies function's name, parameters and
return type. It doesn't contain function body.

A function prototype gives information to the compiler that the function may later be used in the program.

Syntax of function prototype

returnType functionName(type1 argument1, type2 argument2, ...);

In the above example, int addNumbers(int a, int b); is the function prototype which provides the following
information to the compiler:
1. name of the function is addNumbers()
2. return type of the function is int
3. two arguments of type int are passed to the function.

#include <stdio.h>

int sum (int a);

int main()
{
int num, result;

printf("Enter the number: ");


scanf("%d", &num);
result = sum(num);
printf("Sum of digits in %d is %d\n", num, result);
return 0;
}

int sum (int num)


{
if (num != 0)
{
return (num % 10 + sum (num / 10)); }
else
{
return 0;
}
}
2018 fall 3(a), 2013 fall 4(b), 2014 spring 5(a), 2015 spring, 2016 fall 5(b), 2016 spring, 2017 fall 4(b), 2017
spring 4(a), 5(a),3(b) Why are functions used? Explain function call by value and call by refrence with
examples.

- The function is the block of code which has some functionality which is designed outside the
main method and called inside the main block whenever we required. Designing the function is
the decomposition at whole task in the various sub units so that whole task could easily solve.

Call by refrence Call by value


#include<stdio.h> #include<stdio.h>
#include<conio.h> #include<conio.h>
Void change (int*a; int*b){ int temp; int sum (int a, int b)
Temp=*a; {int c=a+b;
*a=*b; Return c;
*b=temp; }
Print f (“inside exchange %d and !d”, *a, *b);} Void main ( )
Void main ( ) { {
Int p,q; int x, y, z;
P=90; q=89; print f (“Enter any two numbers”);
Print f ( “Before exchange %d and %d “ p, q); scan f(“%d %d &x, &y);
Change (&p, &q) z=sum ( x,y);
Print f (“After exchange %d and %d”, p, p); print f (“the sum of the given two numbers is
Getch ( ); %d’,z);
} getch ( );
}
In this type of function call, the addresses of When values of actual arguments are passed to
variable or arguments are passed to the function as argument is known as function
function instead of actual values of variables. called by value.
The address is passed to function as actual The values are passed to function as actual
argument. arguments.
Address, location of the value can be stored. Stored value send to the memory.

2016 spring,3(b) Define function, function definition, function calling, function declaration with code
examples.

- A function is defined as self contained block of statements that performs a particular specified
job in a program. Actually it is a logical unit composed of a number of statements grouped into a
single unit.
- Function definition:-
One or more statements that describes the specific task to be done by a function is called
function definition. It consists of function header, which defines function’s name, it’s return type
and it’s argument. List and a function body which is a block of code enclosed in parenthesis.
- Syntax:-
return_type function _name(data_type variable 1, _ _ _ _, data_type variable)
{
Statements;
return value;
}.
- Function declaration or prototype:-
The function declaration or prototype is model of a function. If a function is used before
it is defined in the program, then function declaration or prototype is needed to provide
following information to the complier.
i) The name of the function.
ii) The type of the value return by the function.
iii) The number and the type of arguments that must be supplied while calling the
function.
- Syntax:-

return_type function_name (type 1, type 2, type 3, _ _ _type n);

- Function calling:-
A function is called or accessed by specifying its name, followed by a list of arguments
enclosed in parentheses and separated by commas. For example the function add() with two
arguments is called by add (a,b) to add two numbers. If function call doesn’t require any
arguments an empty pair of parentheses must follow the name of function. The argument
appearing in the function call are refered as actual arguments. In function call, there will be one
argument for each formal argument.

#include <stdio.h>
#include <conio.h>
int addition (int a , int b)
{
int sum;
sum = a + b;
return sum;
}
int main;
{
int a,b sum;
printf (“ Enter two numbers: );
scanf (“%d %d”, &a, &(n*b);
sum = addition (a,b);
printf (“/n the sum is lt %d”, sum);
getch ( );
return o;
}
2017fall
3(a) write a program to print the following pattern.
1
12
123
#include <stdio.h>
#include <conio.h>
void main( )
{
int i, j ,n= 3
for (i=1; i<=n; I + +)
{
for (j= 1; j<=I; j++)
printf(“\t%d”,j);
printf (“ \n”);
}
getch ( );
}

2017 fall,3(b) How can you initialize an one dimensional array? Write a program to search an element
in one dimensional array containing five integer elements.

#include <stdio.h>

#include <conio.h>

#include<stdlib.h>

void main ( )

int a [5],i,j,n;

printf (“enter array elements”);

for(i=0;i<5;i++)

scanf (“%d”,&a[i] );

printf(“\n Enter a number to search”);

scanf(“%d”,&n);

for(i=0;i<5;i++)

if(a[i]==n)

{
printf(“\n The number exists in Array at index %d”,i);

getch();

exit(0);

print f (“\n number not found “);

getch ( );

2017 spring, 2018 fall 5(b),3(a) Define recursion. Write a program to find sum of n natural number using
recursion.

- A recursive function is that type of function which always calls it’s self until a condition
becomes false which is not always required to be apply in many case.
#include<stdio.h>
#include<conio.h>
int sumnatural (int);
int main ( )
{
int n, sum;
printf (“Enter n:”);
scan f (“%d”,& n);
sum =sumnatural (n)
print f (“the sum of first natural number is:% d”, n, sum);
getch ( )
return 0;
}
int sumnatural (int num)
{
if (num z=1)
return 1;
else return num + sumnatural (num-1);
}

2017spring,3(b) differentiate between switch and nested if else statements with a suitable example.

When one of if statement is executed over another if statement then it is known as nested if statement.

Syntax :
if (condiition1){

if condition2){

statement 1;}

elseif (condition 3)

Statement 2;

else (statement 3); }

else (statement 4); }

Statement x;

Switch statement:

When there are number of options ( cases) to be handled. Switch statement is one of the ways of
representing this multi way selection. A switch statements allows user to choose a statement among several
alternatives. The switch statement is useful when a variable is to be compared with different values and incase
it is equal to a constant a set of statements are to be executed. The constants in case statement may be either
char or int type only.

Syntax:

Switch (variable name){

Case A:

statements;

break;

Case B:

statements;

break;

default:

statement x;

#include <stdio.h>
#include <conio.h>

void main( )

float a,b,c;

char A;

print f (“Enter two numbers:”);

scan f(“%f %f” , &a,&b);

print f (“Enter the operator you want to calculate(+, - ,*) :”);

scan f (“%c”,&A);

switch (A){

case ‘+’:

c= a-b;

print f(\n the sum is %f”;c);

break;

case ‘-‘:

c= a-b;

print f (“\n the difference is %f”,c);

break;

case’*’:

c= a*b;

print f (“\n the product is %f”,c);

break;

default;

print f(“invalid operator”);}

getch ( );

2018spring, 2014spring 4(a)2016 fall, 2018spring,3(b) Write a program to generate fibonacci numbers as per
users choice.(recursive function)
#include <stdio.h>

#include<conio.h>

int fibo(int);

void main ( )

int num ,i;

int result;

print f (“Enter how many terms:”);

scanf (“%d”,&num);

print f( fibonanci series\n”);

for (i=o; i<num; i++)

result= fibo(i);

print f (“%d\n”,result);

getch ();

int fibo(int num)

If (num==o) {

return o;

elseif (num==1)

return 1;

else {

return (fibo(num-1) + fibo (num-2));


}

2013 spring,4(b) What is recursive function? Write a recursive program to calculate factorial of a given
number using recursive function.

Recursion in C language is basically the process that describes the action when a function calls a copy of itself
in order to work on a smaller problem. Recursive functions are the functions that call themselves and these type
of function calls are known as recursive calls. The recursion in C generally involves various numbers of
recursive calls. It is considered to be very important to impose a termination condition of recursion. Recursion
code in the C language is generally shorter than the iterative code and it is known to be difficult to understand.

Recursion cannot be applied to all the problem, but Recursion in C language is very useful for the tasks that can
be generally be defined in terms of similar subtasks but it cannot be applied to all the problems. For instance:
recursion in C can be applied to sorting, searching, and traversal problems.

As function call is always overhead, iterative solutions are more efficient than recursion. Any of the problem
that can generally be solved recursively, it can be also solved iteratively. Apart from these facts, there are some
problems that are best suited to only be solved by the recursion for instance: tower of Hanoi, factorial finding,
Fibonacci series, etc

#include <stdio.h>

#include<conio.h>

int factorial (int):

int main( ){

int num ;

int fact;

print f (“Enter a number to find its factorial:”);

scan f (“%d”,&num);

if (num<o){

print f (“factorial of negative number is not possible”);}

else{

fact= factorial (num);

print f (“The factorial is %d,”num fact);}

getch ( );}

int factorial (int num)

{
if (num==0 || num==1)

return 1;

else

return num*factorial(num-1);

2013 spring,2014fall 4(b),2014spring,2016fall,,4(A) Explain different types of storage classes in c-use


examples to illustrate.

The “storageclass” of a variable determined whether the item has a “global”or “local” life time.

C calls these two lifetimes “static” and “automatic”. An item with a global lifetime exists and has a value
through the execution of the program. All functions have global lifetimes.

There are following storage classes which can be used in a c program auto, register, static,extern.

*auto storage class:

Auto is the default storage class for all local variables.

int count;

auto int month;

The example above defines two variables with the same storage class. Auto can only be used within
functions:i.e local variables.

• Register storage class:


Register is used to define local variables that should be stored in register instead of
RAM. This means that the variable has a maximum size equal to the register size (usually one word)
and can have the unary ‘&’ operator applied to it (as it doesn’t have a memory location).
{
register int miles;
}
register should only be used for variables that require quick access such as counters.
static storage class:
static is the default storage class for global variable. The two variables below c count and
road) both have a static storage class.

static int count:


int Road;
{
printf (“%d\n”,Road);
}

2015fall,2015spring,2018 fall, 4(a) What is pointer? Explain memory allocation in c programming why
DMA is better? Explain about memory leak.

A pointer is a variable that contain the address of another variable. A pointer is a derived data type
in C. pointers contain memory address as their values.
There are two types of memory allocation,static and dynamic which are described as below.
Static memory allocation:
The process of allocating memory at the compile time is known as static memory allocation. And
the arrays that receive static memory allocation are called static array.
Dynamic memory allocation:
It is the process of allocating memory storage for use in a computer program during the run time
of that program. Arrays created at the run time is called the dynamic arrays.
Dynamic arrays are created using:
• Pointer variables
• Memory management functions

Memory Management functions:

i) malloc ( )
A block of memory of specified size can be allocated using the function malloc.
Malloc function reserves a block of memory of specified size and return a pointer of type void a
pointer to anything.

Syntax: - ptr=(cast-type*)malloc(byte-size)

Example: - int *ptr=(int*)malloc(n*sizeof(int)); //memory allocated using malloc n is the no of blocks

ii) Calloc ( ):
It is used for storing derived data types such as array and structures.
Malloc allocates single block of memory but calloc allocates multiple blocks of memory each of
same size and sets all bytes to zero.
ptr= (data_type*) calloc (no.of block sizeof ptr each block);
iii) Free ( ):
Deallocates the previously allocated space
Syntax:
free (ptr)
iv) Realloc( ) : -
It modifies the size of previously allocated space.
We can change the memory size already allocated with the help of the function realloc,this
process is called reallocation of memory.
The DMA process reserves the memory required by the program and allows the program to utilize
the memory. When the allocated memory is no more in used ,it returns the allocated memory to the
system. The deallocated memory now is free and any other program can use it. So DMA is better.
In computer science , a memory leak occurs when a computer program incorrectly manages memory
allocations ,in such a way that memory which is no longer needed is not released.

2015 fall,4(b) Write a program using pointer to read an array of integers. Next add the elements in the array
and display the sum on the screen.

#include<stdio.h>
#include<stdlib.h>

int main()
{
int *ptr; //declaration of integer pointer
int limit; //to store array limit integer numbers)
int i; //loop counter
int sum; //to store sum of all elements

printf("Enter limit of the array: ");


scanf("%d",&limit);

declare memory dynamically


ptr=(int*)malloc(limit*sizeof(int));

//read array elements


for(i=0;i<limit;i++)
{
printf("Enter element %02d: ",i+1);
scanf("%d",(ptr+i));
}

//print array elements


printf("\nEntered array elements are:\n");
for(i=0;i<limit;i++)
{
printf("%d\n",*(ptr+i));
}

//calculate sum of all elements


sum=0; //assign 0 to replace garbage value
for(i=0;i<limit;i++)
{
sum+=*(ptr+i);
}
printf("Sum of array elements is: %d\n",sum);

//free memory
free(ptr); //hey, don't forget to free dynamically allocated memory.

return 0;
}

2015 spring ,4(b) What is nested structure? Write a program to input the following records of any 50
employees using structure and display them properly.

1) Name Address Post Salary Date of appointment

Month day year

2013 fall 6(a), 2015 fall 6(a)

2) Roll .no Name Address Faculty Date of Birth

Month day year

Write a program to input 100 students and display the records of computer faculty.

#include<conio.h>

#include<stdio.h>

#include<string.h>

void main ( )

int i;

struct student

int roll no. ;

char name [50]

char address [50];

char faculty [50];

struct date

int mm;
int dd;

int yr;

}dt;

};

struct student std [10];

for (i=0; i<100; i++)

print f (“Enter information of student no. %d\n”,i+1);

print f (“\n Roll No: ”);

Scan f (“%d”, &std [i]. roll no);

printf (“\nName:”);

scanf (“%s”,&std [i]. name);

printf (“\n address: “);

scanf (“%s”,&std[i]. address);

printf (“\n faculty: ”);

scan f (“%s”,&std[i]. faculty);

printf(“\nEnter date of joining: ”);

printf (“\n month: ”);

scanf (“%d”, &std[i]. dt . mm);

printf (“\n day:”);

scan f (“%d”, & std[i]. dt .mm);

printf (“\n year:”);

scanf (“%d”, & std [i] dt. Yr);

printf (“\n record of student \n”);

prin f (“roll no\t name \t address \t faculty \t date of birth \n”);

for (i=0; i<100; i++)

{
If (strcmp (std[i].faculty,”computer”)==0)

print f (“%d\t%s\t%s\t%s\t%d\t%d\t%d|n,” std [i]. roll no,std[i].name, std [i]. address, std[i]. faculty, std
[i].dt.mm,std [i].dt.dd,std[i].dt.yr);

getch ( );

One structure can be nested within another structure in C. In other words, the individual member of a structure
can be other structure as well.

2016 fall.4(a) List the major advantages of recursive function.

Recursion provides a clean and simple way to write code. Some problems are inherently recursive like tree
traversals, Tower of Hanoi, etc. For such problems, it is preferred to write recursive code. We can write such
codes also iteratively with the help of a stack data structure. For example refer Inorder Tree Traversal without
Recursion, Iterative Tower of Hanoi.

2016 spring (2nd part) 2018 fall 6(a),4(a) Define local variables and global variables. Explain different
storages class with examples. Write a program to illustrate the use of static variable.

- Those variables which are declared within function or block is known as local variable. The
initial value is unpredictable. The keyword auto is used.
Those variables which are defined outside the function so that their scope is throughout the
program is known as global variable.
The keyword extern is used.
Static variable are special case of local variables. Static variable are also defined inside the
function or block.
The keyword static is used.
Local variable
#include<stdio.h>
#include<conio.h>
long int fact (int h)
{
int i;
long int f=1;
for (i=1; I<=n; i++)
f*=1;
return (f);
}
int main ( )
{
int num;
printf (“ The factorial is %d”, fact (num));
getch ( );
return 0;
}

Global variable
#include <stdio.h>
#include <conio.h>
int a= 10;
void fun ( )
{
a= 20;
printf(“\t%d”, a ++);
}
int main ( )
{
printf (“\t%d”,a);
fun ( );
printf (“\t %d”, a);
return o;
}

static variable
increment ( )
{
int i=1;
print f (“%d\n”, i);
i+1;
}
void main ( )
{
increment ( );
increment ( );
increment ( );
increment ( );
}
Output 1
1
1
1
1

2016spring, 20189spring, 6(a), 2016fall 5(a),4(b) (Example of DMA) Write a program to sort the array
using dynamic memory allocation.

#include <stdio.h>

#include <conio.h>

void sort (float*, int)

void main (void)

int n,i;

float * marks;

printf (“enter number of elements:”);

scanf (“%d”, &n);

marks = (float*) malloc(n*sizeof (float));

if(marks==NULL)

exit (0 );

printf (“Enter array elements:”);

for (i=0; i<n; i+ +)

scanf (“%f”,(marks + i) );

}
sort (marks, n);

for (i=o; i<n; i++)

print f (“\n Element at %u is %f”, (marks + i), * (marks + i) );

free (marks);

getch ( );

void sort (float *m, int n)

int pass, i, j, temp;

for (pass=0; pass <n-1; pass++ )

for (j=o; j<n-pass-1; j ++)

if (* (m+j) < * (m+j+1))

temp = * (m+ j + 1);

*(m + j + 1)= *(m + j);

*(m + J)= temp

2013spring,2014spring,6(b) What do you need file handling? Describe the different file opening modes
what is the significance of file painter?

The data is written to the standard output and data is read from the standard input. As long as only small
amount of data are being accessed in the form of simple variables and character strings. This type of I/O is
sufficient. However, with large amount of data, the information has to be written to or read from auxiliary/
secondary storage device. Such information is stored on the device in the form of a data file. So we need file
handling.
There are various types of file opening modes. The file opening mode specifies in which a file
should be opened in other words,it specifies the purpose of openingsa file. There are six modes.
i) “r” read mode:
This opens existing files for reading mode only.
ii) “W” write mode:
This mode of file opens a file for writing only.
iii) “a” append mode:
It opens an existing file for appending.
iv) “r+” read + write mode:
It opens existing file for reading and writing
v) “W+” read + write mode:
It opens an existing file for both reading and appending.

A file pointer is a pointer to a structure, which contains information about the file, including its name, current
position of the file, whether the file is being read or written, and whether errors or end of the file have occurred.
The user does not need to Know the details, because the definitions obtained from stdio.h include a structure
declaration called FILE. The only declaration needed for a file pointer is symbolized by

FILE *fp;
This says that fp is the file pointer that points to a FILE structure that establishes the buffer area in RAM and fp
is a pointer variable that indicates the beginning of the buffer area.

Opening a file:
The fopen() function opens a stream for use and links a file with that stream. A file pointer associated with that
file is then returned by the fopen() function. Most often the file is a disk file. The prototype for the fopen()
function is

FILE *fopen(const char* filename, const char *mode);


Where filename is a pointer to a string of characters that make up a valid file name and can also include a path
specification. Another parameter is a pointer to a string, name mode, determines how the file can be opened.
The below table shows the valid modes in which a file may be opened. Strings like “w + b” can also be
represented as “wb+”.

2014fall,5(b) what is pointer variable? How memory of a variable can be initialized dynamically? Explain
with example.

- Definition of pointer and explain DMA WITH EXAMPLE (ALREADY DONE)


2014SPRING,5(b) What is pointer? How does a pointer differ from an array? Explain dynamic memory
allocation.

ARRAY POINTER
1)Type var-name [size]. 1)Type * var-name;
2) Store the value of the variables of 2)Store the address of another variable of same
homogeneous data type. datatype as the pointer variables datatype.
3)An array of pointer can be generated. 3)A pointer to an array can be generated.

4)An array can store the number of elements, 4)A pointer can store the address of only one
mentioned in the size of array variable. variable at one time.

2015fall, 2016fall 6(b),2017springg 5(b),5(a) define structure and union. Explain way of declaring and
accessing member of them with suitable example also. Different between structure and union.

- A structure is a collection of different types ofvariables under a single name and each variable
has a name which is used to select it from the structure. A structure is a convienent way of
grouping several pieces of related information together. A structure can be defined as a user
defined data type.
Struct structure_name
{
Data__type member_variable1;
Data_type member_variable2;

Data_type member_variable n;

A union is similar to a structure with respect to syntax and use. The union also contains members whose
individual data type may differ from one another. The distinction is that all member within a union share the
same storage area of computer memory.

STRUCTURE UNION
1)The keyword struct is used to define a 1)The keyword union is used to define a union.
structure.
2)When a variable is associated with a 2) when a variable is associated with a
structure ,the complier allocates the memory union,the complier allocates the memory by
for each member. The size of structure is considering the size of the largest memory. So
greater than or equal to the sum of sizes of its size of union is equal to the size of largest
members. The smaller members may end with members size number.
us used slack bytes.
3)Each member within a structure is assigned 3) Memory allocated is shared by individual
unique storage area of location. member of union.
4)Altering the value of a member willnot affect 4) altering the value of any of the member will
other members of the structure. alter other member values.
5)Several members of a structure can initialize 5)Only the first member of a union can be
at once. initialized.
Struct student { Union student {
Char name [20]; Char name [20];
Int roll; Int roll;
Float marks; Float marks;
} struct object; } union_object;

2015fall,5(b) Write a program to read the name ,author and price of 500books in a library from the
file”library.dat”. Now print the book name and price of those books whose price is above rs 300.

#include <stdio.h>

#include <conio.h>

void main ( ) {

struct library {

char bname [30]; char aname [30]; int price

};

struct library lib[500];

int i;

FILE *F;

F= fopen (“c:\ library.dat”, “w”);

if (F= = NULL)

printf (“File not opened”);

else {

for (i=0; i<500; i + +)

printf (“\n Enter the book name: \n”);

scanf (“%s”, &lib[i]. bname);

printf (“\n Enter the author name:\n”);

scanf (“%s”, &lib[i]. aname);

printf(“\n Enter the book price:\n”);

scanf (“%d”, &lib[i].price);


}

for (i=0; i<500; i ++)

if (lib[i]. price > 300)

printf (“\n Bookname \t Author \t price);

printf (“\n …………..”);

printf( “\n%s\t%s\t%d”, lib [i]. bname \t lib [i]. aname \t lib [i]. price);

fclose (F);

getch ( );

2015fall 6(c) Different between user defined and library functions with suitable examples

- The function is the block of code which has some functionality which is designed outside the
main method and called inside the main block whenever we required. There are two types of
functions library and user defined type.
i) Library function:
These functions have already been written complied and placed in libraries.
printf, scanf, getch etc are some examples of library function.

• LF(library functions) are Predefined functions.


• UDF(user defined functions) are the function which r created by user as per his own requirements.
• UDF are part of the program which compile runtime
• LF are part of header file
(such as MATH.h) which is called runtime.
• In UDF the name of function id decided by user
• in LF it is given by developers.
• in UDF name of function can be changed any time
• LF Name of function can't be
changed.

ii) User defined functions:


These are the functions which the programmer creates and uses in a c
program. These functions can be used by given means:
• Function call by value
• Function call by reference
• Function return type without argument
• Function return type with argument

2013 fall Q.No. 6b What are file opening modes? Write a Program to open a new file, read name, address and
telephone number of 10 employees from the user and write to a file.

Ans. - Data file

The data is written to the standard output and data is read from the standard input. As long as only small
amount of data are being accessed in the form of simple variables and character strings. This type of I/O is
sufficient. However, with large amount of data, the information has to be written to or read from auxiliary/
secondary storage device. Such information is stored on the device in the form of a data file.

Whenever we open or create a file, we have to specify what we are going to do with the file. A file in 'C'
programming can be created or opened for reading/writing purposes. A mode is used to specify whether we
want to open a file for any of the below-given purposes. Following are the different types of modes in 'C'
programming which can be used while working with a file.

File Mode Description

R Open a file for reading. If a file is in


reading mode, then no data is deleted if
a file is already present on a system.
W Open a file for writing. If a file is in
writing mode, then a new file is created
if a file doesn't exist at all. If a file is
already present on a system, then all
the data inside the file is truncated, and
it is opened for writing purposes.

A Open a file in append mode. If a file is


in append mode, then the file is
opened. The content within the file
doesn't change.

r+ open for reading and writing from


beginning

w+ open for reading and writing,


overwriting a file

a+ open for reading and writing,


appending to file

In the given syntax, the filename and the mode are specified as strings hence they must always be enclosed
within double quotes.
To create a file in a 'C' program following syntax is used,
FILE *fp;
fp = fopen ("file_name", "mode");
In the above syntax, the FILE is a data structure which is defined in the standard library.
fopen is a standard function which is used to open a file.
• If the file is not present on the system, then it is created and then opened.
• If a file is already present on the system, then it is directly opened using this function.
fp is a file pointer which points to the type file.
Program
#include <stdio.h>
#include <conio.h>
#include<stdlib.h>
Void main()
{
int n;
struct emp
{
char name[15];
char address[25];
char telph[15];
}rec[10];
for(n=0;n<10;n++)
{
printf(“\n Enter name, Address and Telephone number of employee number %d :”, n+1);
gets(rec[n].name);
gets(rec[n].address);
gets(rec[n].telph);
}
FILE *fp;
Fp=fopen(“employee.txt”,”w”);
If(fp==NULL)
{
printf(“ \nFile I/o error”);
exit(0);
}
for(n=0;n<10;n++)
{
fprintf(“fp”,”%s %s %s”,rec[n].name,rec[n].address,rec[n].telph);
}
printf(“ \n 10 employees data has been saved”);
fclose(fp);
getch();
}

2013 2.b Write a program to display the following menu. (Spring)

i. Conversion of Ascii code to char


ii. To find sum of n natural numbers
iii. Exit from program

And to perform task as per users’ choice repeatedly until his/her choice to exit.

Solution: -

#include<stdio.h>
#include <conio.h>
#include<stdlib.h>
void main()
{
int choice=1;
while(1)
{
printf(“\n\n\t\t MENU”);
printf(“\n\n\t 1. Convert Ascii Code to Char”);
printf(“\n\n\t 2. To find sum of n natural numbers”);
printf(“\n\n\t 3. To Exit”);
printf(“\n\n\t Please perss your Choice number : ”);
scanf(“%d”,&choice);
switch(choice)
{
case 1:
int asc;
puts(“ enter a ascii code to convert to character:”);
scanf(“%d”,&asc);
printf(“\n The Character equivalent of Ascii code %d is %c”,asc,asc);
break;
case 2:
int term,count,sum=0;
printf(“\n Enter the total number of terms of natural numbers to find Sum : “);
scanf(“%d”,&term);
for(count=1;count<=term;count++)
sum=sum+count;
printf(“\n Sum of %d natural numbers=%d”,term,sum);
break;
case 3:
exit(0);
default:
printf(“\n\t Bad choice number….”);
getch();
break;
}
printf(“\n press enter to continue……”);
getch();
}
}
2013 spring 5.a Write a program using pointer to read in an array of integers and print its elements in
reverse order.

Solution:-
#include <stdio.h> 35679
#include <stdlib.h> 97653
void reverse_array(int *ar , int n);
int main()
{
int n, c, *pointer;
printf(‘\n How many items do you have?”);
scanf("%d",&n);

pointer = (int*)malloc(sizeof(int)*n);

if( pointer == NULL )


exit(EXIT_FAILURE);

for ( c = 0 ; c < n ; c++ )


scanf("%d",(pointer+c));

reverse_array(pointer, n);
printf("Original array on reversal is\n");

for ( c = 0 ; c < n ; c++ )


printf("%d\n",*(pointer+c));

free(pointer);

return 0;
}
void reverse_array(int *pointer, int n)
{
int *s, c, d;

s = (int*)malloc(sizeof(int)*n);

if( s == NULL )
exit(EXIT_FAILURE);

for ( c = n - 1, d = 0 ; c >= 0 ; c--, d++ )


*(s+d) = *(pointer+c);

for ( c = 0 ; c < n ; c++ )


*(pointer+c) = *(s+c);

free(s);
}

2013 Spring 6.a Given a structure of employee :

Name ,address, telephone,salary, year (date )of joining(mm dd yy). Write a program to input data of 100
employee and display records of those employees living in “ pokhra”.

Solution: -
# include <stdio.h>
#include <conio.h>
#include<stdlib.h>
#include<string.h>
Void main()
{
int n;
struct join{
int yy, mm, dd;
}
struct emp
{
char name[15];
char address[25];
char telph[15];
float salary;
join date;
}rec[100];
for(n=0;n<100;n++)
{
printf(“\n Enter name, Address , Telephone number, salary and join date in mm/dd/yy of employee number %d
:”, n+1);
gets(rec[n].name);
gets(rec[n].address);
gets(rec[n].telph);
scanf(“%f”,&rec[n].salary);
scanf(“%d %d %d”,&rec[n].date.mm,&rec[n].date.dd,&rec[n].date.yy);
}
FILE *fp;
Fp=fopen(“employee.txt”,”w”);
If(fp==NULL)
{
printf(“ \nFile I/o error”);
exit(0);
}
for(n=0;n<100;n++)
{
fprintf(“fp”,”%s %s %s %f %d %d
%d”,rec[n].name,rec[n].address,rec[n].telph,rec[n].salary,rec[n].date.mm,rec[n].dd,rec[n].date.yy);
}
printf(“ \n 100 employees data has been saved”);
fclose(fp);
FILE *fp;
Fp=fopen(“employee.dat”, ”r”);
If(fp==NULL)
{
printf(“ \nFile I/o error”);
exit(0);
}
for(n=0;n<100;n++)
{
fscanf(“fp”,”%s %s %s %f %d %d
%d”,&rec[n].name,&rec[n].address,&rec[n].telph,&rec[n].salary,&rec[n].date.mm,&rec[n].dd,&rec[n].date.yy);
}
printf(“\n Employee who are living in Pokhra are :);
for(n=0;n<100;n++)
{
If(strcmp(rec[n].address,”pokhra”)==0)
printf(”\n%s \t %s\t %s\t %f\t %d/ %d/
%d\n”,rec[n].name,rec[n].address,rec[n].telph,rec[n].salary,rec[n].date.mm,rec[n].dd,rec[n].date.yy);
}
Fclose(fp);
getch();
}

2014 fall 5.a Write a program to sort (ascending order) n integer values in an array using pointer.

Solution: -
#include<stdio.h>
#include<stdlib.h>
void sort(int n, int *x);
void main()
{
int i, n,*x;
printf( “\n\t How many numbers do you have:”);
scanf(“%d”,&n);
x=(int *) malloc(n * sizeof(int));
for(i=0;i<n; i++)
{
printf(“\n i=%d x=”,i+1);
scanf(“%d”,x+1);
}
sort(n,x);
printf (“\n\n Sorted Items in Ascending order are :\n\n”);
for (i=0; i<n; i++)
printf(“ i=%d \t x-=%d\n”,i+1,*(x+i));
getch();
)
void sort(int n, int *x)
{
int i, item, temp;
for(item=0; item<n-1; item++)
for(i=item+1; i<n;i++)
if(*(x+i)<*(x+item))
{
temp=*(x+ item);
*(x+ item)=*(x+ i);
*(x+ i)=temp;
}
}

2014 Fall 6. B. What is significance of file pointer in file handling? Consider a following structure

Rollno name, Address, faculty, Date of birth(mm dd yy). Write a program to create “student.txt” file to
store the above records for 100 students, Also display those records of Students who are not from
Pokhra.

Solution : -

A file pointer is a pointer to a structure, which contains information about the file, including its name, current
position of the file, whether the file is being read or written, and whether errors or end of the file have occurred.
The user does not need to Know the details, because the definitions obtained from stdio.h include a structure
declaration called FILE. The only declaration needed for a file pointer is symbolized by
1. FILE *fp;
This says that fp is the file pointer that points to a FILE structure that establishes the buffer area in RAM and fp
is a pointer variable that indicates the beginning of the buffer area.

Opening a file:
The fopen() function opens a stream for use and links a file with that stream. A file pointer associated with that
file is then returned by the fopen() function. Most often the file is a disk file. The prototype for the fopen()
function is

1. FILE *fopen(const char* filename, const char *mode);


2. Where filename is a pointer to a string of characters that make up a valid file name and can also include a path
specification. Another parameter is a pointer to a string, name mode, determines how the file can be opened.
The below table shows the valid modes in which a file may be opened. Strings like “w + b” can also be
represented as “wb+”.

# include <stdio.h>
#include <conio.h>
#include<string.h>
void main()
{
int n;
struct date{
int yy,mm,dd;
}
struct stud
{
int rollno;
char name[15];
char address[25];
char faculty[15];
date dob;
}rec[100];
for(n=0;n<100;n++)
{
printf(“\n Enter rollno, name, Address ,faculty, and birth date in mm/dd/yy of student number %d :”, n+1);
scanf(“%d”,&rec[n].rollno);
gets(rec[n].name);
gets(rec[n].address);
gets(rec[n].faculty);
scanf(“%d %d %d”,&rec[n].dob.mm,&rec[n].dob.dd,&rec[n].dob.yy);
}
FILE *fp;
fp=fopen(“student.txt”,”w”);
If(fp==NULL)
{
printf(“ \nFile I/o error”);
exit(0);
}
for(n=0;n<100;n++)
{
fprintf(“fp”,”%d %s %s %s %d %d
%d”,rec[n].rollno,rec[n].name,rec[n].address,rec[n].faculty,rec[n].date.mm,rec[n].dd,rec[n].date.yy);
}
printf(“ \n 100 Students data record has been saved”);
fclose(fp);
FILE *fp;
fp=fopen(“student.txt”,”r”);
If(fp==NULL)
{
printf(“ \nFile I/o error”);
exit(0);
}
for(n=0;n<100;n++)
{
fscanf (“fp”,”%d %s %s %s %d %d
%d”,&rec[n].rollno,&rec[n].name,&rec[n].address,&rec[n].faculty,&rec[n].date.mm,&rec[n].dd,&rec[n].date.y
y);
}
printf (“\n students who are not living in Pokhra are :);
for(n=0;n<100;n++)
{
If(strcmp(rec[n].address,”pokhra”)!=0)
printf(”\n%d\t %s\t %s\t %s\t %d/ %d/
%d\n”,rec[n].rollno,rec[n].name,rec[n].address,rec[n].faculty,rec[n].date.mm,rec[n].dd,rec[n].date.yy);
}
fclose(fp);
getch();
}

2014 Spring 6. A What is nested structure? Create a structure called book having member
name,price,author and published date in day,month and year. Write a program to read 100 books
information from the user and display those books having price greater than 250.

Solution : -

• Structure written inside another structure is called as nesting of two structures.


• Nested Structures are allowed in C Programming Language.
• We can write one Structure inside another structure as member of another structure.

Way 1 : Declare two separate structures

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

struct Employee
{
char ename[20];
int ssn;
float salary;
struct date doj;
}emp1;

1. Structure members are accessed using dot operator.


2. ‘date‘ structure is nested within Employee Structure.
3. Members of the ‘date‘ can be accessed using ’employee’
4. emp1 & doj are two structure names (Variables)

Way 2 : Declare Embedded structures

struct Employee
{
char ename[20];
int ssn;
float salary;
struct date
{
int date;
int month;
int year;
}doj;
}emp1;

Accessing Nested Members :

Accessing Month Field : emp1.doj.month


Accessing day Field : emp1.doj.day
Accessing year Field : emp1.doj.year

# include <stdio.h>
#include <conio.h>
#include<string.h>
void main()
{
int n;
struct date{
int day,month,year;
}
struct book
{
char name[15];
float price;
char author[15];
date pubdate;
}books[100];
for(n=0;n<100;n++)
{
printf(“\n Enter, name,price author, and published date of book number %d :”, n+1);
gets(books[n].name);
scanf(“%f”,&books[n].price);
gets(books[n].author);
scanf(“%d %d %d”,&books[n].pubdate.day,&books[n].pubdate.month,&books[n].pubdate.year);
}
clrscr();
printf(“\n\t, name\tprice\t author\t published date of book price greater than 250: are”);
for(n=0;n<100;n++)
{
If(books[n].price>250)
printf(“\n\t%s\t%f\t%s\t%d \%d\
%d”,books[n].name,books[n].price,books[n].author,books[n].pubdate.day,books[n].pubdate.month,books[n].pu
bdate.year);
}getch();
}
2015 fall. 4.b . Write a program using pointers to read in an array of integers. Next add the elements in
array and display the sum on the screen.

Solution : -
#include <stdio.h>
#include <malloc.h>

void main()
{
int i, n, sum = 0;
int *a;

printf("Enter the size of array A \n");


scanf("%d", &n);

a = (int *) malloc(n * sizeof(int));

printf("Enter Elements of the List \n");


for (i = 0; i < n; i++)
{
scanf("%d", a + i);
}

for (i = 0; i < n; i++)


{
sum = sum + *(a + i);
}

printf("Sum of all elements in array = %d\n", sum);

2015 Spring 6a. Use recursive function to evaluate :


f(x)=x-(x3/3!)+(x5/5!)-(x7/7!)+………

Solution : -
#include<stdio.h>

long factorial(int);

void main()
{
int x,n,t=0,c;
long fn=0;

printf("Enter value of x and no. of terms:");


scanf("%d %d",&x, &n);
c=1;
fn=x;
for(t=2;t<=n; t++)
{
C=c+2;
if(t%2!=0)
fn=fn+ (pow(x,c)/factorial(c))
else
fn=fn-(pow(x,c)/factorial(c));
}
printf("f(%d)= %ld\n",x,fn);
}

getch();
}
long factorial(int n)
{
if (n == 0) // Base case
return 1;
else
return (n*factorial(n-1));
}
2015 Spring. 6.b. What is 2-D Array? Write a program in C to read the elements of a 3X4 matrix and
find the biggest and smallest elements of the matrix.

Solution :-

The two-dimensional array can be defined as an array of arrays. The 2D array is organized as matrices which
can be represented as the collection of rows and columns. However, 2D arrays are created to implement a
relational database lookalike data structure. It provides ease of holding the bulk of data at once which can be
passed to any number of functions wherever required.

Declaration of two dimensional Array in C

The syntax to declare the 2D array is given below.

data_type array_name[rows][columns];
for ex.
int twodimen[3][4];

Here, 3 is the number of rows, and 4 is the number of columns.

Program :-

#include<stdio.h>
int main(){
int i, j, max, small;
int arr[3][4];
//Reading data elements
for(i=0;i<3;i++){
printf(“\n Enter elements of row no. %d”,i+1);

for(j=0;j<4;j++){
printf(“\n Column no %d elements value:-“, j+1);
scanf("%d", &arr[i][j]);
}//end of j
}//end of i
max=arr[0][0];
small=arr[0][0];
For(i=0; i<3;i++)
For(j=0; j<4; j++)
{
If(arr[i][j]>max)
max=arr[i][j];
If(arr[i][j]<small)
small=arr[i][j];
}
printf(“\n The biggest elements of Array is %d”, max);
printf(“\n The Smallest Element of Array is %d”,small);
getch();
}
2016 fall. 6.a Write a program to create structure for the following data for
student(RN,Name,Phone,address and semester). Read the 10 students by user and write only those
students whose semester is 1 in the file “student.txt” .

Solution :-
#include <stdio.h>
#include <conio.h>
#include<stdlib.h>
void main()
{
int n;
struct stud
{
int rn;
char name[15];
char phone[15];
char address[25];
int sem;
}rec[10];
for(n=0;n<10;n++)
{
printf(“\n Enter roll, name, phone , address and semester of student number %d :”, n+1);
scanf(“%d”,&rec[n].rn);
gets(rec[n].name);
gets(rec[n].phone);
gets(rec[n].address);
scanf(“%d”,&rec[n].sem);
}
FILE *fp;
Fp=fopen(“ student.txt”,”w”);
If(fp==NULL)
{
printf(“ \nFile I/o error”);
exit(0);
}
for(n=0;n<10;n++)
{if( rec[n].sem==1)
fprintf(“fp”,”%s %s %s”, rec[n].rn, rec[n].name, rec[n].phone, rec[n].address,rec[n].sem );
}
printf(“ \n students data record has been saved whose semester is 1”);
fclose(fp);
getch();
}
2016 Spring. 6.b. Why is file handling necessary in c- programming ? Write a program to input name,
address, faculty, program and GPA(in maximum 4.0) of 500 students and store them in “Result.dat” data
file and display the records of those students whose faculty is “Engineering” and GPA>3.5.

Solution :-

File Handling concept in C language is used to store data records permanently in computer’s storage device
like Dbms. Using this concept we can store our data in Secondary memory (Hard disk). Without file handling
C-program only can perform i/o operation including processing but can not store data in the secondary device
permanently. All files related function are available in stdio.h header file.
Program :

# include <stdio.h>
#include <conio.h>
#include<string.h>
void main()
{
int n;
struct stud
{
char name[15];
char address[25];
char faculty[15];
char program[15];
float Gpa;
}rec[500];
for(n=0;n<500;n++)
{
printf(“\n Enter name, Address ,faculty, program and GPA(<=4.0) of student number %d :”, n+1);
gets(rec[n].name);
gets(rec[n].address);
gets(rec[n].faculty);
gets(rec[n].program);
scanf(“%f”, &rec[n].GPA);
}
FILE *fp;
fp=fopen(“result.dat”,”w”);
If(fp==NULL)
{
printf(“ \nFile I/o error”);
exit(0);
}
for(n=0;n<500;n++)
{
fprintf(“fp”,” %s %s %s %s %f ”,rec[n].name,rec[n].address,rec[n].faculty,rec[n].program,rec[n].GPA);
}
printf(“ \n Students data record has been saved”);
fclose(fp);
FILE *fp;
fp=fopen(“result.dat”,”r”);
If(fp==NULL)
{
printf(“ \nFile I/o error”);
exit(0);
}
for(n=0;n<500;n++)
{
fscanf (“fp”,” %s %s %s %s
%f”,&rec[n].name,&rec[n].address,&rec[n].faculty,&rec[n].program,&rec[n].GPA);
}
printf (“\n students whose faculty is engineering and gpa>3.5 are :);
for(n=0;n<500;n++)
{
If(strcmp(rec[n].program,”Engineering”)==0 && GPA>3.5)
printf(”\n %s\t %s\t %s\t %s\t%f\n”,rec[n].name,rec[n].address,rec[n].faculty,rec[n].program,rec[n].GPA);
}
fclose(fp);
getch();
}

2017 fall. 5.a. Explain the relationship between arrays and pointers. How can a pointer variable be used
to access and modify single dimentional and multi dimensional arrays?
Solution :-In C programming, pointers and array shares a very close relationship. Array is a data structure that
holds finite sequential collection of similar type data. We use array to store a collection of similar type data
together. To access an array element we use index. These index starts from 0 and goes up to N-1 (where N is
size of the array). Array name gives address of first element of array. Array members are accessed using
pointer arithmetic. Compiler uses pointer arithmetic to access array element. Array parameters are always
passed as pointers, even when we use square brackets.

Relationship between pointers and array

Consider the below array declaration,

int arr[5];

It declares an integer array with a capacity of five elements. To access any element of the given array we use
array index notation. For example to access zeroth element we use arr[0], similarly to access fifth element we
use arr[4].

Let us transform things in the context of pointers.

int * ptr = &arr[0]; or int * ptr= arr; both are same

The above statement declares an integer pointer pointing at zeroth array element.
To access and modify single dimension array using pointer

Array elements are stored sequentially in memory. Below is the memory representation of array

int arr[] = {10, 20, 30, 40, 50};

Since array elements are stored sequentially, hence you can easily apply pointer arithmetic to iterate though
elements. We can use following pointer arithmetic operations to access and modify array elements.

int arr[5];
int * ptr = arr; // Integer pointer pointing at arr[0]

ptr[0] = 10; // Assigns 10 to arr[0]


ptr++; // ptr now points at arr[1]
ptr--; // ptr now points back at arr[0]

*(ptr + 4) = 100; // Assigns 100 to arr[4].


// Note, ptr currently pointing at arr[0] not arr[1].
// Hence (ptr + 4) will point at arr[4]
*ptr=*ptr+10; //adds 10 to arr[0]. i.e. modify the array through array.
*(arr + 0) = 10; // Assigns 10 to arr[0]

Pointer to Multidimensional Arrays

1. Pointers and two dimensional Arrays:

In a two dimensional array, we can access each element by using two subscripts, where first subscript represents
the row number and second subscript represents the column number. The elements of 2-D array can be accessed
with the help of pointer notation also. Suppose arr is a 2-D array, we can access any element arr[i][j] of the
array using the pointer expression *(*(arr + i) + j).
Pointers and Three Dimensional Arrays
In a three dimensional array we can access each element by using three subscripts. Thus the pointer
expression *(*(*(arr + i ) + j ) + k) is equivalent to the subscript expression arr[i][j][k].
We know the expression *(arr + i) is equivalent to arr[i] and the expression *(*(arr + i) + j) is equivalent
arr[i][j]. So we can say that arr[i] represents the base address of ith 2-D array and arr[i][j] represents the base
address of the jth 1-D array.
// C program to print the elements of 3-D
// array using pointer notation
#include<stdio.h>
int main()
{
int arr[2][3][2] = {
{
{5, 10},
{6, 11},
{7, 12},
},
{
{20, 30},
{21, 31},
{22, 32},
}
};
int i, j, k;
for (i = 0; i < 2; i++)
{
for (j = 0; j < 3; j++)
{
for (k = 0; k < 2; k++)
printf("%d\t", *(*(*(arr + i) + j) +k));
printf("\n");
}
}

return 0;
}

2017 fall. 5.b How do you define and use double indirection pointers, pointer to array and array of pointers?
Give examples codes.
Solution :-
Double indirection pointer :-
when we define a pointer to pointer. The first pointer is used to store the address of the variable. And the
second pointer is used to store the address of the first pointer. That is why they are also known as double
pointers(double indirection pointer).
To declare a pointer to pointer in C?
Declaring Pointer to Pointer is similar to declaring pointer in C. The difference is we have to place an additional
‘*’ before the name of pointer.
Syntax:
int **ptr; // declaring double pointers
// C program to demonstrate pointer to pointer
int main()
{
int var = 789;

// pointer for var


int *ptr2;

// double pointer for ptr2


int **ptr1;

// storing address of var in ptr2


ptr2 = &var;

// Storing address of ptr2 in ptr1


ptr1 = &ptr2;

// Displaying value of var using


// both single and double pointers
printf("Value of var = %d\n", var );
printf("Value of var using single pointer = %d\n", *ptr2 );
printf("Value of var using double pointer = %d\n", **ptr1);

return 0;
}

Pointers To Array :-
we can use a pointer to point to an array, and then we can use that pointer to access the array elements. Lets
have an example,
# include<stdio.h>
Void main()
{
int I;
int a[5]={1,2,3,4,5};
int *p=a; // same as int *p=&a[0]
for( i=0; i<5; i++)
{
printf(“%d “,*p);
p++;
}
}
In the above program, the pointer *p will print all the values stored in the array one by one. We can also use
the Base address (a in above case) to act as a pointer and print all the values.
In the above program, the pointer *p will print all the values stored in the array one by one. We can also use
the Base address (a in above case) to act as a pointer and print all the values.
Array of pointers: -

An array of pointers is an indexed set of variables, where the variables are pointers (referencing a
location in memory). An array of pointers is an indexed set of variables, where the variables
are pointers (referencing a location in memory). An array of pointers is useful for the same reason that
all arrays are useful: it allows to numerically index a large set of variables. Below is an array of pointers
in C that points each pointer in one array to an integer in another array. The value of each integer is
printed by dereferencing the pointers. In other words, this code prints the value in memory of where
the pointers point.

#include <stdio.h>
const int ARRAY_SIZE = 5;
int main ()
{
/* first, declare and set an array of five integers: */
int array_of_integers[] = {5, 10, 20, 40, 80};
/* next, declare an array of five pointers-to-integers: */
int i, *array_of_pointers[ARRAY_SIZE];
for ( i = 0; i < ARRAY_SIZE; i++)
{
/* for indices 1 through 5, set a pointer to
point to a corresponding integer: */
array_of_pointers[i] = &array_of_integers[i];
}
for ( i = 0; i < ARRAY_SIZE; i++)
{
/* print the values of the integers pointed to
by the pointers: */
printf("array_of_integers[%d] = %d\n", i, *array_of_pointers[i] );
}
return 0;
}
2017 fall. 6.a How do you declare and initialize array of structure variables.
Solution: -
An array of structres in C can be defined as the collection of multiple structures variables where each
variable contains information about different entities. The array of structures in C are used to store
information about multiple entities of different data types. The array of structures is also known as the
collection of structures.

Let's see an example of an array of structures that stores information of 5 students and prints it.

#include<stdio.h>
#include <string.h>
struct student{
int rollno;
char name[10];
};
int main(){
int i;
struct student st[5]; //st[5] is declared as array of structure variable having 5 index
printf("Enter Records of 5 students");
for(i=0;i<5;i++){
printf("\nEnter Rollno:"); //this block initializing or assigning the structure elements through array of structure
variable
scanf("%d",&st[i].rollno);
printf("\nEnter Name:");
scanf("%s",&st[i].name);
}
printf("\nStudent Information List:");
for(i=0;i<5;i++){
printf("\nRollno:%d, Name:%s",st[i].rollno,st[i].name);
}
return 0;
}
2017 fall. 6.b. Write a program to create a file “hello.txt”. Write data into the file and finally read the data from
the file.
Solution: -
#include <stdio.h>
Void main(){
char buff[255];//creating char array to store data of file
FILE *fp;
fp = fopen("hello.txt", "w");//opening file for writing data
fprintf(fp, "Hello file by fprintf...\n");//writing data into file
fclose(fp);//closing file
fp = fopen("file.txt", "r");// opening file for reading data and displaying
while(fscanf(fp, "%s", buff)!=EOF){
printf("%s ", buff );
}
2017 Spring. 4.b Write a program to find sum of 5 numbers supplied by user
using DMA.

Solution : -

#include<stdio.h>
#include<stdlib.h>

int main()
{
int *ptr; //declaration of integer pointer
int limit=5; //to store array limit (5 integer numbers)
int i; //loop counter
int sum; //to store sum of all elements

//printf("Enter limit of the array: ");


//scanf("%d",&limit);

//declare memory dynamically


ptr=(int*)malloc(limit*sizeof(int));

//read array elements


for(i=0;i<limit;i++)
{
printf("Enter element %02d: ",i+1);
scanf("%d",(ptr+i));
}

//print array elements


printf("\nEntered array elements are:\n");
for(i=0;i<limit;i++)
{
printf("%d\n",*(ptr+i));
}

//calculate sum of all elements


sum=0;//assign 0 to replace garbage value
for(i=0;i<limit;i++)
{
sum+=*(ptr+i);
}
printf("Sum of array elements is: %d\n",sum);

//free memory
free(ptr); //hey, don't forget to free dynamically allocated memory.

return 0;
}
2017 spring 6.b. Write a program to generate all prime numbers from 1 to 200
Solution : -

#include<stdio.h>
void main()
{
int n,i,fact,j;
printf("Enter the last Number upto which prime numbers to display: ");
scanf("%d",&n);
printf("Prime Numbers are: \n");
for(i=1; i<=n; i++)
{
fact=0;
for(j=1; j<=n; j++)
{
if(i%j==0)
fact++;
}
if(fact==2)
printf("%d " ,i);
}
getch();
}

2018 fall. 3.b Write a menu driven program to work following cases take appropriate input whenever
required
1. Reverse a number
2. Find sum of individual digit
3. Check for prime
4. Exit

Solution : -
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
void main()
{
int ch,n,s=0,rev=0,r,j,flag;
while(1)
{
printf(“\n\n\t\t\tMain Menu\n\n”);
printf(“\n\t 1. To Reverse number\n”);
printf(“\n\t 2. To find sum of individual digit\n”);
printf(“\n\t 3. To check the number is prime or not\n”);
printf(“\n\t\t Please type your Choice number to perform the task :…..”);
scanf(“%d”,&ch);
switch(ch)
{
case 1:
printf(“\n Enter a number to reverse it:”);
scanf(“%d”,&n);
while(n>0)
{
r=n%10;
rev=rev*10+r;
n=n/10;
}
printf(“\n Reverse number is %d”,rev);
break;
case 2:
printf(“\n Enter a number to find sum of digits : ”);
scanf(“%d”,&n);
while(n>0)
{
r=n%10;
s=s+r;
n=n/10;
}
printf(“\n sum of individual digits is %d”,s);
break;
case 3:
printf("Enter a number \n");
scanf("%d", &n);

if (n <= 1)
{
printf("%d is not a prime numbers \n", n);
exit(1);
}
flag = 0;
for (j = 2; j <= n / 2; j++)
{
if ((n % j) == 0)
{
flag = 1;
break;
}
}
if (flag == 0)
printf("%d is a prime number \n", num);
else
printf("%d is not a prime number \n", num);
break;
case 4:
exit(0);
break;
default:
printf(“\n invalid choice…..”);
getch();
}getch();
}
}

2018 Spring 3.b. Write a program to read one dimensional array, sort the numbers in ascending order
and display the sorted numbers.

Solution : -
#include <stdio.h>
#define MAX 100
int main()
{
int arr[MAX],n,i,j;
int temp;

printf("Enter total number of elements: ");


scanf("%d",&n);

//read array elements


printf("Enter array elements:\n");
for(i=0;i< n;i++)
{
printf("Enter element %d: ",i+1);
scanf("%d",&arr[i]);
}

//sort array
for(i=0;i< n;i++)
{
for(j=i+1;j< n;j++)
{
if(arr[i]>arr[j])
{
temp =arr[i];
arr[i] =arr[j];
arr[j] =temp;
}
}
}

printf("\nArray elements after sorting:\n");


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

2018 spring 6.b What is significance of file pointer in file handling? Consider the following
Rollno name Address faculty Date of birth(mm dd yy)
Write a program to create “student.txt” file to store the above records for 100 students . Also display
those records of students who are not from kathmandu.

Solution : -

A file pointer is a pointer to a structure, which contains information about the file, including its name, current
position of the file, whether the file is being read or written, and whether errors or end of the file have
occurred. The user does not need to Know the details, because the definitions obtained from stdio.h include a
structure declaration called FILE. The only declaration needed for a file pointer is symbolized by

2. FILE *fp;
This says that fp is the file pointer that points to a FILE structure that establishes the buffer area in RAM and fp
is a pointer variable that indicates the beginning of the buffer area.

Opening a file:
The fopen() function opens a stream for use and links a file with that stream. A file pointer associated with
that file is then returned by the fopen() function. Most often the file is a disk file. The prototype for the
fopen() function is

3. FILE *fopen(const char* filename, const char *mode);


4. Where filename is a pointer to a string of characters that make up a valid file name and can also include a
path specification. Another parameter is a pointer to a string, name mode, determines how the file can be
opened.

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

void main()
{
int n;
struct date{
int yy,mm,dd;
}
struct stud
{
int rollno;
char name[15];
char address[25];
char faculty[15];
date dob;
}rec[100];
for(n=0;n<100;n++)
{
printf(“\n Enter rollno, name, Address ,faculty, and birth date in mm/dd/yy of student number %d :”, n+1);
scanf(“%d”,&rec[n].rollno);
gets(rec[n].name);
gets(rec[n].address);
gets(rec[n].faculty);
scanf(“%d %d %d”,&rec[n].dob.mm,&rec[n].dob.dd,&rec[n].dob.yy);
}
FILE *fp;
fp=fopen(“student.txt”,”w”);
If(fp==NULL)
{
printf(“ \nFile I/o error”);
exit(0);
}
for(n=0;n<100;n++)
{
fprintf(“fp”,”%d %s %s %s %d %d
%d”,rec[n].rollno,rec[n].name,rec[n].address,rec[n].faculty,rec[n].date.mm,rec[n].dd,rec[n].date.yy);
}
printf(“ \n 100 Students data record has been saved”);
fclose(fp);
FILE *fp;
fp=fopen(“student.txt”,”r”);
If(fp==NULL)
{
printf(“ \nFile I/o error”);
exit(0);
}
for(n=0;n<100;n++)
{
fscanf (“fp”,”%d %s %s %s %d %d
%d”,&rec[n].rollno,&rec[n].name,&rec[n].address,&rec[n].faculty,&rec[n].date.mm,&rec[n].dd,&rec[n].date.y
y);
}
printf (“\n students who are not living in Pokhra are :);
for(n=0;n<100;n++)
{
If(strcmp(rec[n].address,”pokhra”)!=0)
printf(”\n%d\t %s\t %s\t %s\t %d/ %d/
%d\n”,rec[n].rollno,rec[n].name,rec[n].address,rec[n].faculty,rec[n].date.mm,rec[n].dd,rec[n].date.yy);
}
fclose(fp);
getch();
}

You might also like