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

Structured Programming Language Handnote

The document outlines the syllabus for a structured programming language course, focusing on C programming techniques including flowcharts, algorithms, data types, control structures, functions, and memory management. It includes a list of reference books and questions from various chapters that cover essential programming concepts and practices. The syllabus emphasizes practical programming skills and theoretical knowledge necessary for understanding structured programming.
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)
6 views

Structured Programming Language Handnote

The document outlines the syllabus for a structured programming language course, focusing on C programming techniques including flowcharts, algorithms, data types, control structures, functions, and memory management. It includes a list of reference books and questions from various chapters that cover essential programming concepts and practices. The syllabus emphasizes practical programming skills and theoretical knowledge necessary for understanding structured programming.
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/ 155

STRUCTURED PROGRAMMING LANGUAGE

SYLLABUS
COMPUTER PROGRAMMING TECHNIQUES: flowchart, pseudocode and algorithm; structured programming
language: data types, operators, expressions; control structures; functions and program structure:
parameter passing conventions, scope rules and storage classes, recursion; header files;
preprocessor; pointers and arrays; strings; multidimensional array; dynamic memory allocation;
linked list: single linked list, double linked list, circular linked list; user defined data types:
structures, unions, enumerations; bitwise operations; input and output: standard input and output,
formatted input and output; error handling; file access; variable length argument list; command line
parameters; error handling; graphics; linking; library functions.
REFERENCE LANGUAGE: C

REFERENCE BOOKS:
1) Shaum’s Outline of Theory and Problems of Programming with C,B. S. Gottfried, McGraw Hill,
3rdEdition.
2) Teach Yourself CHerbert Schildt, Published by Osborne, 3rd Edition.
CHAPTER 1 PAGE NO: 12
COMPUTER PROGRAMMING TECHNIQUES

Sl. No Question Years


1 What is programming language? 2012
2 What is structured programming language? 2018, 2021, 2022,2023
Write down the advantages and disadvantages of structured
3
programming.
4 What is an algorithm? 2017, 2019, 2022
5 What are the properties of an algorithm? 2022
6 What is a flowchart? 2019
7 Define flowchart & switch statement. 2010, 2020
8 What is pseudocode? 2018, 2021, 2022
9 Distinguish between algorithm and flowchart. 2018, 2021
10 Distinguish between algorithm and pseudocode.
11 Describe the characteristics of a program.
Write down the general form and flowchart of the following
12
statements:
(i) else…….. if ladder 2019, 2022,2023
(ii) SWITCH
(iii) FOR
Draw the flowchart that shows the process of compiling and running a
13 2018
C program.
14 Describe the symbols used in a flowchart. 2019
15 Write down the salient features of structured programming language. 2020
16 Define a flowchart to find the largest value among three numbers. 2020
17 Write an algorithm to determine whether a number is odd or even. 2021
Write an algorithm and flowchart to calculate the temperature from
18 2022
Fahrenheit to Celsius.

CHAPTER 2 PAGE NO: 26


STRUCTURED PROGRAMMING LANGUAGE

Sl No. Question Years


2021, 2019,
1 What is a structured programming language?
2020
2 Explain different control structures used in structured programming. 2021,2023
3 Write down the characteristics of structured programming language. 2019, 2020
4 What is C programming?
Sl No. Question Years
5 Write down the importance of C language. 2018
2007, 2009,
2012, 2014,
6 Describe the basic structure of a C program.
2016, 2020,
2022
2010, 2013,
7 Write down the steps of executing a C program.
2017
8 Briefly explain different forms of the main() function used in C. 2007
Distinguish between the following pairs: (i) main() and void
9
main(void) (ii) int main() and void main()
10 Where are blank spaces permitted in a C program? 2016
2023,2021,
11 Why and when do we use the #include and #define directives?
2017, 2016
12 Define data types.
2008, 2011,
Describe the four basic data types used in C language. How could we
13 2018, 2020,
extend the range of values they represent?
2022
14 What do you mean by preprocessor directive? Explain it. 2023,2021
15 Define tokens. 2019, 2022
16 Define constant. 2019
17 Define identifiers. 2017, 2019
18 Describe the rules for identifiers. 2007
19 Define keywords. 2017, 2019
20 Define constants and describe different types of constants. 2017
21 How to use constants in a C program?
22 What are the rules of constants?
2011, 2016,
23 What is a variable? 2017, 2019,
2022
24 How to declare & initialize C variables?
2011, 2016,
25 What is meant by the “value” of a variable?
2017
2008, 2016,
26 Distinguish between local and global variables with examples. 2018, 2020,
2022
27 How do variables and symbolic names differ? 2009
28 Differentiate between variable declaration & definition in C.
29 What are trigraph characters? How are they useful? 2007
30 Write down the purpose of the qualifiers const and volatile. 2011
31 Describe the process of explicit conversion of data types in C. 2012
32 Write down the uses of continue and break. 2020
33 Describe different types of tokens (represent through a table). 2022

CHAPTER 3 PAGE NO: 45


OPERATORS AND EXPRESSIONS

Topic SL No. Question Years


2018, 2019,
1 Define operator. How many types of operator in C?
2022
2011, 2016,
2 Describe the types of operators.
2018
3 Describe arithmetic operators in C.
4 Describe the assignment operators in C.
5 Describe the relational operators in C. 2018, 2020
6 Describe the logical operators in C. 2018, 2020
7 Describe the bitwise operators in C.
Operators 8 Describe the Increment/decrement Operators. 2019
9 Describe the special operators in C.
2017,
10 Differentiate between x++ and ++x.
2022,2023
11 Differentiate between a-- and –a. 2018
With examples, describe the rules for ++ and –
12 2021
operators.
13 Describe expression. 2018
Describe symbolic constant. Write down the rules for
14 2021, 2019
declaring symbolic constant?
15 What is control structure?
16 Define Decision Control statement.
17 What is meant by branching?
18 Write down the general form of if statements.
19 Write down the general form of if-else statements. 2017
2017, 2018,
20 Write down the general form of nested if-else.
2021
Define algorithm and flowchart. Draw the flowchart of
21 2017
else if ladder.
Describe nesting of if else statement with flowchart and
22 2007
examples.
In what ways does a switch statement differ from an if
Control 23 2008, 2018
statement?
Structures
24 Describe if statement with flowchart.
25 Describe if else statement with flowchart.
26 Describe switch statement with flowchart. 2018, 2021
27 Describe nesting of IF statement.
2016, 2017,
28 What is looping process? 2018, 2020,
2021
29 Briefly describe different types of loop. 2017
30 Describe While loop with example. 2021
31 Describe for loop with example. 2018
32 Describe Nested for loop with example.
33 Describe do While loop with example.
Topic SL No. Question Years
Distinguish between counter controlled and sentinel
34 2016
controlled loop.
Differentiate between entry controlled loop and exit
35 2017, 2021
controlled loop.
36 Describe entry controlled loop and exit controlled loop. 2018, 2020
37 Describe infinite loop & Time delay loop. 2012, 2020
38 Difference between break and continue? 2021, 2010

CHAPTER 4 PAGE NO: 74


FUNCTIONS AND PROGRAM STRUCTURE

SL
Question Years
No.
1 What is a function? Are functions required when writing a C program? 2018, 2022
2 State three advantages to the use of functions.
What is meant by a function call? From what parts of a program can a
3
function be called?
4 How to call C functions in a program?
2018, 2020,
5 What do you mean by call by value and call by reference?
2021
6 What is function definition? 2011
7 Mention the merits of user-defined functions. 2021
8 Different aspects of function calling.
9 Why prototyping is essential in a program? 2021
10 Define user-defined function and library function with example. 2019, 2009
11 What are arguments? What is their purpose?
12 Define: (i) Function prototype (ii) Function Argument 2009
What are formal arguments? What are actual arguments? What is the
13
relationship between formal arguments and actual arguments?
14 Write down the actual and formal parameters in C language. 2018
15 Define recursion. Difference between iteration and recursion. 2018, 2021
2010, 2012,
16 Briefly explain different forms of main() function used in C.
2016
17 What is storage class? What are the meanings of storage classes? 2007, 2022
18 Describe different types of storage classes in C program. 2018, 2022
What is the output of the following code? p=10; q=--p+20; r=p++ -25;
19
printf ("%d %d %d",p,q,r);
What is the output of the following code? int x=-10,y=3;
20 2021
printf("%d\n",x/y10); y=-y; printf("%d",x/y10);
SL
Question Years
No.
21 Why and do we need to use functions? 2020
Consider the following C code and find out every value of the variables
22 (x,y,z)- Int x=5,y=8,z=3; x=x+(z++); printf(“%d%d”,x%y,x/y); y=--x;
printf(“%d%d%d”,x,y,z);

CHAPTER 5 PAGE NO: 86


HEADER FILES

SL No. Question Years


1 What is a header file with example? 2019
Why do we need to use #include <math.h> and #include <ctype.h>
2
statement in a C program?
3 What do you mean by library function? 2018

CHAPTER 6 PAGE NO: 87


PREPROCESSOR

SL
Question Years
No.
1 Difference between stack & heap memory in C language?
2 What is the difference between compilers vs interpreters in C language?
What is a preprocessor directive? Write down the functions of <stdio.h>
3 2022
and <math.h> header files.

CHAPTER 7 PAGE NO: 89


POINTERS AND ARRAYS

SL
Question Years
No.
2012, 2017, 2019, 2021,
1 What is pointer?
2022
2 Declare and initialize a pointer variable? 2012, 2017, 2020
3 What is null pointer?
2007, 2008, 2009, 2010,
4 What is array? 2011, 2012, 2013, 2014,
2015, 2017, 2019, 2022
5 Define Linear array? 2021
SL
Question Years
No.
6 Write the advantages and disadvantages of array. 2019, 2022
Write down the merits and demerits of using pointer with
7
respect to array?
What are some arithmetic operators that are permitted to use
8 2021
with pointer? Give Example.
9 What are the advantages of using linked list over array?
10 Declare and initialize the types of array. 2014, 2015, 2018, 2021
Describe declaration and initialization of two-dimensional
11 2012, 2018
arrays.
12 What do you understand by overflow and underflow of data? 2021
Define a two-dimensional integer array and input data values
13 2008, 2011
of 4 rows of 5 columns each.
What are the basic differences between an array and a
14 2014, 2015
structure?
How can an array be explicitly initialized at runtime? What is
15 the purpose of a memory management function malloc and 2010, 2012, 2014, 2020
calloc?
How can you overcome the limitation of arrays using
16 2012
structure?
What is a null statement? What are the purposes of a null
17 2012
statement?
Define structure and union. Write down the differences
18 2019, 2021
between structure and array.
Write down the advantages and disadvantages of using
19 2020
pointers.

CHAPTER 8 PAGE NO: 99


STRINGS

SL
Question Years
No.
1 Define string. 2021, 2022
2 Describe C string functions. 2018
Mention some string handling functions and describe them with example.
Or, Describe the different types of string handling functions in C language 2011, 2019, 2021,
3
with example. Or, Write down four string handling functions with their 2022
action.
Describe the limitations of using getchar and scanf function for reading
4 2008, 2020
string?
5 Describe the following C functions: strcmp(), strcat(), strcpy(), and strlen().
6 Describe C – strcat() function.
7 Describe C – strncat() function.
8 Describe C – strcpy() function.
SL
Question Years
No.
9 Describe C – strncpy() function.
10 Describe C – strlen() function.
11 Describe C – strcmp() function.
12 Describe C – strcmpi() function.

CHAPTER 9 PAGE NO: 108


DYNAMIC MEMORY ALLOCATION

SL No. Question Years


1 Describe the dynamic memory allocation in C. 2018
2 Difference between static memory allocation and dynamic memory allocation in C.
3 Difference between malloc() and calloc() functions in C.

CHAPTER 10 PAGE NO: 110


LINKED LIST
SL No. Question Year(s)
1 What is a linked list? Describe the linked list representation in memory.
2 What are the advantages of using linked lists over arrays? 2018
3 What is a circular linked list? Describe the circular linked list representation in memory.

CHAPTER 11 PAGE NO: 113


USER DEFINED DATA TYPES

SL
Question Years
No.
1 What is structure in C? 2008
2 What is the difference between C variable, C array, and C structure?
3 Describe C structure declaration in a separate header file.
In which way does structure differ from an array? Describe with examples, the
4 2016
different ways of assigning values of structure members.
Derive the difference between structure and union in C. Or, differentiate with 2012, 2016,
5
syntax between structure and union. 2018, 2022

CHAPTER 12 PAGE NO: 117


INPUT AND OUTPUT
SL No. Question Years
1 Explain printf() function in C language.
2 Write down the differences between printf() and fprintf(). 2021
3 Write down the differences between scanf() and fscanf(). 2021
4 Distinguish between the following functions:
(i) rewind & ftell 2020
(ii) printf & fprintf
(iii) BOF & EOF
(iv) getc & putc

CHAPTER 13 PAGE NO: 121


FILE ACCESS

SL
Question Years
No.
1 What is a file? 2007, 2015, 2016, 2019
2 Describe the basic file operations in C programming. 2015
Describe different types of file opening mode? Or discuss modes for
3 2011, 2019, 2021
opening a file used in C language.
4 Describe the mode of operations performed on a file in C language.
Describe an example program for file open, file read, and file close in C
5
language. Or describe inbuilt functions for file handling in C language.
What are the errors that could occur during file operation and how could
6 2018, 2011
you solve them? Or describe error handling in file operation.
7 Describing the opening and closing function of a FILE. 2007
8 What is the significance of the EOF function? 2014, 2022
9 Write down the advantages of files. 2014, 2020, 2022
10 Define file handling mode. 2022

CHAPTER 14 PAGE NO: 128


VARIABLE LENGTH ARGUMENTLIST & COMMAND LINE PARAMETER
ERROR HANDLING, LINKING & LIBRARY FUNCTIONS

SL No. Question Years


1 What is errno?
2 Define perror() and strerror().
3 Explain Divide by Zero Errors.
4 What is linker?
5 Do you mean by actual and formal parameter? Explain with an example.
6 Distinguish between the following: 2011, 2016, 2022
(i) Actual and formal parameter
(ii) Automatic and static variable
C PROGRAMS& ALGORITHMS
PAGE NO: 131

SL
Question Years
No.
1 Write a program to find the area of a circle where pi is a symbol of constant.
Write a program to convert the given temperature in Fahrenheit to Celsius
2
and vice versa.
Write a program to convert the given temperature in Fahrenheit to Celsius
3 2020
where cel=((fah-32)*5/9).
Area of a triangle is given by the formula A=√(s(s-a)(s-b)(s-c)) where a, b, c
4 are sides of the triangle and 2s=a+b+c. Write a C program to compute the
area of the triangle given the values of a, b, and c.
The numbers in the sequence 1, 1, 2, 3, 5, 8, 13… are called Fibonacci
5 numbers. Write a C program using a for loop to calculate and print the first m 2020
Fibonacci numbers.
Write a C program to copy one string into another and count the number of
6 2021
characters copied.
7 Write a C program to read from a file and display it on the screen. 2021
Write a C program to display the real, imaginary, and equal roots of a
quadratic equation: ax² + bx + c = 0. (Use the following conditions: There is
8 2022
only one root if a=0 (x=-c/b); there are no real roots if b²-4ac is negative;
otherwise, there are two real roots.)
9 Write a C program to test whether a given string is a palindrome or not. 2022
10 Write a program to read a matrix of size m×n and print its transpose.
Write a program using pointers to read in an array of integers and print its
11 2018
elements in reverse order.
Write a C program to determine whether a number is ‘odd’ or ‘even’ and
12
print the message: NUMBER IS EVEN OR NUMBER IS ODD.
13 Write a program to find the nth Fibonacci number. 2018
14 Write a program to find the area and circumference of a circle. 2022
15 Write a program to calculate the area and perimeter of a triangle. 2020
16 Write a C program to test whether the given year is leap or not. 2014, 2021
17 Write a C program to evaluate De Morgan's rule. 2010
18 Write a C program to append the contents of one file to another file. 2018, 2019, 2020
Write a C program to compute the sum of all elements stored in an integer
19 2017
array using pointers.
Write a C program to write integers from 1 to 10 and store data into the file
20 2017
named “razu.dat”.
21 Write a C program to multiply two matrices. 2019
22 Write a C program to determine the largest value from three numbers. 2019
Write a C program to calculate the sum of the following series: 1 + 2² + 3³ +
23 2019
4⁴ + … + 50⁵
24 Write a C program to find the factorial of an integer. 2019
25 Write a C program to add 1 to 50. 2020
26 Write a C program to read an array and display its elements in reverse order. 2020, 2021
SL
Question Years
No.
27 Write a C program that prints the smallest number from three numbers. 2022
Write a C program to exchange the values of two variables (x, y) using a
28 2022
pointer.
Write a C program to read the content of a file and write the contents to
29 2022
another file.
CHAPTER 1
COMPUTER PROGRAMMING TECHNIQUES

Sl. No Question Years


1 What is programming language? 2012
2 What is structured programming language? 2018, 2021, 2022,2023
Write down the advantages and disadvantages of structured
3
programming.
4 What is an algorithm? 2017, 2019, 2022
5 What are the properties of an algorithm? 2022
6 What is a flowchart? 2019
7 Define flowchart & switch statement. 2010, 2020
8 What is pseudocode? 2018, 2021, 2022
9 Distinguish between algorithm and flowchart. 2018, 2021
10 Distinguish between algorithm and pseudocode.
11 Describe the characteristics of a program.
Write down the general form and flowchart of the following
12
statements:
(i) else…….. if ladder 2019, 2022
(ii) SWITCH
(iii) FOR
Draw the flowchart that shows the process of compiling and running a
13 2018
C program.
14 Describe the symbols used in a flowchart. 2019
15 Write down the salient features of structured programming language. 2020
16 Define a flowchart to find the largest value among three numbers. 2020
17 Write an algorithm to determine whether a number is odd or even. 2021
Write an algorithm and flowchart to calculate the temperature from
18 2022
Fahrenheit to Celsius.

CHAPTER 1
COMPUTER PROGRAMMING TECHNIQUES

1) What is programming language? (2012)


Solution: A programming language is a formal language that specifies a set of instructions that can
be used to produce various kinds of output. Programming languages generally consist
of instructions for a computer. Programming languages can be used to create programs that
implement specific algorithms.
The term programming language usually refers to high-level languages, such
as basic, c, c++, cobol, java, fortran, ada, and pascal.

2) What is structure programming language? (2018,2021,2022)


Solution: Structured programming (sometimes known as modular programming) is a subset of
procedural programming that enforces a logical structure on the program being written to make it
more efficient and easier to understand and modify.

3) Write down the advantages and disadvantages of structure programming.


Solution: Advantages of structure programming
✓ Complexity can be reduced using the concepts of divide and conquer.
✓ Logical structures ensure clear flow of control.
✓ Increase in productivity by allowing multiple programmers to work on different parts of the
project independently at the same time.
✓ Modules can be re-used many times, thus it saves time, reduces complexity and increase
reliability.
✓ Easier to update/fix the program by replacing individual modules rather than larger amount of
code.
✓ Ability to either eliminate or at least reduce the necessity of employing goto statement.
Disadvantages of structure programming
✓ Since goto statement is not used, the structure of the program needs to be planned meticulously.
✓ Lack of encapsulation
✓ Same code repetition
✓ Lack of information hiding.
✓ Change of even a single data structure in a program necessitates changes at many places
throughout it, and hence the changes becomes very difficult to track even in a reasonable sized
program.
✓ Not much reusability of code.
✓ Can support the software development projects easily up to a certain level of complexity. If
complexity of the project goes beyond a limit, it becomes difficult to manage.

4) What is algorithm?(2017,2019,2022)
Solution: an algorithm is a procedure or formula for solving a problem, based on conduction 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.

5) What are the properties of algorithm?


Solution: Properties of algorithm
Simply writing the sequence of instructions as an algorithm is not sufficient to accomplish certain
task. It is necessary to have following properties associated with an algorithm.
✓ Non ambiguity: each step in an algorithm should be non-ambiguous. That means each
instruction should be clear and precise. The instruction in any algorithm should not denote any
conflicting meaning. This property also indicates the effectiveness of algorithm.
✓ Range of input: the range of input should be specified. This is because normally the algorithm is
input driven and if the range of input is not being specified then algorithm can go in an infinite
state.
✓ Multiplicity: the same algorithm can be represented into several different ways. That means we
can write in simple english the sequence of instruction or we can write it in form of pseudo code.
Similarly, for solving the same problem we can write several different algorithms.
✓ Speed: the algorithmis written using some specified ideas. Bus such algorithm should be efficient
and should produce the output with fast speed.
✓ Finiteness: the algorithm should be finite. That means after performing required operations it
should be terminate.

6) What is flowchart?(2019,2022)
Ans: A flowchart is a formalized graphic representation of a logic sequence, work or manufacturing
process, organization chart, or similar formalized structure.

7) Define flowchart & switch statement.(2010)


Ans: Switch statement is one of computer programming languages, which means a type of selection
control mechanism used to allow the value of a variable or expression to change the control flow of
program execution via a multiway branch. It is easy to understand, read, maintain and verify that all
values are handled. There are two main variants of switch statements, the first one is a structured
switch, which takes exactly one branch, and the second one is an unstructured switch which
functions as a type of goto.
Flowchart is a formalized graphic representation of a logic sequence, workflow or manufacturing
process, or similar formalized structure.

8) What is pseudocode? (2018,2021,2022)


Solution: pseudocode is an informal way of programming description that does not require any
strict programming language syntax or underlying technology considerations. It is used for creating
an outline or a rough draft of a program. Pseudocode summarizes a program’s flow, but excludes
underlying details. System designers write pseudocode to ensure that programmers understand a
software project's requirements and align code accordingly.

9) Distinguish between algorithm and flowchart. (2018,2021)


