C PROGRAMMING QUESTION BANK Final
C PROGRAMMING QUESTION BANK Final
NNCE I / 02 C / QB
CS3251- PROGRAMMING IN C
I YEAR / II SEMESTER
PREPARED BY
VERIFIED BY
TECNOLOGY
1
Dr.NNCE I / 02 C / QB
UNIT-I
PART- A-2 Marks
1. Write down the steps involved in writing a program to solve a problem.
To design a program, a programmer must determine three basic steps:
a. The instruction to be performed.
b. The sequence in which those instructions are to be performed.
c. The data required to perform those instructions.
2
Dr.NNCE I / 02 C / QB
3
Dr.NNCE I / 02 C / QB
14.What is identifier? Give any two examples for an identifier. (Jan 2009)
Identifiers are the names given to variable program elements such as variables,
4
Dr.NNCE I / 02 C / QB
17.Is ‘main’ a keyword in C language? Justify your answer. (May 2011,NOV 2023)
The name main is not a keyword in C.
From the compiler's perspective, main() is a function.
Just like any other function that you may define in your program, such as
factorial(), sort().
The simplest way to prove is that you can create a variable "main" in the
5
Dr.NNCE I / 02 C / QB
20.Give two examples for logical and relational expression. (Jan 2011)
Relational Expression Logical Expression
(a>b) if((a>b)&&(a>c))
(a==b) if((a>b)||(a>c))
Operator Meaning
6
Dr.NNCE I / 02 C / QB
7
Dr.NNCE I / 02 C / QB
Double d = 10.21;
printf("%d", sizeof(a+d)); //8
8
Dr.NNCE I / 02 C / QB
34.Write the limitations of using getchar() and scanf() functions for reading
strings. (Jan 2009)
getchar(): It is written in standard I/O library. It reads a single character only from a
9
Dr.NNCE I / 02 C / QB
standard input device. This function is not use for reading strings.
Scanf: It is use for reading single string at a time. When there is a blank was typed,
the scanf() assumes that it is an end.
35. What are the pre-processor directives? (Jan 2014, May 2014, 2015)
Preprocessor directives are the commands used in preprocessor and they begin with
“#” symbol. Before a C program is compiled in a compiler, source code is processed
by a program called preprocessor. This process is called preprocessing.
Macro Syntax: #define
This macro defines constant value and can be any of the basic
data types.
Header file Syntax: #include <file_name>
inclusion The source code of the file “file_name” is included in the
main program at the specified place.
Conditional Syntax: #ifdef, #endif, #if, #else, #ifndef
compilation Set of commands are included or excluded in source
program before compilation with respect to the condition.
Unconditional Syntax: #undef, #pragma
compilation #undef is used to undefine a defined macro variable.
#Pragma is used to call a function before and after main
function in a C program.
10
Dr.NNCE I / 02 C / QB
RAM. This means that the variable has a maximum size equal to the register size
(usually one word) and can‟t have the unary '&' operator applied to it (as it does not
have a memory location). Ex. register int a=200;
44.What will be the output for the following program when the value of i is 5 and 10?
(June-2012)
#include<stdio.h> Output
void main() Five (if I is 5)
{ No output if I is 10
inti;
scanf(“%d”,&i);
if(i=5){
11
Dr.NNCE I / 02 C / QB
printf(“five”); }.
PART-B
1. Explain in detail about the Structure of C Program.(APRIL 2022,2024)
STRUCTURE OF C PROGRAM
Documentation section
Preprocessor section
Definition section
13
Dr.NNCE I / 02 C / QB
14
Dr.NNCE I / 02 C / QB
Static Variable:
Static variables are the variables for which contents of variables
available throughout the program.
It may be an internal or external type, depending upon where it is declared.
If declared outside of the body , it will be a static or global.
If it is declared inside the body or block it will be auto variable.
These are permanent with in the function.
Syntax:
storage_class_type data_type var1,var2,…varn;
Example:
static int a,b;
static float x,y;
static char sex;
Example:
extern int a,b;
extern float x,y;
extern char sex;
Example Program: Output
#include<stdio.h> in fun1() d=124
#include<conio.h> in fun2() d=510
int d=510; in main() d=510
void main()
{
clrscr();
fun1();
fun2();
printf(“in main() d=%d”,d);
getch();
}
fun1()
{
int d=124;
printf(“in fun1() d=%d”,d);
}
fun2()
{
printf(“in fun2() d=%d”,d);
}
Register Variable
It is a special storage area in central processing unit.
The arithmetic and logical operations are carried out with in these register.
Register access is faster than memory access.
The values of register variable stored with in the registers of computer
cpu rather than in memory.
Syntax:
Storage_class_type data_type var1,var2,…varn;
Example:
register int a,b;
Example Program: Output:
#include<stdio.h>
#include<conio.h> value of i is: 0
16
Dr.NNCE I / 02 C / QB
Example: a+b
Here a, b-> Operator + -> Operand
Types of operators
a) Arithmetic Operators
b) Relational Operators
c) Logical Operators
d) Assignment Operators
e) Increment/ Decrement Operators
f) Conditional Operators(Ternary
Operator)
g) Bitwise Operators
ARITHMETIC OPERATOR
17
Dr.NNCE I / 02 C / QB
a-b 3.0
#include <stdio.h>
int main()
{
int a = 9,b = 4, c; output
c = a+b; a+b=13
printf("a+b = %d \n",c); a-b=5
c = a-b; a*b=36
printf("a-b = %d \n",c); a/b=2
c = a*b;
Remainder when a divided by b=1
printf("a*b = %d \n",c);
c = a/b;
printf("a/b = %d \n",c);
c = a%b;
return 0;
}
RELATIONAL OPERATORS:
Used to compare two or more operands.
Opera Meaning Exam Retur
to r pl e n
Valu
es
< is less than 2<9 1
<= is less than or 2<=2 1
equal to
> is greater than 2>9 0
>= is greater than or 3>=2 1
equal to
== is equal to 2==3 0
!= is not equal to 2!=2 0
Syntax:
Program For Relational Operators
#include<stdio.h>
#include<conio.h>
void main ()
{
clrscr();
printf(“\N Condition : Return Values \n”);
printf(“\n5!=5 :%5d”, 5!=5);
printf(“\n5==5 :%5d”, 5==5);
printf(“\n5>=50 :%5d”, 5>=50);
printf(“\n5<=50 :%5d”, 5<=50);
printf(“\n5!=3 %5d”, 5!=3);
}
LOGICAL OPERATOR: Used to combine the results of two or more conditions.
19
Dr.NNCE I / 02 C / QB
ASSIGNMENT OPERATOR:
It is used to assign a value of a variable to another variable
Syntax:
Variable=expression(or)value;
Example:
X=10;
X=a+b;
20
Dr.NNCE I / 02 C / QB
#include<stdio.h>
#include<conio.h>
void main ()
{
int i,j,k;
clrscr();
k=(i=4,j=5);
printf(“k=%d”, k);
getch();
}
INCREMENT AND DECREMENT OPERATORS
++ is a increment operator
--is a decrement operator
It is also called as unary operator
Operator Meaning
++x Pre increment
--x Pre decrement
x++ Post increment
x-- Post decrement
Program For Increment And Decrement Operator
#include<stdio.h>
void main ()
{
int a=10;
printf(“a++ = %d”, a++);
printf(“++a = %d”, ++a);
printf(“a-- = %d”, a--);
printf(“--a = %d”, --a);
}
blocks.
‘C’ language provides the following conditional statements.
if statements
if…..else statements
nested if….else statements
if……else ladder
IF STATEMENTS
The if statement is a decision making statement
Used to control the flow of execution by executing statements when the condition
is true (or) false.
Properties of If statement:
If condition is true, it execute true statement
FLOW CHART:
If condition is false it does not do anything.
Condition must be in parenthesis
SYNTAX: EXAMPLE:
Condition
if(condition) #include<stdio.h>
{ void main()
True statement; {
} int a; True statement
printf(“enter the value”);
scanf(“%d”,&a);
True statement
if(a==10)
{
printf(“Both are equal”);
}
}
IF…..ELSE STATEMENT
It is two way decision making statement
It has two block
if & else
if block is executed when the condition is true,
else block is executed when the condition is false.
22
Dr.NNCE I / 02 C / QB
SYNTAX: EXAMPLE:
if(condition is true) #include<stdio.h>
{ #include<conio.h>
True statement; void main() condition
} {
else int num,rem;
True statement False statement
{ clrscr();
False statement; printf(“Enter ur number”);
} scanf(“%d”,&num);
rem=num%2;
if(rem==0)
printf(“the number is
even”);
else
printf(“the number is odd”);
getch();
}
if(a<b)
{
if(a<c) small=a; else small=c;
}else
{
if(b<c)
small=b;
else
small=c;
}
printf(“the smallest value is”)
}}
IF….ELSE LADDER
Number of logical conditions is checked for executing various statements.
If three are more than three alternatives and indentation is not consistent, it may
be different for you to determine the logical structure of the if statement
if(condition 1) #include<stdio.h>
{ main()
Statement 1; {
}
int a,b,c,d;
else if(condition 2)
{ printf(“enter the four numbers”);
Statement 2; scanf(“%d%d%d%d”,&a,&b,&c,&d);
} if((a<b)&&(a<c)&&(a<d))
else if(condition 3) printf(“a is greater”);
{ else
Statement 3; if((b>a)&&(b>c)&&(b>d))
}
printf(“b is greater”);
else
{ else
default-statement; if((c>a)&&(c>b)&&(c>d))
} printf(“c is greater”);
else
printf(“d is greater”);
return(0);
24
Dr.NNCE I / 02 C / QB
FLOW CHART
25
EXAMPLE:
Dr.NNCE I / 02 C / QB
#include<stdio.h>
#include<conio.h>
void main()
{
int a, b, c, option;
printf(“\n 1.Addition”);
printf(“\n 2.subtraction”);
printf(“\n 3.multiplication”);
printf(“\n 4.Division”);
printf(“\n 5.Exit”);
printf(“\n Enter two number”);
scanf(“%d %d”, &a, &b);
printf(“\n Enter your option”)
scanf(“%d”, &option);
switch(option)
{
Case 1:
c=a+b;
printf(“\n Addition=%d” ,c);
break;
case 2:
c=a-b;
printf(“\n subtraction=
%d”,c); break;
case 3:
c=a*b;
printf(“\n multiplication=%d”,c);
break;
case 4:
c=a/b;
printf(“\n division=%d”,c);
break;
case 5:
Exit(0);
break;
default:
printf(“Invalid Choice”);
}
getch();
26
Dr.NNCE I / 02 C / QB
5. Describe the statements for looping OR Explain the various looping constructs.
BRANCHING AND LOOPING (NOV 2022)
Loop:
A loop is defined as a block of statements which are repeatedly
executed for certain number of times. They are three types of loop
control statements
for
while
do-while
WHILE LOOP:
It is repetitive control structure used to executed the statements
within the body until the condition becomes false. The while loop
is an entry controlled loop statement
In that condition is evaluated first ,if it is true, then the body of the loop is
executed.
while(test condition)
{ #include<stdio.h>
body of the loop; void main()
} { condition
int number, digit, rev=0;
printf(“Enter the number:”);
while(number!=0)
{
digit=number%10;
rev=rev*10+digit;
number=number/10; Body of the loop
}
printf(“%d”,rev);
getch();
}
27
Dr.NNCE I / 02 C / QB
do #include<stdio.h>
{ #include<conio.h>
Statement; void main()
} { Body of the loop
while(condition); int i=2,sum=0;
do
{
sum=sum+i;
i++;
condition
}
while(i<=10)
printf(“sum of the numbers upto 10 is=%d”,sum);
getch();
}
FOR LOOP
It is used to execute set of instructions repeatedly until the condition becomes
false.
Initialize counter: It is used to initialize the counter variable
Test condition:
It is used to test the condition.
Increment / decrement counter:
It is used to Increment / decrement the counter variable
SYNTAX:
For(initialize counter; test condition; increment/decrement counter)
{
statement 1;
statement 2;
}
#include<stdio.h>
#include<conio.h>
main()
{
int i, sum=0;
for(i=1;i<=10;i++)
{
sum=sum+i;
}
printf(“The addition of numbers upto 10 is %d”,sum);
getch();
}
28
Dr.NNCE I / 02 C / QB
Goto Statement:
This statement does not require any condition.
This statement passes control any where the program
ie., control is transferred to another part of program without testing the application.
Break statement:
It is used to terminate the loop.
When break is used inside loop, control is automatically transferred to first statement
after the loop.
SYNTAX(goto): EXAMPLE(goto) SYNTAX(break):
#include<stdio.h>
goto label; #include<conio.h>
Break;
void main()
………… {
………… int a,b;
label: printf(“Enter a number”); EXAMPLE:
scanf(“%d %d”,&a,&b); #include<stdio.h>
{
if(a==b) #include<conio.h>
SYNTAX(goto): { void main()
goto equal; {
goto label; } int i;
………… else for(i=1;i<=10;i++)
{ {
…………
printf(“A & B are equal”);
label: if(a==b)
exit(0);
29 break;
}
equal: printf(“%d”,i);
printf(“A & B are not equal”); }
}
Dr.NNCE I / 02 C / QB
#include <stdio.h>
main()
{
int n, i, c = 0;
printf("Enter any number n:");
scanf("%d", &n);
for (i = 1; i <= n; i++)
{
if (n % i == 0)
{
c++;
}
}
if (c == 2) {
printf("n is a Prime number");
}
else {
printf("n is not a Prime number");
}
return 0;
}
OUTPUT:
Enter any
number n:55
n is not a
Prime number
30
Dr.NNCE I / 02 C / QB
31
Dr.NNCE I / 02 C / QB
UNIT-II
PART- A
1. Define array. Give example. (Jan 2009, 2014,)
Array can be define as a collection of similar data elements of similar data type
that are stored in consecutive memory locations. They are referenced by an
index/subscript.
Syntax: data_type array_name [size] Ex.: int rollno[10];
32
Dr.NNCE I / 02 C / QB
i. The elements of array share the same name and they are
distinguished from one another with helps of an elements
number.
ii. An elements of array a[] can be assigned
iii. The array elements are stored in continuous memory locations.
collectively in the format of an array. Each variable, as an element of the array, can be
accessed either through the array elements references or through a pointer that
references the array.
12. What are the limitation of one-dimensional and two dimensional arrays?
The limitations of one dimensional array are
a. There is no easy method to initialize large number of array elements
b. It is difficult to initialize selected array
element The limitations of two dimensional
arrays are
a. Deletion of any element from an array is not possible
b. Wastage of memory when it is specified in large array size
36
Dr.NNCE I / 02 C / QB
PART-B
1. Explain in detail about Array(APR 2022)
37
Dr.NNCE I / 02 C / QB
ARRAY
Array is collection of similar data items ,that are stored under a common name.
A value in an array is identified by index or subscript enclosed in square
brackets with array name.
Ex: n elements in array q is q[0],q[1],q[2]..q[n]
ARRAY TYPES
One Dimensional Array
Two Dimensional Array
Multidimensional Array
#include<stdio.h>
main()
{
int i,j,a[20]={0},sum=0,n,t,b[20]={0},k=0,c1,
max=0,mode; float x=0.0,y=0.0;
printf("\nEnter the limit\n");
scanf("%d",&n);
printf("Enter the set of numbers\n");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
sum=sum+a[i];
}
x=(float)sum/(float)n;
printf("Mean\t= %f",x);
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(a[i]>a[j])
{
38
Dr.NNCE I / 02 C / QB
t=a[i];
a[i]=a[j];
a[j]=t;
}
}
} if(n%2==0)
y=(float)(a[n/2]+a[(n-1)/2])/2;
else
y=a[(n-1)/2]; printf("\nMedian\t= %f",y);
for(i=0;i<n-1;i++)
{
mode=0;
for(j=i+1;j<n;j++)
{
if(a[i]==a[j])
{
mode++;
}
}
if((mode>max)&&(mode!=0))
{
k=0;
max=mode;
b[k]=a[i];
k++;
}
else if(mode==max)
{
b[k]=a[i];
k++;
}
}
for(i=0;i<n;i++)
{
if(a[i]==b[i])
c++;
39
Dr.NNCE I / 02 C / QB
}
if(c==n)
printf("\nThere is no mode");
else
{
printf("\nMode\t= ");
for(i=0;i<k;i++)
printf("%d ",b[i]);
}
}
OUTPUT:
Enter the limit 5
Enter the set of numbers 1 2 3 4 5
Mean = 3.000000
Median = 3.000000
There is no mode
OUTPUT:
Enter the number of rows and
columns of matrix 2
2
Enter the elements of
first matrix 1 2
34
Enter the elements of
second matrix 5 6
21
Sum of entered
matrices
6 8
5 5 (NOV 2022)
{
int a[3][3],b[3][3],c[3][3],i,j,k;
clrscr();
printf("enter the a
matrix\n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf("a[%d][%d] : ",i+1,j+1);
scanf("%d",&a[i][j]);
}
}
printf(“enter the b matrix\n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf("b[%d][%d] : ",i+1,j+1);
scanf("%d",&b[i][j]);
}}
printf(“multiplication of 2matrices:\
n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
c[i][j]=0;
for(k=0;k<3;k++)
{
c[i][j]+=a[i][k]*b[k][j];
}
printf("\t%d",c[i][j]);
}
printf("\n\n");
42
Dr.NNCE I / 02 C / QB
}
getch();
}
4.PROGRAM FOR TRANSPOSE OF MATRIX (NOV 2022,APR 2024)
#include<stdio.h>
int main()
{
int a[10][10], b[10][10], i, j, m, n;
43
Dr.NNCE I / 02 C / QB
213
897
153
Transpose of matrix:
281
195
373
5.C PROGRAM FOR MATRIX SCALING (NOV 2022)
#include<stdio.h>
int main()
{
int i, j, rows, columns, a[10][10], Number;
printf("\n Enter Number of rows and columns\
n"); scanf("%d %d", &i, &j);
printf("\n Please Enter the Matrix Elements \n");
for(rows = 0; rows < i; rows++)
{
for (columns = 0;columns < j;columns++)
{
scanf("%d", &Multiplication[rows][columns]);
} }
printf("\n Enter the Multiplication Value :
"); scanf("%d", &Number);
for(rows = 0; rows < i; rows++)
{
for(columns = 0; columns < j; columns++)
{
a[rows][columns] = Number * a[rows][columns];
}
}
printf("\n The Result of a Scalar Matrix Multiplication is : \n");
for(rows = 0; rows < i; rows++)
{
for(columns = 0; columns < j; columns++)
{
44
Dr.NNCE I / 02 C / QB
45
Dr.NNCE I / 02 C / QB
STRING:
The group of characters, digit and symbols enclosed within quotes is called as
String (or) character Arrays. Strings are always terminated with ‘\0’ (NULL)
character. The compiler automatically adds ‘\0’ at the end of the strings.
Example:
char name[]={‘C’,’O’,’L’,’L’,’E’,’G’,’E’,’E’,’\0’};
S.No Function Purpose
C
1 strcpy(s1, s2); Copies string s2 into string s1.
2 strcat(s1, s2); Concatenates string s2 onto the end of string s1.
3 strlen(s1); Returns the length of string s1.
4 strcmp(s1, Returns 0 if s1 and s2 are the same; less than 0 if s1<s2;
s2); greater than 0 if s1>s2.
5 strchr(s1, ch); Returns a pointer to the first occurrence of character ch in
string s1.
6 strstr(s1, s2); Returns a pointer to the first occurrence of string s2 in string
s1.
7 strlwr() Used to convert string to lower case
8 strupr() Used to convert string to upper case
9 strdup() Used to duplicate a string
{
int arr[20];
int i,size,key;
printf("\n\t-- Linear Search --\n\n");
printf("Enter total no. of
elements : ");
scanf("%d",&size);
for(i=0; i<size; i++)
{
printf("Enter %d
element : ",i+1);
scanf("%d",&arr[i]);
}
printf("Enter the element to
be searched: ");
scanf("%d",&key);
for(i=0; i<size; i++)
{
if(key==arr[i])
{
printf("Element exits in the list at position :
%d",i+1);
break;
}
}
getch();
}
Output:
-- Linear Search --
Enter total no. of elements : 3
Enter 1 element : 25
Enter 2 element : 36
Enter 3 element : 45
Enter the element to be
searched: 36 Element
exits in the list at
49
Dr.NNCE I / 02 C / QB
position : 2
Selection Sort
PROGRAM
#include <stdio.h>
int main()
{
int arr[10]={6,12,0,18,11,99,55,45,34,2};
int n=10;
int i, j, position, swap;
for (i = 0; i < (n - 1); i++)
{
position = i;
for (j = i + 1; j < n; j++)
{
if (arr[position] > arr[j])
position = j;
}
51
Dr.NNCE I / 02 C / QB
if (position != i)
{
swap = arr[i];
arr[i] = arr[position];
arr[position] = swap;
}
}
for (i = 0; i < n; i++)
printf("%d\t", arr[i]);
return 0;
}
OUTPUT:
0 2 6 11 12 18 34 45 99
UNIT-III
PART-A
1. What is a function? (Nov 2014)
A function is a group of statements that together perform a task. Every C program
has at least one function which is main(), and all the most trivial programs can define
additional functions.
52
Dr.NNCE I / 02 C / QB
task.
53
Dr.NNCE I / 02 C / QB
a. The library functions are predefined a. The user defined functions are defined by
set of functions. the user.
b. Their task is limited b. Their task is based on user requirement.
c. The user can use the functions c. The user can modify the function
but cannot change or modify according to the requirement.
them.
57
Dr.NNCE I / 02 C / QB
58
Dr.NNCE I / 02 C / QB
Expression Resul
t
C =*y + 10 Value of c is 30
C = *z + *y Value of c is 50
C = *x + 10 + *y Value of c is 40
C = ++*x Value of c is 11
PART-B:
1. Explain in detail about the function with an example.(APR 2022)
Function:
A Function is a set of instructions that are used to perform specified tasks which
repeatly occurs in the main program.
Function is itself a block of code which can solve simple or complex task/calculations.
59
Dr.NNCE I / 02 C / QB
}
return(f);
}
2. Describe the concept of Recursion with an Example.
A function that calls itself is known as a recursive function. And, this technique is
known as recursion.
Example:
#include<stdio.h>
#include<conio.h>
void main()
{
int n,f;
int fact(int)
printf("Enter a no.");
scanf("%d",&n);
f=fact(n);
printf("The factorial of a no. is:=%d",f);
}
int fact(int n)
{
Int f=1;
if(n=0)
return(f);
else
return(n*fact(n- 1));
}
int main()
{
int x,y,n,answer;
printf("What do you want to do?\n");
printf("1.sin 2.cos 3. tan 4. sinh 5.cosh 6.tanh 7.1og10 8. square root. 9.exponent
10.power.");
scanf ("%d",&n);
if (n<9 && n>0)
{
printf("\n What is x? ");
scanf("%f",&x);
switch (n)
{
case 1: answer = sine(x); break;
case 2: answer = cosine(x); break;
case 3: answer = tangent(x); break;
case 4: answer = sineh(x); break;
case 5: answer = cosineh(x); break;
case 6: answer = tangenth(x); break;
case 7: answer = logten(x); break;
case 8: answer = squareroot(x); break;
case 9: answer = exponent(x); break;
}
}
if (n==10)
{
printf("What is x and y?\n");
scanf("%f%f",&x,&y);
answer = power(x,y);
}
if (n>0 && n<11)
printf("%f",answer);
else
printf("Wrong input.\n");
return 0;
63
Dr.NNCE I / 02 C / QB
}
float sine(float x)
{
return (sin (x*PI/180));
}
float cosine(float x)
{
return (cos (x*PI/180));
}
float tangent(float x)
{
return (tan(x*PI/180));
}
float sineh(float x)
{
return (sinh(x));
}
float cosineh(float x)
{
return (sinh(x));
}
float tangenth(float x)
{
return (sinh(x));
}
float logten(float x)
{
return (log10(x));
}
float squareroot(float x)
{
return (sqrt(x));
}
float exponent(float x)
{
return(exp(x));
}
float power(float x, float y)
{
return (pow(x,y));
}
64
Dr.NNCE I / 02 C / QB
Functions can be differentiated into 4 types according to the arguments passed and value
returns these are:
Function with arguments and return value
Function with arguments and no return value
Function with no arguments and with return value
Function with no arguments and no return value
Function with arguments and return value:
Syntax:
Function declaration: int function ( int );
Function call: function( x );
Function definition:
int function( int x )
{
statements;
return x;
}
Example:
#include <stdio.h>
#include <string.h>
int function(int, int[]);
int main()
{
int i, a = 20;
int arr[5] = { 10, 20, 30, 40, 50 };
a = function(a, &arr[0]);
printf("value of a is %d\n", a);
for (i = 0; i < 5; i++) {
printf("value of arr[%d] is %d\n", i, arr[i]);
}
return 0;
}
int function(int a, int* arr)
{
int i;
65
Dr.NNCE I / 02 C / QB
a = a + 20;
OUTPUT:
value of a is 40
value of arr[0] is 60
value of arr[1] is 70
value of arr[2] is 80
value of arr[3] is 90
value of arr[4] is 100
Functions with arguments but no return Values:
When a function has arguments, it receives any data from the calling function but it
returns no values. These are void functions with no return values.
Syntax:
Function declaration : void function ( int );
Function call : function( x );
Function definition:
void function( int x )
{
statements;
}
Example:
#include <stdio.h>
void function(int, int[], char[]);
int main()
{
int a = 20;
int ar[5] = { 10, 20, 30, 40, 50 };
char str[30] = "thendralkani"; // function call
function(a, &ar[0], &str[0]);
66
Dr.NNCE I / 02 C / QB
return 0;
}
Output
value of a is 20
value of ar[0] is 10
value of ar[1] is 20
value of ar[2] is 30
value of ar[3] is 40
value of ar[4] is 50
value of str is thendralkani
Function with no argument and no return value:
When a function has no arguments, it does not receive any data from the calling
function. Similarly, when it does not return a value, the calling function does not receive any
data from the called function.
SySyntax:
Function declaration : void function();
Function call : function();
Function definition :
void function()
{
statements;
}
Example:
67
Dr.NNCE I / 02 C / QB
#include <stdio.h>
void value(void);
void main() {
value();
}
void value(void)
{
float year = 1, period = 5, amount = 5000, inrate = 0.12;
float sum;
sum = amount;
while (year <= period) {
sum = sum * (1 + inrate);
year = year + 1;
}
printf(" The total amount is :%f", sum);
}
}}
Output: The total amount is :8811.708984
Functions with no arguments but return values:
There could be occasions where we may need to design functions that may not take any
arguments but returns a value to the calling function. An example of this is getchar function
which has no parameters but it returns an integer and integer-type data that represents a
character.
Syntax
68
Dr.NNCE I / 02 C / QB
int sum();
int main()
{
int num;
num = sum();
printf("Sum of two given values = %d", num);
return 0;
}
int sum()
{
int a = 50, b = 80, sum;
sum = sqrt(a) + sqrt(b);
return sum;
}
OUTPUT:
Sum of two given values = 16
69
Dr.NNCE I / 02 C / QB
return 0;
}
5.Explain pointer operators and pointer arithmetic in c.
pointer operators are used to work with memory addresses and indirectly access data stored
in memory.
return 0;
}
An array of pointers in C is an array where each element is a pointer, typically used to point
to different memory locations (e.g., strings, integers, structs).
Example:
#include <stdio.h>
int main() {
int a = 10, b = 20, c = 30;
int *arr[3]; // Array of 3 integer pointers
arr[0] = &a;
arr[1] = &b;
arr[2] = &c;
return 0;
}
Output:
Value at arr[0] = 10
Value at arr[1] = 20
Value at arr[2] = 30
In C, a pointer to an array is a pointer that points to an entire array (not just the first element
of the array). This is different from a pointer to the first element of an array.
Syntax
int (*ptr)[5];
71
Dr.NNCE I / 02 C / QB
Example
#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;
}
7.Write C Program to Sorting a Names Using Array of Pointers
#include <stdio.h>
#include <string.h>
#define SIZE 5
#define MAX_LEN 100
72
Dr.NNCE I / 02 C / QB
}
}
int main() {
// Declare array of string pointers and actual strings
char name1[MAX_LEN] = "thendral";
char name2[MAX_LEN] = "nila";
char name3[MAX_LEN] = "Jeeva";
char name4[MAX_LEN] = "keerthi";
char name5[MAX_LEN] = "aadhini";
printf("Original list:\n");
for (int i = 0; i < SIZE; i++) {
printf("%s\n", names[i]);
}
sortNames(names, SIZE);
printf("\nSorted list:\n");
for (int i = 0; i < SIZE; i++) {
printf("%s\n", names[i]);
}
return 0;
}
73
Dr.NNCE I / 02 C / QB
Formal parameters
The actual parameters are the parameters that are specified in calling function.
The formal parameters are the parameters that are declared at called function.
When a function gets executed, the copy of actual parameter values are copied into
formal parameters.
In C Programming Language, there are two methods to pass parameters from
calling function to called function and they are as follows...
Call by value
Call by reference
Call 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
call 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>
74
Dr.NNCE I / 02 C / QB
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
PART – A
1. Distinguish between arrays and structures.(NOV 2022)
Arrays Structures
a. An array is a collection of data items a. A structure is a collection of data items
Of same data type. of different data types. Structures can be
Arrays can only be declared. declared and defined.
b. There is no keyword for arrays b. The keyword for structures is struct.
c. An array name represents the c. A structure name is known as tag. It is a
address of the starting element Shorthand notation of the declaration.
d. An array cannot have bit fields d. A structure may contain bit fields
75
Dr.NNCE I / 02 C / QB
(APR 2023)
Structure Union
a. Every member has its own memory. a. All members use the same memory.
b. The keyword used is struct. b. The keyword used is union.
c. All members occupy separate memory c. Different interpretations for the
location, hence different same memory location are
interpretations of the same memory possible.
location are not possible.
d. Consumes more space compared to d. Conservation of memory is possible.
union.
Structure can be defined as a collection of different data types which are grouped
together and each element in a C structure is called member. To access structure
members in C, structure variable should be declared. The keyword used is struct.
3. How will you define a structure?(NOV 2022)
A structure can be defined as
struct tag
{ datatype member 1;
datatype member 2;
………
………
datatype member n;
};
where struct is a keyword, tag is a name that identifies structures, member 1,
member 2,….. member n are individual member declarations.
76
Dr.NNCE I / 02 C / QB
types in the same memory location. Union can be defined 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 multi-purpose.
78
Dr.NNCE I / 02 C / QB
18. How will you access the structures member through pointers?
The structures member can be accessed through pointers by the following ways
a. Referencing pointer to another address to access memory
b. Using dynamic memory allocation
21. Consider the declaration and illustrate the application of size of operator to
this structure. (Nov 2010)
struct student
Size of this is 3 bytes:1 byte for name and 2 bytes for integer num.
{
char name;
int num;
} S;
79
Dr.NNCE I / 02 C / QB
element at desired position the list needs to be traversed. Similarly, traversing of the
list is required for locating the element which needs to be deleted.
Part-B
};
1. What is a structure? Create a structure with data members of various
types and declare two structure variables. Write a program to read data
into these and print the same. Justify the need for structured data type.
(NOV 2022,APR2022)
It is the collection of dissimilar data types or heterogenous data types
grouped together. It means the data types may or may not be of same type.
Structure declaration:
struct tagname
{
Datatype member1;
81
Dr.NNCE I / 02 C / QB
Datatype member2;
Datatype member3;
………
………
Datatype member n;
};
struct tagname
{
struct element 1;
struct element 2;
struct element 3;
………
………
struct element n;
};
Structure variable declaration;
struct student
{
int age;
char name[20];
char branch[20];
}; struct student s;
83
Dr.NNCE I / 02 C / QB
if(!found) {
printf("\nEmployee with Number %d not found.\n", searchEmpNo);
84
Dr.NNCE I / 02 C / QB
return 0;
}
2. Define and declare a nested structure to store date, which including day,
month and year.(NOV 2023)
Nested structure in C using struct is also known as structure within a structure
#include <stdio.h>
int main() {
struct Employee emp;
return 0;
Explanation:
struct Date is a standalone structure that holds day, month, and year.
void main()
{
struct student s[200];
int i; s[i].roll=i+1;
86
Dr.NNCE I / 02 C / QB
pointers can be used with structures to dynamically manage memory and pass structures to
functions efficiently.
Example:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// Define a structure
struct Employee {
int empNo;
char name[50];
float salary;
};
int main() {
struct Employee *emp; // Declare a pointer to a structure
emp = (struct Employee *)malloc(sizeof(struct Employee));
// Allocate memory for one Employee
87
Dr.NNCE I / 02 C / QB
if (emp == NULL) {
printf("Memory allocation failed.\n");
return 1;
}
return 0;
}
4.Write a C program to create mark sheet for students using self referential structure.
#include<stdio.h> (NOV 2022,APR2022,NOV 2023)
#include<conio.h>
struct mark_sheet{
char name[20];
long int rollno;
int marks[10];
int total;
float average;
char rem[10];
char cl[20];
}students[100];
int main(){
88
Dr.NNCE I / 02 C / QB
int a,b,n,flag=1;
char ch;
clrscr();
printf("How many students : \n");
scanf("%d",&n);
for(a=1;a<=n;++a)
{
clrscr();
printf("\n\nEnter the details of %d students : ", n-a+1);
printf("\n\nEnter student %d Name : ", a);
scanf("%s", students[a].name);
printf("\n\nEnter student %d Roll Number : ", a);
scanf("%ld", &students[a].rollno);
students[a].total=0;
for(b=1;b<=5;++b)
{
printf("\n\nEnter the mark of subject-%d : ", 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(students[a].cl,"Distinction");
elseif((students[a].average>=60)&&(flag==1))
strcpy(students[a].cl,"First Class");
elseif((students[a].average>=50)&&(flag==1))
strcpy(students[a].cl,"Second Class");
elseif((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;
89
Dr.NNCE I / 02 C / QB
}
for(a=1;a<=n;++a)
{
clrscr();
printf("\n\n\t\t\t\tMark Sheet\n");
printf("\nName of Student : %s", students[a].name);
printf("\t\t\t\t Roll No : %ld", students[a].rollno);
printf("\n ");
for(b=1;b<=5;b++){
printf("\n\n\t Subject %d \t\t :\t %d", b, students[a].marks[b]);
}
printf("\n");
printf("\n\n Totl Marks : %d", students[a].total);
printf("\t\t\t\t Average Marks : %5.2f",students[a].average);
printf("\n\n Class : %s", students[a].cl);
printf("\t\t\t\t\t Status : %s", students[a].rem);
printf("\n\n\n\t\t\t\t Press Y for continue . . . ");
ch = getche();
if((ch=="y")||(ch=="Y"))
continue;
}
return(0);
}
In C, dynamic memory allocation allows you to allocate memory at runtime (i.e., during
the execution of the program), instead of compile time. This is useful when you don’t know
the amount of memory needed in advance (e.g., array size, number of students, etc.).
Dynamic memory allocation is done using the following functions from <stdlib.h>:
Function Description
malloc() Allocates uninitialized memory
90
Dr.NNCE I / 02 C / QB
Function Description
calloc() Allocates memory and initializes to zero
realloc() Reallocates memory to a new size
free() Frees dynamically allocated memory
Example:
/#include <stdio.h>
#include <stdlib.h>
int main() {
int *arr; // Pointer to hold base address of array
int n, i;
// Input elements
printf("Enter %d integers:\n", n);
for (i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
// Display elements
printf("You entered:\n");
for (i = 0; i < n; i++) {
printf("%d ", arr[i]);
91
Dr.NNCE I / 02 C / QB
}
printf("\n");
return 0;
}
A singly linked list is a linear data structure where each element (node) contains two parts:
In a singly linked list, each node points to the next node in the sequence, and the last node
points to NULL, indicating the end of the list.
Below is an example C program that demonstrates basic operations on a singly linked list:
insertion, traversal, and deletion.
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data; // Data part
struct Node* next; // Pointer to the next node
};
// Function to create a new node
struct Node* createNode(int data) {
struct Node* newNode = (struct Node*) malloc(sizeof(struct Node));
// Allocate memory for the new node
92
Dr.NNCE I / 02 C / QB
// Inserting nodes
insertAtBeginning(&head, 10);
insertAtBeginning(&head, 20);
insertAtEnd(&head, 30);
insertAtEnd(&head, 40);
insertAtBeginning(&head, 50);
return 0;
}
Output:
Linked List after insertions:50 -> 20 -> 10 -> 30 -> 40 -> NULL
Linked List after deleting the first node:20 -> 10 -> 30 -> 40 -> NULL
the typedef keyword is used to create an alias (a new name) for an existing data type. This can
make your code easier to read, improve portability, and allow for better abstraction.
Purpose:
Create aliases for existing data types, making code more readable.
94
Dr.NNCE I / 02 C / QB
Syntax:
typedef existing_type new_name;
existing_type: This is the original data type that you want to create an alias for.
New_name: This is the alias (or new name) that will represent the existing type.
Output:
a: 10, b: 20.50
typedef is commonly used with structures to simplify type declarations, especially when
working with pointers to structures.
#include <stdio.h>
struct Person {
char name[50];
int age;
};
typedef struct Person Person;
int main() {
Person p1;
snprintf(p1.name, sizeof(p1.name), "Alice");
95
Dr.NNCE I / 02 C / QB
p1.age = 25;
printf("Name: %s, Age: %d\n", p1.name, p1.age);
return 0;
}
Output:
In C, a union is a special data type that allows storing different data types in the same memory
location. Unlike a structure, where each member has its own memory location, a union
shares the same memory location for all its members. This means that only one member of the
union can hold a value at a time.
Memory Sharing: All members of a union share the same memory space, and the size
of the union is determined by the size of its largest member.
Single Value Storage: Only one member of the union can store a value at any given
time.
Efficient Memory Use: Unions are useful when you need to store different types of
data but only need to store one type at a time, saving memory.
Syntax of Union:
union union_name {
data_type member1;
data_type member2;
// other members
};
Example: Union in C
#include <stdio.h>
// Define a union
union Data {
int i;
float f;
char c;
};
96
Dr.NNCE I / 02 C / QB
int main() {
// Declare a union variable
union Data data;
// At this point, only 'data.c' holds a valid value, as the other members were overwritten.
return 0;
}
Output:
97
Dr.NNCE I / 02 C / QB
return 0;
}
Output:
Storage classes in C define the scope, visibility, lifetime, and memory location of variables
and/or functions. They tell the compiler how long to keep a variable in memory, where to
store it, and who can access it.
#include <stdio.h>
void example() {
auto int a = 10; // 'auto' is optional
printf("Value of a: %d\n", a);
}
Can't use & (address-of) operator (registers don’t have memory addresses in C).
Used for variables that require fast access, like loop counters.
#include <stdio.h>
void example() {
register int i;
for (i = 0; i < 5; i++) {
printf("%d ", i);
}
}
Can also be used with global variables to restrict scope to the file.
Output:
99
Dr.NNCE I / 02 C / QB
FILE PROCESSING
UNIT V
PART-A
1. What is a file?(NOV 2022)
A file is a collection of related data stored on a secondary storage device like hard disk. Every
file contains data that is organized in hierarchy as fields, records, and databases. Stored as
sequence of bytes logically contiguous (may not be physically contiguous on disk
100
Dr.NNCE I / 02 C / QB
6. What are the statements used for reading a file? (Nov 2014)
a. FILE*p;Initialize file pointer.
b. fp=fopen(“File_name” ”r”);Open text file for reading.
c. Getc(file_pointer_name);Reads character from file.
d. fgets(str,length,fp); Reads the string from the file.
101
Dr.NNCE I / 02 C / QB
102
Dr.NNCE I / 02 C / QB
Mod Description
103
Dr.NNCE I / 02 C / QB
e
R Opens a text file in reading mode
W Opens or create a text file in writing mode.
A Opens a text file in appended mode.
r+ Opens a text file in both reading and writing
mode.
w+ Opens a text file in both reading and writing
mode.
104
Dr.NNCE I / 02 C / QB
29. How do you search data in a data file using random access method?
Use the fseek() function to perform random access input / output on a file. After
the file was opened by the fopen() function, the fseek would require three parameters
105
Dr.NNCE I / 02 C / QB
to work: a file pointer to the file, the number of bytes to search, and the point of
origin in the file.
PART-B
In file processing in C, “files” typically refer to data files that a program can open, read,
write, or modify. These files can be of various types based on structure, content, and usage.
1. Text Files
Examples:
data.txt
report.csv
logfile.log
2. Binary Files
Examples:
data.bin
image.jpg
archive.zip
Example:
A file storing a list of employee structs in binary format.
106
Dr.NNCE I / 02 C / QB
4. Delimited Files
Examples:
5. Log/Configuration Files
Examples:
settings.ini
error.log
Each of these file types can be processed using C's standard file handling functions from
stdio.h, such as:fopen(), fclose(), fread(), fwrite(), fprintf(), fscanf(), fgets(), fputs()
108
Dr.NNCE I / 02 C / QB
In C programming, a sequential access file is typically handled using standard I/O functions
like fopen(), fgets(), fscanf(), fprintf(), etc. These allow you to read and write files from start
to finish in order.
Basic Example
#include <stdio.h>
int main() {
FILE *fp;
fp = fopen("employees.txt", "w"); // Open for writing
if (fp == NULL) {
printf("Error opening file!\n");
return 1;
}
// Writing records
fprintf(fp, "001 John_Smith 50000\n");
fprintf(fp, "002 Jane_Doe 55000\n");
fprintf(fp, "003 Alice_Jones 60000\n");
#include <stdio.h>
int main() {
FILE *fp;
char id[10], name[50];
int salary;
if (fp == NULL) {
printf("File not found!\n");
return 1;
}
// Reading sequentially
109
Dr.NNCE I / 02 C / QB
fclose(fp);
return 0;
}
Key Points:
Files are processed line by line (or record by record) in the order they appear.
You can't jump to a specific record — this is sequential access, not random access.
It is simple and works well for log files, reports, and simple databases.
C program that reads numbers from a sequential access file and calculates their average.
10
20
30
40
50
#include <stdio.h>
int main() {
FILE *fp;
int number, sum = 0, count = 0;
float average;
if (fp == NULL) {
printf("Error: Could not open file.\n");
return 1;
}
110
Dr.NNCE I / 02 C / QB
fclose(fp);
if (count == 0) {
printf("No numbers found in the file.\n");
} else {
average = (float)sum / count;
printf("Average = %.2f\n", average);
}
return 0;
}
Notes:
4.Write a C program for random access file processing with a transaction processing
system.
It simulates updating a student's balance based on transaction input using a binary file.
Goal
Structure Definition
typedef struct {
int roll;
char name[30];
float balance;
111
Dr.NNCE I / 02 C / QB
} Student;
Step-by-Step Implementation
1. Create a Binary File with Student Records
#include <stdio.h>
typedef struct {
int roll;
char name[30];
float balance;
} Student;
void createFile() {
FILE *fp = fopen("students.dat", "wb");
Student s;
if (!found)
112
Dr.NNCE I / 02 C / QB
void displayFile() {
FILE *fp = fopen("students.dat", "rb");
Student s;
printf("\nStudent Records:\n");
while (fread(&s, sizeof(Student), 1, fp)) {
printf("Roll: %d, Name: %s, Balance: %.2f\n", s.roll, s.name, s.balance);
}
fclose(fp);
}
4. main() Function
int main() {
int roll;
float amount;
int choice;
createFile(); // Step 1: Initial setup
printf("\nTransaction Processing:\n");
printf("Enter Roll No to update: ");
scanf("%d", &roll);
printf("Enter transaction amount (+ for deposit, - for withdrawal): ");
scanf("%f", &amount);
return 0;
}
Key Concepts:
113
Dr.NNCE I / 02 C / QB
command line arguments to pass filenames and other input data to your program at runtime.
This is especially useful in file processing, where you might want to specify the input/output
file without hardcoding it.
if (argc != 2) {
printf("Usage: %s <filename>\n", argv[0]);
return 1;
}
fp = fopen(argv[1], "r"); // Use command line argument as file name
if (fp == NULL) {
printf("Error opening file: %s\n", argv[1]);
return 1;
}
printf("Contents of %s:\n\n", argv[1]);
while ((ch = fgetc(fp)) != EOF) {
putchar(ch);
}
fclose(fp);
return 0;
}
Compile & Run:
gcc file_read.c -o file_read
./file_read input.txt
114
Dr.NNCE I / 02 C / QB
115
Dr.NNCE I / 02 C / QB
116