C Praogramming
C Praogramming
Idea of Algorithm:
Representation of Algorithm
Flowchart, Pseudo code with examples
From algorithms to programs, Source code.
Programming Basics:
Structure of C program
Writing and executing the first C program.
Syntax and logical errors in compilation, Object and executable code.
Components of C language. Standard I/O in C.
Fundamental data types, Variables and Memory locations.
Storage classes.
Short Questions & Answers
Q1. What are the various functions of an Operating System?
Ans: (i) Process Management (ii) Memory Management (iii) CPU Scheduling
(iv) I/O Management (v) Network Management. (vi) Security management.
Q3.What is the difference between low level language and high level language?
Ans: Low level language is machine language in form of 0 and 1 or Assembly language in Mnemonics
(e.g : ADD , SUB ,DIV, STR, LOAD)which can be understand by computer hardware. It is very
difficult to understand by the user. Each type of CPU has its own machine language depending
on the hardware.
High level language is those which are used by programmers to create computer instructions, coding
the programs and to develop the software’s. These are closer to human languages and are combination of
natural language like English & some mathematical expressions and Language Syntax and rules. These are
easier to understand, write and maintain as compared to low level languages. Example: Ada, Pascal,
FORTRAN, C, C++, Java, C #, COBOL.
Ans : Software is basically a collection of programs , where as programs are set of instructions which are
stored electronically in computer system. Example : Adobe photo shop, railway reservation software, anti virus
software, gaming softwares, operating system.
Ans: In computer programming, a data type is a classification identifying one of various types of data, such as
floating-point, integer, or Boolean, that determines the possible values for that type; the operations that can be
done on that type; and the way the values of that type are stored.
(a) Integer : In more common parlance, whole number; a number that has no fractional part.
e.g : 23, 678, -18 etc.
(b) Floating-point : A number with a decimal point. For example, 3 is an integer, but 3.5 is a floating-
point number. Another representation of floating point constant is 3.5 x 10-3 . Here 3.5 is a mantissa
and 10-3 is exponent.
(c) Character (text): Readable text . E.g : A, b , Z, c , d.
Ans : (i) Speed : Computers can perform millions of operations per second. Speed is given in nanoseconds
and pico seconds.
(ii) Accuracy: A computer is very fast , reliable, and robust electronic device. It always gives accurate
results, provided set of instructions are correct data and set of instructions to it.
(i) Automation : These are used to automate any type of mechanical devices , or day to day
problems.
(ii) Versatile : Computer systems are flexible towards the changing technology, hardware and
softwares. They also can be used as personal computers, for scientific purpose, fr weather
forecasting , for military operations and business analysis too.
(iv) Memory : Like human beings computers can also store large set of information and data
Fetched from real world . Memory is used to store information. Primary and secondary
memory are designed inside the system.
Ques 11. What are tokens in C programming language? Describe with examples.Ans: In C programming
tokens are defined as the smallest unit of a program which is indivisible. Program is combination of these C
tokens. There are following six types of token categories :
(i) Keywords: These are set of fixed or reserved words that can not be used as an identifier or variable.
E.g: printf, scanf, gets, stdio, clrscr, int , float , char, signed, break, for , while etc.
(ii) Identifiers: These are used to identify the data and other objects in a program. These are names
given to variables, array, functions consisting of alphabets, numerals and underscore.
Identifiers never start with a number. E.g : a , ab, akash_cse, ab123.
(iii) Constants : Those data objects which are fixed and values can’t be changed.
E.g : Integer constant : 1 , 34, 257, -675 etc.
Floating constant : 0.02, 3.145159, 2.14E-3 etc.
Char constant : A single character inclosed in a single quotes. E.g : ‘a’, ‘&’, ‘x’ etc. In
computer characters are stored using machine’s character sets in ASCII form.
(iv) String constants : Sequence of characters stored within double quotes. E.g : “abc”, “ xy67”,
“computer” etc.
(v) Special characters : @ , $ , &, !, }, % etc.
(vi) Operators : this is a symbol that specifies the mathematical, logical, or relational operation to be
performed .e.g : = , -, &&, /, =, = = etc.
Ques 12. What is an algorithm? What is its purpose? Mention the characteristics of algorithm. Write an
algorithm to print the first 10 natural numbers. Also draw its flow chart.
Ans : Algorithm is a formally defined procedure for performing calculation. If a procedure is formally defined
then it must be represented in a formal way i.e programming language. The algorithm gives step by step
solution to reach some goal of a problem or to find a solution of existing problem. Purpose of algorithms is to
implement re-usability in software applications. Once we have designed the overview of solution to any
problem in algorithmic form it can be coded in any language like C , C++,Java etc.
Psuedo Code : Algorithms can be represented in the fofm of pseudo code and flow chart both. Psuedo code is
the way to write any algorithm using some formal notations of mathematics, programming syntax and English
words step by step.
(i) Sequence : Each step of algorithm is executes in specific order one after another.
(ii) Decision : When the output of a process depends on certain decision criterion, then Decision
statements are used. E.g : if x = y, then print “ EQUAL”. Decision statements may either evaluate to
TRUE or FALSE.
(iii) Repetition: This involves execution of one or more steps for a number of times repeatedly.
Programming constructs such as while, do-while and for loops are used.
Algorithm to Print the First N natural numbers
(i) Input : This is the process of entering data and instructions /programs into the computer system
with the help of input devices (e.g : Keyboard, Mouse, Microphone etc.)Input device converts the
input data into binary code ( 0 or 1) for further processing.
(ii) Storage : Storage is the process of saving and storing the data and information in computer
memory. It also stores intermediate results.
(a) Primary Storage : This is aslo called main memory, which is directly accessible by the CPU
at very high speeds.It is used to store the data and parts of programs, the intermediate resultsof
processing and current job results.
Primary memeory is volatile in nature i.e. as sson as computer is switched off, data is
erased/lost from the memory. It is also expensive E.g : RAM(random access Memory)
(b) Secondary storage : Also known as auxiliary memory. This is non-volatile memory
And data is permanently stored in this. E.g : magnetic Disks, CD ,DVD, Hard Disk,
Pen Drives, Memory Cards etc.
Central Processing Unit (CPU) : This is also called processor which is chip inside the
Cabinet of computer system . It is referred as the brain of computer. It carries out instructions of a computer
program by performing basic arithmetic , logical , control and I/O operations specified by instruction. Speed of
CPU is measured in Giga Hertz (Ghz).
(iii) Control Unit : A control unit handles all the processor signals. It directs all the input and output
flow, fetches instructions from microprograms and directs it to other units of computer by timing
and control signals.Control unit takes care about correct execution of instructions.
(iv) ALU : Arithmetic and logic unit is used to perform arithmetic opeartions and logical operations.
Arithmetic operations include adition , subtraction, division, multiplication , trignometrical
operation (like Sin, Cos etc)
Logical operations consists of Boolean operations that predict either TRUE/1 or FALSE/0.
Example : logical AND, NOT, XOR, OR etc.
(v) Output : This consists of operation that provides the result regarding certain input
And sends data from computer to another device provided in the system.
O/P peripheral devices are printers, speakers, monitors, projectors, headphones etc.
Each sub system is then refined into more primary and smaller sub systems. This is called modularization.
Modularization makes the program to understand , write and debug.
Structured Programming : This implements logical structure on the program to be written. Thus
program becomes more efficient, simple and easy. This allows program loaded into memory and to be reused
.Modules are coded separately and tested. After that all the modules are combined together to make larger sub
system. Language like C , Pascal support structured programming. Each module has its own local data
and performs specific task.
Syntax and logical errors : When compiler compiles the program then due certain wrong inputs and wrong
codes errors occur. Syntax Error occurs when code or program has grammatical mistakes due to mistyping.
Like missing parenthesis, not using ; etc.Syntax error leads to no output.
Logical Error are those which give the output which is not required for certain inputs due to wrong
interpretation of algorithm and logic in code.
Loader : This is an Operating system utility that copies programs from a storage A storage device to main
memory, where they can be executed.
Absolute Loader : Loads the object program from translation time address and transfers control to it.
Bootstrap loader : This loader is responsible for loading the OS when system is turned ON and transferring
control to it. It is present in ROM area of main memory.
Linker : Also called link editor / binder. It is a program that combines object modules to form an executable
program. This simplifies the designing of large softwares because they can be divided into smaller modules
and afterwards can be combined using linker.
Ques 16. What is the structure of C program ? What are header files and their uses. Explain formatted
input output functions.
2) Preprocessor directive
3) Global variable declaration
4) main function( )
{
Local variables;
Statements;
}
User defined function
}
}
Comment line
It indicates the purpose of the program. It is represented as
/*……………………………..*/
Comment line is used for increasing the readability of the program. It is useful in explaining the program and
generally used for documentation. It is enclosed withi the decimeters. Comment line can be single or multiple
line but should not be nested. It can be anywhere in the program except inside string constant & character
constant.
Preprocessor Directive:
#include<stdio.h> tells the compiler to include information about the standard input/output library. It is also
used in symbolic constant such as #define PI 3.14(value). The stdio.h (standard input output header file)
contains definition &declaration of system defined function such as printf( ), scanf( ) etc. Generally printf()
function used to display and scanf() function used to read value
Global Declaration:
This is the section where variable are declared globally so that it can be access by all the functions used in the
program. And it is generally declared outside the function.
main()
It is the user defined function and every function has one main() function from where actually program is
started and it is encloses within the pair of curly braces. The main( ) function can be anywhere in the program
Header Files : When we work with large projects, it is desirable to separate out some procedures from main()
function of the program. Some procedures need to be used several times in different programs. So one solution
is to copy the code of that procedure from one program to another several times , which results in waste of
time.
So another solution is to make procedures and store them in a different file called header files. System defined
Header files contain the definitions of Library functions like printf(), scanf(), getch() , puts(), pow(), clrscr()
etc.Conventionally , header files ends with a ‘ . h’ extension and names can use only letters, digits, dashes ,
and underscores. Header files can be system define in compiler it self or programmers can design their own
header files too.
Examples : stdio.h : standard input & output ( functions like printf() ,scanf() are defined.)
conio.h : console input & output. ( getch(), clrscr () are defined.)
string.h : for string handling functions. ( )
math.h : Math functions like pow(), sin(), log() , sqrt() are defined.
stdlib.h : Library functions like exit (),
Foramtted Input & output functions : C language supports two formatting functions
printf () and scanf (). Printf() is used to convert text data stored in the program onto text stream for
o/p to the monitor. Scanf is used to convert text stream coming from keyboard to data values and stores
them in program variables. These are called as formatted Input and output functions because they have
special format to read and write The text from streams and then converting them into binary stream.
Ques 17. What are storage classes? Explain their types briefly.
Ans : Storage class in C decides the part of storage to allocate memory for a variable.
It also determines the scope of a variable. All variables defined in a C program get some
physical location in memory where variable's value is stored.
Memory and CPU registers are types of memory locations where a variable's value can be
stored.
The storage class of a variable in C determines the life time of the variable if this is 'global' or
'local'.
Along with the life time of a variable, storage class also determines variable's storage location
(memory or registers), the scope (visibility level) of the variable, and the initial value of the
variable.
There are four storage classes in C those are automatic, register, static,
and external.
(i) Automatic Storage Class:
This is the default storage class for all the variables declared inside a function or a
block.
Auto variables can be only accessed within the block/function they have been
declared and not outside them (which defines their scope).
They are assigned a garbage value by default whenever they are declared.
Variables having automatic storage class are local to the block which they are
defined in, and get destroyed on exit from the block.
#include <stdio.h> }
int main( ) printf ( "%d ", i);
{ }
auto int i = 1; printf( "%d\n", i);
{ }
auto int i = 2;
{ OUTPUT
auto int i = 3; ======
321
printf ( "\n%d ", i);
(ii) Register Storage Class:
The register specifier declares a variable of register storage class.
Variables belonging to register storage class are local to the block in which they
are defined.
Variables are placed in CPU registers, not in memory.
Register variables are also given no initial value by the compiler.
(iii) Static Storage Class:
The static specifier gives the declared variable static storage class.
Static variables are not visible outside their function or file, but they maintain
their values between calls.
Static variables can be used within function or file.
Static variables have default initial value zero and initialized only once in
their lifetime.
When we use extern specifier the variable cannot be initialized because with extern specifier variable is
declared, not defined. #include <stdio.h>
extern int x;
int main()
{
printf("x: %d\n", x);
}
int x = 10;
UNIT-2
Module – 2 : (Arithmetic expressions & Conditional Branching)
Arithmetic expressions and precedence
Operators and expression using numeric and relational operators
Mixed operands, Type conversion
Logical operators, Bit operations
Assignment operator, Operator precedence and associativity.
Conditional Branching:
Applying if and switch statements
Nesting if and else
Use of break and default with switch.
Short Question & Answers
Ques 1 What are C expressions? Give examples.
Ans : An expression is a combination of variables, constants, operators and function call. It can be
arithmetic, logical and relational for example:-
int z = x+y
// arithmatic expression
a>b // relational
a= =b // logical
func(a, b) // function call
Expressions consisting entirely of constant values are called constant expressions. But if i were declared
to be an integer variable, the expression 180 + 2 – j would not represent a constant expression.
Ques : 2 Define the term C operator. Explain Arithmetic and Logical Operators.
Ans: An operator is a symbol which helps the user to command the computer to do a certain mathematical
or logical manipulations. Operators are used in C language program to operate on data and variables.
All the basic arithmetic operations can be carried out in C. Example : +, -, %, / , *, &&, etc.Both unary
and binary operations are available in C language. Unary operators operate on a single operand, where
operand can be a constant, a variable or a valid C expression. Binary operators operate on two operands.
Ternary operators operate on three operands.
Unary Operators: +a (unary plus), -a (unary minus), ++a (pre increment) , !a(logical NOT).
Ans: = (assignment operator) in C language is used to assign the value of right-hand side
value/variable/expression to the left hand side variable .e.g: a = 4; here constant 4 at R.H.S is called r-
value and identifier a at the L.H.S is called l-value
= = ( Equality Operator )in C language is used to check the value of left hand variable/expression with
the right hand Variable/expression. Whether the two values are equal or not. It returns true if these are
equal else it will return false.
e.g. (2==3) : It means whether 2 is equal to 3 or not which is false so output is 0.
(3==3) : It mean 3 is equal to 3 ,which is true so output is 1
Ques 6. What is the difference between the pre-increment operator and the post-increment
Operator? Give example also.
Ans. (i) The pre-increment operator increases the operand's value by 1 first, and then returns the modified
Value.
(iv) The post-increment operator stores a copy of the operand value in a temporary Location and then
increases the operand value by 1. For example given x = 1, the ++x expression returns 2, while the
x++ expression returns1.
EXAMPLE: What is the output of the following C code?
main()
{ int i =5 , ;
printf ( “ %d %d %d %d %d ” , i++ , i-- , ++i , --i , i ) ;
}
Ans: 4 5 5 4 5
Ques 9. What will be the value of x when the following segment is executed?
int x=10, y=15;
x=(x<y) ? (y+x) : (y-x) ;
Ans. Output – 25
2)
(ii) Shift operator shift the bits either to left or right. The syntax of shift operation can be given as:
Operand op num , Where the bits in operand are shifted left or right depending on the operator
( left if operator is << and right if operator is >>) = 00011101
X << 1 produces 00111010
Shifting once to the left multiplies the number by 2. Hence multiple shifts of 1 to the left result in
multiplying by 2 several times. If x = 0001 1101 then x >>4 produces 0000 0001. Shifting from right by
1 bit divides the number by 2.
Ques 13. What is meant by type conversion and type casting? Why it is necessary? Explain about
implicit and explicit type conversion with examples.
Ans : When any C expression or statement involves different data types e.g : multiplication of a float
number by integer number , then to get the correct result in terms of values Type conversion / Type
casting is required in programming. In this we change a variable of one data type to variable of another
data type.
2)
** When a char type is operated with an int type char is promoted to int.
** When a float type data is operated with an int , then int is promoted to float.
** When any operand is double then another operand is also converted to double
(e) Type casting : It is also called as forced conversion. It is done when value of higher data type is to
be converted to lower data type. This conversion is under programmer’s control , not in compiler’s
control.
Demotion : float f = 3.5 ;
int I ;
I=f;
Statement I = f results in f to be demoted to type int , i.e. the fractional part of f will be lost and I will
contain 3 not 3.5 ; this is called down conversion/demotion. But result is not correct so explicit type
2)
casting is required. Explicit type casting is done by placing the target data type in parantheses
followed by the variable name that has to be converted.
Variable 2 = (data type) variable1
e.g : float salary = 10000.00 ;
int tot_sal =0;
sal = (int ) salary
** When floating point numbers are converted to integers , the digits after decimal are truncated.
Ques 14. What is conditional branching statement ? Explain switch case statements in detail , with
a proper example.
Ans : The conditional branching statements help to jump from one part of the program to another
depending whether a particular condition is true or false. These decision control statements include :
(vi) if statement (ii) if – else statement (iii) if – else-if statement (iv) switch statement.
A switch case statement is a multi-way decision statement that is simplified version of if – else block.
Staement blocks refer to statements lists that may contain zero or more statements. These statements ar
not enclosed within opening and closing braces.
Switch statements are mostly used in following situations :
• When there is only one variable to evaluate in the expression.
• When many conditions are being tested for.
• Switch case is preferable over if –else if many conditions are to be tested.
Statement block N ;
Break ; Switch case compares the value of integer
Default : expression/variable with the value of each case
Statement block D ; statement that comes in that case.If value of switch
Break ; expression and case number matches then that statement
} block is executed.
Statement x ;
Default Case : When switch expression does not
matches with any case value , then statements in default
case are executed. ( default case is optional).
Use of break in switch case : The break statement must be used after each case statement in ideal
conditions. If it is not used then the case which is matched and all the cases following that case are
executed resulting in logical error or incorrect output.
Some Rules of Switch – Case statements
• Control expression inside switch must be integer type variable or integeral expression
E.g : switch ( int n) , switch ( int x + 6) etc.
• Each case label should be followed by a constant or a constant expression.
• Every case label must have unique constant expression value.
• Case labels must end with a colon.
• Default label can be placed anywhere in switch block. There must be only one default in
switch program.
• case labels should not be logical or relational expressions.
• Order in which case labels are written are not fixed.
Example 1 of switch case with break Example 2 of switch case without break
# include <stdio.h>
# include <conio.h> # include <stdio.h>
Void main() Int main()
{ {
char grade = ‘C Int option =1;
‘switch (grade) Switch (option)
{ {
Case ‘O ’ : Case 1 : printf (“ I am in case 1\n”) ;
Printf ( “ \n Outstanding ”) ; Case 2 : printf ( “ I am in case 2\n”) ;
2)
Ques 15. What is the meaning of statement in C language. Briefly explain its classification withexample.
Ans : A statement is the smallest logical unit that can independently exist in a C program. No entity
smaller than statement (i.e variables, expressions, constants etc ) can exist independently in a program.
Example : a= b + 5 is an expression , but when it is terminated by a semicolon , like a = b + 2 ; then it
becomes a assignment statement. It can be also called arithmetic statement , because operator + is also
associated here.
Classification of C statements : (a) Based upon the type of action they perform.
(iv) Based upon the number of constituent statements.
(v) Based upon their role.
Executable statements: These represent the instructions that are to be performed when the code is
executed. Executable statement appears only inside the function body. Example : looping
statement, branching statements, assignment statements .
Important Programs
1. Program to find the simple interest, given 2. Ramesh’s basic salary is input through the
principle, rate of interest and time. keyboard. His dearness allowance is 40% of
basic salary, and house rent allowance is
20% of basic salary. Write a program to
calculate his Gross Salary.
3. Program to find the area of a circle, given 4. Program to find the area of a triangle,
the radius. given three sides a, b and c.
5. Program to swap the values of two variables 6. Program to multiply a given number with
without using third variable. 2n ,without using multiplication operator.
#include<stdio.h> #include<stdio.h>
#include<conio.h> #include<conio.h>
void main() void main()
{ {
int a , b ;
int num , n , result ;
clrscr() ;
clrscr() ;
printf(“Enter the values of a and b \n”) ;
printf(“Enter the number to be
scanf(“%d %d” ,&a , &b) ;
printf(“Values variables before swapping multiplied \n”) ;
are a=%d \t b=%d: \n”, a , b) ; scanf(“%d” ,&num) ;
a=a+b; printf(“Enter the value of n \t”) ;
b=a–b; scanf(“%d”, &n) ;
a= a–b; result = num << n ;
printf(“Values of a and b after swapping printf(“Result of multiplication = %d”,
are:\n”) ; result);
printf(“a=%d\t\t b=%d”,a ,b) ; getch() ;
getch(); }
}
2)
7. Program for finding the sum of a five digit no. 8. . Write a C program to check whether a
given integer is odd or even.
9. Write a C program to find the largest of three 10. Program to determine whether a triangle is
numbers. right angle , scalene, equilateral or isosceles
where the Sides a , b and c are entered by the
user. Also check whether the triangle is possible
or not?
UNIT-3
Iteration and loops:
Use of while, do while and for loops
Multiple for loop variables
Use of break and continue statements.
Functions:
Introduction, types of functions
Functions with array
Passing parameters to functions
Call by value and Call by reference
Recursive functions
Programming for Problem Solving(UNIT -
Ques 1: Can we use continue statement within the body of switch statement like break?
Ans: No,a continue can appear only in or as a loop body. A switch statement is a branching statement is a
branching statement and not a looping statement .
Ans :
Ans: By definition, the while statement does not end with a semicolon. However, it's legal in C to put a
Semicolon right after the while statement like this: while (expression); which means there is a null
Statement controlled by the while statement. Remember that the result will be quite different from what
you expect if you accidentally put a semicolon at the end of the while statement.
Programming for Problem Solving(UNIT -
Ques 4. Write a program to generate even number series from 1 to 50 , using while loop.
Ques 5. For every use of a for loop, we can implement an equivalent while loop. So when should
we prefer to use these in different programs?
Ans: A while loop is preferred over a for loop when the number of iterations to be performed is not known
in advance. The termination of the while loop is based on the occurrence of some particular condition, i.e
specific sentinel value. Whereas the for loop is preferred when no. of iterations to performed are known
beforehand .
Output : 1 2 3 4 5 6 7 8 9 10
Ans: OUTPUT: 1 1 , 1 3, 2 1 , 33
Programming for Problem Solving(UNIT -
Ques 9. What do you mean by iteration? Explain entry and exit controlled loops with example. Givethe
classification of loops also.
Ans : The versatility of the computer lies in its ability to perform a set of instructions repeatedly. Some
specified portion of code is repeated n times , till a particular condition is satisfied. This repetitive operation
is done through a loop control instruction.
A program loop is the combination of body of the loop and a control statement. Control statement tests
certain conditions and then directs the repeated execution of the statements contained in the body of the
loop.
Depending on the position of control statement inside the loop. Two types of control structures are defined
(a) Entry controlled loop (b) Exit controlled loop.
In Entry controlled loop pre testing is done. In exit controlled loop post testing is done.
Types of loop statements in C language are : (i) while loop (ii) do while loop (iii) for loop.
Classification of Loops : Based on the nature of control variable and the kind of value assigned to it for
testing the control expression, the loops may be classified as :
Ques10. How is for loop executed? Give its syntax and example. What are additional features
of for loop?
Ans : for loop is a entry controlled loop. It provides a most concise structure in program as
compared to while loop and do while- loop. It is used when number of iterations are known before
hand in the program.
(i) After execution the control is transferred back to the for statement after evaluating the last
statement in the loop.
(j) Now control variable is updated again, and test test condition is checked for true/false.
(k) If test condition is true body of loop is executed again , otherwise exit from the loop occurs.
(i) Multiple Initialization: In this more than one variable can be initialized at a time in the for
statement. E.g : p = 1;
for ( n = 0 ; n < 17 ; n++), in this loop we can reconstruct as follows:
Ques 10. (a) Explain break and continue statement with examples.
(b) What are the properties of nested loops?
Syntax of break with while loop Syntax of break with for loop
while (test condition) for( ……)
{ {
…….. ……..
……… ………
if( condition) if( condition)
break ; break ;
……. …….
…….. ……..
} }
Transfers control out of the loop while. Transfers control out of the for loop.
Example : Example :
# include<stdio.h> # include <stdio.h>
void main() void main()
{ {
int i=1; int i=1;
while( i<=10) for ( ; ;)
{ {
if(i= = 5) printf ( “ \n %d ” , i);
break; if( i= = 5)
printf( “ \n %d ” , i); break;
++i;
} }
} }
(vi)Continue statement :
(a) This keyword is used inside the loop body
(b) When compiler encounters a continue statement, then rest of the statements in loop areskipped and
control is unconditionally transferred to the start statement of the loop.
(c) When it is present inside the nested loop, it only terminates current iteration of the nearestenclosing
loop.
(d) There is no limitation on the number of continue statements that can be present inside the loop
Programming for Problem Solving(UNIT -
Syntax of continue with while loop Syntax of continue with for loop
while (test condition) for( ……)
{ {
…….. ……..
……… ………
if( condition) if( condition)
continue ; continue ;
……. …….
…….. ……..
}an be udes to control }
Transfers control out of the loop while. Transfers control out of the for loop.
Example : Example:
# include<stdio.h> # include<stdio.h>
void main() void main()
{ {
int i=1; int i;
while( i<=10) for ( i=1; i<=10 ; i++)
{ {
if(i%2 = = 0) if(i%2 = = 0)
continue ; continue;
printf( “ \n %d ” , i); printf( “ \t %d ” , i);
++i;
} }
} }
Output : 1 3 57 9
Nested Loops :. Another outer loop is used to control the number of times that a whole loop is repeated. Loops that
can be placed inside other loop. This feature can work with any loop but it is mostly useful in for loop because of
Example : void main() Output :
{ 1 1
int i,j; 1 3
for(i=1; i<3; i++) 2 1
for(i=1; j<4; j++) 2 3
{
if(j= = 2 ) continue ;
printf ( “ %d %d \n” , i,j ) ;
}}
simplicity of for loops. A for loop can be used to control the number of times that a particular set of statements will be
execute . Indentation of nested loops should be proper. Loops can be nested to any level .
1. Write a C program to find the factorial of a 2. Program to generate the table of any number
given number. using loop
#include<stdio.h>
#include<conio.h> #include<conio.h>
#include <stdio.h> void main()
void main() {
{ int t , num , t ;
long int i,fact=1,num; clrscr() ;
clrscr() ; printf (“Enter the number whose table is to be
printf("Enter the number\n"); generated : \n” ) ;
scanf("%ld",&num); scanf(“%d”, & num ) ;
if( num <= 0) printf ( “ Table of %d is :” , num) ;
fact = 1; for ( i=1 ; i<= 10 ; i++ )
else {
{ t = num * i ;
for(i = 1; i <= num; i++) printf( “\n %d x %d = %d ” , num , i , t ) ;
{ fact = fact * i ;} }
} /* End of else */ getch () ;
printf("Factorial of %ld =%ld\n", num, fact ); }
} \* End of main() *\
Programming for Problem Solving(UNIT -
#include <stdio.h> .
#include <conio.h> #include <stdio.h>
void main() #include <stdio.h>
{ void main()
{
int i, num; int fib1=0, fib2=1, fib3, limit, count=0;
int flag = 1; printf("Enter the limit to generate the
clrscr(); fibonacci sequence\n");
printf(“ Enter the number”) ; scanf("%d", &limit);
scanf(“ %d” , & num) ; printf("Fibonacci sequence is ...\n");
for( i = 2; i< num; i++) printf("%d",fib1);
{ printf("%d",fib2);
if((num % i) = = 0) count = 2; /* fib1 and fib2 are already used */
{ while( count < limit)
prime = 0; {
} fib3 = fib1 + fib2; count ++ ;
} printf("%d\n",fib3);
fib1 = fib2;
if (prime = = 1) fib2 = fib3;
printf("%d is prime number.", num); }
else getch();
printf("%d is not a prime number.", num); } /* End of main() */
getch();
}
5. Program to accept an integer and reverse it. 6. Program to calculate the sum of the series
up to first 100 terms: 14 + 34 + 54 + 74 + … + n
terms.
#include<conio.h>
#include <stdio.h> #include<stdio.h>
void main() #include<conio.h>
{ #include<math.h>
long num, rev = 0, temp, digit; void main ()
printf("Enter the number\n"); { int n , i , sum = 0 ;
scanf("%ld", &num); clrscr();
/*For better programming, choose printf(“ENTER THE NUMBER OF
'long int' */ TERMS\n”) ;
scanf(“%d” , &n) ;
Programming for Problem Solving(UNIT -
7 .Program to generate the sum of the following 8.Printing the pattern of program
series:- sum = x + x2 / 2! + x4 / 4! + …… + x n / *
n! **
***
****
*****
#include<stdio.h>
#include<conio.h> #include<stdio.h>
#include<math.h> #include<conio.h>
void main ()
void main () {
{ int row, col;
int , x , n , , j ,fact =0, clrscr();
float sum ; for (row=1;row<=5; row++)
clrscr(); {
printf(Enter the no. whose series is to be found: ”) ; for (col=1 ; col <=row; col ++)
scanf(“%d”, &x) ; printf( “ * “);
printf(“Enter the no. of terms up to which series is printf( “\n”);
to be generated”) ; }
scanf(“%d”, &n) ; getch();
sum = x ; }
for (i=1 ; i<=n ; i++)
{
if (i%2 = = 0)
{
fact =1;
for (j=1 ; j<=i ; j++)
Programming for Problem Solving(UNIT -
{ fact = fact * j ;
}
9.Program to print the following pattern : 10. Program to print the following pattern
5 4 321 (FLOYD’S TRAINGLE) :
4 3 2 1 1
3 2 1 2 3
4 5 6
7 8 9 10
#include<stdio.h> #include<stdio.h>
#include<conio.h> #include<conio.h>
11. WAP to detect Armstrong Numbers in three 12. Program to find binary equivalent of a decimal
digits between 100 to 999. number entered by user.
# include<stdio.h> # include<stdio.h>
# include<conio.h> # include<conio.h>
void main() void main()
{ {
int d=3 , n , x=0 ; int r , n ;
int k , i , cube=0; clrscr() ;
printf ( “Enter the value of n :”) ;
clrscr(); scanf ( “ %d ” , &n) ;
printf( “ \n Following number are printf ( “ Binary number”) ;
Armstrong numbers ”) ; while ( n!=0)
for (k =100 ; k<=999 ; k++) {
{ r=n%2;
n=k ; n=n/2;
while (x<=d) printf ( “ %d ” , r ) ;
{ }
i=n %d ; getch();
cube = cube + pow (i, 3) ; }
n = n/10;
x++;
}
if(cube = = k)
printf ( “ \n \t %d ” , k) ;
}
getch();
} // End of main()
13. Program to calculate m to power n. 14. Program to add first seven terms of
#include<conio.h> following series using for loop :
#include<stdio.h> 1 / 1! + 2 / 2! + 3 / 3! +…….7 / 7!.
void main() #include<conio.h
{ int m , n , i=1; #include<stdio.h>
long int pow =1 ; void main()
clrscr(); {
printf( “ Enter two numbers : ”) ; int i=1, j ; float fact , sum = 0.0;
scanf ( “ %d %d ” , &m , &n); clrscr();
while ( i<=n) while(i<=7)
{ {
pow = pow * m ; fact = 1.0 ;
i++ ; for (j=1 ; j <=i ; j++)
} fact = fact * j;
printf ( “ \n %d to power %d = %ld ” , m , sum = sum + i/ fact; }
n, pow); printf( “ Sum of series = %f ” , sum);
Programming for Problem Solving(UNIT -
getch(); getch() ; }
}
15. WAP to find the number and their sum 16. WAP to find the average of first n natural
between 100 and 200 divisible by 7. numbers using while loop.
#include<stdio.h> #include<stdio.h>
#include<conio.h> #include<conio.h>
void main() void main()
{
{
int n , i=1, sum = 0 ;
int num , sum = 0 ; float avg = 0.0;
printf( “ Numbers divisible bt 7 b/w 100 & printf( “ Enter the value of n : ”) ;
200 are : \n ”) ; scanf( “ %d ” , &n) ;
for (num = 101 ; num < 200 ; num++) while( i <=n)
{ {
if (num % 7 = = 0 ) sum = sum + i ;
{ printf ( “ %d ” , num ) ; i++;
sum = sum + num ; }
} avg= (float) sum / n ;
} printf(“\n Sum of first %d numbers = %d “,
printf(“ Sum of all integers divisible by 7 b/w n ,sum ) ;
100 & 200 is = %d ”, sum); printf( “ \n The average of first %d numbers
getch() ; = % f ” , n , avg );
} getch() ;
}
17. Program to print the sum of odd numbers 18. WAP to find the sum of following series:
and even numbers separately from 1 to 50. √𝟏 + √𝟏 + √𝟏 +……..+ √𝟏
void main() void main()
{ {
int i; m , sumeven =0 ,sumodd=0; int c , n ;
clrscr(); float sum = 0.0 ;
for ( i = 1 ; i<=50 ;++i) printf(“ Enter the value of n : \n”) ;
{ scanf (“ %d ” , &n) ;
if ( i % 2 = = 0) for (c=1 ; c < n ; c++)
sumeven = sumeven + i; {
else sum = sum + sqrt(c ) ;
sumodd = sumodd + i; }
} printf( “ Sum of square root series = %f”,
printf( “ Sum of even numbers = %d \n”, sum ) ;
sumeven) ; getch();
printf(“ Sum of odd numbers = %d”,
sumodd); }
Programming for Problem Solving(UNIT -
getch();
#include<stdio.h>
#include<conio.h>
void main()
{
int i , n , d , rev=0 , num;
clrscr();
printf( “ Enter the number \n”) ;
scanf( “ %d ” , &num);
n= num ;
while(n >0)
{
d=num %10;
rev=rev *10 +d;
n = num/10;
}
if(rev = = num)
printf( “ \n %d is a palindrome” , num);
else
printf(“ %d is not a palindrome”, num);
getch();
}
void main() }
{
int p =1, n ; printf( “ Sum of Series = %f ”, sum) ;
float sum=0.0, term;
printf(“ Enter the value of x \n”); getch();
scanf( “ %d” , &x) ; }
printf(“Enter the power of nth term\n ”);
scanf(“ %d ”, &n);
while( p<=n)
{
sum = sum + term;
Programming for Problem Solving(UNIT -
21. WAP to check whether a given number is 22. WAP to generate the following pattern:
perfect or not ?
A
void main() A B
{ A B C
int num , sum =0 , i; ABC D
clrscr();
printf(“ Enter the number \n”) ; #include<stdio.h>
scanf(“ %d ”, &num) ; #include<conio.h>
for( i=1 ; i<num ; i++) void main()
{ {
if(num %i = = 0) char i, j ;
sum = sum + i; for ( i=65 ; i<=68 ; i++)
} {
for( j=65;j<=i; j++)
if( num = = sum) {
printf(“ %d is a perfect number”, num); printf( “ %c” , j);
else }
printf(“ %d is not a perfect number”, printf(“ \n”);
num); }
getch(); getch();
}
}
Programming for Problem Solving(UNIT -
Ans: In our c program, every program starts with main () because it tells the C compiler where the program
starts its execution. It always returns an integer value. It is a well-defined user defined function, because
In different programs the body of main() contains different code written by the programmer.
Ans:The local variables are defined within the body of the function or the block. The variable defined is
local to that function or block only. Other functions can access these variables. The compiler shows errors in
case other functions try to access the variables.
Ques 4. What is the meaning of keyword void before the name of a function?
Ans: Keyword void means that the function should not return any value.
Ques5. What is an argument? Differentiate between formal arguments and actual arguments?
Ans: An argument is an entity used to pass the data from calling function to the called function. Formal
arguments are the arguments available in the function definition. They are preceded by their own data types.
Actual arguments are available in the function call.
Ques 6. What is the purpose of return keyword while programming with functions?
Ans : When a function calculates some value , then after that control returns from a function, values
returned are collected in calling function using the keyword ‘return’. A function can return only one
value at a time. Example : Following return statements are incorrect : return (a , b) , return ( x , 12),
Programming for Problem Solving(UNIT -
Because both are trying to return two values. In case if we want to use more than one values in return
keyword syntax is : return value 1, value 2 , value 3…….value n. Here left to right evaluation is done
And the right most value is returned to calling function.
So correct statement are : return (a) , return (x).
But a function body can contain more han one return statements.
E.g : if ( x >= 5)
return (x) ;
else return ( 0) ;
Ques 7. Define exit() function with an example.
Ans : C provides a way to leave the program before it is actually terminated using exit() function.
(i)Syntax : exit(status) , where status is an int variable / constant.
(viii) This function is defined in stdlib.h
header fileExample :
# include<stdio.h>
#include<conio.h>
# include <tdlib.h>
void main()
{
printf( “ C programming is logical and interesting ”) ;
exit (0);
printf ( “ C can be easily learned”) ;
printf ( “ C is a powerful language invented by Denis Ritchie in AT & T labs Bell”);
}
Programming for Problem Solving(UNIT -
Ques 8. What are functions and their types ? What are the elements of user defined functions
, explain?
Ans : Functions break large computing tasks into smaller ones, and make the task of coders easy.
A function is a self-contained block of statements that perform a coherent task of some kind.
In C language we use many small functions rather than few big functions. Functions support
modular programming , in which a software is divided into small modules and each module consists
of several fumctions/sub modules.
In a C program, execution starts from the function main(). A function can activate some another
function. It can also call itself recursively , such functions are called recursive functions.
User Defined functions: Definition of these functions are written by the programmers itself .These
are not already defined in the library of C compiler. Advantages of user defined functions are as
follows :
6) It facilitates top down approach of modular programming.
7) Provides more structured and easy way to read and understand the large & complex codes.
8) It is easy to find faulty functions and their testing and debugging.
9) User defined functions may be used by many other programs (with the help of user defined
Header Files). So repetition of same code again and again can be avoided, which makes less
execution time and reduced code size.
Function declaration: Like variablesin C , all the functions in a C program must be declared before they
are invoked . A function declaration consists of four parts :
Function return type. E.g : int , float , char, void etc.
Function name (Follows the rules of an identifier.)
Parameter or argument list. A function can contain one or more parameters with data type of
arguments.
Termination semicolon.
Prototype definition and declaration of library functions are inside the header files.
Function Call: A function can be called by simply using the function name followed by a list of
actual parameters if any required.
• When the compiler encounters a function call, the control is transferred to the function
definition.
• This function is then executed line by line and a value is returned when return statement is
executed.
Function definition: It is the actual implementation of function, where actual logic of program
is written. A function can only be defined once but can be declared many times.
A function can be declared within the body of some other functions but cannot be defined
within the body of other function.
Programming for Problem Solving(UNIT -
Elements of Function definition: (i) Function name (ii) Function name (iii) List of parameters.
(iv) Local variable declarations (v) function statements (vi) return statements.
Example : #include <stdio.h>
#include<conio.h>
int cal_sum(int , imt , int);
void main()
{
int a , b, c , sum=0 ;
printf(“ Enter the three values :”) ;
scanf( “ %d %d %d”, &a , &b , &c);
sum=cal_sum(a,b,c) ;
printf( “\n Sum = %d ”,sum) ;
}
int cal_sum (int x , int y , int z ) ;
{
int d ;
d= x + y + z ;
return (d) ;
}
Ques 9: Explain Call by Value and Call by Reference methods of parameter passing. In support give
the example programs also.
Ans : Call by Value : In this method values of variables are passed by the calling function to the called
function. New variables are created by the called function to store values of arguments passed to it.
So called function uses a copy of the actual arguments .Changes are reflected only in the called function ,
not the calling function.
Advantage: Arguments passed can be variables (e.g x) , literals (e.g : 6 ) , or expressions (e.g x + 1).
Disadvantage: Copying data consumes additional storage. It can take lot of time to copy , so performance
of function may decrease if it is called several times .
Call by Reference : When a function wants to modify the value of the argument , then we pass arguments
using address of variables. Function parameters are declared as a reference/address. When this is done then
any changes made by the function to the arguments it receives, are visible in the calling function.
For reference an asterisk(*) is placed after the data type in parameter list.
Programming for Problem Solving(UNIT -
Advantage : Since arguments passed are not copied into new variables , it provides greater time and space
efficiency. We can return multiple values using this method.
Disadvantage : Side effect of this method is whrn an argument is passed using call by address, it becomes
difficult to tell whether that argument is meant for input , output or both.
#include<stdio.h> #include<stdio.h>
#include<conio.h> #include<conio.h>
void swap (int x , int y) ; void swap (int *x , int *y) ;
void main() void main()
{ int a , b ; { int a , b ;
clrscr(); clrscr();
printf ( “ Enter the values of two numbers \n”) ; printf ( “ Enter the values of two numbers \n”) ;
scanf( “% d %d “ , &a, &b); scanf( “% d %d “ , &a, &b);
printf( “Values of a and b before swapping : \n”); printf( “Values of a and b before swapping : \n”);
printf ( “ a= %d\t b=%d” , a ,b); printf ( “ a= %d\t b=%d” , a ,b);
swap (a , b) ; swap (a , b) ;
printf( “Values of a and b after swapping : \n”); printf( “Values of a and b after swapping : \n”);
printf ( “ a= %d\t b=%d” , a ,b); printf ( “ a= %d\t b=%d” , a ,b);
getch(); getch();
} }
void swap(int x , int y) void swap(int *x , int *y)
{ {
int t ; int t ;
t = x; t = *x;
x = y; *x = *y;
y=t; *y = t ;
printf(“ In swap function values are : \n” ); printf(“ In swap function values are : \n” );
printf( \n x = %d \t y = %d, x ,y); printf( \n x = %d \t y = %d, x ,y);
} }
Output : Output :
Enter the values of two numbers: a=10 , b=20 Enter the values of two numbers: a=10 , b=20
Values of a and b before swapping :a=10, b=20 Values of a and b before swapping :a=10, b=20
In swap function values are : x= 20, y=10 In swap function values are : x= 20, y=10
Values of a and b after swapping : a =10, b=20 Values of a and b after swapping : a =20, b=10
Programming for Problem Solving(UNIT -
Ans : A recursive function is defined as a function that calls itself again and again to solve a smaller
version of its task until a final call is made. Every recursive solution has two major cases :
Base Case : In this the problem is simple enough to be solved directly without making any furthrt
calls to the same function.
Recursive Case : In this first the given problem is divided into simpler sub parts. Then secondly ,
function calls itself but to handle sub parts of first step.
Basic steps of recursion are analyzed as follows :
• Initially Specify the base case which will terminate the function call itself.
• Check whether the current value processed matches with the value of the base case. If yes,
then process and return the value.
• Divide the problem into smaller sub parts and call the function from sub part.
• Combine the results of sub parts.
• Return the result of the entire problem.
Recursive function for adding 1 + 2 + 3 …n terms.
#include<stdio.h> getch();
#include<conio.h> }
int sum (int) ; // function prototype. int sum (int x) // function definition
void main() {
{ int a = 0 ;
int n , s ; if ( x = = 0)
clrscr(); return 0 ;
printf (“Enter the value of n terms :” ); else
scanf (%d “ , &n) ; a = x + sum(x-1) ; // recursive case.
s = sum( n) ; // function call in main() return(a);
printf (“ Sum of %d natural numbers = %d” , n,s) ; }
Iteration Recursion
1. This uses a set of statements which are This involves selection of a particular structure
repeated. in a function.
2. Repetition is applied to the loop Function calls itself again and again.
constructs.
3. Iteration terminates when loop test Recursion stops when base case is encountered
condition becomes false. in function call , within its definition.
4. Iteration requires a counter variable or a In this base case and recursive case is required.
sentinel value.
5. Less memory consumed More memory is consumed , because each time
a function calls itself , a copy of variables is
created.
#include<stdio.h> #include<stdio.h>
#include<conio.h> #include<conio.h>
int sum (int , int , int ) ; long int rec_fact(long int) ;
float avg (int , int , int ) ; void main ()
// Prototype or declaration of function {
void main() int num , fact ;
{ clrscr() ;
int a , b , c, sum=0 ; printf(“Enter the number”) ;
float av =o ; scanf (“%ld”, &num) ;
s= sum (a , b , c); // function call fact = rec_fact (num) ;
av = avg (a , b , c) ; printf(“Factorial of %ld = %ld”, num , fact) ;
scanf (“%d%d%d”, &a, &b, &c) ; getch() ;
// actual parameters }
printf (“Sum= %d\t Average = %f ” , s , av) ; // recursive definition of factorial
getch() ;
} // End of main () long int rec_fact(long int x) ;
{ int f ;
// Definition of user defined function sum () if(x = = 1 )
int sum (int x , int y , int z ) return 1; // base case
// x , y and z are formal parameters else
{ {
return (x + y + z) ; f = x * rec_fact(x-1) ; // Recursive case
} return (f) ;
/ Definition of user defined function avg () }
float avg (int x , int y , int z ) }
{
float m ;
m = (float) (x + y + z ) / 3;
return m ;
}
Programming for Problem Solving(UNIT -
3. Program to generate the Fibonacci series 4. WAP to find largest number among the
using recursive function given two numbers using a user defined
function large().
#include<stdio.h> #include<stdio.h>
#include<conio.h> #include<conio.h>
int fibo( int) ; float large (float m , float n) ;
void main () void main()
{ {
int n , f ; float x , y , max ;
clrscr() ; float large (float m , float n) ;
printf(“Enter the number upto which series is printf(“ Enter the two numbers \n”);
to be generated \n”) ; scanf( “ %f %f ” , &x , &y) ;
scanf (“%d”, &n) ; printf( “ x = %f and y = %f \n” , x , y ) ;
printf(“Fibonacci series up to %d terms is : \n max = large(x , y) ;
\n”, n ) ; printf(“ The largest number = %f \n ”, max);
}
for (int i=1 ; i< = n ; i++) ; float large (float m , float n)
{ {
f = fibo (i) ; if (m > n)
} return m ;
else
int fibo (int n) // Recursive definition return n ;
{ }
if (n = = 1)
return 0 ; // Base case
if ( n = = 2)
return 1 ;
return ( fibo(n - 1) + fibo(n - 2) ) ;
// At a time two recursive function called
so binary
}
5. WAP that accepts the length and width 6. WAP that accepts the three sides of a
of a rectangle and print the area. The triangle and print the area. The area of a
area of a rectangle is calculated by a user triangle is calculated by a user defined
defined function and returns it value to function and returns it value to main
main program where it is printed. The program where it is printed. The values
values length and width are accepted of three sides are accepted from the
from the keyboard as an integer value. keyboard as an integer value
Also draw the flow chart of program.
# include<stdio.h> # include<stdio.h>
#include<conio.h> #include<conio.h
int rect_area(int , int); #include <math.h>
void main() float tri_area(float , float, float);
{ void main()
int length , width ,area=0 ; {
clrscr() ; float s1 ,s2 ,s3, area=0.0 ;
printf(“ Enter the length and width \n ”); clrscr() ;
scanf( “ %d %d ”, length , width); printf(“ Enter the three sides of triangle \n ”);
printf(“ Length =%d width= %d \n”, scanf( “ %f %f %f”, s1 , s2, s3) ;
&length, & width) ; printf(“ side1 =%f side2= %f side3=%f \n”,
area= rect_area (length , width) ; &s1, & s2, &s3) ;
printf(“ Area of rectangle = %d ”, area); area= tri_area (s1 , s2 ,s3) ;
getch(); printf(“ Area of triangle = %f ”, area);
} getch();
int rect_area(int l , int w) }
{ float tri_area (float a , float b , float c)
return (l *w) {
} perim=0.0 , a=0.0 ;
perim = ( a + b + c) /2 ;
a= sqrt( perim * (perim-a) *(perim-b)
*(perim-c)) ;
return (a);
}
Basic Algorithms:
Searching & Basic Sorting Algorithms (Bubble, Insertion and Selection)
Finding roots of equations.
Short Questions & Answers
Ques 1. How one dimensional array are initialized? Explain.
Ans : An array elements can be initialized like an ordinary variables when declared. The general syntax is as
following : data_type array_name [size] = { list of values separated by comma};
Ques 2.What are the different ways to store the values in arrays?
Ans : (a) Initialization of array during declaration (b) Input values for the elements from the keyboard.
(c) Assign values to individual elements.
Examples: (a) Initialization of array during declaration
int marks [ 5] { 90, 65, 78, 80 , 47}; // initialization at the time of declaration.
90 65 78 80 47
[0] [1] [2] [3] [4]
When values are initialized in a 1-D array they are stored consecutively in memory, starting from index 0 to
size-1 i.e. in above example from 0 to 4 , because size of array is 5.If we declare like this :
int marks [ ] = { 2 , 4, 10}; We have not mentioned the size inside subscript operator, So compiler will
allocate space automatically equal to number of elements inside { } braces.
(c) Assigning Values to individual Elements : This can be done using assignment operator. Any value that
matches to the data type of an array can be assigned to the individual array element.
Example : marks [ 3] = 45 ; // 45 is assigned to 4th index of 1-D array.
Ques 3. Mention some invalid declarations in an array.
Ans : (a) int arr [ j] ; // j is a variable not a constant.
(b) int arr [ 4.7] ; // Size can not be a float value.
(c) int arr [ -1 ] ;
int arr [0 ] // Size must be >= 1
Initialization: data type * ptr_var = & var name 2 ;// & is known as address of operator
Example : // * is called value at address or indirection
operator
int a = 10;
int *p = &a ; // pointer variable p holds the value of variable a.
int a p
10 200
0
2000 4000
(i) 2000 is the address of variable a , and pointer p holds this address as a value. Pointer variable p has
its own address 4000. 10 is the value stored at location a.
Ques 5. WAP in C to print the values and address with the help of pointers.
Ans :
#include<stdio.h>
#include<conio.h>
Void main()
{
int x ;
int *p;
x = 10 ; p = &x ;
printf( “Value of x = %d \n” , x) ;.
printf(“ Variable x has address = %u \n” , &x ) ;
The following declaration and initialization create a string consisting of the word "Hello". To hold the null
character at the end of the array, the size of the character array containing the string is one more than the
number of characters in the word "Hello."
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
If you follow the rule of array initialization then you can write the above statement as follows:
char greeting[] = "Hello";
Following is the memory presentation of the above defined string in C/C++ −
Actually, you do not place the null character at the end of a string constant. The C compiler automatically
places the '\0' at the end of the string when it initializes the array.
Ans : Base address of an array refers to the 1st element of a 1-D array at 0th Index position. If we only write
the name of an array then also it refers to the base address.
E.g : int a [ 5] = { 1 , 4 , 7, 9 , 10 };
a[0] a[1] a[2] a[3] a[4]
90 65 78 80 47
1002 1004 1006 1008 1010
Base address
Here 1002 is the base address of array a. Since it is an integer array, so addresses of each elements will be at
the difference of 2 bytes. While displaying the elements of array, next adjacent address is automatically called
when its previous element is displayed. Using pointers we can access the individual elements.
Increment / decrement of pointers lead to increment /decrement of addresses based on the data type of
pointers.
Ans : (i) gets() :This is a library function . Definition is stored in string.h header file. This function reads the
string as gets(str) , where str is the name of character array str.It takes the starting address of an string which
will hold the input.This function does not terminates if a blank space occurs between two strings as in scanf().
(ii) puts() : The string can be displayed by writing puts(str). This function overcomes the
drawback of printf. The puts() function writes a line of output on the screen. It terminates the
line by ‘\n’ .
(iii) sprint() : This is formatted output is written to memory area rather than directly on the
output screen. Syntax is as following :
sprint( char * buffer , const char* format string [ arg 1,arg2 ….arg n] ) ;
E.g : void main()
{
char buf [100] ;
int num = 10 ;
sprint( buf , “ num = %d ” , num ) ;
}
(iv) strcmp() : This function compares the string pointed to by str1 with string pointed by str2.
Syntax strcmp( const char *str1 , const char str2) ;
Function returns zero if the strings are equal. Otherwise it returns a value less than
zero or greater than zero if str1 is less than or greater than str2 respectively.
Ans : The 2-D arrays are also known as matrix which are created in row and column form.
Syntax to declare: data_type array_name [i ] [j ] ; Where two subscripts i and j are rows and
columns of a 2-D array. Subscripts i and j must be set at compile time.
E.g : int a [ 2] [3] ; // 2-D array with 2 rows and 3 columns.
Initialization of 2-D array : int a [2] [3] = { 0, 2, 3, 10, 30, 20 } ;
Matrix can be arranged in Row major and column major forms. In Row major form firstly elements of
1st row , then 2nd row …so on are stored . In column major form 1st column , then 2nd column…son on are
stored.
0 2 3
Row major form : 10 20 30 OR int a[2] [3] = { { 0,2,3} , { 10, 20, 30}} ;
0 3 30
Column Major form : 2 10 20
While initializing a 2-D array , it is necessary to mention 2nd dimension(number of columns), whereas 1stdimension is
optional.
E.g : int arr [ ] [2] = { 12 , 34 , 23 , 45 };
Compulsory.
Optional
Ans : The concept of array is very much dependent on pointers. Elements of array occupy contiguous memory
locations depending on the data type of elements stored. Array location is a form of a pointer notation. The
name of the array is the starting/base address of an array.
Use of pointers : We can access the values of array elements using pointers as mentioned below:
(i) Expression a [ i] is equivalent to write * ( a + i ). If a is the name of array, then compiler implicitly
takes a = &a[0] . To print the value of third element of the array , we can use the expression
*( a + 2). Because a [i] = * (a + i).
Ques 12. (i) What is referencing and dereferencing in pointers. Give an example.(ii)What
are the rules for pointers and Pointer arithmetic?
Ans : Referencing in pointers : In this a pointer variable is used to refer the address of an object . use of
reference operator (& , ampersand), also called address of operator. This is a unary operator on left side of
operands. The operand should be a variable of arithmetic type or pointer type.
E.g : float f = 12.5 ;
float * fptr ;
fptr = &f ;
Dereferencing a pointer : When we want to access the value stored at a particular address in a variable ,
then we use dereferencing with the help of pointers. This operator is also known as value at address operator
, ( * , asterisk) . Operand of * operator must be a pointer type variable.. This is a unary operator.
E.g : If we write *(p) or *(&a) = value at address of variable a.
// Referencing & Dereferencing of pointers
void main()
{
int a = 12;
int *i = &a;
printf (“ Value of a is = %d \n ” , a) ;
printf ( “ Value by dereferencing a = %d \n ” , *i) ;
printf ( “ Value of a = %d \n” , *(&a))
printf ( “ Address of a = %u ” , & a) ;.
}
Rules of pointers
(a) A pointer can be assigned /initialized with the address of a variable. A pointer can’t hold a
non address value , so it can only be initialized with addresses.
(b) A pointer to a specific data type variable /object can’t point to an object of another data type.
E.g : Following is an invalid assignment :
void main()
{
int val = 10 ;
float * ptr = & val ;
printf ( “ value of variable = %d \n” , val) ;
printf ( “ Pointer ptr holds the address = %u \n ” , ptr) ;
}
(c) Increment and decrement operator can be applied to pointer variables which will change the addresses
Accordingly.
E.g : float * fptr ;
fptr = ptr ++ // post increment and initially , ptr = 2000 (address).
So address will be incremented by 4 bytes because of float data type .So fptr = 2004.But ptr will
remain 2000 because it is post increment. Similarly , If we perform ptr - - , then new address will be
1996.
(d) Subtraction: Subtraction between two pointer variables gives the difference in number of bytes ,
( subscripts of two array elements)depending on data type of variables. E,g : Consider following float
array b
Let pointer p1 = 1002 and pointer p2 = 1010. So p1 – p2 = 2 , i.e difference of two subscripts , where each
subscript element is of 4 bytes (Array is float type)). So , 4 x 2 = 8 bytes.
Subtraction of two pointers is useful only if both the pointers hold the address of variables in same array.
Ques 13. WAP in C to read and display n numbers Ques 14. WAP in C Find the smallest
Using an array. number of a 1-D array .
#include<stdio.h> #include < stdio.h>
#include<conio.h> #include <conio.h>
void main() void main()
{ {
int i=0 , n , arr [20] ; int arr [ 100 ] , min, i , n, s , pos ;
clrscr(); float avg_marks = 0.0 ;
printf ( “ Enter the number of elements : \n” ) ; clrscr() ;
scanf( “ %d ” , &n) ; printf ( “ Number of elements in array\n”) ;
printf( “ \n Enter the elements \n”) ; scanf( “ %d ” , &n) ;
for ( i=0 ; i<n ; i++) printf ( “ Enter elements of array\n”) ;
{ for( i = 0; i < n ; i++)
printf( “ \n arr [ %d] = ” , i ); {
scanf( “ %d” , &arr[ i]) ; scanf ( “ %d” , &a[ i] ) ;
} }
printf( “ \n The array elements are \n ”) ; Small = a[0] ;
Pos =0 ;
For ( i=0 ; I <n ; I ++)
for (i=1 ; i<n ; i++)
printf ( “ arr[%d] = %d \t ”, i , arr[i]) ; { If (small > a[i])
{
getch(); Small = a[ I ] ;
Pos =I ;
}
}
printf ( “ Smallest number of array is %d at
position %d \n “ , small , pos + i);
getch () ;
}
Ques 15.WAP in C to enter number of digits. Form Ques 16. WAP in C to calculate the sum and
a number using these digits. average of marks , secured by students
using array named marks[ ] .Number of
students must be read through keyboard.
#include<stdio.h> #include < stdio.h>
#include<conio.h> #include <conio.h>
#include<math.h> void main()
void main {
{ int marks[ 200 ] , i , sum = 0, studs ;
int num =0, digit [10], n , i ; float avg_marks = 0.0 ;
clrscr() ; clrscr() ;
printf( “Enter the number of digits for number \n” ) ; printf ( “ Enter the number of students \n”);
scanf ( “ %d ” , &n) ; scanf ( “ %d” , & studs) ;
for( i=0 ; i < n; i ++) printf ( “ Enter the marks of all students \n”) ;
{ for( i = 0; i < studs ; i++)
printf ( “ \n Enter the %d digit : ” , i ) ; {
scanf( “ %d” , &digit [i]) ; printf ( “Enter the marks of students %d
} \n\t”,marks[i]);
i=0 ; scanf ( “ %d” , & marks [i]) ; i)
while ( i < n) }
{ for (i =0 ; i < studs ; i++ )
num = num + digit [ i] + pow (10,i) ; { sum = sum + marks [i] ; }
i++; avg_marks = (float) sum / studs ;
} printf ( “ Sum of marks = %d” , sum);
printf( “ \n The number = %d ” , num) ; printf( “\n Average marks of %d students =
getch(); %f ”, studs , avg_marks ) ;
} getch () ;
}
Ques 17. WAP in C to print the elements of an Ques 18.WAP in C to check whether an array of
array using pointers. integers contain a duplicate number or not.
#include<stdio.h> #include<stdio.h>
#include<conio.h> #include<conio.h>
void main()
{
{
int b [3] = { 10 , 20 , 30 } ; int i , n ,j , arr [20] , flag=0 ;
printf( “Elements are %d %d %d \n”, b[0], b[1] , clrscr();
printf ( “ Enter the number of elements : \n” ) ;
b[2]) ;
scanf( “ %d ” , &n) ;
printf(“ Elements are %d %d %d \n” , *(b +0), printf( “ \n Enter the elements \n”) ;
*(b+1) , *(b + 2)) ; for ( i=0 ; i<n ; i++)
{
getch();
printf( “ \n arr [ %d] = ” , i );
} scanf( “ %d” , &arr[ i]) ;
}
for ( i=0 ; i < n ; i ++)
{
for( j= i +1 ; j < n ; j++ )
{
if (arr [i] = = arr [j] && i!= j)
{
flag =1;
printf ( “ Duplicate numbers found at
location %d and %d “, i , j) ;
}
}
if (flag=0)
Printf( “ \n No duplicate numbers found ”)
getch(); }
Ques 19. What operations can be performed on 1-D arrays? Explain linear searching. WAP to
demonstrate linear searching in an array.
SEARCHING: The technique for finding the desired data element that has been stored in an array is
known as searching .After searching is completed , there may be two cases w.r.t data
element : Case 1: Search is successful , if it locates an element at required position
Case 2 : Search is unsuccessful , if it fails to locate an element .
Example : #include<stdio.h>
#include<conio.h>
void main()
{ int arr[ 10 ] = { 15, 20 , 30 , 9 , 14 , 56 , 40 , 100 , 67, 7 };
int i , num ;
printf( “ Enter the key element to be searched in array\n”);
scanf ( “ %d” , & num);
for(I = 0 ; i <10 ; i ++ )
{ if (num = = arr [ i ])
{ printf ( “ %d number is found \n ”, num) ;
break ;
}
else
{
printf( “ %d number not found ” , num ) ;
}}
getch () ; } // End of main()
Ques 20 : What is sorting ? WAP in C to sort the elements of an array using bubble sort.
Ans : Term sorting means arranging the elements of an array in some relevant order which may be either
ascending / descending. If A is an array then , the elements of an array arranged in ascending order will be
such that : A[0 ] < A[ 1 ] < A[ 2 ] < ……A[N-1]. Example : if we have elements of array as :
A[ ] = { 21 , 34 ,11, 9 , 1 , 0 , 22} ; Then the sorted array in ascending order will be as given below :
A[ ] = { 0 , 1 , 9 , 11 , 21 , 22 , 34}.Efficient sorting algorithms are used to optimize the use of other
Algorithms like search and merge algorithms which require sorted lists to work properly.
Two types of Sorting exist : (i)Internal Sorting (ii) External Sorting.
Internal sorting deals with sorting the data stored in computer’s memory.External sorting deals with the data
stored in files . It is used when large data can not be stored in memory of computer.
Bubble Sort: In this method of sorting array elements is done by repeatedly moving the largest elements to
the highest index position of the array( if using ascending order). In this consecutive adjacent pairs of
elements are compared with each other. If element at lower index is greater than the element at higher index,
the two elements interchange their positions. This process continues till the list if unsorted elements are
finished.
Program of Bubble Sort Algorithm in C.
#include <stdio.h>
#include <conio.h> printf ("The numbers arranged in ascending
void main () order are given below\n");
{
int i,j, a, n, number[30]; for (i=0; i<n; ++i)
clrscr(); printf ("%d",number[i]);
printf ("Enter the value of N\n"); getch();
scanf ("%d", &n); } /* End of main() */
printf ("Enter the numbers \n");
for (i=0; i<n; ++i) …………………………………………………….
scanf ("%d",& number[i]) ; Output
Enter the value of N
for (i=0; i<n ; ++i)
5
{ for (j=i+1; j<n; ++j) Enter the numbers 80 20 67 10 45
if (number[i] > number[j]) The numbers arranged in ascending
{ order are given below
a= number[i]; 10 20 45 67 80
number[i] = number[j];
number[j] = a; } }
Ques 21. Write a C program to accept a matrix of Ques 22. Write a C program to accept a matrix of
order M x N and find the sum of each row and order m x n and find its transpose .
each column
#include <stdio.h>
#include <stdio.h> #include <conio.h>
#include<conio.h> void main ()
void main () {
{ int mat [10][10];
int m1[10][10]; int i, j, m, n ;
int i, j, m, n, sum=0; printf ("Enter the order of the matrix \n");
clrscr() ; scanf ("%d %d", &m ,&n);
printf ("Enter the order of the matrix\n"); printf ("Enter the elements of the matrix\n");
scanf ("%d %d", &m, &n); for (i=0; i<m;++i)
printf ("Enter the co-efficients of the matrix\n"); {
for (i=0; i<m ; ++i) for (j=0;j<n;++j)
{ for (j=0 ; j<n ; ++j) {
{ scanf ("%d", &m1[i][j]) ; } scanf ("%d",& mat[i][j]);
} }
}
for (i=0;i<m;++i) printf ("The given matrix is \n");
{ for (j=0;j<n;++j) for (i=0;i<m;++i) // Here outer loop is now for
{ sum = sum + m1[i][j] ; } counter variable i
printf ("Sum of the %d row is = {
%d\n", i, sum) ; for (j=0;j<n;++j)
sum = 0; } {
printf (" %d", mat[i][j]);
for (j=0; j<n ;++j ) }
{ for (i=0 ; i< m ; ++i) printf ("\n");
{ sum = sum+m1[i][j] ; } }
printf ("Sum of the %d column is = printf ("Transpose of matrix is \n");
%d\n", j, sum); for (j=0; j<n; ++j) // Here outer
loop is now for counter variable j
} getch () ; {
} /*End of main() */ for (i=0 ;i<m ;++i)
/* {
Output printf (" %d",mat[i][j]);
Enter the order of the matrix }
33 printf ("\n");
Enter the co-efficients of the matrix }
123 } /* End of main() */
456
789 -------------------------------------------------------------
Sum of the 0 row is = 6 Output
Sum of the 1 row is = 15 Enter the order of the matrix
Sum of the 2 row is = 24 22
Sum of the 0 column is = 12 Enter the coefficients of the matrix
Sum of the 1 column is = 15 3 -1
Sum of the 2 column is = 18 60
The given matrix is
3 -1
60
Transpose of matrix is
36
-1 0
OUTPUT: else
{
Enter number of rows and columns of first matrix ( printf("Matrix Multiplication is Not Possibl
MAX 10) e");
3 }
3 getch();
Enter number of rows and columns of second matri }
x MAX 10)
3
3
Ques 24.WAP to find the length of a string without using library function.
#include<stdio.h>
#include<conio.h> printf("The length of a string is the number of
void main() characters in it\n");
{ printf("So, the length of %s =%d\n", string,
char string[50]; length);
int i , length = 0; }
printf ("Enter a string\n"); /*----------------------------------------------------
gets (string); Output
for (i=0; string[i] != '\0'; i++) Enter a string
{ length++ ; hello
} The length of a string is the number of
characters in it
So, the length of hello = 5
Ques 25. Program to compare two strings using user defined function. If strings are identical display
“The Two Strings are Identical” otherwise the strings are different.
#include<stdio.h> if (flag==0)
#include<conio.h> printf("Both strings are equal\n");
void main() if (flag==1)
{ printf("String1 is greater than string2\n",
int count1=0,count2=0,flag=0,i; str1, str2);
char str1[10],str2[10]; if (flag == -1)
clrscr(); printf("String1 is less than string2\n", str1,
puts("Enter a string:"); str2);
gets(str1); getch(); }
puts("Enter another string:"); /*----------------------------------------
gets(str2); Output
/*Count the number of characters in str1*/ Enter a string:
while (str1[count1]!='\0') happy
count1++; Enter another string:
/*Count the number of characters in str2*/ HAPPY
while (str2[count2]!='\0') String1 is greater than string2
count2++;
i=0 ; RUN2
while ( (i < count1) && (i < count2)) Enter a string:
{ if (str1[i] == str2[i]) Hello
{ i++; Enter another string:
continue ; Hello
} Both strings are equal
if (str1[i]<str2[i])
{ flag = -1; RUN3
break; Enter a string:
} gold
Programming for Problem Solving(UNIT-4)
Ques 26. WAP in C to reverse a string Ques 27. WAP in C to reverse a string
input through the keyboard. using a user defined function.
#include<stdio.h> #include<stdio.h>
#include<conio.h>
#include<conio.h>
char* mystrrev(char*s)
int main()
int main()
{ {
int i= -1; char str [ 20] ;
char str[100]; puts(“ Enter a string”) ;
char rev[100]; gets(str) ;
char *strptr = str; mystrrev (str) ;
char *revptr = rev; puts(“After the reversal string is : ”) ;
clrscr(); puts(str);
printf("Enter the string:n"); getch();
scanf("%s",str); }
while(*strptr) char* mystrrev (cahr* s)
{ {
strptr++; int i=0 , j=0 ;
i++; char temp;
} while (s[i] !=’\0’)
while(i >=0) i++;
{strptr--; i-- ;
*strptr = *revptr; while (i > j)
revptr++; {
--i; temp = s[i] ;
Programming for Problem Solving(UNIT-4)
} s[i] = s[j] ;
printf("nn Reversed string is:%s", rev); s[j] = temp ;
return 0; j++ , i-- ;
getch(); }
return s ;
}
}
Ans : (i) Passing Arrays to functions : When we need to pass an entire array to a function, we can
pass the name of the array. Entire array is always passed by reference to the function. Following are
the rules to pass 1-D array in a function :
Rule 1. The actual argument in the function call should only be the name of the array without any
subscript, because name of an array represents base address.
Rule 2. Formal parameters in the function definition must be of array type or pointer type ( i.e pointer
to first element of the array.) If formal parameter is of array type , it will be implicitly converted to
pointer type.
Rule 3. Parameter type in the function declaration should be of array type or pointer type.
Example :
void main() // Calling function. Note : When an entire array is to be sent to the
{ called function, the calling function just needs to
int arr [5] = { 1 ,4 , 10 , 45 , 65 }; pass the name of array.
func(arr) ; In cases where called function does not makes
} any changes to the array, the array must be
void func (int arr [ 5]) // Called function received as a constant array by the called
{ function. It prevents any type of unnecessary
int i ; modifications by called function to the array
Programming for Problem Solving(UNIT-4)
(ii) Enumerated Data Types : This is a user defined data type based on the basic integer type.
Enumeration has a set of named integer constants. Each integer value is assigned an identifier, also
known as enumeration constant, which can be used as a symbolic name to make program easy to be
read.
Keyword enum is used for this data type.
Syntax : enum enumeration_name { identifier1 , identifier 2, ……., identifier n}.
Enumeration name is optional.
Example : enum COLORS { RED , BLUE , BLACK , GREEN , YELLOW ,PURPLE} ;
Now COLORS is a new data type. COLORS is the name given to the set of constants. In case we
do not assign any value to a constant , default value for the first one in list , RED has value of 0.
Next constants will have sequential values after 0 i.e , 1, 2, 3…so on.
RED = 0 ,BLUE = 1, Black =2 , GREEN = 3 , YELLOW= 4, PURPLE= 5.
We can also initialize symbolic constants explicitly by specific integer values , which may not be
in sequence.
(iii) Union: This is a user defined data type. It is a collection of variables of different data types.
In Unions we can only store information in one field at any one time. It is like a chunk of
memory used to store variables of different data types. When a new value is assigned to a field, the
existing data is replaced with the new data.
data_type var-name1;
data_type var-name2 ;
}
Ques 29. What are structures? What is the advantage of structures over array? Differentiatebetween
Structures and Unions.
Ans : Structures are the user defined data types that is of heterogeneous nature , that means it canstore
information of different data types. Keyword struct is used to declare a structure.
Declaration of structure: struct structure _ name
{
Data_type var-nmae1;Data_type
var-nmae1
};
Example: if we define a structure for a student Each variable name declared inside structure is
, then the Related information can be : rollno , called member of structure. Structure declaration
name , course , fees. This structure can be does not consume any storage space. Example:
declared as : , we can define a variable by writing :
Initialization of structures: A structure can be initialized in the same way as other data types
Programming for Problem Solving(UNIT-4)
are initialized. Initializing a structure means assigning some constants to the members of the
structure. If explicitly, then C automatically does that. For int and float members, values are initialized
to zero and character and string members are initialized to ‘\0’ by default. Initializers are enclosed in
curly braces separated by commas.
Advantage of Structure over Arrays : Structure is advantageous than arrays in the sense that
it can store information of variables of different data types where as arrays have information of only
same data types.
Difference between Structure & Union
Programming for Problem Solving(UNIT-4)
getch();
} // End of main for(i=0 ; i<3 ; i++)
{
std[i].avg = total/3.0 ;
printf( “ %d %s %d %d %d % f\n ”,
std[i] .rollno,std[i].name,std[i].m1,
std[i].m2,std[i].m3,std[i].avg) ;
} // End of for loop
getch() ;
} // End of main()
Programming for Problem Solving(UNIT-4)
Ques 32 : How an array of structure is created ? Explain with the help of a program.
Ans : It is possible to create an array whose elements are of structure type. Such an array is called
Array of Structures. If we consider a book example where we have to display information of book
name , author name , number of pages and its price then it can be stored in a variable of type struct
Programming for Problem Solving(UNIT-4)
book. We can create two variable book1 , book2 and read and display the information about two
books..
But in case if we want to access the information of suppose 100 books , then we will have to create
100 variables like book1 , book2, book3 ,…..book100 . Also we will have to read and display the
information separately for each book. This will be a very long , difficult process ,and time consuming
also. So array of structures will provides an easy way to store information of 100 books.
General Syntax :
struct struct_name
{
Data_type1 member_name1 ;
Data_type2 member_name2 ;
Data_type3 member_name3 ;
……………………………….
Data _type n member_name n ;
} ; struct struct_name struct_var [ index ];
/* Program of Array of Structure for Book information */
#include<stdio.h>
#include<conio.h>
void main
{
struct book
{
char Name[30];
char author[20] ;
int pages ;
float price ;
};
struct book b[ 100 ]; //array of structures.
int i;
for(i=0;i<100;i++)
{
printf("\n Enter details of %d Book ",i+1);
UNIT 5
Module – 5: (Pointers& File Handling)
Pointers
Introduction to Macros, Preprocessors
Introduction to Dynamic memory allocation
malloc(),calloc() and free() functions
Notion to Linked lists
Intoduction to file handling
How to read,open,close files.
Basic Program/s on file handling
Short Questions & Answers
Ques 1.What are Macros? Give examples.
Ans. Macros are the identifiers that represent statements or expressions. To associate meaningful identifiers
with constants, keywords, and statements or expressions, #define directive is used.
If we define a macro i. e SQUARE(x) x*x. Here the macro determines the square of the given number.
Ans. Macro template is defining the macro at the beginning of a program using ‘#’directive. For example
#define CUBE (X ) ( X * X* X) .
Ans. This cause the specified identifier to be no longer defined as a macro name. For example:
.# undef PI
Ans. These are source file inclusion directives, the first way of inclusion searches the prespecified list of
directories for the source file within < >.The second way the source file is first searched in the current
working directory, if the search fails then prespecified list of directories are searched .If still the search
fails,then compiler gives an error unable to include file.
The memory allocated by system to a program is divided into three portions (i) Memory for
functions (ii) Memory for data (iii) Free memory called heap which may be required during
execution of the program.
Some library functions used in dynamic memory allocation have their prototype definition in
header file <stdlib.h>.These functions are as follows:-
malloc():This stands for memory allocation This function allocates a block of memory of the size of
its argument in bytes. It returns a void pointer to the first byte of the memory block
Synatx: void * malloc (size) ;
The function malloc allocates n*sizeof(int) bytes of memory and returns the value of pointer ptri.
Return value of malloc is the value of ptri which is the address of the first byte of the memory
block.Let n=2 , then total bytes occupied are 2 x 2=4 bytes. This is how an array can be allocated
memory at run time. In case allocation is not possible due to lack of sufficient memory , ther return
value will be NULL pointer .For example Code can be:
if (ptri= = NULL)
exit(1) ;
struct book
pages ;
struct book*ptrb ;
Syntax: void* calloc (n , size_mem) ; // Here n is no.of blocks; size_m is size of each block
(iii) realloc( ) :This function reallocates a memory block of size smaller or bigger than the size of the block
earlier allocated by malloc().
Syntax: void* realloc (void *ptr , new_size) ;
e.g: float *ptrf = (float *) malloc ( 5 * sizeof(float) ) ; // allocates 5 x 4= 20 bytes of an array
ptrf = (float *) realloc ( ptrf, 3 * sizeof(float) ) ; // resized array of 3x 4=12 bytes.
(iv) free( ) : This function is used to de-alloacte thememory allocated by the functions malloc() , calloc()
and realloc().The whole allocated memory block is released.
Syntax: void free (void *ptr ) ;
Ques 7. What is File in C? What are different types of file used in file
handling?
Ans. A file is a collection of bytes stored on a secondary storage device, which is generally a disk of some
kind. There are two kinds of files that programmers deal with text files and binary files.
A text file can be a stream of characters that a computer can process sequentially. It is not only processed
sequentially but only in forward direction.
For this reason a text file is usually opened for only one kind of operation (reading, writing, or appending)
at any given time.
A binary file is no different to a text file. It is a collection of bytes. In C Programming Language a byte
and a character are equivalent.
{ char name
[20] ;int
number;
struct List *nextnode ;
The first statement declares the variable fp as a pointer to the data type FILE. As stated earlier, File is a
structure that is defined in the I/O Library. The second statement opens the file named filename and assigns an
identifier to the FILE type pointer fp. fopen() contain the file name and mode (the purpose of opening the
file).
r is used to open the file for read only.
w is used to open the file for writing only.
a is used to open the file for appending data to it.
Closing a File
A file must be closed as soon as all operations on it have been completed. This would close the file
associated with the file pointer. The input output library supports the function to close a file.
Syntax to close file
fclose(file pointer);
Example:
#include<stdio.h>
#include <conio.h>
void main(void)
{
FILE *myfile;
char c;
myfile = fopen("firstfile.txt", "r");
if (myfile == NULL)
Ques 12. Write a C program to create a file called emp.rec and store information about a person in
terms of his name age and salary.
Ans.
#include <stdio.h>
#include <conio.h>
void main()
{
FILE *fptr;
char name[20];
int age;
float salary;