Algorithm Flowchart.
1) Algorithm is done through step 1) Flow chart is a pictorial representation;
by step direction
2) Algorithms are used for 2) Flow charts can be used in the organization
mathematics and computer of different processes for many different
purposes purposes
3) The word ‘algorithm’ came from 3) Flowchart was introduced by frank gilberth
al-khwarizmi
4) The algorithms can be expressed 4) While flowcharts can be analyzed
and analyzed through flowcharts themselves
5) An algorithm is written using 5) An flowchart is a step by step instruction of
natural language. the program.
6) Algorithms are used for 6) Flow charts can be used for many different
mathematics and computer purposes like educational, algorithms and
purposes personal etc.
7) The making of algorithms is quite 7) The making of flowcharts is not that
difficult and complex difficult and complex as compared to
algorithms.
10) Distinguish between algorithm and pseudocode?
Algorithm Pseudocode
1. An algorithm is a well defined 1. A pseudocode is one of the methods
sequence of steps that provides that can be used to represent an
asolution for a given problem algorithm
2. Algorithms can be written in natural 2. Pseudocode is written in a format that
language, is closely related to high level
programming language structures.
11) Describe the characteristics of a program.
Solution:
Desirable program characteristics
There are some important characteristics of well-written computer programs. These characteristics
apply to programs that are written in any programming language, not just c.
✓ Integrity. This refers to the accuracy of the calculations. It should be clear that all other program
Enhancements will be meaningless if the calculations are not carried out correctly. Thus, the
integrity of the calculations is an absolute necessity in any computer program.
✓ Clarityrefers to the overall readability of the program, with particular emphasis on its
underlying logic. If a program is clearly written, it should be possible for another programmer to
follow the program logic without undue effort. It should also be possible for the original author to
follow his or her own program After being away from the program for an extended period of
time. One of the objectives in the design of C is the development of clear, readable programs
through an orderly and disciplined approach to Programming.
✓ Simplicity.The clarity and accuracy of a program are usually enhanced by keeping things as
simple as Possible, consistent with the overall program objectives. In fact, it may be desirable to
sacrifice a certain Amount of computational efficiency in order to maintain a relatively simple,
straightforward program Structure.
✓ Efficiencyis concerned with execution speed and efficient memory utilization. These are
generally Important goals, though they should not be obtained at the expense of clarity or
simplicity. Many Complex programs require a tradeoff between these characteristics. In such
situations, experience and Common sense are key factors.
✓ Modularity. Many programs can be broken down into a series of identifiable subtasks. It is good
Programming practice to implement each of these subtasks as a separate program module. In c,
such Modules are written as functions. The use of a modular programming structure enhances
the accuracy And clarity of a program, and it facilitates future program alterations.
✓ Generality. Usually we will want a program to be as general as possible, within reasonable
limits. For Example, we may design a program to read in the values of certain key parameters
rather than placing Fixed values into the program. As a rule, a considerable amount of generality
can be obtained with very Little additional programming effort.
12) Write down the general form and flow-chart of the following statement:
(2019,2022)
(i) else…….. if ladder
(ii) SWITCH
(iii) FOR
Ans:
(i)Syntax of if...else statement
if(boolean_expression)
{
// Body of if
// If expression is true then execute this
}
else
{
// Body of else
// If expression is false then execute this
}
Flowchart of if...else statement:

The syntax for a switch statement in C programming language is as follows −


switch(expression) {

case constant-expression :
statement(s);
break; /* optional */

case constant-expression :
statement(s);
break; /* optional */

/* you can have any number of case statements */


default : /* Optional */
statement(s);
}
Flow Diagram
C For Loop Syntax
for( triad statement )
{

}
13) Draw the flow chart that shows the process of compiling and running a C program.
(2018, 2007)
14) Describe the symbols used in flow-chart.(2019)
Ans: Flowchart Symbols:
Flowcharts use special shapes to represent different types of actions or steps in a process. Lines and
arrows show the sequence of the steps, and the relationships among them. These are known as
flowchart symbols.
Common Flowchart Symbols
Rectangle Shape - Represents a process
Oval or Pill Shape - Represents the start or end
Diamond Shape - Represents a decision
Parallelogram - Represents input/output

Start/End Symbol:The terminator symbol marks the starting or ending point of the system. It
usually contains the word "Start" or "End."
Action or Process Symbol:A box can represent a single step ("add two cups of flour"), or and entire
sub-process ("make bread") within a larger process.

Document Symbol:A printed document or report.

Multiple Documents Symbol: Represents multiple documents in the process.

Decision Symbol:A decision or branching point. Lines representing different decisions emerge from
different points of the diamond.

Input/Output Symbol: Represents material or information entering or leaving the system, such as
customer order (input) or a product (output).

Manual Input Symbol: Represents a step where a user is prompted to enter information manually.

Preparation Symbol: Represents a set-up to another step in the process.

Connector Symbol: Indicates that the flow continues where a matching symbol (containing the
same letter) has been placed.

Or Symbol: Indicates that the process flow continues in more than two branches.
Summoning Junction Symbol: Indicates a point in the flowchart where multiple branches converge
back into a single process.

Merge Symbol: Indicates a step where two or more sub-lists or sub-processes become one.

Collate Symbol: Indicates a step that orders information into a standard format.

Sort Symbol: Indicates a step that organizes a list of items into a sequence or sets based on some
pre-determined criteria.

Subroutine Symbol: Indicates a sequence of actions that perform a specific task embedded within a
larger process. This sequence of actions could be described in more detail on a separate flowchart.

Manual Loop Symbol: Indicates a sequence of commands that will continue to repeat until stopped
manually.

Loop Limit Symbol: Indicates the point at which a loop should stop.

Delay Symbol: Indicates a delay in the process.


Data Storage or Stored Data Symbol: Indicates a step where data gets stored.

Database Symbol: Indicates a list of information with a standard structure that allows for searching
and sorting.

Internal Storage Symbol: Indicates that information was stored in memory during a program, used
in software design flowcharts.
Display Symbol: Indicates a step that displays information.

Off Page: Indicates that the process continues off page.

15) Write down the salient features of structure programming language. (2020)
Ans:
Structured programming is a program written with only the structured programming constructions.
Here are the salient features of structure programming language:
I. sequence
II. repetition
III. selection
Sequence: Lines or blocks of code are written and executed in sequential order.
Example:
x=5
y = 11
z=x+y
WriteLine(z)
Repetition: Repeat a block of code (Action) while a condition is true. There is no limit to the
number of times that the block can be executed.
While condition
action
End While
Example:
x=2
While x < 100
WriteLine(x)
x=x*x
End
Selection: Execute a block of code (Action) if a condition is true. The block of code is executed at
most once.
If condition Then
action
End If
Example:
x = ReadLine()
If x Mod 2 = 0
WriteLine("The number is even.")
End If

16) Draw a flow chart to find the largest value among three numbers. (2020)
Ans:
17) Write an algorithm to determine whether a number is odd or even. (2021)
Ans:
Step 1: Start
Step 2: Take Input and Read the Numbers
Step 3: Check that If Number % 2 == 0
If true Then
Print: Your selected Number is an Even Number.
Else
Print: Your selected Number is an Odd Number.
Step 4: End
18) Write down an algorithm and flowchart to calculate the temperature fahrenheit to
Celsius. (2022)
Here's an algorithm to convert temperature from Fahrenheit to Celsius along with a simple flowchart
representation:
Algorithm: Fahrenheit to Celsius Conversion
Step-1: Start
Step-2: Input the temperature in Fahrenheit (F)
Step-3: Calculate the temperature in Celsius (C) using the formula: C = (F - 32) * 5/9
Step-4: Display the temperature in Celsius (C)
Step-5: End
Flowchart: Fahrenheit to Celsius Conversion
CHAPTER 2
STRUCTURED PROGRAMMING LANGUAGE

Sl No. Question Years


2021, 2019,
1 What is a structured programming language?
2020
2 Explain different control structures used in structured programming. 2021
3 Write down the characteristics of structured programming language. 2019, 2020
4 What is C programming?
5 Write down the importance of C language. 2018
2007, 2009,
2012, 2014,
6 Describe the basic structure of a C program.
2016, 2020,
2022
2010, 2013,
7 Write down the steps of executing a C program.
2017
8 Briefly explain different forms of the main() function used in C. 2007
Distinguish between the following pairs: (i) main() and void
9
main(void) (ii) int main() and void main()
10 Where are blank spaces permitted in a C program? 2016
2021, 2017,
11 Why and when do we use the #include and #define directives?
2016
12 Define data types.
2008, 2011,
Describe the four basic data types used in C language. How could we
13 2018, 2020,
extend the range of values they represent?
2022
14 What do you mean by preprocessor directive? Explain it. 2021
15 Define tokens. 2019, 2022
16 Define constant. 2019
17 Define identifiers. 2017, 2019
18 Describe the rules for identifiers. 2007
19 Define keywords. 2017, 2019
20 Define constants and describe different types of constants. 2017
21 How to use constants in a C program?
22 What are the rules of constants?
2011, 2016,
23 What is a variable? 2017, 2019,
2022
24 How to declare & initialize C variables?
25 What is meant by the “value” of a variable? 2011, 2016,
Sl No. Question Years
2017
2008, 2016,
26 Distinguish between local and global variables with examples. 2018, 2020,
2022
27 How do variables and symbolic names differ? 2009
28 Differentiate between variable declaration & definition in C.
29 What are trigraph characters? How are they useful? 2007
30 Write down the purpose of the qualifiers const and volatile. 2011
31 Describe the process of explicit conversion of data types in C. 2012
32 Write down the uses of continue and break. 2020
33 Describe different types of tokens (represent through a table). 2022

CHAPTER 2
STRUCTURED PROGRAMMING LANGUAGE

1) What is structure programming language? (2021,2020,2019)


Ans: Structured programming (sometimes known as modular programming) is a subset of
procedural programming that enforces a logical structure on the program being written to make it
more efficient and easier to understand and modify.

2) Explain different control structures used in structured programming. (2021)


Ans: Control Structures are just a way to specify flow of control in programs. Any algorithm or
program can be clearer and more understood if they use self-contained modules called as logic or
control structures. It basically analyzes and chooses in which direction a program flows based on
certain parameters or conditions. There are three basic types of logic, or flow of control, known as:
1. Sequence logic, or sequential flow
2. Selection logic, or conditional flow
3. Iteration logic, or repetitive flow
Sequential Logic (Sequential Flow)
Sequential logic as the name suggests follows a serial or sequential flow in which the flow depends
on the series of instructions given to the computer. Unless new instructions are given, the modules
are executed in the obvious sequence.

Module A

Module B

Module C

Sequential Control Flow


Selection Logic (Conditional Flow)
Selection Logic simply involves a number of conditions or parameters which decides one out of
several written modules. The structures which use this type of logic are known as Conditional
Structures.

If (condition) then:
[Module A]
[End of If Structure]

For more examples follow – geeksforgeeks.org

Iteration Logic (Repetitive Flow)


The Iteration logic employs a loop which involves a repeat statement followed by a module known
as the body of a loop.
Repeat-For Structure:
Repeat for i = A to N by I:
[Module]
[End of loop]
Repeat-While Structure:
Repeat while condition:
[Module]
[End of Loop]

3) Write down the characteristics of structured programming language.


(2019,2020)
Ans: The main characteristics of Structured Programming are:
✓ The code should be in modular nature.
✓ There should be single entry and single exit for each module ( i.e. no unconditional gates).
✓ At least one construct each for sequence, condition and iteration.

4) What is C programming?
Ans:C is a general-purpose, procedural, imperative computer programming language developed in
1972 by Dennis M. Ritchie at the Bell Telephone Laboratories to develop the UNIX operating system.
C is the most widely used computer language. It keeps fluctuating at number one scale of popularity
along with Java programming language, which is also equally popular and most widely used among
modern software programmers.
5) Write down the importance of C language? (2018)
Ans:
Important features of C programming language
➢ Simple
Every c program can be written in simple English language so that it is very easy to understand and
developed by programmer.
➢ Platform dependent
A language is said to be platform dependent whenever the program is execute in the same
operating system where that was developed and compiled but not run and execute on other
operating system. C is platform dependent programming language.
➢ Portability
It is the concept of carrying the instruction from one system to another system. In C Language .C
file contain source code, we can edit also this code. .exe file contain application, only we can
execute this file. When we write and compile any C program on window operating system that
program easily run on other window based system.
When we can copy .exe file to any other computer which contain window operating system then it
works properly, because the native code of application an operating system is same. But this exe
file is not execute on other operation system.
➢ Powerful
C is a very powerful programming language, it have a wide verity of data types, functions, control
statements, decision making statements, etc.
➢ Structure oriented
C is a Structure oriented programming language.Structure oriented programming language aimed on
clarity of program, reduce the complexity of code, using this approach code is divided into sub-
program/subroutines. These programming have rich control structure.
➢ Modularity
It is concept of designing an application in subprogram that is procedure oriented approach. In c
programming we can break our code in subprogram.
For example we can write a calculator programs in C language with divide our code in subprograms.
➢ Case sensitive
It is a case sensitive programming language. In C programming 'break and BREAK' both are different.
If any language treats lower case latter separately and upper case latter separately than they can be
called as case sensitive programming language [Example c, c++, java, .net are sensitive programming
languages.] other wise it is called as case insensitive programming language [Example HTML, SQL is
case insensitive programming languages].
➢ Middle level language
C programming language can supports two level programming instructions with the combination of
low level and high level language that's why it is called middle level programming language.
➢ Compiler based
C is a compiler based programming language that means without compilation no C program can be
executed. First we need compiler to compile our program and then execute.
➢ Syntax based language
C is a strongly tight syntax based programming language. If any language follow rules and regulation
very strictly known as strongly tight syntax based language. Example C, C++, Java, .net etc. If any
language not follow rules and regulation very strictly known as loosely tight syntax based language.
Example HTML.
➢ Efficient use of pointers
Pointers is a variable which hold the address of another variable, pointer directly direct access to
memory address of any variable due to this performance of application is improve. In C language
also concept of pointer are available.
6) Describe the basic structure of a C program?
(2007, 2008, 2009, 2012, 2014, 2016, 2020,2022)
Ans:
Basic Structure of C Program

➢ Documentation Section
This section consists of comment lines which include the name of programmer, the author and other
details like time and date of writing the program. Documentation section helps anyone to get an
overview of the program.
➢ Link Section
The link section consists of the header files of the functions that are used in the program. It provides
instructions to the compiler to link functions from the system library.
➢ Definition Section
All the symbolic constants are written in definition section. Macros are known as symbolic constants.
➢ Global Declaration Section
The global variables that can be used anywhere in the program are declared in global declaration
section. This section also declares the user defined functions.
➢ Main () Function Section
It is necessarily had one main () function section in every C program. This section contains two parts,
declaration and executable part. The declaration part declares all the variables that are used in
executable part. These two parts must be written in between the opening and closing braces. Each
statement in the declaration and executable part must end with a semicolon (;). The execution of
program starts at opening braces and ends at closing braces.
➢ Subprogram Section
The subprogram section contains all the user defined functions that are used to perform a specific
task. These user defined functions are called in the main() function.

7) Write down the steps of executing a C program. (2010,2013,2017)


Ans:
The compilation and execution process of C can be divided in to multiple steps:
✓ Preprocessing - Using a Preprocessor program to convert C source code in expanded source code.
"#includes" and "#defines" statements will be processed and replaced actually source codes in
this step.
✓ Compilation - Using a Compiler program to convert C expanded source to assembly source code.
✓ Assembly - Using a Assembler program to convert assembly source code to object code.
✓ Linking - Using a Linker program to convert object code to executable code. Multiple units of
object codes are linked to together in this step.
✓ Loading - Using a Loader program to load the executable code into CPU for execution

8) Briefly explain different from of main() function used in C. (2007)


Ans:
The main is a part of every C program permits different types of main statement. Following types
allowed –
✓ main ()
The empty pair of parentheses indicates that the function has no argument.
✓ int main ()
integer means that the function return an integer value to the operating system
✓ void main ()
The keyword void means that the function does not return any information to the operating
system
✓ main(void)
The keyword void means that the function does not return any argument.
✓ void main(void)
The keyword void means that the function does not return any information to the operating
system and the function has no argument.
✓ int main(void)
integer means that the function return an integer value to the operating system and the
function has no argument.
When integer is specified, the last statement of the program must be return “0”

9) Distinguish between the following pairs:-


(i) main() and void main (void)
(ii) int main() and void main ()
Ans:
main()
• The return type of the function "main" is void, i.e. it does not return anything to the OS.
• Nothing has been said about the arguments in main, which means that you can either pass
the arguments to main or not pass anything at all.
void main(void)
• The return type of the function "main" is void, i.e. it does not return anything to the OS.
• "void" means that you're not allowed to pass any argument to the main. Doing this would
result into a compiler error.
int main(void)
• The return type of the function is "int", i.e. it is supposed to return an integer value to the
OS.
• "void" means that you're not allowed to pass any argument to the main. Doing this would
result into a compiler error.
int main()
• The return type of the function is "int", i.e. it is supposed to return an integer value to the
OS.
• Nothing has been said about the arguments in main, which means that you can either pass
the arguments to main or not pass anything at all

10) Where the blank spaces permitted in a C program.(2016)


Ans: C code consists of a number of tokens. A C token is the smallest element that the C compiler
does not break down into smaller parts. A token can be a function name, such as main, or a C
reserved word. All C words should be written continuously. For example, the expressionvoid ma
in(void)is not legal because no blank characters are allowed between the characters a and i in the
word main.
Between tokens, white-space characters (such as blank, tab, or the carriage return) can be inserted,
but this is optional. For example, the linevoid main(void) is equivalent to void main ( void ) or
void main ( void)
In general, it is acceptable to add blanks between tokens but not acceptable to add blanks within
tokens.
11) Why and when do we use the # include and #define directive?
(2016, 2017, 2021)
Ans: # include: In the C Programming Language, the #include directive tells the preprocessor to
insert the contents of another file into the source code at the point where the #include directive is
found. Include directives are typically used to include the C header files for C functions that are held
outsite of the current source file.
Syntax
The syntax for the #include directive in the C language is:
#include <header_file>
Or
#include "header_file"
header_file: The name of the header file that you wish to include. A header file is a C file that
typically ends in ".h" and contains declarations and macro definitions which can be shared between
several source files.

# define:define is used in c language to declare a constant before the main function. Define is
basically a keyword which makes the variable constant and available throughout the whole program.
It's used to ease out calculations for example if you wanted to calculate the area of a circle and at the
same time you wanted to convert radians into degrees, you can use a single constant named pi with a
value of 3.14 and use it to do the calculations, its better to use 1 variable than 2.
If you want to look at the syntax, its like this
#include <stdio.h>
#define pi 3.1415
main()
….
So that's how you declare a constant.

12) Define data types.


Ans: C supports several different types of data, each of which may be represented differently within
the computer’sMemory. The basic data types are listed below. Typical memory requirements are
also given. The memoryRequirements for each data type will determine the permissible range of
values for that data type. Note that theMemory requirements for each data type may vary from one c
compiler to another.
There are four data types in C language. They are,
Types Data Types
Basic data types int, char, float, double
Enumeration data type Enum
Derived data type pointer, array, structure, union
Void data type Void
13) Describe the four basic data types used in C language. How could we extend the range
of values they represent? (2008,2011,2018,2020,2022)
Ans: Basic data types in c language:
Integer data type:
• Integer data type allows a variable to store numeric values.
• “int” keyword is used to refer integer data type.
• The storage size of int data type is 2 or 4 or 8 byte.
• It varies depend upon the processor in the CPU that we use. If we are using 16 bit processor, 2
byte (16 bit) of memory will be allocated for int data type.
• Like wise, 4 byte (32 bit) of memory for 32 bit processor and 8 byte (64 bit) of memory for 64
bit processor is allocated for int datatype.
• Int (2 byte) can store values from -32,768 to +32,767
• Int (4 byte) can store values from -2,147,483,648 to +2,147,483,647.
• If you want to use the integer value that crosses the above limit, you can go for “long int” and
“long long int” for which the limits are very high.

Character data type:


• Character data type allows a variable to store only one character.
• Storage size of character data type is 1. We can store only one character using character data
type.
• “char” keyword is used to refer character data type.
• For example, ‘A’ can be stored using char datatype. You can’t store more than one character using
char data type.
• Please refer C – Strings topic to know how to store more than one characters in a variable.

Float data type:


• The float data type is used for single-precision floating-point numbers.
• It usually uses 4 bytes of memory and represents values with fractional parts. The range of
values is approximately 1.2e-38 to 3.4e38.
Double data type:
Double is used to store double precision floating point values. It is the greater version of float which
can store real numbers with precision up to 15 decimal places.
• The size of the double is 8 bytes.
• The range of double is 1.7×10-308 to 1.7×10+308.
• It can store values up to 15 decimal points without loss of precision.
• The format specifier for double is %lf
The tabular form of basic data types:
Data type Description Memory required
Int Integer quantity 2 bytes or one word
(varies from
One compiler to
another)
Char Single character 1 byte
Float Floating-point number (i.e., a number containing a 1 word (4 bytes)
decimal point andor an exponent)
Double Double-precision floating-point number (i.e., more 2 Words (8 bytes)
significant figures, and an exponent which may
Be larger in magnitude)
Extend the range of values:
Float:
To extend the range of int, you can use modifiers like long int and long long int, which allocate more
memory to store larger values. For example:
long int: This usually extends the range to approximately -9,223,372,036,854,775,808 to
9,223,372,036,854,775,807.
long long int: This further extends the range to approximately –
9,223,372,036,854,775,808 to 9,223,372,036,854,775,807.
Character:
To extend the range of char, you can use the unsigned char data type, which represents positive
values only and can thus represent a larger range of values from 0 to 255.
Float:
To extend the range of float, you can use the double data type, which provides double precision and
uses 8 bytes of memory. The range of values it can represent is approximately 2.3e-308 to 1.7e308.
Double:
To extend the range and precision, you can use the long double data type. This type varies in size and
range depending on the platform and compiler, but it generally provides extended precision beyond
that of double.

14) What do you mean by preprocessor directive? Explain it. (2021)


Ans: The preprocessor will process directives that are inserted into the C source code. These
directives allow additional actions to be taken on the C source code before it is compiled into object
code. Directives are not part of the C language itself. Preprocessor directives begin with a pound (#)
symbol and may have several arguments.
Directive Description Example
#include Include another C file into the current file at the location of #include <stdio.h>
the #include statement prior to compiling the source code.
#define Define a macro which can be used as a constant throughout #define AGE 50
the source code.
#undef Clear a macro which was previously defined. #undef AGE
#if Conditional expresssion which can be used to include source #if AGE > 50
code for compilation.
#ifdef Allows the inclusion of source code if the provided macro #ifdef SOLARIS
identifier has been defined. Equivalent to #if
defined(identifier).
#ifndef Allows the inclusion of source code if the provided macro #ifndef WINDOWS
identifier has not been defined.
#warning Report a warning message and continue preprocessing. #warning Non-critical
error found
#error Report error and stop preprocessing. #error Windows is an
unsupported platform

15) Define tokens. (2019,2022)


Ans:C tokens are the basic buildings blocks in C language which are constructed together to write a C
program.Each and every smallest individual units in a C program are known as C tokens.
C tokens are of six types. They are,
1. Keywords (eg: int, while),
2. Identifiers (eg: main, total),
3. Constants (eg: 10, 20),
4. Strings (eg: “total”, “hello”),
5. Special symbols (eg: (), {}),
6. Operators (eg: +, /,-,*)

16) Define constant. (2017,2019)


Ans: In programming, a constant is a value that never changes. The other type of values that
programs use is variables, symbols that can represent different values throughout the course of a
program.
A constant can be
a number, like 25 or 3.6
a character, like a or $
a character string, like "this is a string"

17) Define identifiers. (2017,2019)


Ans: Identifiers in c language:
Each program elements in a C program are given a name called identifiers. Names given to identify
Variables, functions and arrays are examples for identifiers. Eg. X is a name given to integer variable
in above program.

