Structured Programming Language Handnote
Structured Programming Language Handnote
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
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);
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.
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.
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.
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
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
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
CHAPTER 1
COMPUTER PROGRAMMING TECHNIQUES
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.
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.
case constant-expression :
statement(s);
break; /* optional */
case constant-expression :
statement(s);
break; /* optional */
}
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.
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.
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.
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.
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
CHAPTER 2
STRUCTURED PROGRAMMING LANGUAGE
Module A
Module B
Module C
If (condition) then:
[Module A]
[End of If Structure]
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.
# 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.
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
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;
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.
CHAPTER 3
OPERATORS AND EXPRESSIONS
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.
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
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
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).
Truth table for bit wise operation & bit wise operators:
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
123456789
#include <stdio.h>
intmain()
{
inti=20;
while(i>10)
{
printf("%d ",i);
i--;
}
}
OUTPUT:
20 19 18 17 16 15 14
13 12 11
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
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.
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.
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)
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.
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
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
int main() {
recursion();
}
Recursion Vs Iteration
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);
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.
• `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.
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.
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.
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.
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.
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.
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.
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
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
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
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.
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};
int printf(const char* str, ...); int fprintf(FILE *fptr, const char *str, ...);
ftell(fp); rewind(fp);
int printf(const char* str, ...); int fprintf(FILE *fptr, const char *str, ...);
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);
}
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”);
main(){
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:
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;}
int main()
{
int num;
int result;
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;
Perimeter = a+b+c;
s = (a+b+c)/2;
Area = sqrt(s*(s-a)*(s-b)*(s-c));
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;
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];
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
void main()
{
int num, sum = 0;
int main()
{
int a[5], i;
int main() {
int num1, num2, num3;
printf("Enter three numbers: ");
scanf("%d %d %d", &num1, &num2, &num3);
int smallest = num1;
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);
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);
return 0;
}