Programming in C - CS3251 - Question Bank
Programming in C - CS3251 - Question Bank
PART A (2 Marks)
1. What are the various types of operators?
C supports the following types of operators
Unary
Unary Plus +
Unary Minus -
Increment ++
Decrement --
Binary
Arithmetic +,-,*,/,%
Relational <,>,<=,>=,==,!=
Logical &&,||,!
Bitwise &,|,^,<<,>>
Assignment =
Shorthand assignment +=, -=,*=,/=,%=
Ternary
?:
Special
Sizeof(), *. ->
A storage class represents the visibility and a location of a variable. It tells from what part of code
we can access a variable. A storage class is used to describe the following things:
The variable scope.
The location where the variable will be stored.
The initialized value of a variable.
A lifetime of a variable.
Auto storage class
The variables defined using auto storage class are called as local variables. Auto stands for automatic
storage class. A variable is in auto storage class by default if it is not explicitly specified.
The scope of an auto variable is limited with the particular block only. Once the control goes out of the
block, the access is destroyed. This means only the block in which the auto variable is declared can
access it.
A keyword auto is used to define an auto storage class. By default, an auto variable contains a garbage
value.
Example, auto int age;
The program below defines a function with has two local variables
int add(void) { int a=13;
auto int b=48; return a+b;}
We take another program which shows the scope level "visibility level" for auto variables in each block code wh
OUTPUT:
321
Extern stands for external storage class. Extern storage class is used when we have global functions or
variables which are shared between two or more files.
Keyword extern is used to declaring a global variable or function in another file to provide the
reference of variable or function which have been already defined in the original file.
The variables defined using an extern keyword are called as global variables. These variables are
accessible throughout the program. Notice that the extern variable cannot be initialized it has
already been defined in the original file
Example, extern void display();
First File: main.c
#includeFile: original.c
Second
<stdio.h> extern
i; #include
<stdio.h>
main() { i=48;
Result:
printf("value of the external integer is = %d\n", i);
value of the external integer is = 48
The static variables are used within function/ file as local static variables. They can also be used as
a global variable
Static local variable is a local variable that retains and stores its value between function calls
or block and remains visible only to the function or block in which it is defined.
Static global variables are global variables visible only to the file in which it is declared.
Example: static int count = 10;
Keep in mind that static variable has a default initial value zero and is initialized only once in its
lifetime.
Result:
#include <stdio.h> /* function declaration */
void next(void);
Global variables
iteration=14 andare accessible throughout the file whereas static variables are accessible only to the
counter=
static int counter
particular part of a=code.
7; /* global variable */
7 iteration=15 and
main() {
counter= 8 iteration=16
The lifespan of a static variable is in the entire program code. A variable which is declared or
while(counter<10)
initialized using static keyword always contains zero as a default value.
{ next();
counter++; }
return 0;}
void next( void ) { /* function definition */
static int iteration = 13; /* local static variable
*/ iteration ++;
printf("iteration=%d and counter= %d\n", iteration, counter);}
Register storage class
You can use the register storage class when you want to store local variables within functions or
blocks in CPU registers instead of RAM to have quick access to these variables. For example,
"counters" are a good candidate to be stored in the register.
Example: register int age;
The keyword register is used to declare a register storage class. The variables declared using
register storage class has lifespan throughout the program.
It is similar to the auto storage class. The variable is limited to the particular block. The only
difference is that the variables declared using register storage class are stored inside CPU registers
instead of a memory. Register has faster access than that of the main memory.
The variables declared using register storage class has no default value. These variables are often declared at the
OUTPUT:
error: address of register variable 'weight' requested
The next table summarizes the principal features of each storage class which are commonly used in C programm
Extern Outside all Memory Zero Entire the file and other files program runtime
functions where the variable is
declared as extern
DECISION STATEMENTS
It checks the given condition and then executes its sub-block. The decision statement decides the
statement to be executed after the success or failure of a given condition.
Types:
Decision making is about deciding the order of execution of statements based on certain conditions
or repeat a group of statements until certain specified conditions are met. C language handles
decision-making by supporting the following statements,
if statement
switch statement
goto statement
The if statement may be implemented in different forms depending on the complexity of conditions
to be tested. The different forms are,
1. Simple if statement
2. if....else statement
Simple if statement
The general form of a simple if statement is,
if(expression)
statement inside;
statement outside;
If the expression returns true, then the statement-inside will be executed, otherwise statement-
inside is skipped and only the statement-outside is executed.
Example:
#include
void main( )
if...else
{ statement
The general form of a simple if...else statement is,
int x,
Ifif(expression)
the
y; xexpression
= is true, the statement-block1 is executed, else statement-block1 is skipped
and statement-block2 is executed.
{ 15;
Example:
statement
y = 13; block1;
} if (x > y )
else{
}
x is greater than y
#include
void main( )
Nested
{ if....else statement
The general form of a nested if...else statement is,
int x,
if( y;
expression
x= )
{ 15;
if(
y =expression1
18; )
{if (x > y )
{ statement block1;
y is greater than x
statement block2;
else
statement block3;
}
if expression is false then statement-block3 will be executed, otherwise the execution continues
and enters inside the first if to perform the check for the next if block, where if expression 1 is true
the statement-block1 is executed otherwise statement-block2 is executed.
Example:
#include <stdio.h>
void main( )
int a, b, c;
printf("Enter 3 numbers...");
if(a > b)
if(a > c)
else
}
else
{
if(b > c)
{
printf("b is the greatest");
}
else
{
printf("c is the greatest");
}
}
}
else if ladder
The general form of else-if ladder is,
if(expression1)
{
statement block1;
}
else if(expression2)
{
statement block2;
}
else if(expression3 )
{
statement block3;
}
else
default statement;
The expression is tested from the top(of the ladder) downwards. As soon as a true condition is
found, the statement associated with it is executed.
Example :
#include <stdio.h>
void main( )
int a;
printf("Enter a number...");
scanf("%d", &a);
else if(a%8 == 0)
printf("Divisible by 8");
else if(a%5 == 0)
printf("Divisible by 5");
else
printf("Divisible by none");
Loop is a block of statements which are repeatedly executed for certain number of times. Types
1. For loop
2. Nested for loops
3. While loop
4. do while loop
5. do-while statement with while loop
While Loop
A while loop is the most straightforward looping structure. The basic format of while loop is as
follows:
It is while
an entry-controlled
(condition) loop. In while loop, a condition is evaluated before processing a body of the
loop. If a condition
{ is true then and only then the body of a loop is executed. After the body of a
loop is statements;
executed then control again goes back at the beginning, and the condition is checked if it is
true, the same process is executed until the condition becomes false. Once the condition becomes
false, the control goes out of the loop.
After exiting the loop, the control goes to the statements which are immediately after the loop. The
body of a loop can contain more than one statement. If it contains only one statement, then the curly
braces are not compulsory. It is a good practice though to use the curly braces even we have a single
statement in the body.
In while loop, if the condition is not true, then the body of a loop will not be executed, not even once. It
is different in do while loop which we will see shortly.
Do-While loop
A do-while loop is similar to the while loop except that the condition is always executed after the
body of a loop. It is also called an exit-controlled loop.
The basic format of while loop is as follows:
Asdowe
{ saw in a while loop, the body is executed if and only if the condition is true. In some cases,
westatements
have to execute a body of the loop at least once even if the condition is false. This type of
operation can be achieved by using a do-while loop.
} while (expression);
In the do-while loop, the body of a loop is always executed at least once. After the body is executed,
then it checks the condition. If the condition is true, then it will again execute the body of a loop
otherwise control is transferred out of the loop.
Similar to the while loop, once the control goes out of the loop the statements which are
immediately after the loop is executed.
The critical difference between the while and do-while loop is that in while loop the while is written
at the beginning. In do-while loop, the while condition is written at the end and terminates with a
semi-colon (;)
The following program illustrates the working of a do-while loop:
We are going to print a table of number 2 using do while loop.
#include<stdio.h> #include<conio.h> int main()
{
int num=1;
}
Output:
2
4
6
8
10
12
14
16
18
20
In the above example, we have printed multiplication table of 2 using a do-while loop. Let's see how the pro
First, we have initialized a variable 'num' with value 1. Then we have written a do-while loop.
In a loop, we have a print function that will print the series by multiplying the value of num with 2.
3. After each increment, the value of num will increase by 1, and it will be printed on the
screen.
4. Initially, the value of num is 1. In a body of a loop, the print function will be executed in this
way: 2*num where num=1, then 2*1=2 hence the value two will be printed. This will go on
until the value of num becomes 10. After that loop will be terminated and a statement which
is immediately after the loop will be executed. In this case return 0.
For loop
A for loop is a more efficient loop structure in 'C' programming. The general structure of for loop is as
follows:
The value;
for(initial initial condition;
value of theincrementation
for loop is performed only once. )
or decrementation
{
The condition is a Boolean expression that tests and compares the counter to a fixed value
statements;
after each iteration, stopping the for loop when false is returned.
} incrementation/decrementation increases (or decreases) the counter by a set value. Following program illust
The
Output:
1
2
3
4
5
6
7
8
9
10
The above program prints the number series from 1-10 using for loop.
1. We have declared a variable of an int data type to store values.
2. In for loop, in the initialization part, we have assigned value 1 to the variable number. In the
condition part, we have specified our condition and then the increment part.
3. In the body of a loop, we have a print function to print the numbers on a new line in the
console. We have the value one stored in number, after the first iteration the value will be
incremented, and it will become 2. Now the variable number has the value 2. The condition
will be rechecked and since the condition is true loop will be executed, and it will print two
on the screen. This loop will keep on executing until the value of the variable becomes 10.
After that, the loop will be terminated, and a series of 1-10 will be printed on the screen.
In C, the for loop can have multiple expressions separated by commas in each part. For
example:
Notice that loops can also be nested where there is an outer loop and an inner loop. For each iteration of t
Consider the following example, that uses nested for loops output a multiplication table:
Output:
1x0=0
1x1=1
1x2=2
1x3=3
1x4=4
1x5=5
2x0=0
2x1=2
2x2=4
2x3=6
2x4=8
2 x 5 = 10
The nesting of for loops can be done up-to any level. The nested loops should be adequately indented to
make code readable. In some versions of 'C,' the nesting is limited up to 15 loops, but some provide
more.
4. Explain operators inC
C language supports a rich set of built-in operators. An operator is a symbol that tells the compiler to
perform a certain mathematical or logical manipulation. Operators are used in programs to
manipulate data and variables.
C operators can be classified into following types:
Arithmetic operators
Relational operators
Logical operators
Bitwise operators
Assignment operators
Conditional operators
Special operators
ARITHMETIC OPERATORS
C supports all the basic arithmetic operators. The following table shows all the basic arithmetic
operators.
OperatorDescription
% remainder of division
Relational operators
The following table shows all relation operators supported by C.
Operator Description
Logical operators
|| Logical OR (a || b) is true
Bitwise operators
Bitwise operators perform manipulations of data at bit level. These operators also perform shifting
of bits from right to left. Bitwise operators are not applied to float or double(These are datatypes,
we will learn about them in the next tutorial).
Operator Description
| Bitwise OR
^ Bitwise exclusive OR
0 0 0 0 0
0 1 0 1 1
1 0 0 1 1
1 1 1 1 0
The bitwise shift operator, shifts the bit value. The left operand specifies the value to be shifted and
the right operand specifies the number of positions that the bits in the value have to be shifted
Assignment Operators
Assignment operators supported by C language are as follows.
Conditional operator
1. Ternary Operator
2. ? : Operator
It is actually the if condition that we use in C language decision making, but using conditional
operator, we turn the if condition statement into a short and simple operator.
The syntax of a conditional operator is :
The first expression (expression 1) generally returns either true or false, based on which it is
decided whether (expression 2) will be executed or (expression 3)
If (expression 1) returns true then the expression on the left side of " : " i.e (expression 2) is
executed.
If (expression 1) returns false then the expression on the right side of " : " i.e (expression 3)
is executed.
Special operator
Introduction
A program which processes the source code before it passes through the compiler is known as preprocessor.
The commands of the preprocessor are known as preprocessor directives.
It is placed before the main().
It begins with a # symbol.
They are never terminated with a semicolon.
Preprocessor Directives
The preprocessor directives are divided into four different categories which are as follows:
1. Macro expansion
There are two types of macros - one which takes the argument and another which does not
take any argument.
Values are passed so that we can use the same macro for a wide range of values.
Syntax:
#define name replacement
Where,
name – it is known as the micro template.
replacement text – it is known as the macro expansion.
i);
Some of the predefined macros which are readily available are as follows:
Macro Description
LINE It contains a current line number as a decimal constant.
FILE It contains the current filename as a string literal.
DATE It shows the current date as a character literal in the ―MMM DD YYYY‖
format.
TIME It shows the current time as a character literal in ―HH:MM:SS‖ format.
STDC It is defined as 1 when the compiler complies with the ANSI standard.
TIMESTAMP It is a sing literal in the form of ―DDD MM YYYY Date HH:MM:SS‖. It is used to
spec and time of the last modification of the current source file.
2. File inclusion
The file inclusion uses the #include.
Syntax:
#include filename
The content that is included in the filename will be replaced at the point where the directive
is written.
By using the file inclusive directive, we can include the header files in the programs.
Macros, function declarations, declaration of the external variables can all be combined in
the header file instead of repeating them in each of the program.
The stdio.h header file contains the function declarations and all the information regarding
the input and output.
If the first way is used, the file and then the filename in the current working directory and
the specified list of directories would be searched.
If the second way, is used the file and then the filename in the specified list of directories
would be searched.
3. Conditional compilation
The conditional compilation is used when we want certain lines of code to be compiled or
not.
It uses directives like #if, #elif, #else,
#endif Syntax
If there are a number of conditions to be checked we can use the #elif instead of #else and #if.
4. Miscellaneous directive
There are some directives which do not fall in any of the above mentioned categories.
There are two directives:
i) #undef : This directive is used in relation to the #define directive. It is used to undefine a defined
macro.
ii) #pragma : It is a specialized and rarely used directive. They are used for turning on and off
certain features.
Following table will show you various directives that we have studied in this chapter:
Directives Description
#define It substitutes a preprocessor macro.
#include It inserts a particular header file from another file.
#undef A preprocessor macro is undefined.
#ifdef It returns true if the macro is defined.
#ifndef It returns true if the macro is not defined.
#if It tests if the compile time condition is true.
#else It is an alternative for #if.
#elif It has #else and #if in one statement.
#endif The conditional preprocessor is ended.
#error It prints the error message on stderr.
#pragma It issues special commands to the compiler by using a standardized method.
UNIT- II - ARRAYS AND STRINGS
PART A
1. Define Array
Array is a collection of similar type of values
All values are stored in continuous memory locations
All values share a common name
Linear data structure. The elements are organized in a sequential order.
9. Define Sorting
Sorting is a process of arranging the elements either in ascending order or descending order.
10. Sort the following elements using selection sort method. 23,55,16,78,2
Step1:Find smallest element in the list & exchange the element with first element of the list
2,55,16,78,23
Step2: Find second smallest value & exchange it with the second element of the list
2,16,55,78,23
Step 3: Continue the process until all the elements are arranged in the order
2,16,23,78,55
Step 4: 2,16,23,55,78
PART B
1. Write a c program to multiply two matrices (2D array) which will be entered by
a user.
Ans:
#include <stdio.h>
int main()
{
int m, n, p, q, c, d, k, sum = 0; int first[10]
[10], second[10][10], multiply[10][10];
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;
}
}
return 0;
}
2. Write a c program to find scaling of two matrices (2D array) which will be entered by a
user.(5)
Ans:
#include<stdio.h>
int main(){
/* 2D array declaration*/
int disp[2][3];
/*Counter variables for the loop*/
int i, j;
for(i=0; i<2; i++)
{ for(j=0;j<3;j++) {
printf(―enter the value to be scaled‖); scanf(―
%d‖,&z);
printf("Enter value for disp[%d][%d]:", i, j);
scanf("%d", &z*disp[i][j]);
}
}
3. Write a c program to find determinant of two matrices (2D array) which will be entered by
void main()
{
int arr1[10][10],i,j,n;
int det=0;
}
}
printf("The matrix is :\n");
for(i=0;i<3;i++)
{
for(j=0;j<3 ;j++)
printf("% 4d",arr1[i][j]);
printf("\n");
}
for(i=0;i<3;i++)
det = det + (arr1[0][i]*(arr1[1][(i+1)%3]*arr1[2][(i+2)%3] -
arr1[1][(i+2)%3]*arr1[2][(i+1)%3]));
if (j == c - 1) {
printf("\n\n");
}
}
return 0;
}
selection Sort in C
Selection sort is another algorithm that is used for sorting. This sorting algorithm, iterates through
the array and finds the smallest number in the array and swaps it with the first element if it is
smaller than the first element. Next, it goes on to the second element and so on until all elements are
sorted.
Example of Selection Sort
Consider the array:
[10,5,2,1]
The first element is 10. The next part we must find the smallest number from the remaining array.
The smallest number from 5 2 and 1 is 1. So, we replace 10 by 1.
The new array is [1,5,2,10] Again, this process is repeated.
Finally, we get the sorted array as [1,2,5,10].
Let us continue with this article on Selection Sort in C and see how the algorithm works,
Algorithm for Selection Sort:
Step 1 − Set min to the first location
Step 2 − Search the minimum element in the array
Step 3 – swap the first location with the minimum value in the array
Step 4 – assign the second element as min.
Step 5 − Repeat the process until we get a sorted array.
Let us take a look at the code for the the programmatic implementation,
Code for Selection Sort:
#include <stdio.h>
int main()
{
int a[100], n, i, j, position, swap;
printf("Enter number of elementsn");
scanf("%d", &n);
printf("Enter %d Numbersn",
n); for (i = 0; i < n; i++)
scanf("%d", &a[i]);
for(i = 0; i < n - 1; i++)
{
position=i;
for(j = i + 1; j < n; j++)
{
if(a[position] > a[j])
position=j;
}
if(position != i)
{
swap=a[i];
a[i]=a[position];
a[position=swap;
}
}
printf("Sorted Array:n");
for(i = 0; i < n; i++)
printf("%dn", a[i]);
return 0;
}
7. Explain Linear search in C
A linear search, also known as a sequential search, is a method of finding an element within a list. It
checks each element of the list sequentially until a match is found or the whole list has been
searched.
Binary Search: Search a sorted array by repeatedly dividing the search interval in half. Begin with an
interval covering the whole array. If the value of the search key is less than the item in the middle of the
interval, narrow the interval to the lower half. Otherwise narrow it to the upper half. Repeatedly check
until the value is found or the interval is empty.
Example :
The idea of binary search is to use the information that the array is sorted and reduce the time
complexity to O(Log n).
int main(void)
{
int arr[] = { 2, 3, 4, 10, 40 };
int x = 10;
int n = sizeof(arr) / sizeof(arr[0]);
int result = binarySearch(arr, 0, n - 1, x);
(result == -1) ? cout << "Element is not present in array"
: cout << "Element is present at index " << result;
return 0;
}
Output :
Element is present at index 3
Iterative implementation of Binary Search
int main(void)
{
int arr[] = { 2, 3, 4, 10, 40 };
int x = 10;
int n = sizeof(arr) / sizeof(arr[0]);
int result = binarySearch(arr, 0, n - 1, x);
(result == -1) ? cout << "Element is not present in array"
: cout << "Element is present at index " << result;
return 0;
}
Output :
Element is present at index 3
Time Complexity:
The time complexity of Binary Search can be written as
The
T(n)above recurrence
= T(n/2) +c can be solved either using Recurrence T ree method or Master method. It falls in
case II of Master Method and solution of the recurrence is .
Auxiliary Space: O(1) in case of iterative implementation. In case of recursive implementation, O(Logn)
recursion call stack space.
Unit III Functions and pointers
PART A
1. What is a function?
Function is a set of instructions
Self contained block
Performs a specific task
Used to avoid redundancy of code
2. What is the need for functions?
To reduce the complexity of large programs
To increase the readability
To achieve reusability
To avoid redundancy of code
To save Memory
3. What are the uses of pointer?
Saves Memory Space
Used for dynamic memory allocation
Faster execution
Used to pass array of values to a function as a single argument
4. Define typedef .
The typedef keyword enables the programmer to create a new data type name by
using an existing data type.
By using typedef, no new data is created, rather an alternate name is given to a
known data type.
Indirection operator : *- Dereferencing operator is used to access the value at the pointer variable
Ex: int a=5; int
*p=&a; printf(―
%d‖,*(p));
Formal argument: Specified in the function definition statement. It takes either copy
or address of the actual arguments
Valid operation
The pointer holds the address 2000. This value is added with 1.
The data type size of the constant is added with the address. p=
2000+(2*1)=2002
8. List out any 4 math functions
pow(x,y) : used to find power of value of xy .Returns a double value log10(x)
: used to find natural logarithmic value of x
13. State the advantages of user defined functions over pre-defined function.
A user defined function allows the programmer to define the exact function of the
module as per requirement. This may not be the case with predefined function. It
may or may not serve the desired purpose completely.
A user defined function gives flexibility to the programmer to use optimal
programming instructions, which is not possible in predefined function.
14. Write the syntax for pointers to structure.
Struct S
char datatype1;
int datatype2; float
datatype3;
};
more memory and are generally slow. Instead, you can use loop.
Example:
void recursion()
int main()
recursion();
19. What are the functions supports for dynamic memory allocation?
The functions supports for dynamic memory allocation are,
malloc()
realloc()
calloc()
free()
PART B
#include <stdio.h>
int addition(int num1, int num2)
{
int sum;
sum = num1+num2; return
sum;
}
int main()
{
int var1, var2; printf("Enter
number 1: ");
scanf("%d",&var1);
return 0;
}
Prototype Syntax
function-prototype-declaration:
declaration-specifiers(opt) declarator;
The declarator includes a parameter type list, which can consist of a single parameter of type void . In
its simplest form, a function prototype declaration might have the following format:
storage_class(opt) return_type(opt) function_name (
type(1) parameter(1), ..., type(n) parameter(n) );
Consider the following function definition:
char function_name( int lower, int *upper, char (*func)(), double y )
{}
The corresponding prototype declaration for this function is:
char function_name( int lower, int *upper, char (*func)(), double y );
A prototype is identical to the header of its corresponding function definition specified in the prototype
style, with the addition of a terminating semicolon (;) or comma (,), as appropriate (depending on
whether the prototype is declared alone or in a multiple declaration).
Function prototypes need not use the same parameter identifiers as in the corresponding function
definition because identifiers in a prototype have scope only within the identifier list. Moreover, the
identifiers themselves need not be specified in the prototype declaration; only the types are required.
For example, the following prototype declarations are equivalent:
char function_name( int lower, int *upper, char (*func)(), double y );
char function_name( int a, int *b, char (*c)(), double d );
char function_name( int, int *, char (*)(), double );
Though not required, identifiers should be included in prototypes to improve program clarity and
increase the type-checking capability of the compiler.
Variable-length argument lists are specified in function prototypes with ellipses. At least one parameter
must precede the ellipses. For example:
char function_name( int lower, ... );
Data-type specifications cannot be omitted from a function prototype.
3. What is recursion? Write a C program to find the sum of the digits, to find the factorial of a
number and binary search using recursion.
Ans: The process in which a function calls itself directly or indirectly is called recursion and
the corresponding function is called as recursive function.
Factorial:
#include<stdio.h>
long int multiplyNumbers(int n);
int main() {
int n;
printf("Enter a positive integer: ");
scanf("%d",&n);
printf("Factorial of %d = %ld", n, multiplyNumbers(n));
return 0;
}
long int multiplyNumbers(int n)
{ if (n>=1)
return n*multiplyNumbers(n-1);
else
return 1;
}
Binary search:
#include <stdio.h>
void binary_search(int [], int, int, int);
void bubble_sort(int [], int);
int main()
{
int key, size, i;
int list[25];
5. Explain about pointers and write the use of pointers in arrays with suitable example.
Ans: 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.
#include <stdio.h>
int main()
{
int i;
int a[5] = {1, 2, 3, 4, 5};
int *p = a; // same as int*p = &a[0]
for (i = 0; i < 5; i++)
{
printf("%d", *p);
p++;
}
return 0;
}
6. Explain the concept of pass by value and pass by reference. Write a C program to
swap the content of two variables using pass by reference.
` Pass by value: In this approach we pass copy of actual variables in function as a parameter.
Hence any modification on parameters inside the function will not reflect in the actual variable. For
example:
#include<stdio.h>
int main(){
int a=5,b=10;
swap(a,b);
printf("%d %d",a,b);
return 0;
}
void swap(int a,int b)
{ int temp;
temp =a;
a=b;
b=temp;
}
Output: 5 10
(b) Pass by reference: In this approach we pass memory address actual variables in function as a
parameter. Hence any modification on parameters inside the function will reflect in the actual variable.
For example:
#incude<stdio.h>
int main(){
int a=5,b=10;
swap(&a,&b);
printf("%d %d",a,b);
return 0;
}
void swap(int *a,int *b)
{ int *temp;
*temp =*a;
*a=*b;
*b=*temp;
}
Output: 10 5
UNIT IV :
STRUCTURES
AND UNIUON
1. Compare arrays and structures.
Comparison of arrays and structures is as follows.
Arrays Structures
A structure is a collection of data items of
An array is a collection of data items of same different data types. Structures can be declared
data type. Arrays can only be declared. and defined.
Structure Union
Every member has its own memory. All members use the same memory.
The keyword used is struct. The keyword used is union.
All members occupy separate memory location, Different interpretations for the same memory
hence different interpretations of the same location are possible. Conservation of memory
memory is
location are not possible. Consumes more space possible
compared to union.
3. Define Structure in C.
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.
4. What you meant by structure definition?
A structure type is usually defined near to the start of a file using a typedef
statement. typedef defines and names a new type, allowing its use throughout the
program. typedefs usually occur just after the #define and #include statements in a
file.
Here is an example structure
definition. typedef struct {
char
name[64];
char
course[1
28]; int
age;
int year;
} student;
This defines a new type student variables of type student can be declared as
follows. student st_rec;
{
member definition;
member definition;
...
member definition;
} [one or more union variables];
RAM. This means that the variable has a maximum size equal to the register size
(usually one word) and cant have the unary '&' operator applied to it (as it does not
have a memory location).
{
register int Miles;
}
{
int Count; auto int Month;
}
The example above defines two variables with the same storage class. auto can only
be used within functions, i.e. local variables.
code files as well as the file name that we want that appears when an error
takes place. Its format is:
#line number "filename"
Where number is the new line number that will be assigned to the next code line.
The line numbers of successive lines will be increased one by one from this point on.
Struct S
{
char datatype1; int
datatype2; float
datatype3;
};
struct name {
member 1;
member 2;
...
};
The above illustrated structure prototype describes one node that comprises of two
logical segments. One of them stores data/information and the other one is a
pointer indicating where the next component can be found. .Several such inter-
connected nodes create a chain of structures.
18. What is singly linked list?
A linear linked list is a chain of structures where each node points to the next
node to create a list. To keep track of the starting node's address a dedicated pointer
(referred as startpointer) is used. The end of the list is indicated by a NULLpointer.
In order to create a linked list of integers, we define each of its element (referred as
node) using the following declaration.
struct node_type {
int data;
};
This statement creates the starting node of list. A block of memory whose
size is equal to the sizeof(node) is allocated to the node pointer start. Typecasting
is used because otherwise malloc will return pointer to character.
PART-B
Structure
declaration- struct
tagname
Data type
member1; Data
type member2;
Data type
member3;
………
………
struct
{
Data type member1;
………
………
struct tagname
struct element 1;
struct element 2;
struct element 3;
………
………
struct element n;
};
char branch[20];
}; struct student s;
Like primary variables structure variables can also be initialized when they are
declared. Structure templates can be defined locally or globally. If it is local it can be used
within that function. If it is global it can be used by all other functions of the program.
struct student
int age=20;
char
name[20]=‖sona‖;
}s1;
A structure can be
{
int age,roll;
char name[20];
} struct student
s2={17,102,‖rupa‖};
If initialiser is less than no.of structure variable, automatically rest values are taken as zero.
Dot operator is used to access the structure elements. Its associativety is from left to right.
s1.roll; s1.age;
Elements of structure are stored in contiguous memory locations. Value of structure variable can be
assigned to another structure variable of same type using assignment operator.
Example:
} s1,s2;
Unary, relational, arithmetic, bitwise operators are not allowed within structure variables.
2. Write a C program to store the employee information using structure and
search a particular employee using Employee number.
/*C program to read and print employee's record using structure*/
#include <stdio.h>
/*structure declaration*/
struct employee{
char name[30];
int empId;
float salary;
};
int main()
{
/*declare structure variable*/
struct employee emp;
struct time
int hr,min;
};
struct day
{
};
struct student
char nm[20];
struct day d;
4. Explain about array of structures and pointers in structures with example program.
Array of structures
When database of any element is used in huge amount, we prefer Array of structures.
Example: suppose we want to maintain data base of 200 students, Array of structures is used.
#include<stdio.h>
#include<string.h>
struct student
};
void main()
s[i].roll=i+1;
printf("\nEnter information of students:");
for(i=0;i<200;i++)
scanf("%s",s[i].branch); printf("\n");
for(i=0;i<200;i++)
printf("\nName:");
puts(s[i].name);
printf("\nBranch:");
puts(s[i].branch);
struct student
{
char name[30];
int roll,age,marks[5];
5. Write a C program to create mark sheet for students using self referential structure.
#include<stdio.h>
#include<conio.h>
struct mark_sheet{
char name[20];
int marks[10];
int total;
float
average; char
rem[10];
char cl[20];
}students[100];
int main(){
int
a,b,n,flag=1;
char ch;
clrscr();
scanf("%d",&n); for(a=1;a<=n;+
+a){
clrscr();
scanf("%s", students[a].name);
scanf("%ld", &students[a].rollno);
students[a].total=0;
for(b=1;b<=5;++b){
scanf("%d", &students[a].marks[b]);
students[a].total += students[a].marks[b];
if(students[a].marks[b]<40)
flag=0;
}
students[a].average = (float)(students[a].total)/5.0; if((students[a].average>=75)&&(flag==1)) strcpy(s
else if((students[a].average>=60)&&(flag==1)) strcpy(students[a].cl,"First Class");
else
if((students[a].average>=50)&&(flag==1))
strcpy(students[a].cl,"Second Class");
else
if((students[a].average>=40)&&(flag==1))
strcpy(students[a].cl,"Third Class");
if(flag==1)
strcpy(students[a].rem,"Pass");
else
strcpy(students[a].rem,"Fail");
flag=1;
for(a=1;a<=n;++a)
{ clrscr();
printf("\n\n\t\t\t\tMark Sheet\n");
printf("\n ");
for(b=1;b<=5;b++){
printf("\n\n \n");
ch = getche();
if((ch=="y")||(ch=="Y"))
continue;
return(0);
}
6. Discuss about dynamic memory allocation with suitable example C
program. Dynamic memory Allocation
The process of allocating memory at the time of execution or at the runtime, is called dynamic
memory location.
Two types of problem may occur in static memory allocation.
If number of values to be stored is less than the size of memory, there would be wastage of
memory.
If we would want to store more values by increase in size during the execution on assigned size
then it fails.
Allocation and release of memory space can be done with the help of some library function called
dynamic memory allocation function. These library function are called as dynamic memory
allocation function. These library function prototype are found in the header file, ―alloc.h‖ where
it has defined.
Function take memory from memory area is called heap and release when not required.
Pointer has important role in the dynamic memory allocation to allocate memory.
malloc():
This function use to allocate memory during run time, its declaration is void*malloc(size);
malloc ()
st
returns the pointer to the 1 byte and allocate memory, and its return type is void, which can be
type cast such as:
int *p=(datatype*)malloc(size)
If memory location is successful, it returns the address of the memory chunk that was allocated
and it returns null on unsuccessful and from the above declaration a pointer of type(datatype) and
size in byte.
And datatype pointer used to typecast the pointer returned by malloc and this typecasting is
necessary since, malloc() by default returns a pointer to void.
Example int*p=(int*)malloc(10);
st
So, from the above pointer p, allocated IO contigious memory space address of 1 byte and is
stored in the variable.
We can also use, the size of operator to specify the the size, such as
Moreover , it returns null, if no sufficient memory available , we should always check the malloc
return such as, if(p==null)
Example:
main()
int n , avg,i,*p,sum=0;
%d‖,&n);
p=(int *)malloc(n*size(int));
if(p==null)
for(i=0;i<n;i++) scanf(―
%d‖,(p+i)); for(i=0;i<n;i++)
Printf(―%d‖,*(p+i));
sum=sum+*p;
avg=sum/n; printf(―avg=
%d‖,avg);
A linked list is made up of many nodes which are connected in nature. Every node is mainly
divided into two parts, one part holds the data and the other part is connected to a different node. It is similar
if(add_to_end)
printf("\n Adding node to end of list with value [%d]\n",val);
else
printf("\n Adding node to beginning of list with value [%d]\n",val);
if(add_to_end)
{
curr->next = ptr;
curr = ptr;
}
else
{
ptr->next = head;
head = ptr;
}
return ptr;
}
while(ptr != NULL)
{
if(ptr->val == val)
{
found = true;
break;
}
else
{
tmp = ptr;
ptr = ptr->next;
}
}
if(true == found)
{
if(prev)
*prev = tmp;
return ptr;
}
else
{
return NULL;
}
}
del = search_in_list(val,&prev);
if(del == NULL)
{
return -1;
}
else
{
if(prev != NULL)
prev->next = del->next;
if(del == curr)
{
curr = prev;
}
else if(del == head)
{
head = del->next;
}
}
free(del);
del = NULL;
return 0;
}
void print_list(void)
{
struct test_struct *ptr = head;
return;
}
int main(void)
{
int i = 0, ret = 0;
struct test_struct *ptr = NULL;
print_list();
print_list();
print_list();
for(i = 1; i<10; i += 4)
{
ptr = search_in_list(i, NULL);
if(NULL == ptr)
{
printf("\n Search [val = %d] failed, no such element found\n",i);
}
else
{
printf("\n Search passed [val = %d]\n",ptr->val);
}
print_list();
ret = delete_from_list(i);
if(ret != 0)
{
printf("\n delete [val = %d] failed, no such element found\n",i);
}
else
{
printf("\n delete [val = %d] passed \n",i);
}
print_list();
}
return 0;
}
UNIT V
FILE PROCESSING
1. Why files are needed?
When a program is terminated, the entire data is lost. Storing in a file will
preserve your data even if the program terminates.
If you have to enter a large number of data, it will take a lot of time to enter them all.
However, if you have a file containing all the data, you can easily access the
contents of the file using few commands in C.
You can easily move your data from one computer to another without any changes.
2. Types of Files
When dealing with files, there are two types of files you should know about:
1. Text files
2. Binary files
Text files
Text files are the normal .txt files that you can easily create using Notepad or any simple text
editors.
When you open those files, you'll see all the contents within the file as plain text. You can
easily edit or delete the contents.
They take minimum effort to maintain, are easily readable, and provide least security and
takes bigger storage space.
Binary files
Instead of storing data in plain text, they store it in the binary form (0's and 1's).
They can hold higher amount of data, are not readable easily and provides a better security
than text files.
FILE *fptr;
4. How to open a file?
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 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.
8. What is file?
A file is a semi-permanent, named collection of data. A File is usually stored on
magnetic media, such as a hard disk or magnetic tape.
Semi-permanent means that data saved in files stays safe until it is deleted or
modified.
Named means that a particular collection of data on a disk has a name,
like mydata.dat and access to the collection is done by using its name.
A very common data processing operation is report generation. This is when the
data in a file (or files) is processed by a program to generate a report of some kind. The
report might be a summary of the financial state of a corporation, or a series of bills for its
customers, or a series of checks to be mailed to its employees.
Large corporations have very large databases kept on many high capacity disks and
processed by programs running on large computers called mainframe
Management information science is the field that studies how to organize and
manage the information of a corporation using computers and files. Usually the business
school of a university has a management information science department.
1. Sequential Access — The data are placed in the file in a sequence like beads on a
string. Data are processed in sequence, one after another. To reach a particular item
of data, all the data that proceeds it first must be read.
2. Random Access — The data are placed into the file by going directly to the
location in the file assigned to each data item. Data are processed in any order. A
particular item of data can be reached by going directly to it, without looking at any
other data.
A sequential file works like a reel of tape. (In fact, sequential files are often stored on reels of
magnetic tape.) Data in a sequential file are processed in order, starting with the first item, the
processing the second, then the third and so on. To reach data in the middle of the file you
must go through all the data that preceeds it.
A random access file works like a sampler box of chocolate. You can access a particular item
by going directly to it. Data in a random acess file may be accessed in any order. To read
data in the middle of the file you can go directly to it. Random access files are sometimes
called direct access files.
You might think that all files should be random access. But random access files are much
more difficult to imp.
important for your program especially when you want to control your program from outside
instead of hard coding those values inside the code.
The command line arguments are handled using main() function arguments
where argc refers to the number of arguments passed, and argv[] is a pointer array which
points to each argument passed to the program.
{
printf("One argument expected.\n");
}
}
14. Write the functions for random access file processing.
1. fseek()
2. ftell()
3. rewind()
Syntax: ferror(fptr);
Where fptr is a file pointer.
PART-B
Files: As we know that Computers are used for storing the information for a
Permanent Time or the Files are used for storing the Data of the users for a Long time
Period. And the files can contains any type of information means they can Store the text,
any Images or Pictures or any data in any Format. So that there must be Some
Mechanism those are used for Storing the information, Accessing the information and
also Performing Some Operations on the files
There are Many files which have their Owen Type and own names. When we Store a
File in the System, then we must have to specify the Name and the Type of File. The
Name of file will be any valid Name and Type means the application with the file has
linked.
So that we can say that Every File also has Some Type Means Every File belongs to
Special Type of Application software‘s. When we Provides a Name to a File then we
also specify the Extension of the File because a System will retrieve the Contents of the
File into that Application Software. For Example if there is a File Which Contains Some
Paintings then this will Opened into the Paint Software.
1) Ordinary Files or Simple File: Ordinary File may belong to any type of Application
for example notepad, paint, C Program, Songs etc. So all the Files those are created by a
user are Ordinary Files. Ordinary Files are used for Storing the information about the
user Programs. With the help of Ordinary Files we can store the information which
contains text, database, any image or any other type of information.
2) Directory files: The Files those are Stored into the a Particular Directory or Folder.
Then these are the Directory Files. Because they belongs to a Directory and they are
Stored into a Directory or Folder. For Example a Folder Name Songs which Contains
Many Songs So that all the Files of Songs are known as Directory Files.
3) Special Files: The Special Files are those which are not created by the user. Or The
Files those are necessary to run a System. The Files those are created by the System.
Means all the Files of an Operating System or Window, are refers to Special Files. There
are Many Types of Special Files, System Files, or windows Files, Input output Files. All
the System Files are Stored into the System by using. sys Extension.
4) FIFO Files: The First in First Out Files are used by the System for Executing the
Processes into Some Order. Means To Say the Files those are Come first, will be
Executed First and the System Maintains a Order or Sequence Order. When a user
Request for a Service from the System, then the Requests of the users are Arranged into
Some Files and all the Requests of the System will be performed by the System by using
Some Sequence Order in which they are Entered or we can say that all the files or
Requests those are Received from the users will be Executed by using Some Order
which is also called as First in First Out or FIFO order.
Files are not made for just reading the Contents, we can also Perform Some other
operations on the Files those are Explained below As :
1) Read Operation: Meant To Read the information which is Stored into the Files.
2) Write Operation: For inserting some new Contents into a File.
3) Rename or Change the Name of File.
4) Copy the File from one Location to another.
5) Sorting or Arrange the Contents of File.
6) Move or Cut the File from One Place to Another.
7) Delete a File
8) Execute Means to Run Means File Display Output.
#include<stdio.h>
#include<conio.h>
struct s
{
char name[50];
int height;
};
int main(){
struct s a[5],b[5];
FILE *fptr;
int i;
clrscr();
fptr=fopen("file.txt","wb");
for(i=0;i<5;++i)
{
fflush(stdin);
printf("Enter name: ");
gets(a[i].name);
printf("Enter height: ");
scanf("%d",&a[i].height);
}
fwrite(a,sizeof(a),1,fptr);
fclose(fptr);
fptr=fopen("file.txt","rb");
fread(b,sizeof(b),1,fptr); for(i=0;i<5;+
+i)
{ printf("Name: %s\nHeight: %d",b[i].name,b[i].height);
}
fclose(fptr);
getch();
}
argv [ ] (ARGument Vector) denotes to a pointer array that is pointing to every argument
that has been passed to your program.
#include <stdio.h>
if( argc == 2 )
{
printf("\n Value given by user is: %s \t", argv[1]);
}
else if( argc > 2 )
{
printf("\n Many values given by users.\n");
}
else
{
printf(" \n Single value expected.\n");
}
}
***************************************