18) Describe the rules for identifiers. (2007)


Ans:Rules for constructing identifier name in c:
1. First character should be an alphabet or underscore.
2. Succeeding characters might be digits or letter.
3. Punctuation and special characters aren’t allowed except underscore.
4. Identifiers should not be keywords.

19) Define keywords. (2017,2019)


Ans: Keywords in c language:
Keywords are pre-defined words in a C compiler. Each keyword is meant to perform a specific
function in a C program. Since keywords are referred names for compiler, they can’t be used as
variable name.
C language supports 32 keywords which are given below. Click on each keywords below for detail
description and example programs.
Auto Double Case Enum
Int Struct Register Typedef
Const Float Default Goto
Short Unsigned Sizeof Volatile
Break Else Char Extern
Long Switch Return Union
Continue For Do If
Signed Void Static While

20) Define contants.describe different types of constants. (2017)


Ans:
Constants
There are four basic types of constants in c.
They are
1) Integer constants,
2) Floating-point constants,
3) Character Constants
4) String constants and
5) Enumeration constants:
Integer constants:
Integer constants are the numeric constants(constant associated with number) without any
fractional part or exponential part. There are three types of integer constants in C language: decimal
constant(base 10), octal constant(base 8) and hexadecimal constant (base 16).
Decimal digits: 0 1 2 3 4 5 6 7 8 9
Octal digits: 0 1 2 3 4 5 6 7
Hexadecimal digits: 0 1 2 3 4 5 6 7 8 9 A B C D E F.

Floating-point constants:
Floating point constants are the numeric constants that has either fractional form or exponent form.
For example:
-2.0
0.0000234
-0.22E-5

Character constants:
Character constants are the constant which use single quotation around characters. For example: 'a',
'l', 'm', 'F' etc.
Escape Sequences:
Sometimes, it is necessary to use newline(enter), tab, quotation mark etc. in the program which
either cannot be typed or has special meaning in C programming. In such cases, escape sequence are
used. For example: \n is used for newline. The backslash(\) causes "escape" from the normal way
the characters are interpreted by the compiler.

String constants:
String constants are the constants which are enclosed in a pair of double-quote marks. For example:
"good" //string constant
"" //null string constant
" " //string constant of six white space
"x" //string constant having single character.
"Earth is round\n" //prints string with newline
Enumeration constants:
Keyword enum is used to declare enumeration types. For example:
enum color {yellow, green, black, white};
Here, the variable name is color and yellow, green, black and white are the enumeration constants
having value 0, 1, 2 and 3 respectively by default.
21) How to use constants in a c program?
Ans: We can define constants in a C program in the following ways.
1. By “const” keyword
2. By “#define” preprocessor directive

22) What are the rules of constant?


Ans: the following rules apply to all numeric-type constants.
1. Commas and blank spaces cannot be included within the constant.
2. The constant can be preceded by a minus (-) sign if desired. (actually the minus sign is an operator
that Changes the sign of a positive constant, though it can be thought of as a part of the constant
itself.)
3. The value of a constant cannot exceed specified minimum and maximum bounds. For each type of
Constant, these bounds will vary from one c compiler to another. Let us consider each type of
constant individually.

23) What is variable? (2016,2011,2017,2019,2022)


Ans: C variable is a named location in a memory where a program can manipulate the data. This
location is used to hold the value of the variable. The value of the C variable may get change in the
program. C variable might be belonging to any of the data type like int, float, char etc.

24) How to declaring & initializing c variable?


Ans: Variables should be declared in the C program before to use. Memory space is not allocated for
a variable while declaration. It happens only on variable definition.
Variable initialization means assigning a value to the variable.
Type Syntax
Variable declaration Data_type variable_name;
Example: int x, y, z; char flat, ch;
Variable initialization Data_type variable_name = value;
Example: int x = 50, y = 30; char flag = ‘x’, ch=’l’;

25) What is meant by the “value ” of a variable? (2011,2016,2017)


Ans: In programming, a variable is a value that can change, depending on conditions or on
information passed to the program. Typically, a program consists of instruction s that tell the
computer what to do and data that the program uses when it is running. The data consists
of constants or fixed values that never change and variable values (which are usually initialized to
"0" or some default value because the actual values will be supplied by a program's user). Usually,
both constants and variables are defined as certain data type s. Each data type prescribes and limits
the form of the data. Examples of data types include: an integer expressed as a decimal number, or a
string of text characters, usually limited in length.

26) Distinguish between local and global variables with example?


(2008, 2016, 2018, 2020,2022)
Ans:
Global Variable- Local Variable-
1. Global Variable Are That Variable Which is 1. The Variables That Are Declared
Define At The Top Of The Programmer (After Inside A Function Are
Header Files) Called Local Variables.
2. We Can Access From Any Where. 2. We Can’t Access From Any
Where.
3. There Initial Values int=0, float=0.000000, 3. There Initial Values Are Garbage.
char- “Blank Space(Non-Printable Char)”.
4. Scope[Availability] is Through Out Of The Program 4. Scope[Availability] is until that
function or block are executed.
5. Life-Time[Active in Memory] is Until Total 5. Life-Time[Active in Memory] is Until
Program is Executed. That Function is Executed
6. They Are Stored in Data Segment Area,Which is 6. They Are Stored in Stack
Public Area. Hence They Are Also Called as Public
Variables
7. While modifications in a global variable can be 7. it cannot be done with local variables.
made from anywhere
8. in the case of global variables, one cannot be sure in 8. An added advantage of the local
which function it will be modified or when the variable is that it makes it easier to
variable values will be modified. On the other hand, debug and maintain the applications
in a local variable, there is nothing to trace.

27) How do variables and symbolic names differ? (2009)


Ans:
Difference between Symbolic name and variable
==>An instance of an object is created when a variable is declared. Declaration of a symbolic name
just defines a name that can be used in a program.
Example:
int myVar; // an instance of an object
#define MYVAR 25 // definition of a symbolic name
==> Symbolic names are called constant identifier. Since the symbolic names are constant, their
value can’t be change within the program. On the other hand variable value can be changed within
the program.

28) Differentiate between variable declaration & definition in C.


Ans:
A declaration introduces an identifier and describes its type, be it a type, object, or function. A
declaration is what the compiler needs to accept references to that identifier. These are declarations:
extern int bar;
extern int g(int, int);
double f(int, double); // extern can be omitted for function declarations
class foo; // no extern allowed for type declarations

A definition actually instantiates/implements this identifier. It's what the linker needs in order to
link references to those entities. These are definitions corresponding to the above declarations:
int bar;
int g(int lhs, int rhs) {return lhs*rhs;}
double f(int i, double d) {return i+d;}
class foo {};
A definition can be used in the place of a declaration.

29) What are trigraph characters? How are they useful? (2007)
Ans:
A trigraph is a three-character replacement for a special or nonstandard character in a text file. A
trigraph can be used in place of a symbol that is not present on a keyboard or in a character set.
However, some programs cannot properly interpret them.
The following table denotes the most commonly encountered trigraphs in computer applications.
Trigraph Character
represented
??= #
??( [
??) ]
??< {
??> }
??/ \
??' ^
??! ~
Some keyboard does not support some characters. But we can use them by trigraph characters. If a
keyboard does not support square brackets, we can still use them in a program using the trigraph ??(
and ??) .

30) write down the purpose of the qualifiers const and volatile. (2011)
Ans: const
const is used with a datatype declaration or definition to specify an unchanging value
Examples:
const int five = 5;
const double pi = 3.141593;
const objects may not be changed
The following are illegal:
const int five = 5;
const double pi = 3.141593;

pi = 3.2;
five = 6;
volatile
volatile specifies a variable whose value may be changed by processes outside the current program
One example of a volatile object might be a buffer used to exchange data with an external device:
int
check_iobuf(void)
{
volatile int iobuf;
int val;

while (iobuf == 0) {
}
val = iobuf;
iobuf = 0;
return(val);
}
if iobuf had not been declared volatile, the compiler would notice that nothing happens inside the
loop and thus eliminate the loop
31) Describe the process of explicite conversion of data types in c? (2012)
Ans: This process is also called type casting and it is user defined. Here the user can type cast the
result to make it of a particular data type.
The syntax in C:
(type) expression
Type indicated the data type to which the final result is converted.
// C program to demonstrate explicit type casting
#include<stdio.h>
int main()
{
double x = 1.2;

// Explicit conversion from double to int


int sum = (int)x + 1;

printf("sum = %d", sum);

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

32) Write down the uses of Continue and Break. (2020)


Use of break:
• The Break statement is used to exit from the loop constructs.
• The break statement is usually used with the switch statement, and it can also use it within the
while loop, do-while loop, or the for-loop.
• When a break statement is encountered then the control is exited from the loop construct
immediately.
Use of continue:
• The continue statement is not used to exit from the loop constructs.
• The continue statement is not used with the switch statement, but it can be used within the
while loop, do-while loop, or for-loop.
• When the continue statement is encountered then the control automatically passed from the
beginning of the loop statement.
33) Describe different types of token. (2022)
In the C programming language, tokens are the smallest units that make up a program. They are used
to represent various elements such as keywords, identifiers, constants, operators, and more. Here
are the different types of tokens in C:
1. Keywords: Keywords are reserved words in C that have predefined meanings and cannot be used
as identifiers (variable or function names). Examples include `int`, `if`, `else`, `for`, `while`, `return`,
etc.
2. Identifiers: Identifiers are user-defined names used to represent variables, functions, arrays, etc.
They must follow certain rules, such as starting with a letter or underscore, followed by letters,
digits, or underscores. Examples: `count`, `sum`, `my_function`, etc.
3. Constants:
a.Integer Constants: Integer constants are whole numbers without decimal points. They can be
written in decimal (base 10), octal (base 8), or hexadecimal (base 16) formats. Examples: `123`,
`076`, `0xAB`.
b.Floating-point Constants: Floating-point constants are numbers with decimal points. They
include fractional parts and can also be written in scientific notation. Examples: `3.14`, `2.0e-5`.
c.Character Constants: Character constants represent single characters enclosed in single quotes.
Examples: `'A'`, `'7'`, `'\n'`.
d.String Constants: String constants are sequences of characters enclosed in double quotes.
Examples: `"Hello, world!"`, `"C programming"`.
4. Stringizing Operator: This is used in conjunction with the preprocessor to convert a macro
parameter into a string constant.
5.Token Pasting Operator: This is also used in macros to concatenate two tokens into a single
token.
6. Operators: Operators perform operations on variables and values. C has a wide range of
operators, including arithmetic, relational, logical, assignment, bitwise, and more. Examples: `+`, `-`,
`*`, `/`, `==`, `!=`, `&&`, `=`, `<<`, `>>`.
7.Punctuation: Punctuation symbols are used to structure and separate code. Examples: `,`, `;`, `(`,
`)`, `{`, `}`.
8. Comments: Comments are used to add explanatory notes within the code that are ignored by the
compiler. There are two types: single-line comments starting with `//` and multi-line comments
enclosed between `/*` and `*/`.
9.Whitespace: Whitespace characters, such as spaces, tabs, and newlines, are used to separate
tokens and enhance code readability.
10. Preprocessor Directives: Preprocessor directives are used to provide instructions to the
preprocessor, which processes code before actual compilation. Examples: `#include`, `#define`,
`#ifdef`, `#ifndef`.
These tokens form the fundamental building blocks of C programs and are used to define the
structure, behavior, and logic of the code.

CHAPTER 3
OPERATORS AND EXPRESSIONS

Topic SL No. Question Years


2018, 2019,
Operators 1 Define operator. How many types of operator in C?
2022
Topic SL No. Question Years
2011, 2016,
2 Describe the types of operators.
2018
3 Describe arithmetic operators in C.
4 Describe the assignment operators in C.
5 Describe the relational operators in C. 2018, 2020
6 Describe the logical operators in C. 2018, 2020
7 Describe the bitwise operators in C.
8 Describe the Increment/decrement Operators. 2019
9 Describe the special operators in C.
10 Differentiate between x++ and ++x. 2017, 2022
11 Differentiate between a-- and –a. 2018
With examples, describe the rules for ++ and –
12 2021
operators.
13 Describe expression. 2018
Describe symbolic constant. Write down the rules for
14 2021, 2019
declaring symbolic constant?
15 What is control structure?
16 Define Decision Control statement.
17 What is meant by branching?
18 Write down the general form of if statements.
19 Write down the general form of if-else statements. 2017
2017, 2018,
20 Write down the general form of nested if-else.
2021
Define algorithm and flowchart. Draw the flowchart of
21 2017
else if ladder.
Describe nesting of if else statement with flowchart and
22 2007
examples.
Control In what ways does a switch statement differ from an if
23 2008, 2018
Structures statement?
24 Describe if statement with flowchart.
25 Describe if else statement with flowchart.
26 Describe switch statement with flowchart. 2018, 2021
27 Describe nesting of IF statement.
2016, 2017,
28 What is looping process? 2018, 2020,
2021
29 Briefly describe different types of loop. 2017
30 Describe While loop with example. 2021
31 Describe for loop with example. 2018
32 Describe Nested for loop with example.
Topic SL No. Question Years
33 Describe do While loop with example.
Distinguish between counter controlled and sentinel
34 2016
controlled loop.
Differentiate between entry controlled loop and exit
35 2017, 2021
controlled loop.
36 Describe entry controlled loop and exit controlled loop. 2018, 2020
37 Describe infinite loop & Time delay loop. 2012, 2020
38 Difference between break and continue? 2021, 2010

CHAPTER 3
OPERATORS AND EXPRESSIONS
1) Define operator. How many types of operator in C?
Or, What are the different types of operator used in C language? (2018,2019,2022)
Solution: The symbols which are used to perform logical and mathematical operations in a C
program are called C operators. These C operators join individual constants and variables to form
expressions. Operators, functions, constants and variables are combined together to form
expressions.
Consider the expression A + B * 5. where, +, * are operators, A, B are variables, 5 is constant and A +
B * 5 is an expression.
Types of c operators:
C language offers many types of operators. They are,
1. Arithmetic operators
2. Assignment operators
3. Relational operators
4. Logical operators
5. Bit wise operators
6. Conditional operators (ternary operators)
7. Increment/decrement operators
8. Special operators
2) Describe the types of operators. (2011,2016,2018)
Types of Operators Description
Arithmetic_operators These are used to perform mathematical calculations like addition,
subtraction, multiplication, division and modulus
Assignment_operators These are used to assign the values for the variables in C programs.

Relational operators These operators are used to compare the value of two variables.

Logical operators These operators are used to perform logical operations on the given
two variables.
Bit wise operators These operators are used to perform bit operations on given two
variables.
Conditional (ternary) Conditional operators return one value if condition is true and
operators returns another value is condition is false.
Increment/decrement These operators are used to either increase or decrease the value of
operators the variable by one.
Special operators &, *, sizeof( ) and ternary operators.

3) Describe arithmetic operators in c


Solution: C Arithmetic operators are used to perform mathematical calculations like addition,
subtraction, multiplication, division and modulus in C programs.
Arithmetic Operators/Operation Example
+ (Addition) A+B
– (Subtraction) A-B
* (multiplication) A*B
/ (Division) A/B
% (Modulus) A%B
Example program for c arithmetic operators:
In this example program, two values “40” and “20” are used to perform arithmetic operations such
as addition, subtraction, multiplication, division, modulus and output is displayed for each operation.
#include <stdio.h>

int main()
{
int a=40,b=20, add,sub,mul,div,mod;
add = a+b;
sub = a-b;
mul = a*b;
div = a/b;
mod = a%b;
printf("Addition of a, b is : %d\n", add);
printf("Subtraction of a, b is : %d\n", sub);
printf("Multiplication of a, b is : %d\n", mul);
printf("Division of a, b is : %d\n", div);
printf("Modulus of a, b is : %d\n", mod);
}
OUTPUT:
Addition of a, b is : 60
Subtraction of a, b is : 20
Multiplication of a, b is :
800
Division of a, b is : 2
Modulus of a, b is : 0

4) Describe the assignment operators in c.


In C programs, values for the variables are assigned using assignment operators.
For example, if the value “10” is to be assigned for the variable “sum”, it can be assigned as “sum =
10;”
There are 2 categories of assignment operators in C language. They are,
1. Simple assignment operator ( Example: = )
2. Compound assignment operators ( Example: +=, -=, *=, /=, %=, &=, ^= )
Operators Example/Description
= sum = 10;
10 is assigned to variable sum
+= sum += 10;
This is same as sum = sum + 10
-= sum -= 10;
This is same as sum = sum – 10
*= sum *= 10;
This is same as sum = sum * 10
/= sum /= 10;
This is same as sum = sum / 10
%= sum %= 10;
This is same as sum = sum % 10
&= sum&=10;
This is same as sum = sum & 10
^= sum ^= 10;
This is same as sum = sum ^ 10
Example program for c assignment operators:
In this program, values from 0 – 9 are summed up and total “45” is displayed as output.
Assignment operators such as “=” and “+=” are used in this program to assign the values and to sum
up the values.
# include <stdio.h>

intmain()
{
intTotal=0,i;
for(i=0;i<10;i++)
{
Total+=i;// This is same as Total = Toatal+i
}
printf("Total = %d",Total);
}
OUTPUT:

Total = 45

5) Describe the relational operators in c. (2018,2020)


Solution: Relational operators are used to find the relation between two variables. i.e. to compare
the values of two variables in a C program.
Operators Example/Description
> x > y (x is greater than y)
< x < y (x is less than y)
>= x >= y (x is greater than or equal to y)
<= x <= y (x is less than or equal to y)
== x == y (x is equal to y)
!= x != y (x is not equal to y)
Example program for relational operators in c:
In this program, relational operator (==) is used to compare 2 values whether they are equal are not.
If both values are equal, output is displayed as ” values are equal”. Else, output is displayed as “values
are not equal”.
#include <stdio.h>

intmain()
{
intm=40,n=20;
if(m==n)
{
printf("m and n are equal");
}
else
{
printf("m and n are not equal");
}
}

OUTPUT:
m and n are not equal
6) Describe the logical operators in c. (2018,2020)
Solution: These operators are used to perform logical operations on the given expressions. There
are 3 logical operators in C language. They are, logical AND (&&), logical OR (||) and logical NOT (!).
Operators Example/Description
&& (logical AND) (x>5)&&(y<5)
It returns true when both conditions are true
|| (logical OR) (x>=10)||(y>=10)
It returns true when at-least one of the condition is true
! (logical NOT) !((x>5)&&(y<5))
It reverses the state of the operand “((x>5) && (y<5))”
If “((x>5) && (y<5))” is true, logical NOT operator makes it false
EXAMPLE PROGRAM FOR LOGICAL OPERATORS IN C:
#include <stdio.h>

intmain()
{
intm=40,n=20;
into=20,p=30;
if(m>n&&m!=0)
{
printf("&& Operator : Both conditions are true\n");
}
if(o>p||p!=20)
{
printf("|| Operator : Only one condition is true\n");
}
if(!(m>n&&m!=0))
{
printf("! Operator : Both conditions are true\n");
}
else
{
printf("! Operator : Both conditions are true. "\
"But, status is inverted as false\n");
}
}
Output:
&& Operator : Both conditions are true
|| Operator : Only one condition is true
! Operator : Both conditions are true. But,
status is inverted as false
In this program, operators (&&, || and !) are used to perform logical operations on the given
expressions.
• && operator – “if clause” becomes true only when both conditions (m>n and m! =0) is true. Else,
it becomes false.
• || Operator – “if clause” becomes true when any one of the condition (o>p || p!=20) is true. It
becomes false when none of the condition is true.
• ! Operator – It is used to reverses the state of the operand.
• If the conditions (m>n && m!=0) is true, true (1) is returned. This value is inverted by “!”
operator.
• So, “! (m>n and m! =0)” returns false (0).

7) Describe the bit wise operators in c.


Solution: These operators are used to perform bit operations. Decimal values are converted into
binary values which are the sequence of bits and bit wise operators work on these bits.
Bit wise operators in C language are & (bitwise AND), | (bitwise OR), ~ (bitwise OR), ^ (XOR), << (left
shift) and >> (right shift).

Truth table for bit wise operation & bit wise operators:

Below are the bit-wise operators and their name in c language.


1) & – Bitwise AND
2) | – Bitwise OR
3) ~ – Bitwise NOT
4) ^ – XOR
5) << – Left Shift
6) >> – Right Shift

Consider x=40 and y=80. Binary form of these values are given below.
x = 00101000
y= 01010000
All bit wise operations for x and y are given below.
1) x&y = 00000000 (binary) = 0 (decimal)
2) x|y = 01111000 (binary) = 120 (decimal)
3) ~x = 11111111111111111111111111 11111111111111111111111111111111010111 = -
41 (decimal)
4) x^y = 01111000 (binary) = 120 (decimal)
5) x << 1 = 01010000 (binary) = 80 (decimal)
6) x >> 1 = 00010100 (binary) = 20 (decimal)
Example program for bit wise operators in c:
In this example program, bit wise operations are performed as shown above and output is displayed
in decimal format.
#include <stdio.h>
intmain()
{
intm=40,n=80,AND_opr,OR_opr,XOR_opr,NOT_opr;
AND_opr=(m&n);
OR_opr=(m|n);
NOT_opr=(~m);
XOR_opr=(m^n);
printf("AND_opr value = %d\n",AND_opr);
printf("OR_opr value = %d\n",OR_opr);
printf("NOT_opr value = %d\n",NOT_opr);
printf("XOR_opr value = %d\n",XOR_opr);
printf("left_shift value = %d\n",m<<1);
printf("right_shift value = %d\n",m>>1);
}
Output:
AND_opr value = 0
OR_opr value = 120
NOT_opr value = -41
XOR_opr value = 120
left_shift value = 80
right_shift value = 20

8) Describe the Increment/decrement Operators.(2019)


Solution: Increment operators are used to increase the value of the variable by one and decrement
operators are used to decrease the value of the variable by one in C programs.
Syntax:
Increment operator: ++var_name; (or) var_name++;
Decrement operator: – -var_name; (or) var_name – -;
Example:
Increment operator : ++ i ; i ++ ;
Decrement operator : – – i ; i – – ;

Example program for increment operators in c:


In this program, value of “i” is incremented one by one from 1 up to 9 using “i++” operator and
output is displayed as “1 2 3 4 5 6 7 8 9”.
//Example for increment operators
#include <stdio.h>
intmain()
{
inti=1;
while(i<10)
{
printf("%d ",i);
i++;
}
}
OUTPUT:

123456789

Example program for decrement operators in c:


In this program, value of “I” is decremented one by one from 20 up to 11 using “i–” operator and
output is displayed as “20 19 18 17 16 15 14 13 12 11”.
//Example for decrement operators

#include <stdio.h>
intmain()
{
inti=20;
while(i>10)
{
printf("%d ",i);
i--;
}
}
OUTPUT:
20 19 18 17 16 15 14
13 12 11

9) Desccribe the special operators in c:


Solution: Below are some of the special operators that the C programming language offers.
Operators Description
& This is used to get the address of the variable.
Example : &a will give address of a.
* This is used as pointer to a variable.
Example : * a where, * is pointer to the variable a.
Sizeof () This gives the size of the variable.
Example : size of (char) will give us 1.
Example program for & and * operators in c:
In this program, “&” symbol is used to get the address of the variable and “*” symbol is used to get
the value of the variable that the pointer is pointing to. Please refer C – pointer topic to know more
about pointers.
#include <stdio.h>
int main()
{
int *ptr, q;
q = 50;
/* address of q is assigned to ptr */
ptr = &q;
/* display q's value using ptr variable */
printf("%d", *ptr);
return 0;
}
Output:
50
10) Differentiate between x++ and ++x .
Or, Differentiate between y++ and ++y. (2017,2022)
++x x++
1) ++x is the pre-increment. 1) x++ is post increment.
2) The value of x is first incremented and then 2) The value of x is assigned first and then
assigned to x. incremented.
3) In the case of y =++x , y will become (x+1), x 3) In the case of y = x++ , y will become x and x
will become (x+1). Which meansthat prefix willbecome (x+1). Which also means that
adds the value before processing the postfix process the data/command first before
data/command. it adds the value
4) For example 4) For example
int x=2; int x=2;
++x; x++;
Printf(“%d”,x); Printf(“%d”,x);
Output= 3 Output= 3
Here x will be before 2 then increment 1 and
display the result 3.

11) Differentiate between a-- and –a. (2018)


--a a--
1) –a is the pre- decrement. 1) a-- is post decrement.
2) The value of a is first decrement and then 2) The value of a is assigned first and then
assigned to x. decrement.
3) In the case of b =--a , b will become (a-1), a 3)In the case of b = a-- , b will become a and a
will become (a-1). Which meansthat prefix willbecome (a-1). Which also means that postfix
minus the value before processing the process the data/command first before it minus
data/command. the value
4) For example 4)For example
int a=2; int a=2;
--a; a--;
Printf(“%d”,a); Printf(“%d”,a);
Output= 1 Output= 1
Here a will be before 2 then decrement 1 and
display the result 1.
12) With examples describe the rules for ++ and – operator. (2021)
Ans: For description follow the question number 10 and 11 and add this example
int main() { int main() {
int a = 5, b = 8; int a = 5, b = 8;
printf("%d\n", a++); printf("%d\n", a--);
printf("%d\n", ++b); printf("%d\n", --b);
return 0; return 0;
} }
Output: 5 and 9 Output: 5 and 7
13) Describe expression (2018)
Solution: Expressions
An expression represents a single data item, such as a number or a character. The expression may
consist of a Single entity, such as a constant, a variable, an array element or a reference to a function.
It may also consistOf some combination of such entities, interconnected by one or more operators.
The use of expressions Involving operators is particularly common in c, as in most other
programming languages. Expressions can also represent logical conditions that are either true or
false. However, in c the Conditions true and false are represented by the integer values 1 and
0,respectively. Hence logical-type Expressions really represent numerical quantities.
Example several simple expressions are shown below.
a+b
x=y
c=a+b
x <= y
x==y
++i
The first expression involves use of the addition operator (+). This expression represents the sum
of the values Assigned to the variables a and b. The second expression involves the assignment
operator (=). In this case, the expression causes the value Represented by y to be assigned to x. We
have already encountered the use of this operator in several earlier examples

14) Describe symbolic constant. Write down the rules for declaring symbolic constant?
(2019,2021)
Ans: Symbolic constants
Asymbolic constant is a name that substitutes for a sequence of characters. The characters may
represent a Numeric constant, a character constant or a string constant. Thus, a symbolic constant
allows a name to appear In place of a numeric constant, a character constant or a string. When a
program is compiled, each occurrence Of a symbolic constant is replaced by its corresponding
character sequence. Symbolic constants are usually defined at the beginning of a program. The
symbolic constants may then Appear later in the program in place of the numeric constants,
character constants, etc. That the symbolic Constants represent.
A symbolic constant is defined by writing
#define name text
Where name represents a symbolic name, typically written in uppercase letters, and text represents
the Sequence of characters that is associated with the symbolic name.
#define name text The rules for constructing the name part are the same as that for constructing
identifiers. However, typically symbolic names are written in uppercase letters The text part can be a
character constant, numeric constant or string constant
# must be the first character in the line
#define statements can appear anywhere within the program but before the symbolic constant is
referenced in the program. Normally they are placed at the beginning of the program
#define statements must not end with a semicolon, since they are preprocessor directives (like
#include) and not executable C statements

15) What is control structure? (2019)


Ans: Control Structure: A statement that is used to control the flow of execution in a program is
called control structure. It combines instruction into logical unit. Logical unit has one entry point and
one exit point.
Types of control structures
1. Sequence
2. Selection
3. Repetition
4. Function call

16) Define Decision Control statement


Solution: decision control statements (if-else and nested if) is a group of statements are executed
when condition is true. If condition is false, then else part statements are executed.
There are 3 types of decision making control statements in C language. They are,
1. if statements
2. if else statements
3. nested if statements

17) What is meant by branching?


Solution: Branching.
When an "Algorithm" makes a choice to do one of two (or more things) this is called branching.
The C language programs follows a sequential form of execution of statements. Many times it is
required to alter the flow of sequence of instructions. C language provides statements that can alter
the flow of a sequence of instructions. These statements are called as control statements. To jump
from one part of the program to another,these statements help. The control transfer may be
unconditional or conditional. Branching Statemnt are of following categories:
1) If Statement
2) The If else Statement
3) Compound Relational tests
4) Nested if Statement
5) Switch Statement

18) Write down the general form of if statements.


Solution:An if statement consists of a Boolean expression followed by one or more statements.
Syntax
The syntax of an 'if' statement in C programming language is −
if(boolean_expression) {
/* statement(s) will execute if the boolean expression is true */
}
If the Boolean expression evaluates to true, then the block of code inside the 'if' statement will be
executed. If the Boolean expression evaluates to false, then the first set of code after the end of the
'if' statement (after the closing curly brace) will be executed.
C programming language assumes any non-zero and non-null values as true and if it is
either zero or null, then it is assumed as false value.
Flow Diagram

19) Write down the general form of if-else statements, (2017)


Solution : An if statement can be followed by an optional else statement, which executes when the
Boolean expression is false.

Syntax
The syntax of an if...else statement in C programming language is −
if(boolean_expression) {
/* statement(s) will execute if the boolean expression is true */
} else {
/* statement(s) will execute if the boolean expression is false */
}
If the Boolean expression evaluates to true, then the if block will be executed, otherwise, the else
block will be executed.
C programming language assumes any non-zero and non-null values as true, and if it is
either zero or null, then it is assumed as false value.
Flow Diagram
20) Write down the general form of nested if-else. (2017,2018,2021)
Ans : Nested If..else statement
When an if else statement is present inside the body of another “if” or “else” then this is called nested
if else.
Syntax of Nested if else statement:
if(condition) {
//Nested if else inside the body of "if"
if(condition2) {
//Statements inside the body of nested "if"
}………………………..
else {
//Statements inside the body of nested "else"
}
}
else {
//Statements inside the body of "else"
}
Flow Diagram
21) Define algorithm and flowchart. Draw the flowchart of else ….if ladder.
(2017)
Solution: The else ….if ladder can be shown by the following flowchart,
22) Describing nesting of if else statement with flowchart and examples (2007)
Nesting of if....else statement:
When a series of conditions are to be checked, we may have to use more than one if... else statement
in the nested form.
if (test condition 1)
{
if (test condition 2)
{
statement block 1;
}
else
{
statement block 2;
} statement m;
}
else
{
if (test condition 3)
{
statement block 3;
}
else
{
statement block 4
} statement n;
}
statement x;
If the test condition 1 is true then, test condition 2 is checked and if it is true, then the statement
block 1 will be executed and the control will be transferred to statement m and it will executed and
then statement x will be executed.
If the test condition 1 is true but test condition 2 is false, statement block 2 will be executed and the
control is transferred to statement m and it will be executed and then statement x will be executed.
If the test condition 1 is false, then test condition 3 is checked and if it is true, statement block 3 will
be executed, then control is transferred to statement n and it will be executed and then statement x
will be executed.
If the test condition 1 is false and test condition 3 is also false, statement block 4 will be executed,
then the control is transferred to statement n and it will be executed and then statement x is
executed.
23) In what ways does a switch statement differ from an if statement.
(2008, 2018)
Solution:
BASIS FOR IF-ELSE SWITCH
COMPARISON
Basic Which statement will be executed 1. Which statement will be executed is
depend upon the output of the decided by user.
expression inside if statement.
Expression if-else statement uses multiple 2. switch statement uses single expression
statement for multiple choices. for multiple choices.
Testing if-else statement test for equality 3. switch statement test only for equality.
as well as for logical expression.
Evaluation if statement evaluates integer, 4. switch statement evaluates only
character, pointer or floating- character or integer value.
point type or boolean type.
Sequence of Either if statement will be 5. switch statement execute one case after
Execution executed or else statement is another till a break statement is
executed. appeared or the end of switch statement
is reached.
Default Execution If the condition inside if 6. If the condition inside switch statements
statements is false, then by does not match with any of cases, for
default the else statement is that instance the default statements is
executed if created. executed if created.
Editing It is difficult to edit the if-else 7. It is easy to edit switch cases as, they are
statement, if the nested if-else recognized easily.
statement is used.

24) Describing if statement with flowchart.


Solution: An if statement consists of a Boolean expression followed by one or more statements.
Syntax
The syntax of an 'if' statement in C programming language is −
if(boolean_expression) {
/* statement(s) will execute if the boolean expression is true */
}
If the Boolean expression evaluates to true, then the block of code inside the 'if' statement will be
executed. If the Boolean expression evaluates to false, then the first set of code after the end of the
'if' statement (after the closing curly brace) will be executed.
C programming language assumes any non-zero and non-null values as true and if it is
either zero or null, then it is assumed as false value.
Flow Diagram
25) Describing if else statement with flowchart
Ans: An if statement can be followed by an optional else statement, which executes when the
Boolean expression is false.
Syntax
The syntax of an if...else statement in C programming language is −
if(boolean_expression) {
/* statement(s) will execute if the boolean expression is true */
} else {
/* statement(s) will execute if the boolean expression is false */
}
If the Boolean expression evaluates to true, then the if block will be executed, otherwise, the else
block will be executed.
C programming language assumes any non-zero and non-null values as true, and if it is
either zero or null, then it is assumed as false value.
Flow Diagram
26) Describing switch statement with flowchart (2018)
Solution: A switch statement allows a variable to be tested for equality against a list of values. Each
value is called a case, and the variable being switched on is checked for each switch case.
Syntax-The syntax for a switch statement in C programming language is as follows −
switch(expression) {
case constant-expression :
statement(s);
break; /* optional */
case constant-expression :
statement(s);
break; /* optional */
/* you can have any number of case statements */
default : /* Optional */
statement(s);}
The following rules apply to a switch statement −
1) The expression used in a switch statement must have an integral or enumerated type, or be of a
class type in which the class has a single conversion function to an integral or enumerated type.
2) You can have any number of case statements within a switch. Each case is followed by the value
to be compared to and a colon.
3) The constant-expression for a case must be the same data type as the variable in the switch,
and it must be a constant or a literal.
4) When the variable being switched on is equal to a case, the statements following that case will
execute until a break statement is reached.
5) When a break statement is reached, the switch terminates, and the flow of control jumps to the
next line following the switch statement.
6) Not every case needs to contain a break. If no break appears, the flow of control will fall
through to subsequent cases until a break is reached.
7) A switch statement can have an optional default case, which must appear at the end of the
switch. The default case can be used for performing a task when none of the cases is true.
No break is needed in the default case.
Flow Diagram
27) Describing nesting of IF statement
Solution: It is always legal in C programming to nest if-else statements, which means you can use
one if or else if statement inside another if or else if statement(s).
Syntax
The syntax for a nested if statement is as follows −
if( boolean_expression 1) {

/* Executes when the boolean expression 1 is true */


if(boolean_expression 2) {
/* Executes when the boolean expression 2 is true */
}
}
You can nest else if...else in the similar way as you have nested ifstatements.

28) What is looping process? (2016,2017,2018,2020,2021)


Solution: In computer programming, a loop or looping process is a sequence of instruction s that is
continually repeated until a certain condition is reached. Typically, a certain process is done, such as
getting an item of data and changing it, and then some condition is checked such as whether a
counter has reached a prescribed number. If it hasn't, the next instruction in the sequence is an
instruction to return to the first instruction in the sequence and repeat the sequence. If the condition
has been reached, the next instruction "falls through" to the next sequential instruction or branches
outside the loop. A loop is a fundamental programming idea that is commonly used in writing
programs.

29) Briefly describe different types of loop. (2017)


Or, Make a comparisons in terms of their functions, of the for loop, while loop and do-
while loop with example. (2016)
Solution: the sequence of statements to be executed is kept inside the curly braces { } known as
the Loop body. After every execution of the loop body, condition is verified, and if it is found to
be true the loop body is executed again. When the condition check returns false, the loop body is not
executed, and execution breaks out of the loop.
Types of Loop
There are 3 types of Loop in C language, namely:
1. While loop: In while loop control statement, loop is executed until condition becomes false.
2. For loop: In for loop control statement, loop is executed until condition becomes false.
3. Dowhile loop : In do..while loop control statement, while loop is executed irrespective of the
condition for first time. Then 2nd time onwards, loop is executed until condition becomes false.

30) Describe While loop with example. (2021)


Solution:
In while loop control statement, loop is executed until condition becomes false.
While loop can be addressed as an entry control loop. It is completed in 3 steps.
Variable initialization.(e.g int x = 0;)
condition(e.g while(x <= 10))
Variable increment or decrement ( x++ or x-- or x = x + 2 )
Syntax :
variable initialization;
while(condition)
{
statements;
variable increment or decrement;
}
Example: Program to print first 10 natural numbers
#include<stdio.h>
void main()
{
int x;
x =1;
while(x <=10)
{
printf("%d\t", x);
/* below statement means, do x = x+1, increment x by 1*/
x++;
}
}
Output
1 2 3 4 5 6 7 8 9 10

31) Describe for loop with example. (2018)


Ans: The Infinite Loop: A loop that repeats indefinitely and never terminates is called an Infinite
loop.
In the following examples, we demonstrate what kind of mistakes can lead to an infinite loop:
Example:
short int i;
for (i = 32765; i < 32768; i++)
{
printf("%d\n", i);
}
Examples of defining infinite loop
There are numerous ways to write an infinite loop. Here I am listing some of the general preferred
infinite loop structures. You can use any of the below approach to define infinite loop.
• for loop
• while loop
• do while loop
• go to statement
• C macros
Define infinite for loop
for(;;)
{
// Do your task here
}
All parts of a for loop is optional. In the above loop structure there is no condition to check and
terminate the loop. Hence, the loop iterates indefinitely.

Define infinite while loop


while(1)
{
// Do your task here
}
In the above while loop inside the loop condition i.e. while(1) you can use any non-zero integer to
make it infinite loop. A non-zero integer in C is treated as true whereas zero is treated as false.

Define infinite do...while loop


do
{
// Do your task here
} while(1); // You can use any non-zero integer
Define infinite loop using goto statement
infinite_loop:
// Do your task here
goto infinite_loop;
In above program the goto statement transfer program control indefinitely to the infinite_loop label.
Define infinite loop using macros
#define FOREVER for(;;)

int main()
{
FOREVER
{
// Do your task here
}

return 0;
}
Time delay loop: Time delay loops are often used in programs. These are loops that have no other
function than to kill time. Delay loops can be created by specifying an empty target statement.
For example:for(x=0;x<1000;x++);
This loop increments x one thousand times but does nothing else. The semicolon that terminates the
line is necessary because the for expects a statement.

32) Describe Nested for loop with example.


Solution: for loop is used to execute a set of statements repeatedly until a particular condition is
satisfied. We can say it is an open ended loop.. General format is,
for(initialization; condition; increment/decrement)
{
statement-block;
}
In for loop we have exactly two semicolons, one after initialization and second after the condition. In
this loop we can have more than one initialization or increment/decrement, separated using comma
operator. But it can have only one condition.
The for loop is executed as follows:
It first evaluates the initialization code.Then it checks the condition expression.If it is true, it
executes the for-loop body.Then it evaluate the increment/decrement condition and again follows
from step 2.When the condition expression becomes false, it exits the loop.
Example: Program to print first 10 natural numbers
#include<stdio.h>
void main()
{
int x;
for(x =1; x <=10; x++)
{
printf("%d\t", x);
}
}
Output
1 2 3 4 5 6 7 8 9 10

33)Describe do While loop with example.


Solution: In some situations it is necessary to execute body of the loop before testing the condition.
Such situations can be handled with the help of do-while loop. do statement evaluates the body of
the loop first and at the end, the condition is checked using while statement. It means that the body
of the loop will be executed at least once, even though the starting condition inside while is
initialized to be false. General syntax is,
do
{
.....
.....
}
while(condition)
Example: Program to print first 10 multiples of 5.
#include<stdio.h>

void main()
{
int a, i;
a =5;
i =1;
do
{
printf("%d\t", a*i);
i++;
}
while(i <=10);
}
Output
5 10 15 20 25 30 35 40 45 50
34)Distinguish between counter controlled and sentinel controlled loop. (2016)
Ans:
Topics Counter controlled loop Sentinel controlled loop
Number of Previously known number of Unknown number of execution occurs.
execution execution occurs.
Condition Condition variable is known as Condition variable is known as sentinel
variable counter variable. variable.
Value and The value of the variable and the The limitation for the condition variable
limitation of limitation of the condition for the is strict but the value of the variable
variable variable both are strict. varies in this case.
= = = = =Examples
=== ======
sum = 0; do
n = 1; {
while (n <= 10) printf(“Input a number.\n”);
{ scanf("%d", &num);
sum = sum + n*n; }
n = n+ 1; while(num>0);
} ======
========

35) Differentiate between entry controlled loop and exit controlled loop.
(2017, 2021)
Solution:
Entry Controlled Loop Exit Controlled Loop
1. Test condition is checked first, and then loop 1. Loop body will be executed first, and then
body will be executed. condition is checked.
2. If Test condition is false, loop body will not be 2. If Test condition is false, loop body will be
executed. executed once.
3. for loop and while loop are the examples of 3. do while loop is the example of Exit
Entry Controlled Loop. controlled loop.
4. Entry Controlled Loops are used when 4. Exit Controlled Loop is used when checking
checking of test condition is mandatory of test condition is mandatory after
before executing loop body. executing the loop body.
36) Describe entry controlled loop and exit controlled loop. (2018,2012)
Solution: Entry controlled loop - The loop which has a condition check at the entrance of the
loop, the loop executes only and only if the condition is satisfied is called as entry control loop.
EX-
1. while loop
2. For loop
2) Exit controlled loop - The loop which keeps on executing until a particular condition is satisfied
and when the condition is satisfied according to the criteria the loop exits, this is known as exit
controlled loop.
EX-
1. While loop (during polling)

37)Describe infinite loop & Time delay loop.(2012)


Ans:
A loop that repeats indefinitely and never terminates is called an Infinite loop.
Most of the time we create infinite loops by mistake. However, this doesn’t mean that the infinite
loops are not useful. Infinite loops are commonly used in programs that keep running for long
periods of time until they are stopped like the web server.
In the following examples, we demonstrate what kind of mistakes can lead to an infinite loop:
short int i;
for (i = 32765; i < 32768; i++)
{
printf("%d\n", i);
}
Time delay in C
In this post, we will see how to give a time delay in C code. Basic idea is to get current clock and add
the required delay to that clock, till current clock is less then required clock run an empty loop.
Here is implementation with a delay function.
38)Difference between, break and continue?(2010)
Difference Between break and continue
break continue
A break can appear in both switch and loop (for, A continue can appear only in loop (for, while,
while, do) statements. do) statements.
A break causes the switch or loop statements to A continue doesn't terminate the loop, it causes
terminate the moment it is executed. Loop or the loop to go to the next iteration. All iterations
switch ends abruptly when break is of the loop are executed even if continue is
encountered. encountered. The continue statement is used to
skip statements in the loop that appear after the
continue.
The break statement can be used in both switch The continue statement can appear only in loops.
and loop statements. You will get an error if this appears in switch
statement.
When a break statement is encountered, it When a continue statement is encountered, it
terminates the block and gets the control out of gets the control to the next iteration of the loop.
the switch or loop.
A break causes the innermost enclosing loop or A continue inside a loop nested within a switch
switch to be exited immediately. causes the next loop iteration.
CHAPTER 4
FUNCTIONS AND PROGRAM STRUCTURE

1) What is a function? Are functions required when writing a c program?


(2018, 2022)
Solution: A function will process information that is passed to it from the calling portion of the
program, and return a single value.
Information is passed to the function via special identifiers called arguments (alsocalled
parameters), and returned via the return statement.
A function definition has two principal components: the first line (including the argument
declarations), and The body of the function.
The syntax of the function is,
Data- type name( type 1 arg 1, type 2 arg 2, . . ., type n arg n)
{
……….
Function body
……….
Return expression
}
Uses of c functions:
1) C functions are used to avoid rewriting same logic/code again and again in a program.
2) There is no limit in calling c functions to make use of same functionality wherever required.
3) We can call functions any number of times in a program and from any place in a program.
4) A large c program can easily be tracked when it is divided into functions.
5) The core concept of c functions are, re-usability, dividing a big task into small pieces to achieve
the functionality and to improve understandability of very large c programs.

2) State three advantages to the use of functions.


Solution: The three advantages to the use of functions are :-
1. The use of programmer-defined functions allows a large program to be broken down into a
number of smaller, self-contained components, each of which has some unique, identifiable
purpose. Thus
2. The use of a finction avoids the need for redundant (repeated) programming of the same
instructions.
3. The use of functions also enables a programmer to build a customized library of frequently used
routines or of routines containing system-dependent features.

3) What is meant by a function call? From what parts of a program can a function be called?
Solution: A function can be accessed (i.e., called) by specifling its name, followed by a list of
arguments enclosed in Parentheses and separated by commas. If the function call does not require
any arguments, an empty pair of Parentheses must follow the name of the function. The function call
may be a part of a simple expression (such as an assignment statement), or it may be one of the
operands within a more complex expression.

4) How to call c functions in a program?


Or What do you mean by call by value and call by reference. (2018, 2020, 2021)
Solution: There are two ways that a C function can be called from a program. They are,
• Call by value
• Call by reference
1. Call by value:
In call by value method, the value of the variable is passed to the function as parameter.The value of
the actual parameter can not be modified by formal parameter.
Different Memory is allocated for both actual and formal parameters. Because, value of actual
parameter is copied to formal parameter.
Actual parameter – This is the argument which is used in function call.
Formal parameter – This is the argument which is used in function definition
Example program for c function (using call by value):
In this program, the values of the variables “m” and “n” are passed to the function “swap”.
These values are copied to formal parameters “a” and “b” in swap function and used.
1 #include<stdio.h>
2 // function prototype, also called function declaration
3 voidswap(inta,intb);
4
5 intmain()
6 {
7 intm=22,n=44;
8 // calling swap function by value
9 printf(" values before swap m = %d \nand n = %d",m,n);
10 swap(m,n);
11 }
12
13 voidswap(inta,intb)
14 {
15 inttmp;
16 tmp=a;
17 a=b;
18 b=tmp;
19 printf(" \nvalues after swap m = %d\n and n = %d",a,b);
20 }
OUTPUT:
values before swap m = 22
and n = 44
values after swap m = 44
and n = 22

2. Call by reference:
In call by reference method, the address of the variable is passed to the function as parameter.
The value of the actual parameter can be modified by formal parameter.
Same memory is used for both actual and formal parameters since only address is used by both
parameters.
Example program for c function (using call by reference):
In this program, the address of the variables “m” and “n” are passed to the function “swap”.
These values are not copied to formal parameters “a” and “b” in swap function.
Because, they are just holding the address of those variables.
This address is used to access and change the values of the variables.
1 #include<stdio.h>
2 // function prototype, also called function declaration
3 voidswap(int*a,int*b);
4
5 intmain()
6 {
7 intm=22,n=44;
8 // calling swap function by reference
9 printf("values before swap m = %d \n and n = %d",m,n);
10 swap(&m,&n);
11 }
12
13 voidswap(int*a,int*b)
14 {
15 inttmp;
16 tmp=*a;
17 *a=*b;
18 *b=tmp;
19 printf("\n values after swap a = %d \nand b = %d",*a,*b);
20 }

OUTPUT:
values before swap m = 22
and n = 44
values after swap a = 44
and b = 22

5) What is function definition? (2011)


Ans: Function Definition:A function is a group of statements that together perform a task.
A function declaration tells the compiler about a function's name, return type, and parameters.
A function definition provides the actual body of the function. The C standard library provides
numerous built-in functions that your program can call.

6) Mention the merits of user defined function? (2021)


Ans: A function is a block of organized, reusable code that is used to perform a single, related action.
Functions provide better modularity for your application and a high degree of code reusing. You
have already seen various functions like printf() and main(). These are called built-in functions
provided by the language itself. Good thing about functions is that they are famous with several
names. Different programming languages name them differently, for example, functions, methods,
sub-routines, procedures, etc. If you come across any such terminology, then just imagine about the
same concept.
#include <stdio.h>
1. void printName();
2. void main ()
3. {
4. printf("Protiva");
5. printName();
6. }
7. void printName()
8. {
9. printf("publication");
10. }
Output: Protiva publication
Merits of User defined function:
1. By using functions, we can avoid rewriting same logic/code again and again in a program.
2. We can call C functions any number of times in a program and from any place in a program.
3. We can track a large C program easily when it is divided into multiple functions.
4. Reusability is the main achievement of C functions.

7) Different aspects of function calling.


Ans:
1. function without arguments and without return value
2. function without arguments and with return value
3. function with arguments and without return value
4. function with arguments and with return value

8) Why prototyping is essential in a program? (2021)


Ans: Here we will see why we should use function prototype in C. The function prototypes are used
to tell the compiler about the number of arguments and about the required datatypes of a function
parameter, it also tells about the return type of the function. By this information, the compiler cross-
checks the function signatures before calling it. If the function prototypes are not mentioned, then
the program may be compiled with some warnings, and sometimes generate some strange output. If
some function is called somewhere, but its body is not defined yet, that is defined after the current
line, then it may generate problems. The compiler does not find what is the function and what is its
signature. In that case, we need to function prototypes. If the function is defined before then we do
not need prototypes.
#include<stdio.h>
void function(int); //prototype
main() {
function(50);
}
void function(int x) {
printf("The value of x is: %d", x);
}
Output
The value of x is: 50

9) Define user-defined function and library function with example. (2019,2009)


Library functions are those functions which are already defined in C library,
example printf(), scanf(), strcat() etc. You just need to include appropriate header files to use these
functions. These are already declared and defined in C libraries.
A User-defined functions on the other hand, are those functions which are defined by the user at
the time of writing program. These functions are made for code reusability and for saving time and
space.

10) What are arguments? What is their purpose?


Solution: the term argument refers to any expression within the parentheses of a function call.
An argument represents the value that you pass to a procedure parameter when you call the
procedure. The calling code supplies the arguments when it calls the procedure.
The arguments appearing in the function call are referred to as actual arguments, in contrast to the
formal Arguments that appear in the first line of the function definition. (they are also known simply
as arguments, Or as actual parameters.)In a normal function call, there will be one actual argument
for each formal Argument. The actual arguments may be expressed asconstants, single variables, or
more complex Expressions.
The main purpose of arguments in a function is to pass the value.the argument of a function is to
receive the perimeters to the main function. When a single value is passed to a function via an actual
argument, the value of the actual argument is copied into the function. Therefore, the value of the
corresponding formal argument can be altered within the function, but the value of the actual
argument within the calling routine will not change.

11) Define:
(i) Function prototype (2009)
(ii) Function Argument
Ans: Function prototype: A function prototype is a function declaration that specifies the data types
of its arguments in the parameter list. The compiler uses the information in a function prototype to
ensure that the corresponding function definition and all corresponding function declarations and
calls within the scope of the prototype contain the correct number of arguments or parameters, and
that each argument or parameter is of the correct data type.
Function Argument: Function arguments also known as parameters are the variables that will
receive the data sent by the calling program. These arguments serve as input data to the function to
carry out the specified task.
12) What are formal arguments? What are actual arguments? What is the relationship
between formal arguments and Actual arguments?
Or, Write down the actual and formal perameter in C language. (2018)
Solution:
Actual arguments:
The arguments that are passed in a function call are called actual arguments. These arguments are
defined in the calling function.
Formal arguments:
The formal arguments are the parameters/arguments in a function declaration. The scope of formal
arguments is local to the function definition in which they are used. Formal arguments belong to the
called function. Formal arguments are a copy of the actual arguments. A change in formal arguments
would not be reflected in the actual arguments.
The relationship between formal arguments and Actual arguments
a) Formal arguments are declared within the ( ) where as a actual arguments are declared at
beginning.
b) Formal arguments are automatically initialized when a value of actual argument is passed.
c) actual arguments are the source of information; calling programs pass actual arguments to called
functions. The called functions access the information using corresponding formal arguments.

13) Write down the actual and formal perameter in C language. (2018)
Ans: formal parameter — the identifier used in a method to stand for the value that is passed into
the method by a caller.
For example, amount is a formal parameter of processDeposit
actual parameter — the actual value that is passed into the method by a caller.
For example, the 200 used when processDeposit is called is an actual parameter.
actual parameters are often called arguments

14) Define Recursion. Difference between Iteration and Recursion.(2018, 2021)


Ans : Recursion: Recursion is a process by which a function calls itself repeatedly, until some
specified condition has been Satisfied. The process of repeating items in a self-similar way. In
programming languages, if a program allows you to call a function inside the same function, then it is
called a recursive call of the function.
void recursion() {
recursion(); /* function calls itself */
}

int main() {
recursion();
}
Recursion Vs Iteration

15) Briefly explain different from of main() function used in C.


(2010, 2012, 2016)
Solution: The main is a part of every C program permits different types of main statement.
Following types allowed –
1. main ()
The empty pair of parentheses indicates that the function has no argument.
2. int main ()
integer means that the function return an integer value to the operating system
3. void main ()
The keyword void means that the function does not return any information to the operating
system
4. main(void)
The keyword void means that the function does not return any argument.
5. void main(void)
The keyword void means that the function does not return any information to the operating system
and the function has no argument.
6. int main(void)
integer means that the function return an integer value to the operating system and the
function has no argument.
When integer is specified, the last statement of the program must be return “0”.
16) What is storage class? What are the meaning of storage classes? (2007)
Or, Describe different types of storage classes in C program. (2018,2022)
Ans:In C language, each variable has a storage class which decides the following things:
✓ Scope i.e in which all functions, the value of the variable would be available.
✓ Default initial value i.e if we do not explicitly initialize that variable, what will be its default initial
value.
✓ Lifetime of that variable i.e for how long will that variable exist.
The following storage classes are most often used in C programming,
1. Automatic variables
2. External variables
3. Static variables
4. Register variables
Automatic variables
Scope: Local to the method block in which the variable is defined.
Default Initial Value: Any random value i.e garbage value.
Lifetime: Till the end of method block where the variable is defined.
A variable declared inside a function without any storage class specification, is by default
an automatic variable. They are created when a function is called and are destroyed automatically
when the function exits. Automatic variables can also be called local variables because they are local
to a function. By default they are assigned garbage value by the compiler.
External or Global variable
Scope: Global i.e everywhere in the program.
Default initial value: 0(zero).
Lifetime: Till the whole program doesn't finish its execution.
A variable that is declared outside any function is a Global Variable. Global variables remain
available throughout the entire program.By default, initial value of the Global variable is 0(zero). One
important thing to remember about global variable is that their values can be changed by any
function in the program.
Static variables
Scope: Local to the block in which the variable is defined
Default initial value: 0(Zero).
Lifetime: Till the whole program doesn't finish its execution.
A static variable tells the compiler to persist the variable until the end of program. Instead of
creating and destroying a variable every time when it comes into and goes out of scope, static is
initialized only once and remains into existence till the end of program. A static variable can either
be internal or external depending upon the place of declaraction. Scope of internal static variable
remains inside the function in which it is defined. External static variables remain restricted to
scope of file in each they are declared.
They are assigned 0 (zero) as default value by the compiler.
Register variable
Scope: Local to the function in which it is declared.
Default initial value: Any random value i.e garbage value
Lifetime: Till the end of method block, where the variable is defined, doesn't finish its execution.
Register variable inform the compiler to store the variable in CPU register instead of memory.
Register variable has faster access than normal variable. Frequently used variables are kept in
register. Only few variables can be placed inside register. An application of register storage class can
be in using loops, where the variable gets used a number of times in the program.

17) What is the output of the following code?


𝒑 = 𝟏𝟎;
𝒒 = − − 𝒑 + 𝟐𝟎;
𝒓 = 𝒑 + + − 𝟐𝟓;
printf (%d %d %d, 𝒑, 𝒒, 𝒓);
Solution : Since,
𝑝 = 10;
𝑞 = − − 𝑝 + 20;
ℎ𝑒𝑟𝑒, 𝑝𝑤𝑖𝑙𝑑𝑒𝑐𝑟𝑒𝑚𝑒𝑛𝑡 1 𝑢𝑛𝑖𝑡 . 𝑎𝑛𝑑𝑡ℎ𝑒𝑛𝑒𝑤𝑣𝑎𝑙𝑢𝑒𝑜𝑓𝑝 = 9
so
𝑞 = 9 + 20;
𝑞 = 29
𝑟 = 𝑝 + + − 25;
ℎ𝑒𝑟𝑒, 𝑝𝑤𝑖𝑙𝑖𝑛𝑐𝑟𝑒𝑚𝑒𝑛𝑡 1 𝑢𝑛𝑖𝑡 . 𝑎𝑓𝑡𝑒𝑟𝑡ℎ𝑒𝑙𝑖𝑛𝑒𝑒𝑥𝑒𝑐𝑢𝑡𝑒𝑎𝑛𝑑𝑎𝑙𝑟𝑒𝑎𝑑𝑦𝑡ℎ𝑒𝑛𝑒𝑤𝑣𝑎𝑙𝑢𝑒𝑜𝑓
𝑝=9
so,
𝑟 = 9 − 25;
𝑟 = −16;
𝑡ℎ𝑒𝑜𝑢𝑡𝑝𝑢𝑡𝑜𝑓printf (%d %d %d, 𝑝, 𝑞, 𝑟); is
10 29 − 16
18) What is the following Output in this code (2021)
int x=-10,y=3;
printf("%d\n",x/y*10);
y=-y;
printf("%d",x/y*10);
Ans:
int main() {
int x=-10,y=3;
printf("%d\n",x/y*10);
y=-y;
printf("%d",x/y*10);

return 0;
}
Output: -30
30
19) Why do need to use function? (2020)
Ans:
Use of function in C:
• C functions are used to avoid rewriting same logic/code again and again in a program.
• There is no limit in calling C functions to make use of same functionality wherever required.
• We can call functions any number of times in a program and from any place in a program.
• A large C program can easily be tracked when it is divided into functions.
• The core concept of C functions are, re-usability, dividing a big task into small pieces to achieve
the functionality and to improve understandability of very large C programs.

20)Consider the following C code and findout every values of the variables (x,y,z)-
Int x=5,y=8,z=3;
x=x+(z++);
printf(“%d%d”,x%y,x/y);
y=--x;
printf(“%d%d%d”,x,y,z); (2022)
Ans:
Let's break down the given C code step by step and calculate the values of the variables `x`, `y`, and
`z` at each stage:

int x = 5, y = 8, z = 3;
x = x + (z++);
printf("%d%d", x % y, x / y);
y = --x;
printf("%d%d%d", x, y, z);

Initial values: `x = 5`, `y = 8`, `z = 3`


1. `x = x + (z++);`
- `z++` means the current value of `z` (3) is used first, and then `z` is incremented to 4.
- `x = 5 + 3` results in `x = 8`.

2. `printf("%d%d", x % y, x / y);`
- `x % y` means the remainder of the division of `x` by `y`, which is `8 % 8 = 0`.
- `x / y` means the integer division of `x` by `y`, which is `8 / 8 = 1`.
- The `printf` statement prints `00`.
After this point, `x` has changed to 8.
• `y = --x;`
- `--x` decrements the value of `x` before it's assigned to `y`, so `x` becomes 7 and `y` becomes 7.

Final values: `x = 7`, `y = 7`, `z = 4`

• `printf("%d%d%d", x, y, z);`
- `x` is 7, `y` is 7, and `z` is 4.
- The `printf` statement prints `774`.

So, the values of the variables `x`, `y`, and `z` at the end of the code are:
- `x` = 7
- `y` = 7
-`z`=4
CHAPTER 5
HEADER FILES
1) What is header file? (2019)
Solution: A header file is a file with extension .h which contains C function declarations
and macro definitions to be shared between several source files. There are two types of
header files: the files that the programmer writes and the files that comes with your
compiler.

2) Why we need to use #include<math.h> and #include<ctype.h> statement in C


program.
Solution :
#include<math.h>=The math.h header defines various mathematical functions and one
macro. All the functions available in this library take double as an argument and
return double as the result.
#include<ctype.h> = The ctype.h header file of the C Standard Library declares several
functions that are useful for testing and mapping characters.
All the functions accepts int as a parameter, whose value must be EOF or representable
as an unsigned char.
All the functions return non-zero (true) if the argument c satisfies the condition
described, and zero(false) if not.

3) What do you mean by library function? (2018)


Solution: Library functions in C language are inbuilt functions which are grouped
together and placed in a common place called library.
Each library function in C performs specific operation.
All C standard library functions are declared in many header files which are saved as
file_name.h.
The prototype and data definitions of the functions are present in their respective header
files, and must be included in your program to access them.
For example: If you want to use printf() function, the header file <stdio.h> should be
included.
#include <stdio.h>
int main()
{
printf("C Library Function.");
}
CHAPTER 6
PREPROCESSOR
1. Difference between stack & heap memory in c language?
Solution:
Stack Heap
1) Stack is a memory region where “local 1) Heap is a memory region which is
variables”, “return addresses of function used by dynamic memory
calls” and “arguments to functions” are allocation functions at run time.
hold while C program is executed.
2) CPU’s current state is saved in stack 2) Linked list is an example which
memory uses heap memory.

2. What is difference between compilers vs interpreters in c language?


Solution:
Compiler Interpreter
Compiler generates an Intermediate Code. Interpreter generates Machine Code.
Compiler reads entire program for Interpreter reads single statement at a
compilation. time for interpretation.
Compiler displays all errors and warning at Since Interpreter reads single statement
time and without fixing all errors program so an interpreter display one error at a
cannot be executed. time and you have to fix the error to
interpret next statement.
Compiler needs more memory because of In comparison to Complier, an Interpreter
object (an intermediate code) generation, needs less memory to interpret the
every time when program is being compiled program as interpreter does not generate
an intermediate code (object code) will be any intermediate code, it direct generates
generated. machine code.
The programming languages which use The programming languages which use
Compilers – C, C++, (.Net also has compilers Interpreters – Ruby, Python
for different languages and generates MSIL
code, MSIL code further converts into
Machine Code using JIT Compiler).
3) What is preprocessor directive? Write down the functions of <stdio.h> and
<math.h> header files. (2022)
Preprocessor Directive:
A preprocessor directive is a command that instructs the C preprocessor to perform
specific actions before the compilation process begins. Preprocessor directives are
written with a hash symbol `#` at the beginning and are typically used to include header
files, define macros, and perform conditional compilation. They are processed before the
actual compilation of the code and help modify or customize the code based on specific
requirements.
Functions of `<stdio.h>` Header File:
The `<stdio.h>` header file provides functions for input and output operations in C. It
stands for "standard input-output header" and is a part of the standard C library. Some of
the commonly used functions from `<stdio.h>` are:

- `printf()`: Used to print formatted output to the console.


- `scanf()`: Used to read input from the console.
- `getchar()`: Reads a single character from the console.
- `putchar()`: Writes a single character to the console.
- `fgets()`: Reads a line of text from a file or console.
- `fputs()`: Writes a line of text to a file or console.
- `fopen()`: Opens a file for input/output.
- `fclose()`: Closes an open file.

Functions of `<math.h>` Header File:


The `<math.h>` header file provides functions for mathematical operations and
calculations. It contains various mathematical functions and constants. Some of the
commonly used functions from `<math.h>` are:

- Trigonometric functions: `sin()`, `cos()`, `tan()`, etc.


- Exponential and logarithmic functions: `exp()`, `log()`, `pow()`, etc.
- Square root function: `sqrt()`.
- Rounding functions: `ceil()` (ceiling), `floor()` (floor), `round()` (round to nearest
integer).
- Absolute value function: `fabs()`.
- Minimum and maximum functions: `fmin()`, `fmax()`.
- Value classification functions: `isnan()`, `isinf()`.
- Constants: `M_PI` (pi), `M_E` (e), etc.

These header files, `<stdio.h>` and `<math.h>`, are essential for handling input/output and
mathematical calculations respectively, making them fundamental components of C
programming.
CHAPTER 7
POINTERS AND ARRAYS
1) What is pointer? (2012,2017,2019,2021,2022)
Solution: Pointers in C language is a variable that stores/points the address of another
variable. A Pointer in C is used to allocate memory dynamically i.e. at run time. The
pointer variable might be belonging to any of the data type such as int, float, char, double,
short etc.
Pointer Syntax : data_type *var_name;
Example : int *p; char *p;
Where, * is used to denote that “p” is pointer variable and not a normal variable.

2) Declare and initialize a pointer variable? (2012,2017,2020)


Solution:Declaration of Pointer variable
General syntax of pointer declaration is,
datatype *pointer_name;
Data type of a pointer must be same as the data type of the variable to which the pointer
variable is pointing. void type pointer works with all data types, but is not often used.
Here are a few examples:
int *ip // pointer to integer variable
float *fp;// pointer to float variable
double *dp;// pointer to double variable
char *cp;// pointer to char variable

Initialization of Pointer variable


Pointer Initialization is the process of assigning address of a variable to
a pointer variable. Pointer variable can only contain address of a variable of the same
data type. In C language address operator & is used to determine the address of a
variable.
The & (immediately preceding a variable name) returns the address of the variable
associated with it.
#include<stdio.h>
void main()
{
int a =10;
int *ptr;//pointer declaration
ptr =&a;//pointer initialization
}
3) What is null pointer?
Solution:NULL Pointers
It is always a good practice to assign a NULL value to a pointer variable in case you do
not have an exact address to be assigned. This is done at the time of variable declaration.
A pointer that is assigned NULL is called a null pointer.
The NULL pointer is a constant with a value of zero defined in several standard libraries.
Consider the following program −
#include<stdio.h>
int main (){
int*ptr = NULL;
printf("The value of ptr is : %x\n", ptr );
return0;
}
When the above code is compiled and executed, it produces the following result −
The value of ptr is 0

2) What is array? (2007,2008,2009,2010,2011,2012,2013,2014,2015,2017,2019)


Solution: Arrays a kind of data structure that can store a fixed-size sequential collection
of elements of the same type. An array is used to store a collection of data, but it is often
more useful to think of an array as a collection of variables of the same type.
Instead of declaring individual variables, such as number0, number1, ..., and number99,
you declare one array variable such as numbers and use numbers[0], numbers[1], and ...,
numbers[99] to represent individual variables. A specific element in an array is accessed
by an index.

3) Define Linear Array. (2021)


Ans: A linear array, is a list of finite numbers of elements stored in the memory. In a linear
array, we can store only homogeneous data elements. Elements of the array form a
sequence or linear list, that can have the same type of data. Each element of the array, is
referred by an index set.

4) Write the advantages and disadvantages of array. (2019)


Advantages
✓ It is better and convenient way of storing the data of same datatype with same size.
✓ It allows us to store known number of elements in it.
✓ It allocates memory in contiguous memory locations for its elements. It does not
allocate any extra space/ memory for its elements. Hence there is no memory
overflow or shortage of memory in arrays.
✓ Iterating the arrays using their index is faster compared to any other methods like
linked list etc.
✓ It allows to store the elements in any dimensional array - supports multidimensional
array.
Disadvantages
✓ It allows us to enter only fixed number of elements into it. We cannot alter the size of
the array once array is declared. Hence if we need to insert more number of records
than declared then it is not possible. We should know array size at the compile time
itself.
✓ Inserting and deleting the records from the array would be costly since we add /
delete the elements from the array, we need to manage memory space too.
✓ It does not verify the indexes while compiling the array. In case there is any indexes
pointed which is more than the dimension specified, then we will get run time errors
rather than identifying them at compile time.

5) Write down the merits and demerit of using pointer with respect to array?
(2012,2018)
Ans: Advantages and disadvantages of pointers in c
Benefits (use) of pointers in c:
1.Pointers provide direct access to memory
2.Pointers provide a way to return more than one value to the functions
3.Reduces the storage space and complexity of the program
4.Reduces the execution time of the program
5.Provides an alternate way to access array elements
6.Pointers can be used to pass information back and forth between the calling function
and called function.
7.Pointers allows us to perform dynamic memory allocation and deallocation.
8.Pointers helps us to build complex data structures like linked list, stack, queues, trees,
graphs etc.
9.Pointers allows us to resize the dynamically allocated memory block.
Addresses of objects can be extracted using pointers
Drawbacks of pointers in c:
1.Uninitialized pointers might cause segmentation fault.
2.Dynamically allocated block needs to be freed explicitly. Otherwise, it would lead to
memory leak.
3.Pointers are slower than normal variables.
4.If pointers are updated with incorrect values, it might lead to memory corruption.
5.Basically, pointer bugs are difficult to debug. Its programmers responsibility to use
pointers effectively and correctly.
6) What are some arithmetic operators that are permitted to use with pointer?
Give Example. (2021)
Ans: Pointers variables are also known as address data types because they are used to
store the address of another variable. The address is the memory location that is
assigned to the variable. It doesn’t store any value. Hence, there are only a few
operations that are allowed to perform on Pointers in C language. The operations are
slightly different from the ones that we generally use for mathematical calculations. The
operations are:
1. Increment/Decrement
2. Addition
3. Subtraction
4. Comparison of pointers of the same type.

7) What are the advantages of using linked list over array?


Ans:The advantages of using linked list over array:
1. It can grow ,shrink it means it has variable size, while size of array is fixed.
2. Insertion/deletion of an element at beginning in a linked list is O(1) operation while in
array it is O(n).
3. insertion/ deletion at end can be O(1) if we use rear pointer (like in queue).
4.Less Memory wastage due to dynamic memory allocation.
5. Ease of Insertion/deletion: Only Modification of pointers required.

8) Declare and initialize the types of array. . (2014,2015,2018,2021)


Solution:there are 2 types of c arrays. They are,
1. One dimensional array
2. Multi dimensional array
• Two dimensional array
• Three dimensional array
• Four dimensional array etc…
1. One dimensional array in c:
Syntax : data-type arr_name[array_size];
Array declaration syntax:
data_type arr_name [arr_size];
Array initialization syntax:
data_type arr_name [arr_size]=(value1, value2, value3,….);
Array accessing syntax:
arr_name[index];
2. Two dimensional array in c:
Two dimensional array is nothing but array of array.
Syntax : data_type array_name[num_of_rows][num_of_column];
Array declaration syntax:
data_type arr_name [num_of_rows][num_of_column];
Array initialization syntax:
data_type arr_name[2][2] = {{0,0},{0,1},{1,0},{1,1}};
Array accessing syntax:
arr_name[index];

9) Describe declaration and initialization of two dimensional arrays.


(2009, 2012, 2018)
Solution: two-dimensional arrays
The simplest form of multidimensional array is the two-dimensional array. A two-
dimensional array is, in essence, a list of one-dimensional arrays. To declare a two-
dimensional integer array of size [x][y], you would write something as follows −
Type arrayname [ x ][ y ];
Where type can be any valid c data type and arrayname will be a valid c identifier. A two-
dimensional array can be considered as a table which will have x number of rows and y
number of columns. A two-dimensional array a, which contains three rows and four
columns can be shown as follows −

Thus, every element in the array a is identified by an element name of the form a[ i ][ j ],
where 'a' is the name of the array, and 'i' and 'j' are the subscripts that uniquely identify
each element in 'a'.
Declaration of two dimensional array in c
We can declare an array in the c language in the following way.
Data_type array_name[size1][size2];
A simple example to declare two dimensional array is given below.
int a[3][4];
Here, 3 is the row number and 4 is the column number.

Initializing two-dimensional arrays


Multidimensional arrays may be initialized by specifying bracketed values for each row.
Following is an array with 3 rows and each row has 4 columns.
Int a[3][4] = {
{0, 1, 2, 3} , /* initializers for row indexed by 0 */
{4, 5, 6, 7} , /* initializers for row indexed by 1 */
{8, 9, 10, 11} /* initializers for row indexed by 2 */
};
The nested braces, which indicate the intended row, are optional. The following
initialization is equivalent to the previous example −
Int a[3][4] = {0,1,2,3,4,5,6,7,8,9,10,11};

10) What do you understand by overflow and underflow of data? (2021)


Solution: Overflow and Underflow happen when we assign a value that is out of range of
the declared data type of the variable.
If the (absolute) value is too big, we call it overflow, if the value is too small, we call it
underflow.
Let's look at an example where we attempt to assign the value 101000 (a 1 with 1000 zeros)
to a variable of type int or double. The value is too big for an int or double variable in Java,
and there will be an overflow.
As a second example, let's say we attempt to assign the value 10-1000 (which is very close
to 0) to a variable of type double. This value is too small for a double variable in Java, and
there will be an underflow.

11) Define a two-dimensional integer array and input data values of 4 rows of 5
columns each. (2008,2011)
Solution: Two-dimensional arrays
The simplest form of multidimensional array is the two-dimensional array. A two-
dimensional array is, in essence, a list of one-dimensional arrays. To declare a two-
dimensional integer array of size [x][y], you would write something as follows −
Type arrayname [ x ][ y ];
Where type can be any valid c data type and arrayname will be a valid c identifier. A
two-dimensional array can be considered as a table which will have x number of rows
and y number of columns. A two-dimensional array a, which contains three rows and
four columns can be shown as follows −

Thus, every element in the array a is identified by an element name of the form a[ i ][ j ],
where 'a' is the name of the array, and 'i' and 'j' are the subscripts that uniquely identify
each element in 'a'.
Twodimensional arrays may be initialized by specifying bracketed values for each row.
Following is an array with 4 rows and each row has 5 columns.
Int a[4][5] = {
{0, 1, 2, 3, 4} , /* initializers for row indexed by 0 */
{5, 6, 7, 8, 9} , /* initializers for row indexed by 1 */
{10, 11, 12, 13, 14} /* initializers for row indexed by 2 */
{15, 16, 17, 18, 19} /* initializers for row indexed by 3 */

};
The nested braces, which indicate the intended row, are optional.

12) What are the basic difference between an array and a structure? (2014,2015)
Solution:
Array Structure
Basic An array is a collection of variables A structure is a collection of variables
of same data type. of different data type.
Syntax Type array_name[size]; Struct sruct_name{
type element1;
type element1;
.
.
} variable1, variable2, . .;
Memory Array elements are stored in Structure elements may not be stored
contiguous memory location. in a contiguous memory location.
Access Array elements are accessed by Structure elements are accessed by
their index number. their names.
Operator Array declaration and element Structure element accessing operator is
accessing operator is "[ ]" (square "." (dot operator).
bracket).
Pointer Array name points to the first Structure name does not point to the
element in that array so, array first element in that structure so,
name is a pointer. structure name is not a pointer.
Objects Objects (instances) of an array can Structure objects (instance or structure
not be created. variable) can be created.
Size Every element in array is of same Every element in a structure is of
size. different data type.
Bit filed Bit filed can not be defined in an Bit field can be defined in a structure.
array.
Keyword There is no keyword to declare an "struct" is a keyword used to declare
array. the structure.
User- Arrays are not user-defined they Structure is a user-defined datatype.
defined are directly declared.
Accessing Accessing array element requires Accessing a structure elements require
less time. comparatively more time.
Searching Searching an array element takes Searching a structure element takes
less time. comparatively more time than an array
element.

13) How can an array be explicitly initialized at run time? What is the purpose a
memory management function malloc and calloc? (2010,2012,2014,2020)
Solution: c malloc()
The name malloc stands for "memory allocation".
The function malloc() reserves a block of memory of specified size and return
a pointer of type void which can be casted into pointer of any form.
Syntax of malloc()
ptr = (cast-type*) malloc(byte-size)
Here, ptr is pointer of cast-type. The malloc() function returns a pointer to an area of
memory with size of byte size. If the space is insufficient, allocation fails and returns null
pointer.
ptr = (int*) malloc(100 * sizeof(int));
This statement will allocate either 200 or 400 according to size of int 2 or 4 bytes
respectively and the pointer points to the address of first byte of memory.

C calloc()
The name calloc stands for "contiguous allocation".
The only difference between malloc() and calloc() is that, malloc() allocates single block
of memory whereas calloc() allocates multiple blocks of memory each of same size and
sets all bytes to zero.
Syntax of calloc()
Ptr = (cast-type*)calloc(n, element-size);
This statement will allocate contiguous space in memory for an array of n elements. For
example:
Ptr = (float*) calloc(25, sizeof(float));
This statement allocates contiguous space in memory for an array of 25 elements each of
size of float, i.e, 4 bytes.

14) How can you overcome limitation of arrays using structure? (2012)
Solution: Arrays are used to give common name for all similar data and size , stored at
consecutive memory locations which can be randomly accessed.But as you can observe
we can only store similar data type and similar size.
So structures help use to bind data related to each other like the details of students where
each student has name which is stored in char.Student id is stored in int and few other
details as you can see those are all related data which is best to store at one place ,so in
order to do so structures help us. For your question structures help in storing different
data types , different size and under same name.

15) What is null statement? What are the purpose of null statement? (2012)
Solution: a "null statement" is a statement containing only a semicolon; it can appear
wherever a statement is expected. Nothing happens when a null statement is executed.
The correct way to code a null statement is:
Syntax
/*null value or white space*/;
The "null statement" is an expression statement with the expression missing. It is useful
when the syntax of the language calls for a statement but no expression evaluation. It
consists of a semicolon.
Null statements are commonly used as placeholders in iteration statements or as
statements on which to place labels at the end of compound statements or functions.

16) Define structure and union. Write down the differences between structure and
array. (2019,2021)
Ans:A structure is a user defined data type in C/C++. A structure creates a data type that
can be used to group items of possibly different types into a single type.
A union is a special data type available in C that allows to store different data types in the
same memory location. You can define a union with many members, but only one member
can contain a value at any given time. Unions provide an efficient way of using the same
memory location for multiple-purpose.

Difference between Structure and Array


ARRAY STRUCTURE
Array refers to a collection consisting of Structure refers to a collection consisting
elements of homogenous data type. of elements of heterogenous data type.
Array uses subscripts or “[ ]” (square bracket) Structure uses “.” (Dot operator) for
for element access element access
Array is pointer as it points to the first Structure is not a pointer
element of the collection.
Instantiation of Array objects is not possible. Instantiation of Structure objects is
possible.
Array size is fixed and is basically the number Structure size is not fixed as each
of elements multiplied by the size of an element of Structure can be of different
element. type and size.
Bit filed is not possible in an Array. Bit filed is possible in an Structure.
Array declaration is done simply using [] and Structure declaration is done with the
not any keyword. help of “struct” keyword.
Arrays is a primitive datatype Structure is a user-defined datatype.
Array traversal and searching is easy and fast.
Structure traversal and searching is
complex and slow.
data_type array_name[size]; struct sruct_name{
data_type1 ele1;
data_type2 ele2;
};
Array elements are stored in continuous Structure elements may or may not be
memory locations. stored in a continuos memory location.
Array elements are accessed by their index Structure elements are accessed by their
number using subscripts. names using dot operator.

17) Write down the advantages and disadvantages of using pointer. (2020)
Advantage of using pointers in c:
• Pointers provide direct access to memory
• Pointers provide a way to return more than one value to the functions
• Reduces the storage space and complexity of the program
• Reduces the execution time of the program
• Provides an alternate way to access array elements
• Pointers can be used to pass information back and forth between the calling
function and called function.
• Pointers allows us to perform dynamic memory allocation and deallocation.
• Pointers helps us to build complex data structures like linked list, stack, queues,
trees, graphs etc.
• Pointers allows us to resize the dynamically allocated memory block.
• Addresses of objects can be extracted using pointers
Disadvantage of using pointers in c:
• Uninitialized pointers might cause segmentation fault.
• Dynamically allocated block needs to be freed explicitly. Otherwise, it would lead
to memory leak.
• Pointers are slower than normal variables.
• If pointers are updated with incorrect values, it might lead to memory corruption.
Basically, pointer bugs are difficult to debug. Its programmer’s responsibility to use
pointers effectively and correctly.
Chapter 8
Strings
1) Define string. (2021,2022)
Solution: c strings are nothing but array of characters ended with null character (‘\0’).
This null character indicates the end of the string. Trings are always enclosed by double
quotes. Whereas, character is enclosed by single quotes in c.
Example for c string:
✓ Char string[20] = {‘f’, ’r’, ‘e’, ‘s’, ‘h’, ‘2’, ‘r’, ‘e’, ‘f’, ’r’, ‘e’, ‘s’, ‘h’, ‘\0’};
(or)
✓ Char string[20] = “hello”;
(or)
✓ Char string [] = “hello”;
✓ Difference between above declarations are, when we declare char as “string[20]”, 20
bytes of memory space is allocated for holding the string value.
✓ When we declare char as “string[]”, memory space will be allocated as per the
requirement during execution of the program.

2) Describe c string functions: (2018)


Solution: string.h header file supports all the string functions in c language. All the string
functions are given below.
String Description
functions
strcat ( ) Concatenates str2 at the end of str1
strncat ( ) Appends a portion of string to another
strcpy ( ) Copies str2 into str1
strncpy ( ) Copies given number of characters of one string to another
strlen ( ) Gives the length of str1
strcmp ( ) Returns 0 if str1 is same as str2. Returns <0 if strl < str2. Returns >0 if
str1 > str2
strcmpi ( ) Same as strcmp() function. But, this function negotiates case. “a” and “a”
are treated as same.
strchr ( ) Returns pointer to first occurrence of char in str1
strrchr ( ) Last occurrence of given character in a string is found
strstr ( ) Returns pointer to first occurrence of str2 in str1
strrstr ( ) Returns pointer to last occurrence of str2 in str1
strdup ( ) Duplicates the string
strlwr ( ) Converts string to lowercase
strupr ( ) Converts string to uppercase
strrev ( ) Reverses the given string
strset ( ) Sets all character in a string to given character
strnset ( ) It sets the portion of characters in a string to given character
strtok ( ) Tokenizing given string using delimiter
3) Mention some string handling functions and describe them with example.
Or, Describe the different types of string handling functions in C language with
example.
Or, Describe different types of storage class in C program. (2011, 2019,
2021,2022)
Ans:
Different type of string handling function:
Function Name Description
strcat() Concatenates two strings.
strcmp() Compares two strings.
strcpy() Copies a string from source to destination.
strlen() Returns the length of a srting.
strlwr() Return upper case letter to lower case.
strupr() Return lower case letter to upper case.
Strrev() Reverse of a string.
Strcat() function:
The strcat() function joins two strings together.
General form:
strcat(string1, string2)
Where string1 and string2 are character arrays. When the functions strcat() is executed,
string2 is appended to string1. It does so by removing the null character at the end of
string1 and placing string2 from there. The string at string2 remains unchanged.
Example:
char string1[]={“VERY ”}, string2[]={“GOOD”};
puts(strcat(string1,string2));

Output:
VERY GOOD
strcmp() function:The strcmp() function compares two strings identified by the
arguments and has a value 0 if they are equal. If they are not, it has the numberic
difference between the first nonmatching characters in the strings.
General form:
strcmp(string1, string2);
Where string1 and string2 are character arrays.
Examples:
strcmp(name1, name2);
strcmp(“Rom”, “Ram”);
strcpy() function:
The strcpy() function works almost like a string-assignment operator.
General form:
strcpy(string1, string2);
where string1 and string2 are character arrays.
It assigns the contents of string2 to string1.
Example:
strcpy(city, “DHAKA”);
will assign the string “DHAKA” to the string variable city.
strlen() function:
This funnction counts and returns the number of characters in a string.
General form:
strlen(string);
Where string is a character array.
It returns the value of the length of the string. The counting ends at the first null
character.
Example:
char fname[30]={“DHAKA”};
int length=strlen(fname);
This would set length to 5.
strlwr() function: This function converts all characters in a string from uppercase to
lowercase.
General form:
strlwr(string);
Where string is a character array.
Example:
char string[30]={“DHAKA”};
puts(strlwr(string));
Output:
dhaka
strupr() function:
This function converts all characters in a string from lowercase to uppercase.
General form:
strupr(string);
Where string is a character array.
Example:
char string[30]={“dhaka”};
puts(strupr(string));
Output:
DHAKA
strrev() function: This function reverses the characters in a particular string.
General form:
strrev(string);
Where string is a character array.
Example:
char string[30]={“DHAKA”};
puts(strrev(string));
Output:
AKAHD

4) Describe the limitations of using getchar and scanf function for reading string?
(2008,2020)
Getchar:-Reading a single character can be done by using the function getchar.
Syntax:- variable_name = getchar ( );
Variable_name is a valid ‘c’ name that has been declared as char type. When this
statement is encountered, the computer waits until a key is pressed and then assigns this
character as a value to getchar function. Since getchar is used on the right hand side of an
assignment statement, the character value of getchar is in turn assigned to the
variable_name on the left. The getchar function may be called successively to read the
characters contained in a line of text. Getchar accepts space character.
Scanf : (“control strings”,arg1, arg2, ………… argn);
The control string specifies the field format in which the data is to be entered and
the arguments arg 1, arg 2, arg n specify the address of locations where the data is
stored. Scanf does not accept space character.

5) Describe the following c functions : strcmp(), strcat ( ),strcpy ( ) and strlen( ).


Solution:C supports a wide range of functions that manipulate null-terminated strings −
Sr.No. Function & Purpose
1 strcpy(s1, s2);
Copies string s2 into string s1.
strcpy(s1, "StudyTonight"); //copies "studytonight" to string s1
strcpy(s2, s1); //copies string s1 to string s2

printf("%s\n", s2);

output
StudyTonight
2 strcat(s1, s2);
Concatenates string s2 onto the end of string s1.
strcat("hello", "world");
strcat() function will add the string "world" to "hello" i.e it will ouput helloworld.
3 strlen(s1);
Returns the length of string s1.
int j;
j = strlen("studytonight");
printf("%d",j);
12
4 strcmp(s1, s2);
Returns 0 if s1 and s2 are the same; less than 0 if s1<s2; greater than 0 if s1>s2.
int j;
j = strcmp("study", "tonight");
printf("%d",j);
-1

6) Describe the following c function : strcmp(), strcat ( ),strcpy ( ) and strlen()


Ans: Same as below…………

7) Describe c – strcat() function


Solution : strcat( ) function in c language concatenates two given strings. It concatenates
source string at the end of destination string. Syntax for strcat( ) function is given below.
Char * strcat ( char * destination, const char * source );
Example:
strcat ( str2, str1 ); – str1 is concatenated at the end of str2.
Strcat ( str1, str2 ); – str2 is concatenated at the end of str1. Each string in c is ended up
with null character (‘\0’).
In strcat( ) operation, null character of destination string is overwritten by source string’s
first character and null character is added at the end of new destination string which is
created after strcat( ) operation.
Example program for strcat( ) function in c:
In this program, two strings “hello” and “world” are concatenated using strcat( ) function
and result is displayed as “worldhello”.
1 #include <stdio.h>
2 #include <string.h>
3
4 Intmain()
5 {
6 charsource[]=" hello";
7 chartarget[]="world";
8
9 printf("\nsource string = %s",source);
10 printf("\ntarget string = %s",target);
11
12 strcat(target,source);
13
14 printf("\ntarget string after strcat( ) = %s",target);
15 }
Output:
Source string = hello
target string =world
target string after strcat( ) =world hello

8) Describe c – strncat() function.


Solution: strncat( ) function in c language concatenates (appends) portion of one string at
the end of another string. Syntax for strncat( ) function is given below.
char * strncat ( char * destination, const char * source, size_t num );
• Example :
strncat ( str2, str1, 3 ); – first 3 characters of str1 is concatenated at the end of str2.
Strncat ( str1, str2, 3 ); – first 3 characters of str2 is concatenated at the end of str1.
• As you know, each string in c is ended up with null character (‘\0’).
• In strncat( ) operation, null character of destination string is overwritten by source
string’s first character and null character is added at the end of new destination
string which is created after strncat( ) operation.
Example program for strncat( ) function in c:
In this program, first 5 characters of the string “hello” is concatenated at the end of the
string “world” using strncat( ) function and result is displayed as “world hell”.
1 #include <stdio.h>
2 #include <string.h>
3
4 intmain()
5 {
6 charsource[]=" hello";
7 chartarget[]=" world ";
8
9 printf("\nsource string = %s",source);
10 printf("\ntarget string = %s",target);
11
12 strncat(target,source,5);
13
14 printf("\ntarget string after strncat( ) = %s",target);
15 }
Output:
Source string = hello
target string =world
target string after strcat( ) =world hell

9) Describe c – strcpy() function


Solution: strcpy( ) function copies contents of one string into another string. Syntax for
strcpy function is given below.
Char * strcpy ( char * destination, const char * source );
Example:
strcpy ( str1, str2) – it copies contents of str2 into str1.
Strcpy ( str2, str1) – it copies contents of str1 into str2.
If destination string length is less than source string, entire source string value won’t be
copied into destination string.
For example, consider destination string length is 20 and source string length is 30. Then,
only 20 characters from source string will be copied into destination string and remaining
10 characters won’t be copied and will be truncated.
Example program for strcpy( ) function in c:
In this program, source string “hello” is copied into target string using strcpy( ) function.
1 #include <stdio.h>
2 #include <string.h>
3
4 Intmain()
5 {
6 charsource[]="hello";
7 chartarget[20]="";
8 printf("\nsource string = %s",source);
9 printf("\ntarget string = %s",target);
10 strcpy(target,source);
11 printf("\ntarget string after strcpy( ) = %s",target);
12 return0;
13 }
OUTPUT:
source string = Hello1
target string = Hello2
target string after strcpy( ) = Hello2
10) Describe C – strncpy() function
Solution: strncpy( ) function copies portion of contents of one string into another string.
Syntax for strncpy( ) function is given below.
char * strncpy ( char * destination, const char * source, size_t num );
Example:
strncpy ( str1, str2, 4) – It copies first 4 characters of str2 into str1.
strncpy ( str2, str1, 4) – It copies first 4 characters of str1 into str2.
If destination string length is less than source string, entire source string value won’t be
copied into destination string.
For example, consider destination string length is 20 and source string length is 30.
If you want to copy 25 characters from source string using strncpy( ) function, only 20
characters from source string will be copied into destination string and remaining 5
characters won’t be copied and will be truncated.

11) Describe C – strlen() function


Solution : strlen( ) function in C gives the length of the given string. Syntax for strlen( )
function is given below.
size_t strlen ( const char * str );
strlen( ) function counts the number of characters in a given string and returns the
integer value.
It stops counting the character when null character is found. Because, null character
indicates the end of the string in C.
Example program for strlen() function in c:
In below example program, length of the string “fresh2refres.com” is determined by
strlen( ) function as below. Length of this string 17 is displayed as output.
1 #include <stdio.h>
2 #include <string.h>
3
4 intmain()
5 {
6 intlen;
7 chararray[20]="Hello.com";
8
9 len=strlen(array);
10 printf("\string length = %d \n",len);
11 return0;
12 }
OUTPUT:

string length = 17
12) Describe C – strcmp() function
Solution: strcmp( ) function in C compares two given strings and returns zero if they are
same.
• If length of string1 < string2, it returns < 0 value. If length of string1 > string2, it
returns > 0 value. Syntax for strcmp( ) function is given below.
int strcmp ( const char * str1, const char * str2 );
• strcmp( ) function is case sensitive. i.e, “A” and “a” are treated as different characters

13) Describe C – strcmpi() function


Solution: strcmpi( ) function in C is same as strcmp() function. But, strcmpi( ) function is
not case sensitive. i.e, “A” and “a” are treated as same characters. Where as, strcmp()
function treats “A” and “a” as different characters.
strcmpi() function is non standard function which may not available in standard library in
C.
• Both functions compare two given strings and returns zero if they are same.
• If length of string1 < string2, it returns < 0 value. If length of string1 > string2, it
returns > 0 value. Syntax for strcmp( ) function is given below.
• int strcmpi ( const char * str1, const char * str2 );
Chapter 9
Dynamic memory allocation
1) Describe the dynamic memory allocation in c. (2018)
Solution: The process of allocating memory during program execution is called dynamic
memory allocation.
Dynamic memory allocation functions in c:
C language offers 4 dynamic memory allocation functions. They are,
1. malloc()
2. calloc()
3. realloc()
4. free()
Function Syntax
malloc () malloc (number *sizeof(int));
calloc () calloc (number, sizeof(int));
realloc () realloc (pointer_name, number * sizeof(int));
free () free (pointer_name);

1. MALLOC() FUNCTION IN C:
• malloc () function is used to allocate space in memory during the execution of the
program.
• malloc () does not initialize the memory allocated during execution. It carries
garbage value.
• malloc () function returns null pointer if it couldn’t able to allocate requested amount
of memory.
2. CALLOC() FUNCTION IN C:
• calloc () function is also like malloc () function. But calloc () initializes the allocated
memory to zero. But, malloc() doesn’t.
3. REALLOC() FUNCTION IN C:
• realloc () function modifies the allocated memory size by malloc () and calloc ()
functions to new size.
• If enough space doesn’t exist in memory of current block to extend, new block is
allocated for the full size of reallocation, then copies the existing data to new block
and then frees the old block.
4. FREE() FUNCTION IN C:
1) free () function frees the allocated memory by malloc (), calloc (), realloc () functions
and returns the memory to the system.
2) Difference between static memory allocation and dynamic memory allocation in
c.
Solution:
Static memory allocation Dynamic memory allocation
In static memory allocation, memory is In dynamic memory allocation,
allocated while writing the C program. Actually, memory is allocated while
user requested memory will be allocated at executing the program. That
compile time. means at run time.
Memory size can’t be modified while execution. Memory size can be modified
Example: array while execution.
Example: Linked list

3) Difference between malloc() and calloc() functions in c.


Solution:
malloc() calloc()
It allocates only single block of requested It allocates multiple blocks of requested
memory memory
int *ptr;ptr = malloc( 20 * sizeof(int) );For the int *ptr;Ptr = calloc( 20, 20 * sizeof(int)
above, 20*4 bytes of memory only allocated );For the above, 20 blocks of memory will
in one block. be created and each contains 20*4 bytes
Total = 80 bytes of memory.
Total = 1600 bytes
malloc () doesn’t initializes the allocated calloc () initializes the allocated memory
memory. It contains garbage values to zero
type cast must be done since this function Same as malloc () function int *ptr;ptr =
returns void pointer int *ptr;ptr = (int*)calloc( 20, 20 * sizeof(int) );
(int*)malloc(sizeof(int)*20 );
Chapter 10
Linked list
1) What is link list? Describe the linked list representation in memory. (2020)
Solution: A linked list is a sequence of data structures, which are connected together via
links.Linked List is a sequence of links which contains items. Each link contains a
connection to another link. Linked list is the second most-used data structure after array.
Following are the important terms to understand the concept of Linked List.
Link − Each link of a linked list can store a data called an element.
Next − Each link of a linked list contains a link to the next link called Next.
Linkedlist − A Linked List contains the connection link to the first link called First.
Memory Representation of Linear Linked List:

Let LIST is linear linked list. It needs two linear arrays for memory representation. Let
these linear arrays are INFO and LINK. INFO[K] contains the information part and
LINK[K] contains the next pointer field of node K. A variable START is used to store the
location of the beginning of the LIST and NULL is used as next pointer sentinel which
indicates the end of LIST.
Types of Linked List
Following are the various types of linked list.
1. Simple Linked List − Item navigation is forward only.
2. Doubly Linked List − Items can be navigated forward and backward.
3. Circular Linked List − Last item contains link of the first element as next and the
first element has a link to the last element as previous.

2) What are the advantages of using linked list over array. (2018)
Solution:
Linked List and Arrays are both used for storage of elements, but both are different
techniques. In an array, elements are one after the another(successive memory
allocation). But in linked list, memory is not contiguous.
Advantages :
✓ Size is not an issue as compared to arrays.
✓ Addition/Deletion of an element from the list at any index which is an O(1)
operation in Lists as compared to Arrays.
✓ They can be used as underlying data structures for search trees, etc. I.e. you
construct a search tree, whose lowest level consists of the linked list because lists
express better properties as far as insertions are concerned.

3) What is circular link list? Describe the circular linked list representation in
memory.
Solution: Circular Linked List is a variation of Linked list in which the first element
points to the last element and the last element points to the first element. Both Singly
Linked List and Doubly Linked List can be made into a circular linked list.
Singly Linked List as Circular
In singly linked list, the next pointer of the last node points to the first node.

Doubly Linked List as Circular


In doubly linked list, the next pointer of the last node points to the first node and the
previous pointer of the first node points to the last node making the circular in both
directions.
As per the above illustration, following are the important points to be considered.
• The last link's next points to the first link of the list in both cases of singly as well as
doubly linked list.
• The first link's previous points to the last of the list in case of doubly linked list.
Basic Operations
Following are the important operations supported by a circular list.
• insert − Inserts an element at the start of the list.
• delete − Deletes an element from the start of the list.
• display − Displays the list.
CHAPTER 11
USER DEFINED DATA TYPES
1) What is structure in C? (2008)
Solution: C Structure is a collection of different data types which are grouped together
and each element in a C structure is called member.
✓ If you want to access structure members in C, structure variable should be declared.
✓ Many structure variables can be declared for same structure and memory will be
allocated for each separately.
✓ It is a best practice to initialize a structure to null while declaring, if we don’t assign
any values to structure members.

2) What is the difference between c variable, c array and c structure.


Solution:
✓ C Variable: A normal C variable can hold only one data of one data type at a time.

Int Syntax: int a;


Example: a = 20;
Char Syntax: char b;
Example: b=’Z’;

✓ C Array: An array can hold group of data of same data type.


Int Syntax: int a[3];
Example:
a[0] = 10;
a[1] = 20;
a[2] = 30;
a[3] = ‘\0’;
Char Syntax: char b[10];
Example:
b=”Hello”;
✓ C Structure: A structure can hold group of data of different data types and Data types
can be int, char, float, double and long double etc.
Syntax struct student
{
int a;
char b[10];
}
Example a = 10;
b = “Hello”;
3) Describe c structure declaration in separate header file.
C structure is declared in main source file. Instead of declaring C structure in main source
file, we can have this structure declaration in another file called “header file” and we can
include that header file in main source file as shown below.
Header file name – structure.h
Before compiling and executing below C program, create a file named “structure.h” and
declare the below structure.
struct student
{
int id;
char name[20];
float percentage;
} record;

4) In which way structure differs form an array? Describe with examples., the
different ways of assigning values of structure members. (2016)
Structure differs form an array
an array is a collection of related data elements of the same type(homogeneous).
The following program throws an error
int array[5] = {1, 2, "string", 4, 5};
However, in Structure, you can have elements of different data types(heterogeneous).
The following program compiles without an error.
struct Person {
char name[10];
int age;
float height;
};
Second, an array is a derived data type. Derived data type means they are derived from
fundamental data types. An array can be a collection of int, char, float, double etc. but it is
not a data type in itself. It adds the additional functionality to the existing data types.
But, a structure is a user-defined data type. A user has all the right to create a data type to
satisfy his needs.
An array is a pointer to the first element of it,but a structure is not a pointer.
Array allocates static memory and uses index/subscript for accessing elements of the
array whereas Structures allocate dynamic memory and uses (.) operator for accessing
the member of a structure.
Array of structures:
We can have an array of structures just like we can have an array of integers. The
following code snippet creates an array of structure Book.
struct Book books[2];
'books' is an array of data type 'Book' which can contain two books.
assign values to structure members
There are three ways to do this.
1) Using Dot(.) operator
var_name.memeber_name = value;
2) All members assigned in one statement
struct struct_name var_name =
{value for memeber1, value for memeber2 …so on for all the members}
3) Designated initializers – set the values of a struct member, there is another way to do
the same using designated initializers. This is useful when we are doing assignment of
only few members of the structure. In the following example the structure variable s2 has
only one member assignment.
#include <stdio.h>
struct numbers
{
int num1, num2;
};
int main()
{
// Assignment using using designated initialization
struct numbers s1 = {.num2 = 22, .num1 = 11};
struct numbers s2 = {.num2 = 30};

printf ("num1: %d, num2: %d\n", s1.num1, s1.num2);


printf ("num1: %d", s2.num2);
return 0;
}
Output:
num1: 11, num2: 22
num1: 30
5) Derive Difference between structure and union in c.
Or, Differentiate with syntax between structure and union.
(2012, 2016, 2018, 2022)
C Structure C Union
Structure allocates storage space for all its Union allocates one common storage space
members separately. for all its members.
Union finds that which of its member needs
high storage space over other members and
allocates that much space
Structure occupies higher memory space. Union occupies lower memory space over
structure.
We can access all members of structure at We can access only one member of union at
a time. a time.
Structure example:struct student{int Union example:union student{int mark;
mark;char name[6];double average;}; char name[6];double average;};
For above structure, memory allocation For above union, only 8 bytes of memory
will be like below.int mark – 2 Bytes will be allocated since double data type will
char name[6] – 6 Bytesdouble average – 8 occupy maximum space of memory over
BytesTotal memory allocation =2+6+8 = other data types. Total memory allocation =
16 Bytes 8 Bytes
CHAPTER 12
INPUT AND OUTPUT
1) Explain printf() function in c language:
Solution :In C programming language, printf() function is used to print the “character,
string, float, integer, octal and hexadecimal values” onto the output screen.
✓ We use printf() function with %d format specifier to display the value of an integer
variable.
✓ Similarly %c is used to display character, %f for float variable, %s for string
variable, %lf for double and %x for hexadecimal variable.
✓ To generate a newline,we use “\n” in C printf() statement.
Example program for c printf() function:
#include <stdio.h>
intmain()
{
charch='A';
charstr[20]="Hello.com";
floatflt=10.234;
intno=150;
doubledbl=20.123456;
printf("Character is %c \n",ch);
printf("String is %s \n",str);
printf("Float value is %f \n",flt);
printf("Integer value is %d\n",no);
printf("Double value is %lf \n",dbl);
printf("Octal value is %o \n",no);
printf("Hexadecimal value is %x \n",no);
return0;
}
OUTPUT:
Character is A
String is Hello.com
Float value is 10.234000
Integer value is 150
Double value is 20.123456
Octal value is 226
Hexadecimal value is 96
2) Write down the differences between printf() and f printf (). (2021)
Distinguish between Printf & fprintf:
Printf fprintf
printf function is used to print character fprintf is used to print the string content in
stream of data on stdout console. file but not on stdout console.
Syntax : Syntax :

int printf(const char* str, ...); int fprintf(FILE *fptr, const char *str, ...);

3) Write down the differences between scanf() and fscanf(). (2021)


scanf() fscanf()
The function scanf() is used to read The function fscanf() is used to read the
formatted input from stdin in C language. formatted input from the given stream in C
It returns the whole number of characters language. It returns zero, if unsuccessful.
written in it otherwise, returns a negative Otherwise, it returns The input string, if
value. successful.
int scanf(canst char *characters_set) int fscanf(FILE *stream_name, const char
*set_of_characters)
#include <stdio.h> #include <stdio.h>
int main () { #include <stdlib.h>
char s[20]; int main () {
printf("Enter a string : "); char str1[10];
scanf("%s", s); int year;
printf(" FILE * fp;
Entered string : %s fp = fopen ("file.txt", "w+");
", s); fputs("This is demo text!", fp);
return(0); rewind(fp);
} fscanf(fp, "%s", str1);
Output: Enter a string: Protiva! printf("First word = %s", str1 );
Entered string: Protiva! fclose(fp);
return (0);
}
Output:
Friest word= This
4. Distinguish between the following function: (2015)
(i) Rewind & ftell
(ii) Printf & fprintf
(iii) BOF & EOF
(iv) getc & putc
Answere:
(i)Distinguish between rewind & ftell:
ftell() rewind()
Declaration: long int ftell(FILE *fp) Declaration: void rewind(FILE *fp)
ftell function is used to get current position rewind function is used to move file
of the file pointer. In a C program, we use pointer position to the beginning of the file.
ftell() as below. In a C program, we use rewind() as below.

ftell(fp); rewind(fp);

(ii) Distinguish between Printf & fprintf:


Printf fprintf
printf function is used to print character fprintf is used to print the string content in
stream of data on stdout console. file but not on stdout console.
Syntax : Syntax :

int printf(const char* str, ...); int fprintf(FILE *fptr, const char *str, ...);

(iii) Distinguish between BOF & EOF:


BOF EOF
BOF Indicates that the current record EOF Indicates that the current record
position is before the first record in a position is after the last record in a
Recordset object. Recordset object.
The BOF property returns True (-1) if the The EOF property returns True (-1) if the
current record position is before the first current record position is after the last
record in the Recordset, otherwise it record in the Recordset, otherwise it
returns False (0) returns False (0).
The BOF and EOF properties are set to If a Recordset holds at least one record, the
True if you open an empty Recordset. first record is the current and the BOF and
RecordCount property is zero. EOF properties are False.
(iv) Distinguish between getc & putc:
getc() putc()
Declaration: int getc(FILE *fp) Declaration: int putc(int char, FILE *fp)
getc functions is used to read putc function is used to display a character
a character from a file. In a C program, we on standard output or is used to write into
read a character as below. a file. In a C program, we can use putc as
below.
getc (fp); putc(char, stdout);
putc(char, fp);
CHAPTER 13
FILE ACCESS
1) What is file? (2007,2015,2016,2019)
Solution: File is a collection of bytes that is stored on secondary storage devices like disk.
There are two kinds of files in a system. They are,
1. Text files (ASCII)
2. Binary files
• Text files contain ASCII codes of digits, alphabetic and symbols.
• Binary file contains collection of bytes (0’s and 1’s). Binary files are compiled version
of text files.

2) Describe the basic file operations in c programming. (2015)


Solution: There are 4 basic operations that can be performed on any files in C
programming language. They are,
1. Opening/Creating a file
2. Closing a file
3. Reading a file
4. Writing in a file
Describe the Declaration & Description of file operation
fopen() – To Declaration: FILE *fopen (const char *filename, const char *mode)
open a file fopen() function is used to open a file to perform operations such as
reading, writing etc. In a C program, we declare a file pointer and use
fopen() as below. fopen() function creates a new file if the mentioned file
name does not exist.
FILE *fp;fp=fopen (“filename”, ”‘mode”);
Where,
fp – file pointer to the data type “FILE”. File name – the actual file name
with full path of the file.mode – refers to the operation that will be
performed on the file. Example: r, w, a, r+, w+ and a+. Please refer below
the description for these mode of operations.
fclose() – To Declaration: int fclose(FILE *fp);
close a file fclose() function closes the file that is being pointed by file pointer fp. In a
C program, we close a file as below.fclose (fp);
fgets() – To Declaration: char *fgets(char *string, int n, FILE *fp)
read a file fgets function is used to read a file line by line. In a C program, we use
fgets function as below.
fgets (buffer, size, fp);
where,
buffer – buffer to put the data in.size – size of the buffer fp – file pointer
fprintf() – To Declaration:
write into a int fprintf(FILE *fp, const char *format, …);fprintf() function writes
file string into a file pointed by fp. In a C program, we write string into a file as
below.
fprintf (fp, “some data”); or fprintf (fp, “text %d”, variable_name);

3) Describe different types of file opening mode?


Or, Discuss modes for opening a file used in C language. (2011,2019,2021,2022)
Solution : Opening Files
the fopen( ) function to create a new file or to open an existing file. This call will initialize
an object of the type FILE, which contains all the information necessary to control the
stream. The prototype of this function call is as follows −
FILE *fopen( const char * filename, const char * mode );
Here, filename is a string literal, which you will use to name your file, and
access mode can have one of the following values −
Mode Description
R opens a text file for reading
W opens a text file for writing
A opens a text file for appending. (appending means to add text at the end)
r+ opens a text file for reading and writing
w+ opens a text file for both reading and writing.
(it first cuts the length of the file to zero if it exists, or create a file if it does not
exist)
a+ opens a text file in both reading and writing mode. (It creates a file if it does not
exist. Reading will start from the beginning but writing can only be done at the
end)
If you are going to handle binary files, then you will use following access modes instead
of the above mentioned ones −
"rb", "wb", "ab", "rb+", "r+b", "wb+", "w+b", "ab+", "a+b"

4) Decribe the mode of operations performed on a file in c language.


Solution: There are many modes in opening a file. Based on the mode of file, it can be
opened for reading or writing or appending the texts. They are listed below.
• r – Opens a file in read mode and sets pointer to the first character in the file. It
returns null if file does not exist.
• w – Opens a file in write mode. It returns null if file could not be opened. If file exists,
data are overwritten.
• a – Opens a file in append mode. It returns null if file couldn’t be opened.
• r+ – Opens a file for read and write mode and sets pointer to the first character in the
file.
• w+ – opens a file for read and write mode and sets pointer to the first character in the
file.
• a+ – Opens a file for read and write mode and sets pointer to the first character in the
file. But, it can’t modify existing contents.
EXAMPLE PROGRAM FOR FILE OPEN, FILE WRITE AND FILE CLOSE IN C LANGUAGE:
/*Open,write andcloseafile:*/
# include <stdio.h>
# include <string.h>

intmain()
{
FILE*fp;
chardata[50];
// opening an existing file
printf("Opening the file test.c in write mode");
fp=fopen("test.c","w");
if(fp==NULL)
{
printf("Could not open file test.c");
return1;
}
printf("\n Enter some text from keyboard” \
“ to write in the file test.c");
// getting input from user
while(strlen(gets(data))>0)
{
// writing in the file
fputs(data,fp);
fputs("\n",fp);
}
// closing the file
printf("Closing the file test.c");
fclose(fp);
return0;
}
Output:
Opening the file test.c in write mode
Enter some text from keyboard to write in the file test.c
Hai, How are you?
Closing the file test.c
5) Descibe an example program for file open, file read and file close in c language.
Or, Decribe inbuilt functions for file handling in c language.
Solution: Working with files
When working with files, you need to declare a pointer of type file. This declaration is
needed for communication between the file and program.
FILE *fptr;
Opening a file - for creation and edit
Opening a file is performed using the library function in the "stdio.h" header file: fopen().
The syntax for opening a file in standard I/O is:
ptr = fopen("fileopen","mode")

For Example:
fopen("E:\\cprogram\\newprogram.txt","w");
fopen("E:\\cprogram\\oldprogram.bin","rb");
Closing a File
The file (both text and binary) should be closed after reading/writing.
Closing a file is performed using library function fclose().
fclose(fptr); //fptr is the file pointer associated with file to be closed.
Reading and writing to a text file
For reading and writing to a text file, we use the functions fprintf() and fscanf().
They are just the file versions of printf() and scanf(). The only difference is that, fprint and
fscanf expects a pointer to the structure FILE.
Example : Write to a text file using fprintf()
#include<stdio.h>
#include<stdlib.h>

int main()
{
int num;
FILE *fptr;
fptr = fopen("C:\\program.txt","w");

if(fptr == NULL)
{
printf("Error!");
exit(1);
}

printf("Enter num: ");


scanf("%d",&num);
fprintf(fptr,"%d",num);
fclose(fptr);

return0;
}
6) What are the errors that could occur during file operation and how could you
slove them? (2018)
Or, Describe about the error handling in file operation. (2011)
Solution : While dealing with files,it is possible that an error may occur. This error may
occur due to following reasons:
• Reading beyond the end of file mark.
• Performing operations on the file that has not still been opened.
• Writing to a file that is opened in the read mode.
• Opening a file with invalid filename.
• Device overflow.
Thus, to check the status of the pointer in the file and to detect the error is the file. C
provides two status-enquiry library functions

feof() - The feof() function can be used to test for an end of file condition
Syntax
feof(FILE*file_pointer);
Example
if(feof(fp))
printf(“End of file”);
ferror() - The ferror() function reports on the error state of the stream and returns true if
an error has occurred.
Syntax
ferror(FILE *file_pointer);
Example
if(ferror(fp)!=0)
printf(“An error has occurred”);

7) Describing the opening and closing function of a FILE. (2007)


Solution : A file represents a sequence of bytes, regardless of it being a text file or a
binary file. C programming language provides access on high level functions as well as
low level (OS level) calls to handle file on your storage devices. This chapter will take you
through the important calls for file management.
Opening Files
You can use the fopen( ) function to create a new file or to open an existing file. This call
will initialize an object of the type FILE, which contains all the information necessary to
control the stream. The prototype of this function call is as follows −
FILE *fopen( const char * filename, const char * mode );
Here, filename is a string literal, which you will use to name your file, and
access mode can have one of the following values −
Mode Description
R opens a text file for reading
W opens a text file for writing
A opens a text file for appending. (appending means to add text at the end)
r+ opens a text file for reading and writing
w+ opens a text file for both reading and writing.
(it first cuts the length of the file to zero if it exists, or create a file if it does not
exist)
a+ opens a text file in both reading and writing mode. (It creates a file if it does not
exist. Reading will start from the beginning but writing can only be done at the
end)
If you are going to handle binary files, then you will use following access modes instead
of the above mentioned ones −
"rb", "wb", "ab", "rb+", "r+b", "wb+", "w+b", "ab+", "a+b"
Closing a File
To close a file, use the fclose( ) function. The prototype of this function is −
int fclose( FILE *fp );
The fclose(-) function returns zero on success, or EOF if there is an error in closing the
file. This function actually flushes any data still pending in the buffer to the file, closes the
file, and releases any memory used for the file. The EOF is a constant defined in the
header file stdio.h.
There are various functions provided by C standard library to read and write a file,
character by character, or in the form of a fixed length string.

8) What is the significance of EOF function? (2014,2022)


Solution : EOF is short for End of File. It's not an actual character, but more like
a signal that indicates the end of input stream.
EOF is the named constant to apply for End Of File when reading from a stdio input
stream. In the getchar() prototype, you'll first notice some strange thing is that it returns
not a charvalue, but an int. Normally, EOF translates in some negative integer value
(historically -1) meaning it's impossible to generate that character from the
keyboard/input file.
Definitely, EOF constant is not a character, is the int value getchar(3) returns on end of
file condition. This is also the reason of getchar(3) returning an int instead of
a char value. It is also the reason always EOF maps to a negative value.
getchar(3) returns one of 257 possible values, 0 up to 255 and EOF (which is normally -
1). Viewed as integer values, -1 is not the same as 255. It's one of the oldest implemented
functions in C
9) Write down the advantages of file. (2014,2022)
Solution: The advantages of file
1. Don't have to learn SQL or any special language to get the data you want.
2. File management is built into most of the mainstream languages. You don't have to use
any special adaptor or plugin to work with them.
3. Backing up your data or migrating your data is simple file copy or move which is again
built into most of the operating systems.
4. Data is human readable just using simple text editors which comes builtin with most
of the mainstream OS.

10) Define file handling mode. (2022)


Ans:
File handling mode:
File handling mode in programming refers to the specific mode or purpose for which a file
is opened or created when interacting with files in a programming language. These modes
dictate whether a file is being opened for reading, writing, or both, and whether the file
should be created if it doesn't already exist.
CHAPTER 14
VARIABLE LENGTH ARGUMENT LIST & COMMAND LINE PAREMETER.
ERROR HANDLING, LINKING & LIBRARY FUNCTIONS
1. What is errno?
Solution : As such, C programming does not provide direct support for error handling
but being a system programming language, it provides you access at lower level in the
form of return values. Most of the C or even Unix function calls return -1 or NULL in case
of any error and set an error code errno. It is set as a global variable and indicates an
error occurred during any function call. You can find various error codes defined in
<error.h> header file.
So a C programmer can check the returned values and can take appropriate action
depending on the return value. It is a good practice, to set errno to 0 at the time of
initializing a program. A value of 0 indicates that there is no error in the program.

2. Define perror(). and strerror()


Solution : The C programming language provides perror() and strerror() functions
which can be used to display the text message associated with errno.
• The perror() function displays the string you pass to it, followed by a colon, a
space, and then the textual representation of the current errno value.
• The strerror() function, which returns a pointer to the textual representation of
the current errno value.

3. Explain Divide by Zero Errors


Solution : It is a common problem that at the time of dividing any number,
programmers do not check if a divisor is zero and finally it creates a runtime
error.
The code below fixes this by checking if the divisor is zero before dividing −
#include<stdio.h>
#include<stdlib.h>

main(){

int dividend =20;


int divisor =0;
int quotient;

if( divisor ==0){


fprintf(stderr,"Division by zero! Exiting...\n");
exit(-1);
}
quotient = dividend / divisor;
fprintf(stderr,"Value of quotient : %d\n", quotient );

exit(0);
}
When the above code is compiled and executed, it produces the following result
Division by zero! Exiting...

4. What is linker?
Solution : The linker has two functions. The first, as the name implies, is to combine (link)
various pieces of object code. The second is to resolve the addresses of call and load
instructions found in the object files that it is combining.

5. What doyou mean by actual and formal parameter? Explain with an example.
Ans: Actual Parameters:The values/variables passed while calling a function are called
actual parameters.
Formal Parameters: These are the variables written/declared in function
definition/prototype, and receive their values when a call to that function is made.
The value(s) of the actual parameters are copied to formal parameters when the call to
that function is made.
Example:

int sum(int a, int b) //Statement 1


{
return a+b;
}
int main()
{
int x=10,y=20;
int s = sum(x,y); //Statement 2
return 0;
)
In Statement 1, the variables a and b are called FORMAL PARAMETERS. In Statement 2
the arguments x and y are called ACTUAL PARAMETERS (as they are the actual ones to
hold the values, you can think it like this).
6. Distinguish between the following: (2011, 2016)
(i)Actual and formal parameter (2022)
(ii)Automatic and static variable
Ans: Distinguish between the following:
i. Actual and formal parameter:
Actual vs Formal Parameters
The Actual parameters are the values The Formal Parameters are the variables
that are passed to the function when it defined by the function that receives values
is invoked. when the function is called.
Related Function
The actual parameters are passed by The formal parameters are in the called
the calling function. function.
Data Types
In actual parameters, there is no In formal parameters, the data types of the
mentioning of data types. Only the receiving values should be included.
value is mentioned.
ii. Automatic and static variable:
Automatic (auto) variables Static variables
By default all local variables are static keyword must be used to declare a static
automatic variable. Keyword auto can variable.
be used to declare an automatic
variable, but it is not required.
Automatic variable’s scope is always Static variable’s scope is also local to that
local to that function, in which they are function in which they are declared i.e. static
declared i.e. automatic variable, can be variable can be accessible within the same
accessible within the same block. block.
Automatic variable’s life time is local Static variable’s life time is not limited. Since
(limited), automatic variables exit till it’s scope is local but the variable will be live
the function execution time, when (exist) till the program’s execution.
program’s execution leaves the function
execution, variables are destroyed.
Automatic variables create a new each Static variable create once, when program’s
time when program’s execution enters execution enters in the function first time,
in the function and destroys when destroys when program’s execution finishes,
leaves. they do not again.
C PROGRAMS & ALGORITHMS
1. Write a program to find the area of circle is pi as a symbol of constant.
/* (a) Write a program to find the area of a circle. (Use π as a symbolic constant) */
#include <stdio.h>
#define PI 3.14
int main()
{
float a,r;
scanf("%f",&r);
a=PI*r*r;
printf("%f",a);
return 0;
}

2. Write a program to convert the given temperature in Fahrenheit to Celsius and


vice versa.
/* C Program to convert temperature from Fahrenheit to Celsius and vice versa.*/
#include <stdio.h>
int main()
{
float fh,cl;
int choice;
printf("\n1: Convert temperature from Fahrenheit to Celsius.");
printf("\n2: Convert temperature from Celsius to Fahrenheit.");
printf("\nEnter your choice (1, 2): ");
scanf("%d",&choice);
if(choice ==1){
printf("\nEnter temperature in Fahrenheit: ");
scanf("%f",&fh);
cl= (fh - 32) / 1.8;
printf("Temperature in Celsius: %.2f",cl);
}
else if(choice==2){
printf("\nEnter temperature in Celsius: ");
scanf("%f",&cl);
fh= (cl*1.8)+32;
printf("Temperature in Fahrenheit: %.2f",fh);
}
else{
printf("\nInvalid Choice !!!");
}
return 0;
}

3. Write a program to convert the given temperature in Fahrenheit to Celsius


where cel=((fah-32)*5/9). (2020)
/* C Program to convert temperature from Fahrenheit to Celsius.*/
#include <stdio.h>
int main()
{
float fah,cel;
printf( Convert temperature from Fahrenheit to Celsius.");
printf("\nEnter temperature in Fahrenheit: ");
scanf("%f",&fah);
cel= (fah - 32)*5/9;
printf("Temperature in Celsius: %.2f",cel);
return 0;
}

4. Area of a triangle is given by the formula 𝑨 = √𝒔(𝒔 − 𝒂)(𝒔 − 𝒃)(𝒔 − 𝒄) where


𝒂, 𝒃, 𝒄 are sides of the triangle and 𝟐𝒔 = 𝒂 + 𝒃 + 𝒄. Write a C program to compute
the area of the triangle given the value of 𝒂, 𝒃 and 𝒄.
#include<stdio.h>
#include<math.h>
int main()
{
float a, b, c, Perimeter, s, Area;
printf("\nPlease Enter three sides of triangle\n");
scanf("%f%f%f",&a,&b,&c);
Perimeter = a+b+c;
s = (a+b+c)/2;
Area = sqrt(s*(s-a)*(s-b)*(s-c));
printf("\n Perimeter of Traiangle = %.2f\n", Perimeter);
printf("\n Semi Perimeter of Traiangle = %.2f\n",s);
printf("\n Area of triangle = %.2f\n",Area);
return 0;
}
5. The numbers in the sequence 1 1 2 3 5 8 13 ………………. are called Fibonacci
numbers.Write a C program using for loop to calculate and print the first 𝒎
fibonacci numbers. (2020)
#include <stdio.h>
int main()
{
int i, m, t1 = 0, t2 = 1, nextTerm;
printf("Enter the number of terms: ");
scanf("%d", &m);
printf("Fibonacci Series: ");
for (i = 1; i <= m; ++i)
{
printf("%d, ", t1);
nextTerm = t1 + t2;
t1 = t2;
t2 = nextTerm;
}
return 0;
}

6. Write a c Program to copy one string into another and count the number of
characters copied. (2021)
1. #include <stdio.h>
2. int main()
3. {
4. char s1[1000],s2[1000];
5. int i=0;
6. printf("Enter any string: ");
7. gets(s1);
8. for(i=0;s1[i]!='\0';i++)
9. {
a. s2[i]=s1[i];
b. }
c. s2[i]='\0';
10. printf("Original String =%s\n",s1);
11. printf("Copied String =%s\n",s2);
12. printf("The number of Character = %d",i);
13. return 0;
14. }
Output:
Enter any string: Protiva Publication
Original String =Protiva Publication
Copied String =Protiva Publication
The number of Character = 19

7. Write a c Program to read from a file and display it on the screen. (2021)
1. #include <stdio.h>
2. #include<ctype.h>
3. #include<stdlib.h>
4. int main(){
5. char ch;
6. FILE *fp;
7. fp=fopen("std1.txt","w");
8. printf("enter the text.press cntrl Z:
");
9. while((ch = getchar())!=EOF){
10. putc(ch,fp);
11. }
12. fclose(fp);
13. fp=fopen("std1.txt","r");
14. printf("text on the file:
");
15. while ((ch=getc(fp))!=EOF){
16. if(ch == ',')
17. printf("\t\t");
18. else
19. printf("%c",ch);
20. }
21. fclose(fp);
22. return 0;
23. }
8. Write a c program to display the real, imaginary and equal roots of a quadratic
equation :- 𝒂𝒙𝟐 + 𝒃𝒙 + 𝒄 = 𝟎. [use the following conditions:
𝒄
▪ There is only one root , if 𝒂 = 𝟎 (𝒙 = − 𝒃) ;
▪ There are no real roots, if 𝒃𝟐 − 𝟒𝒂𝒄 is negative.
▪ Otherwise , there are two real roots. (2022)
#include <stdio.h>
#include <math.h>
int main()
{
double a, b, c, determinant, root1,root2, realPart, imaginaryPart;
printf("Enter coefficients a, b and c: ");
scanf("%lf %lf %lf",&a, &b, &c);
determinant = b*b-4*a*c;
// condition for real and different roots
if (determinant > 0)
{
// sqrt() function returns square root
root1 = (-b+sqrt(determinant))/(2*a);
root2 = (-b-sqrt(determinant))/(2*a);
printf("root1 = %.2lf and root2 = %.2lf",root1 , root2);
}
//condition for real and equal roots
else if (determinant == 0)
{
root1 = root2 = -b/(2*a);
printf("root1 = root2 = %.2lf;", root1);
}
// if roots are not real
else
{
realPart = -b/(2*a);
imaginaryPart = sqrt(-determinant)/(2*a);
printf("root1 = %.2lf+%.2lfi and root2 = %.2f-%.2fi", realPart, imaginaryPart,
realPart, imaginaryPart);
}
return 0;
}
9. Write a program using pointers to read in an array of integers and print its
elements in reverse order. (2018)
#include<stdio.h>
#include<conio.h>
#define MAX 30
void main()
{
int size,i,arr[MAX];
int *ptr;
clrscr();
ptr=&arr[0];
printf("Enter the size of array : ");
scanf("%d",&size);
printf("Enter %d integers into array:n",size);
for(i=0;i<size;i++)
{
scanf("%d",ptr);
ptr++;
}
ptr=&arr[size-1];
printf("Elements of array in reverse order are:n");
for(i=size-1;i>=0;i--)
{
printf(" %d",*ptr);
ptr--;
}
getch();}

10. Write a C program to determine whether a number is ‘odd’ or ‘even’ and print
the message
NUMBER IS EVEN
OR
NUMBER IS ODD.
#include <stdio.h>
int main()
{
int number;
printf("Enter an integer: ");
scanf("%d", &number);
// True if the number is perfectly divisible by 2
if(number % 2 == 0)
printf("NUMBER IS EVEN ");
else
printf("NUMBER IS ODD ");
return 0;}

11. White a program to find nth Fibonacci series. (2018)


/*
* C Program to find the nth number in Fibonacci series using recursion
*/
#include <stdio.h>
int fibo(int);

int main()
{
int num;
int result;

printf("Enter the nth number in fibonacci series: ");


scanf("%d", &num);
if (num < 0)
{
printf("Fibonacci of negative number is not possible.\n");
}
else
{
result = fibo(num);
printf("The %d number in fibonacci series is %d\n", num, result);
}
return 0;
}
int fibo(int num)
{
if (num == 0)
{
return 0;
}
else if (num == 1)
{
return 1;
}
else
{
return(fibo(num - 1) + fibo(num - 2));
}
}

12. Write a program to find the area and circumference of a circle. (2022)
#include<stdio.h>
int main() {
int rad;
float PI = 3.14, area, ci;
printf("\nEnter radius of circle: ");
scanf("%d", &rad);
area = PI * rad * rad;
printf("\nArea of circle : %f ", area);
ci = 2 * PI * rad;
printf("\nCircumference : %f ", ci);
return (0);
}
Output
Enter radius of a circle : 1
Area of circle : 3.14
Circumference : 6.28

13. Write a program to calculate the area and perimeter of a triangle. (2020)
#include<stdio.h>
#include<math.h>

int main()
{
float a, b, c, Perimeter, s, Area;

printf("\nPlease Enter three sides of triangle\n");


scanf("%f%f%f",&a,&b,&c);

Perimeter = a+b+c;
s = (a+b+c)/2;
Area = sqrt(s*(s-a)*(s-b)*(s-c));

printf("\n Perimeter of Traiangle = %.2f\n", Perimeter);


printf("\n Semi Perimeter of Traiangle = %.2f\n",s);
printf("\n Area of triangle = %.2f\n",Area);

return 0;
}

14. Write a c program to test whether the given year is leap or not. [2014, 2021]
#include <stdio.h>

int main()
{
int year;

printf("Enter a year: ");


scanf("%d", &year);
if (year % 4 == 0)
{
if (year % 100 == 0)
{
// year is divisible by 400, hence the year is a leap year
if (year % 400 == 0)
printf("%d is a leap year.", year);
else
printf("%d is not a leap year.", year);
}
else
printf("%d is a leap year.", year);
}
else
printf("%d is not a leap year.", year);

return 0;
}
Output 1
Enter a year: 1900
1900 is not a leap year.
Output 2
Enter a year: 2012
2012 is a leap year.
15. Write a C program to evaluate the De-Morgan‟s rule. [ 2010]

We know that,
So the C program to evaluate the De-Morgan‘s rule is given bellow:
structNode{
virtual~Node(){};
virtualNode*copy()=0;
virtualNode*negation()=0;

private:
// Taboo
Node(constNode&);
Node&operator=(constNode&);
};
structAndNode:Node{
Node*left,*right;
AndNode(Node*left,Node*right): left(left), right(right){}
~AndNode(){delete left;delete right;}
Node*copy(){returnnewAndNode(left->copy(), right->copy());}
Node*negation();
};

structOrNode:Node{
Node*left,*right;
OrNode(Node*left,Node*right): left(left), right(right){}
~OrNode(){delete left;delete right;}
Node*copy(){returnnewOrNode(left->copy(), right->copy());}
Node*negation();
};

structNotNode:Node{
Node*x;
NotNode(Node*x): x(x){}
~NotNode(){delete x;}
Node*copy(){returnnewNotNode(x->copy());}
Node*negation();
};
structVarNode:Node{
std::stringvar;
VarNode(const std::string&var):var(var){}
Node*copy(){returnnewVarNode(var);}
};

16. Write a C program to append the contents of one file to another file.
[2018, 2019, 2020]
#include <stdio.h>
#include <stdlib.h>

main()
{
FILE *fsring1, *fsring2, *ftemp;
char ch, file1[20], file2[20], file3[20];

printf("Enter name of first file ");


gets(file1);
printf("Enter name of second file ");
gets(file2);
printf("Enter name to store merged file ");
gets(file3);
fsring1 = fopen(file1, "r");
fsring2 = fopen(file2, "r");
if (fsring1 == NULL || fsring2 == NULL)
{
perror("Error has occured");
printf("Press any key to exit...\n");
exit(EXIT_FAILURE);
}
ftemp = fopen(file3, "w");
if (ftemp == NULL)
{
perror("Error has occures");
printf("Press any key to exit...\n");
exit(EXIT_FAILURE);
}
while ((ch = fgetc(fsring1)) != EOF)
fputc(ch, ftemp);
while ((ch = fgetc(fsring2)) != EOF)
fputc(ch, ftemp);
printf("Two files merged %s successfully.\n", file3);
fclose(fsring1);
fclose(fsring2);
fclose(ftemp);
return 0;
}
Output
Enter name of first file a.txt
Enter name of second file b.txt
Enter name to store merged file merge.txt
Two files merged merge.txt successfully.

17. Write a C program to compute the sum of all elements stored in an integer array
using printer. [2017]
#include <stdio.h>
#include <malloc.h>
voidmain()
{ inti, 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 First List \n");
for(i=0;i< n;i++)
{
scanf("%d", a +i);
}
</* Compute the sum of all elements in the given array */
for(i=0;i< n;i++)
{
sum = sum +*(a +i);
}
printf("Sum of all elements in array = %d\n", sum);
}

Out put
Enter the size of array A
5
Enter Elements of First List
4
9
10
56
100
Sum of all elements in array = 179

18. Write a C program to write integer from 1 to 10 and store data into the file name
“razu.dat”. [2017]
#include <stdio.h>
int main(void) {
// creating a FILE variable FILE *fptr;
// integer variable int num;
// open the file in write mode fptr = fopen("integers", "w");
if (fptr != NULL)
{ printf("File created successfully!\n");
}
else {
printf("Failed to create the file.\n");
// exit status for OS that an error occurred
return -1;
}
// enter integer numbers
printf("Enter some integer numbers [Enter -1 to exit]: ");
while (1)
{ scanf("%d", &num);
if (num != -1)
{ putw(num, fptr);
}
else {
break;
}
}
// close connection
fclose(fptr);
// open file for reading
fptr = fopen("integers", "r");
// display numbers
printf("\nNumbers:\n");
while ( (num = getw(fptr)) != EOF ) {
printf("%d\n", num);
}
printf("\nEnd of file.\n");
// close connection
fclose(fptr);
return 0;
}
19. Write a c program to multiply two matrices.[2019]
#include <stdio.h>
int main()
{
int m, n, p, q, c, d, k, sum = 0;
int first[50][50], second[50][50], multiply[50][50];
printf("Enter number of rows of first matrix:\n");
scanf("%d", &m);
printf("Enter number of columns of first matrix\n");
scanf("%d", &n);
printf("Enter elements of first matrix\n");
for (c = 0; c < m; c++){
for (d = 0; d < n; d++){
scanf("%d", &first[c][d]);
}
}
printf("Enter number of rows of second matrix:\n")
scanf("%d", &p);
printf("Enter number of columns of second matrix\n");
scanf("%d", &q);
if (n != p){
printf("The matrices can't be multiplied with each other.\n");
}
else
{
printf("Enter elements of second matrix\n");
for (c = 0; c < p; c++){
for (d = 0; d < q; d++){
scanf("%d", &second[c][d]);
}
}
for (c = 0; c < m; c++) {
for (d = 0; d < q; d++) {
for (k = 0; k < p; k++) {
sum = sum + first[c][k]*second[k][d];
}
multiply[c][d] = sum;
sum = 0;
}
}
printf("Product of the matrices:\n");
for (c = 0; c < m; c++) {
for (d = 0; d < q; d++){
printf("%d\t", multiply[c][d]);
}
printf("\n");
}
} return 0;
}
Output:
Enter number of rows and columns of first matrix
12
Enter the first matrix
3
5
Enter number of rows and columns of second matrix
21
Enter the first matrix
6
7
Product of matrices:
53
20. Write a c program to determine the largest value of from three numbers. [2019]
#include<stdio.h>
#include<conio.h>
int main()
{
int a,b,c;
printf("enter the numbers: ");
scanf("%d%d%d",&a,&b,&c);
if(a>b)
{
if(a>c)
printf("largest number %d",a);
else
printf("largest number %d",c); }
else
{
if(b>c)
printf("largest number %d",b);
else
printf("largest number %d",c); }
getch();
}
Output:
Enter number: 6
7
8
Largest number 8

21. Write a c program to calculate the sum of following series:


𝟏+𝟐𝟐+𝟑𝟑+𝟒𝟒+⋯………….𝟓𝟎𝟓𝟎 [2019]
#include<stdio.h>
#include<math.h>
int main()
{
int i,n;
float k, sum;
printf("Enter n?");
scanf("%d",&n);
sum= 0;
for(i=1;i<=n;i++)
{
k= 1/i;
sum = sum +pow(k,i);
}
printf("\nSum=%f", sum);
return 0;
}
22. Write a c program to find the factorial of an integer. [2019]
#include<stdio.h>
int main()
{
int n; int f = 1;
printf(―\n Enter a positive interger : ―);
scanf(―%d”,&n);
while(n>0)
{
f = f * n; n–;
}
printf(―\n Factorial of the given number is %d\n‖, f);
return 0;
}

23. Write a C program to add 1 to 50. (2020)


#include <stdio.h>

void main()
{
int num, sum = 0;

for (num = 1; num <= 50; num++)


{
sum = sum + num;
}
printf("Sum = %d \n", sum);
}
24. Write a C program to read an array and display it's elements in reverse
order.(2020)
#include<stdio.h>

int main()
{
int a[5], i;

printf("Enter 5 integer numbers\n");


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

printf("Array elements are:\n");


for(i = 4; i >= 0; i--)
printf("%d\n", a[i]);
return 0;
}
25. Write a C program that prints the smallest number from three numbers. (2022)
#include <stdio.h>

int main() {
int num1, num2, num3;
printf("Enter three numbers: ");
scanf("%d %d %d", &num1, &num2, &num3);
int smallest = num1;

if (num2 < smallest) {


smallest = num2;
}

if (num3 < smallest) {


smallest = num3;
}

printf("The smallest number is: %d\n", smallest);

return 0;
}
26. Write down a C program to exchange the value of two variables (x,y) using a
pointer. (2022)
Ans:
#include <stdio.h>
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
int main() {
int x, y;
printf("Enter the value of x: ");
scanf("%d", &x);

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


scanf("%d", &y);

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


swap(&x, &y);
printf("After swapping: x = %d, y = %d\n", x, y);

return 0;
}
27. Write down a C program to read the content of a file and write the contents to
another file. (2022)
#include <stdio.h>

int main() {
FILE *sourceFile, *targetFile;
char ch;
sourceFile = fopen("source.txt", "r");
if (sourceFile == NULL) {
printf("Failed to open source file.\n");
return 1;
}
targetFile = fopen("target.txt", "w");
if (targetFile == NULL) {
printf("Failed to open target file.\n");
fclose(sourceFile);
return 1;
}
while ((ch = fgetc(sourceFile)) != EOF) {
fputc(ch, targetFile);
}

fclose(sourceFile);
fclose(targetFile);

printf("Contents copied successfully.\n");

return 0;
}

You might also like