[go: up one dir, main page]

0% found this document useful (0 votes)
10 views37 pages

Prog in C Ans Key

This document contains the answer key for the B.E./B.Tech. degree examinations in Computer Science and Engineering at Kathir College of Engineering. It includes questions on programming in C, covering topics such as algorithms, data structures, operators, loops, and file handling. The document provides definitions, comparisons, examples, and programming tasks related to these concepts.

Uploaded by

kanimozhi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views37 pages

Prog in C Ans Key

This document contains the answer key for the B.E./B.Tech. degree examinations in Computer Science and Engineering at Kathir College of Engineering. It includes questions on programming in C, covering topics such as algorithms, data structures, operators, loops, and file handling. The document provides definitions, comparisons, examples, and programming tasks related to these concepts.

Uploaded by

kanimozhi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 37

KATHIR COLLEGE OF ENGINEERING, Coimbatore – 62.

(AUTONOMOUS)

Answer Key

Question Paper Code: 249025


B.E. /B.Tech. DEGREE EXAMINATIONS, NOV/DEC - 2024
First Semester
Computer Science and Engineering
(Common to all Branches)
24CS312 – PROGRAMMING IN C
(Regulations 2024A)
Time: Three Hours Maximum Marks: 100 Marks
PART- A (10x2 = 20 Marks)
Q.No. CO BTL
1. Define Algorithm. CO1 BTL2
The step-by-step procedure to solve any logical and mathematical problem
is called an Algorithm.
• Should be written in simple English
• Each and every instruction should be precise and unambiguous.
• Instructions in an algorithm should not be repeated infinitely.
• Algorithm should conclude after a finite number of steps.
• Should have an end point
• Derived results should be obtained only after the algorithm
terminates.

2. Give the structure of C program. CO1 BTL2


3. Compare while and do while statement with an example. CO2 BTL2
while Loop do-while Loop
i)Condition is checked before i)Condition is checked after
executing the loop body. executing the loop body.
ii)May not execute the loop body even ii)Executes the loop body at least
once if the condition is false initially. once, regardless of the condition.
iii) while(condition) iii)do
{ {
// loop body // loop body
} } while(condition);
4. List out the types of array and give few examples. CO2 BTL3
• It is classified into three types
i) One dimensional Array
Example
int a[4]={20,45,67,89};
ii) Two dimensional Array
Example:
int a[3][2]={{10,20},{30,40},{50,60}};
iii) Multi-dimensional Array
Example:
int arr[2][3][2] = { { {0, 1}, {2, 3}, {4, 5} },{ {6, 7}, {8, 9}, {10,
11} }};

5. Differentiate pass by value and pass by reference. CO3 BTL2


pass by value pass by reference.
i)A copy of the value is passed to i)The memory address (pointer) of
the function. the variable is passed to the
function
ii)Uses the actual variable type Uses pointers (int *) to reference
(e.g., int). the variable
iii)The original variable is not The original variable can be
modified modified through the pointer
iv)Requires additional memory for Does not require additional
the copy. memory; uses the same memory
address
v) No changes to the original Changes to the original variable
variable. occur directly.
6. Specify the features of a pointer with an example. CO3 BTL3
 Stores Address: A pointer contains the address of a variable rather than
the variable's value.
 Data Type Specific: Pointers are strongly associated with a data type,
e.g., int*, float*, etc., indicating the type of data the pointer points to.
 Dereferencing: The * operator is used to access or modify the value
stored at the memory address the pointer is pointing to.
 Pointer Arithmetic: Pointers support arithmetic operations like
increment (++), decrement (--), and addition/subtraction of integers, useful
for traversing arrays.
 Dynamic Memory Access: Pointers allow access to dynamically
allocated memory using functions like malloc() and free().
 Function Arguments: Pointers enable passing variables by reference,
making it possible to modify the original variable inside a function.
7. Mention string handling functions with example. CO4 BTL3
strlen()
 Returns the length of a string (excluding the null terminator).
 Example : printf("Length of str1: %zu\n", strlen(str1));
strcpy()
 Copies one string into another.
 Example : strcpy(str3, str1); printf("str3 after copying: %s\n", str3);
strcat()
 Concatenates (appends) one string to another.
 Example : strcat(str1, str2); printf("str1 after concatenation: %s\n",
str1);
strcmp()
 Compares two strings lexicographically.
 Example : int result = strcmp(str1, str2); printf("Comparison result
of str1 and str2: %d\n", result);
strstr()
 Finds the first occurrence of a substring in a string.
 Example : char *substr = strstr(str4, "C programming");
if (substr != NULL)
{ printf("Substring found: %s\n", substr);}

8. Write a program to illustrate the declaration of a structure with an CO4 BTL3


example.
struct Student {
int id;
char name[50];
float marks;
};
9. Interpret file handling in C. CO5 BTL2
File Handling in C refers to the process of creating, opening, reading,
writing, and closing files. It enables programs to store and retrieve data
permanently on storage devices, rather than using temporary memory (like
variables or arrays) that is erased after program execution.
 fopen()
 fclose()
 fgetc()
 fputc()
 fgets()
 fputs()
 fprintf() and fscanf()
 fread() and fwrite()

10. Outline the fseek() function in C. CO5 BTL2


The fseek() function in C is used to reposition the file pointer in a file. It
allows you to move the file pointer to a specific location, either forward,
backward, or relative to a position in the file. This function is part of the
<stdio.h> library.
Syntax
int fseek(FILE *stream, long offset, int whence);
PART – B (5x16 = 80 Marks)
Q.No COs BTL Marks

11.a) Write an algorithm, flowchart and program to sort an array of CO1 BTL 16
integers in ascending order. 3
Algorithm:
 Start
 Input the size of the array n.
 Declare an array arr[n].
 Input the n elements of the array.
 For i from 0 to n-2:
 For j from 0 to n-i-2:
o If arr[j] > arr[j+1], swap arr[j] and arr[j+1].
 Print the sorted array.
 End
Flowchart:
start

N=length of array yes


Array[i] >
J=i+1 Array[j]
no

Swap Array[i] and


j++ array[j]

no
j<N-i-1 i++

i<N-1

no
Print array
Program:
#include <stdio.h>
int main() {
int n, i, j, temp;
printf("Enter the number of elements: ");
scanf("%d", &n);
int arr[n];
printf("Enter %d elements:\n", n);
for (i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
for (i = 0; i < n - 1; i++) {
for (j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
printf("Sorted array in ascending order:\n");
for (i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}

11.b) Summarize the different types of operators in C with suitable CO1 BTL 16
example. 3
OPERATORS :
Operator is a special symbol that tells the compiler to perform specific
mathematical or logical Operation
 Arithmetic Operators
 Relational Operators
 Logical Operators
 Bitwise Operators
 Assignment Operators
 Ternary or Conditional Operators
Arithmetic Operators: Given table shows all the Arithmetic operator
supported by C Language. Lets suppose variable A hold 8 and B hold
3
. Operator Example (int Result
A=8, B=3)
+ A+B 11
- A-B 5
* A*B 24
/ A/B 2
% A%4 0
Relational Operators:
Which can be used to check the Condition, it always return true or
false. Lets suppose variable hold 8 and B hold 3.

Logical Operator:
Which can be used to combine more than one Condition?. Suppose
you want to combined two conditions A<B and B>C, then you need to
use Logical Operator like (A<B) && (B>C). Here && is Logical
Operator.
Operato Example (int A=8, B=3, C=-10) Result
r
&& (A<B) && (B>C) False
|| (B!=-C) || (A==B) True
! !(B<=-A) True

Truth table of Logical Operator C1 C2 C1&&C2 C1||C2 !C1 !C2


T T T T F F
T F F T F T
F T F T T F
F F F F T T

Assignment operators:
Which can be used to assign a value to a variable. Lets suppose
variable A hold 8 and B hold 3.
Operator Example (int A=8, B=3) Result
+= A+=B or A=A+B 11
-= A-=3 or A=A+3 5
*= A*=7 or A=A*7 56
/= A/=B or A=A/B 2
%= A%=5 or A=A%5 3
Increment and Decrement Operator:
Increment Operators are used to increased the value of the variable by one
and Decrement Operators are used to decrease the value of the variable by
one in C programs.
Both increment and decrement operator are used on a single operand or
variable, so it is called as a unary operator. Unary operators are having
higher priority than the other operators it means unary operators are
executed before other operators.
Increment and decrement operators are cannot apply on constant.
The operators are ++, -- Type of Increment Operator
pre-increment
post-increment
pre-increment (++ variable):
In pre-increment first increment the value of variable and then used inside
the expression (initialize into another variable).
Syntax:
++variable;
post-increment (variable ++):
In post-increment first value of variable is used in the expression
(initialize into another variable) and then increment the value of variable.
Syntax:
variable++;
Type of Decrement Operator:
• pre-decrement
• post-decrement

Pre-decrement (-- variable):


In pre-decrement first decrement the value of variable and then used
inside the expression (initialize into another variable).
Syntax:
--variable;
Post-decrement (variable --):
In Post-decrement first value of variable is used in the expression
(initialize into another variable) and then decrement the value of variable.
Syntax:
variable--;
Ternary Operator:
If any operator is used on three operands or variable is known as Ternary
Operator. It can be represented with ? : . It is also called as conditional
operator
Advantage of Ternary Operator
Using ?: reduce the number of line codes and improve the performance of
application.
Syntax:
Expression 1? Expression 2: Expression 3;
Special Operators:
C supports some special operators
Operator Description
sizeof() Returns the size of an memory location.
& Returns the address of an memory location.
* Pointer to a variable.
12.a) Illustrate the use of looping statements with suitable program CO2 BTL 16
example of each. 3
Iterations or loops are used when we want to execute a statement or block
of statements several times. The repetition of loops is controlled with the
help of a test condition.
• The statements in the loop keep on executing repetitively until the test
condition becomes false.
There are the following three types of loops:-
1. While loop
2. Do-while loop
3. For loop
While loop : - It is the fundamental looping statement in C.
It is suited for the problems where it is not known in advance that
how many times a statement or block of statements will be executed.
The general syntax of while loop is as under:-
while(condition)
{
Statement(s);
}
 Firstly the condition given with while is evaluated. If the condition
evaluates to true then the statements given in the body of the loop are
executed.
 After the execution of all the statements the condition is again
checked and if it again evaluates to true then the statements given in the
body of the loop are again executed.
 In this way the statements are executed again and again until the
condition given evaluates to false.
 For terminating the loop, a termination condition is given in the
loop body which makes the condition false at some point of time and as a
result of which the loop terminates.
 If we do not give the termination condition then the loop goes on
repeating again and again infinite times. Such loops are referred to as
infinite loops.
/*program to find the sum of natural numbers from 1 to 10.*/
#include<stdio.h> #include<conio.h> void main()
{
int i=1,sum=0; while(i<=10)
{
sum=sum+i; i++;
}
printf(“The sum of the numbers is %d”,sum); getch();
}
OUTPUT
55
do-while loop :-
The do-while statement is also used for looping.
 It is similar to while loop and is used for the problems where it is
not known in advance that how many times the statement or block of
statements will be executed.
 In case of do-while, firstly the statements inside the loop body are
executed and then the condition is evaluated.
 As a result of which this loop is executed at least once even if the
condition is initially false. After that the loop is repeated until the
condition evaluates to false.
 Since in this loop the condition is tested after the execution of the
loop, it is also known as post- test loop
The general syntax of do-while loop is as follows:-
do
{
Statement(s);
}while(condition);
/*program*/
#include<stdio.h> #include<conio.h> int main()
{
int i=1; do
{
printf(“%d”,i); i++;
}while(i>=10); return 0;
}
For loop :- The general syntax of for loop consists of three expressions
separated by semicolons. It is given as follows:-
for(expression1;expression2;expression3)
{
Statement(s);
}
Here the expression1 is the initialization expression,expression2 is the test
expression and expression3 is the update expression.
Expression1 is executed only once when the loop starts and is used to
initialize the loop variables.
Expression2 is a condition and is tested before each iteration of the loop.
Expression3 is an update expression and is executed each time after the
body of the loop is executed.
/* program to find sum of numbers */
#include<stdio.h> #include<conio.h> void main()
{
int i=1,n,sum=0; printf(“Enter the number\n”); scanf(“%d\n”,&n);
for(i=1;i<=n;i++)
{
sum=sum+i;
}
printf(“%d”,sum); getch();
}
OUTPUT
Enter the number 15
120
 All the three expressions in the for loop are optional and therefore we
can omit any or all the three expressions but in any case the two
separating semi colons should always be present.
 If we omit the test expression then it is always assumed to be true and
therefore the loop never terminates and becomes an infinite loop.
 If we want to make such loops a finite loop then a separate terminate
condition is given within the loop body

12.b) (i) Write a program in C to calculate the average of elements in a 1D CO2 BTL 8
array. 3
Program:
#include<stdio.h>
#include<conio.h>
void main()
int i,a[50],sum=0,n;
float avg;
clrscr();
printf(“Enter no of elements:”);
scanf(“%d”,&n);
printf(“Enter the values:”);
for(i=0;i<n;i++)
scanf(“%d”,&a[i]);
for(i=0;i<n;i++)
sum=sum+a[i];
for(i=0;i<n;i++)
printf(“\na[%d]=%d”,i,a[i]);
printf(\nSum=%d”,sum);
avg=sum/n;
printf(“\nAverage=%d”,avg);
getch();
}
Output:
Enter no. of elements: 5
Enter the values: 3 5 7 9 11
Sum = 35
Average = 7
(ii) Write a C program to add two 3X3 matrices. CO2 BTL 8
Program: 3
#include <stdio.h>
int main() {
int rows, cols, i, j;
printf("Enter the number of rows: ");
scanf("%d", &rows);
printf("Enter the number of columns: ");
scanf("%d", &cols);
int mat1[rows][cols], mat2[rows][cols], result[rows][cols];
printf("Enter elements of the first matrix (%dx%d):\n", rows, cols);
for (i = 0; i < rows; i++) {
for (j = 0; j < cols; j++) {
printf("Enter element mat1[%d][%d]: ", i, j);
scanf("%d", &mat1[i][j]);
}
}
printf("Enter elements of the second matrix (%dx%d):\n", rows, cols);
for (i = 0; i < rows; i++) {
for (j = 0; j < cols; j++) {
printf("Enter element mat2[%d][%d]: ", i, j);
scanf("%d", &mat2[i][j]);
}
}
for (i = 0; i < rows; i++) {
for (j = 0; j < cols; j++) {
result[i][j] = mat1[i][j] + mat2[i][j];
}
}
printf("Resultant matrix after addition:\n");
for (i = 0; i < rows; i++) {
for (j = 0; j < cols; j++) {
printf("%d ", result[i][j]);
}
printf("\n");
}
return 0;
}
Output:
Enter elements of the first 3x3 matrix:
Enter element mat1[0][0]: 1
Enter element mat1[0][1]: 2
Enter element mat1[0][2]: 3
Enter element mat1[1][0]: 4
Enter element mat1[1][1]: 5
Enter element mat1[1][2]: 6
Enter element mat1[2][0]: 7
Enter element mat1[2][1]: 8
Enter element mat1[2][2]: 9

Enter elements of the second 3x3 matrix:


Enter element mat2[0][0]: 9
Enter element mat2[0][1]: 8
Enter element mat2[0][2]: 7
Enter element mat2[1][0]: 6
Enter element mat2[1][1]: 5
Enter element mat2[1][2]: 4
Enter element mat2[2][0]: 3
Enter element mat2[2][1]: 2
Enter element mat2[2][2]: 1

The resulting matrix after addition is:


10 10 10
10 10 10
10 10 10

13.a) Compare between passing arguments by value and by reference with CO3 BTL 16
examples in detail. 3
Call by Value
In call by value, the function gets a copy of the variable, so changes inside
the function do not affect the original variable.
Example: Swapping the values of the two variables
#include <stdio.h>
void swap(int , int); //prototype of the function
int main()
{
int a = 10;
int b = 20;
printf("Before swapping the values in main a = %d, b = %d\n",a,b);
// printing the value of a and b in main
swap(a,b);
printf("After swapping values in main a = %d, b = %d\n",a,b);
// The value of actual parameters do not change by changing the formal
parameters
//in call by value, a = 10, b = 20
}
void swap (int a, int b)
{
int temp;
temp = a;
a=b;
b=temp;
printf("After swapping values in function a = %d, b = %d\n",a,b); //
Formal parameters, a = 20, b = 10
}
Output
Before swapping the values in main a = 10, b = 20
After swapping values in function a = 20, b = 10
After swapping values in main a = 10, b = 20
Consider the following example for the call by reference.
Call by reference
In call by reference, the function gets the address of the variable, so
changes inside the function affect the original variable.
Example: Swapping the values of the two variables
#include <stdio.h>
void swap(int *, int *); //prototype of the function
int main()
{
int a = 10;
int b = 20;
printf("Before swapping the values in main a = %d, b = %d\n",a,b);
// printing the value of a and b in main
swap(&a,&b);
printf("After swapping values in main a = %d, b = %d\n",a,b);
// The values of actual parameters do change in call by reference, a = 10, b
= 20
}
void swap (int *a, int *b)
{
int temp;
temp = *a;
*a=*b;
*b=temp;
printf("After swapping values in function a = %d, b = %d\n",*a,*b); //
Formal parameters, a = 20, b = 10
}
Output
Before swapping the values in main a = 10, b = 20
After swapping values in function a = 20, b = 10
After swapping values in main a = 20, b = 10
 Use Call by Value:
 When the function does not need to modify the original variable.
 For simple data types (e.g., integers, floats).
 Ensures data safety by not altering the caller's variables.
 Use Call by Reference:
 When the function needs to modify the original variable.
 For large data structures (e.g., arrays, structs) to avoid copying
overhead.
 Requires careful handling to avoid unintended side effects.

13.b) Illustrate the concept of pointers with examples. Include pointer CO3 BTL 16
declaration, initialization, and dereferencing and pointer arithmetic. 3
Pointers
Pointer basics
The pointer in C language is a variable which stores the address of
another variable. This variable can be of type int, char, array, function, or
any other pointer. The size of the pointer depends on the architecture.
However, in 32-bit architecture the size of a pointer is 2 byte.
Consider the following example to define a pointer which stores the
address of an integer.
int n = 10;
int* p = &n; // Variable p of type pointer is pointing to the address of the
variable n of type integer.
Declaring a pointer
The pointer in c language can be declared using * (asterisk symbol). It is
also known as indirection pointer used to dereference a pointer.
int *a;//pointer to int
char *c;//pointer to char
Pointer Example
An example of using pointers to print the address and value is given
below.
#include<stdio.h>
int main(){
int number=50;
int *p;
p=&number;//stores the address of number variable
printf("Address of p variable is %x \n",p); // p contains the address of the
number therefore printing p gives the address of number.
printf("Value of p variable is %d \n",*p); // As we know that * is used to
dereference a pointer therefore if we print *p, we will get the value stored
at the address contained by p.
return 0;
}
Output
Address of number variable is fff4
Address of p variable is fff4
Value of p variable is 50
Pointer Arithmetic in C
We can perform arithmetic operations on the pointers like addition,
subtraction, etc. However, as we know that pointer contains the address,
the result of an arithmetic operation performed on the pointer will also be
a pointer if the other operand is of type integer. In pointer-from-pointer
subtraction, the result will be an integer value. Following arithmetic
operations are possible on the pointer in C language:
o Increment
o Decrement
o Addition
o Subtraction
o Comparison
Incrementing Pointer in C
If we increment a pointer by 1, the pointer will start pointing to the
immediate next location. This is somewhat different from the general
arithmetic since the value of the pointer will get increased by the size of
the data type to which the pointer is pointing.
We can traverse an array by using the increment operation on a pointer
which will keep pointing to every element of the array, perform some
operation on that, and update itself in a loop.
The Rule to increment the pointer is given below:
new_address= current_address + i * size_of(data type)
Test it Now
Where i is the number by which the pointer get increased.
32-bit
For 32-bit int variable, it will be incremented by 2 bytes.
64-bit
For 64-bit int variable, it will be incremented by 4 bytes.
Let's see the example of incrementing pointer variable on 64-bit
architecture.
#include<stdio.h>
int main(){
int number=50;
int *p;//pointer to int
p=&number;//stores the address of number variable
printf("Address of p variable is %u \n",p);
p=p+1;
printf("After increment: Address of p variable is %u \n",p); // in our case,
p will get incremented by 4 bytes.
return 0;
}
Output
Address of p variable is 3214864300
After increment: Address
Decrementing Pointer in C
Like increment, we can decrement a pointer variable. If we decrement a
pointer, it will start pointing to the previous location. The formula of
decrementing the pointer is given below:
new_address= current_address - i * size_of(data type)
32-bit
For 32-bit int variable, it will be decremented by 2 bytes.
64-bit
For 64-bit int variable, it will be decremented by 4 bytes.
Let's see the example of decrementing pointer variable on 64-bit OS.
#include <stdio.h>
void main(){
int number=50;
int *p;//pointer to int
p=&number;//stores the address of number variable
printf("Address of p variable is %u \n",p);
p=p-1;
printf("After decrement: Address of p variable is %u \n",p); // P will now
point to the immidiate previous location.
}
Output
Address of p variable is 3214864300
After decrement: Address of p variable is 3214864296
C Pointer Addition
We can add a value to the pointer variable. The formula of adding value
to pointer is given below:
new_address= current_address + (number * size_of(data type))
Test it Now
32-bit
For 32-bit int variable, it will add 2 * number.
64-bit
For 64-bit int variable, it will add 4 * number.
Let's see the example of adding value to pointer variable on 64-bit
architecture.
#include<stdio.h>
int main(){
int number=50;
int *p;//pointer to int
p=&number;//stores the address of number variable
printf("Address of p variable is %u \n",p);
p=p+3; //adding 3 to pointer variable
printf("After adding 3: Address of p variable is %u \n",p);
return 0;
}
Output
Address of p variable is 3214864300
After adding 3: Address of p variable is 3214864312
As you can see, the address of p is 3214864300. But after adding 3 with p
variable, it is 3214864312, i.e., 4*3=12 increment. Since we are using 64-
bit architecture, it increments 12. But if we were using 32-bit architecture,
it was incrementing to 6 only, i.e., 2*3=6. As integer value occupies 2-
byte memory in 32-bit OS.
C Pointer Subtraction
Like pointer addition, we can subtract a value from the pointer variable.
Subtracting any number from a pointer will give an address. The formula
of subtracting value from the pointer variable is given below:
new_address= current_address - (number * size_of(data type))
Test it Now
32-bit
For 32-bit int variable, it will subtract 2 * number.
64-bit
For 64-bit int variable, it will subtract 4 * number.
Let's see the example of subtracting value from the pointer variable on 64-
bit architecture.
#include<stdio.h>
int main(){
int number=50;
int *p;//pointer to int
p=&number;//stores the address of number variable
printf("Address of p variable is %u \n",p);
p=p-3; //subtracting 3 from pointer variable
printf("After subtracting 3: Address of p variable is %u \n",p);
return 0;
}
Output
Address of p variable is 3214864300
After subtracting 3: Address of p variable is 3214864288
after subtracting 3 from the pointer variable, it is 12 (4*3) less than the
previous address value.
However, instead of subtracting a number, we can also subtract an address
from another address (pointer). This will result in a number. It will not be
a simple arithmetic operation, but it will follow the following rule.
If two pointers are of the same type,
Address2 - Address1 = (Subtraction of two addresses)/size of data type
which pointer points
#include<stdio.h>
void main ()
{
int i = 100;
int *p = &i;
int *temp;
temp = p;
p = p + 3;
printf("Pointer Subtraction: %d - %d = %d",p, temp, p-temp);
}
Output
Pointer Subtraction: 1030585080 - 1030585068 = 3
Dereferencing a pointer means accessing or modifying the value stored at
the memory location the pointer is pointing to. This is achieved using the
dereference operator (*).
Syntax
*pointer
 pointer is a variable that stores the address of another variable.
 Using *pointer accesses the value stored at the address stored in
pointer.
Steps to Dereference a Pointer
1. Declare a variable.
2. Declare a pointer and store the address of the variable in the
pointer.
3. Use the dereference operator (*) to access or modify the value of
the variable indirectly via the pointer.
Example: Dereferencing a Pointer
#include <stdio.h>
int main() {
int num = 10; // Declare an integer variable
int *ptr = &num; // Declare a pointer and store the address of num
printf("Value of num using dereferencing: %d\n", *ptr);
*ptr = 20;
printf("Updated value of num: %d\n", num);
return 0;
}
Output
Value of num using dereferencing: 10
Updated value of num: 20
Explanation
1. int num = 10;
o Declares an integer variable num and initializes it to 10.
2. int *ptr = &num;
o Declares a pointer ptr that stores the address of num.
3. *ptr = 20;
o Dereferences the pointer ptr and modifies the value at the
address it points to, changing num to 20.

14.a) Discuss about various string handling functions with an example. CO4 BTL 16
String Operations: 3
1.String Copy- strcpy
2.String concatenation- strcat
3.String to lowercase – strlwr()
4.String to uppercase – strupr()
5.String length- strlen()
6.String compare – strcmp()
String reverse – strrev()
String Copy:
The strcpy() is used to copy one string to another.
String Concat:
The strcat() is used for string concatenation. It will append a copy of the
source string to the end of the
destination string.
String Lowercase:
The strlwr() is used to convert all the characters of the given string to
lowercase.
String Uppercase:
The strupr() is used to convert all the characters of the given string to
uppercase.
String Length:
The strlen() calculates the length of a given string. It doesn’t count the
null character ‘\0’.
String Compare:
The strcmp() is used to compare two strings.
String Reverse:
The strrev() is the function used to reverses or changes the order of a
given string so that the last
character of the string becomes the first character of the string and so on.
we can also check the
Palindrome of the given string by reversing the original string.
Example Program to copy the given String:
#include<stdio.h>
#include <string.h>
int main(){
char ch[20]={'C', 'P', 'R', 'O', 'G', 'R', 'A', 'M','\0'};
char ch2[]="welcome";
printf ("The value of First String=%s",ch);
printf ("\nThe value of Second String=%s",ch2);
strcpy(ch2,ch);
printf ("\nValue of second string After copy is: %s",ch2);
return 0;
}
Example program for Concatenation of two Strings:
#include<stdio.h>
#include <string.h>
int main(){
char ch[10]={'W', 'e', 'l', 'c', 'o','m','e', '\0'};
char ch2[10]={'t','o','C','\0'};
strcat(ch,ch2);
printf ("Value of first string is: %s",ch);
return 0;
}
Example program to convert the string from uppercase to lowercase:
#include <stdio.h>
#include <ctype.h>
void to_lowercase(char str[]) {
for (int i = 0; str[i] != '\0'; i++) {
str[i] = tolower(str[i]);
}}
int main() {
char str[100];
printf ("Enter a string: ");
fgets(str, sizeof(str), stdin);
to_lowercase(str);
printf ("Lowercase String: %s", str);
return 0;}
Example program to convert the string lowercase to uppercase:
#include <stdio.h>
#include <ctype.h>
// Function to convert a string to uppercase
void to_uppercase(char str[]) {
for (int i = 0; str[i] != '\0'; i++) {
str[i] = toupper(str[i]);
}}
int main() {
char str[100];
printf ("Enter a string: ");
fgets(str, sizeof(str), stdin);
to_uppercase(str);
printf ("Uppercase String: %s", str);
return 0;
}
Example program to find the Length of the string
#include<stdio.h>
#include <string.h>
int main(){
char ch[20]={'j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't', '\0'};
printf ("Length of string is: %d",strlen(ch));
return 0;
}
Example program to compare two strings:
#include<stdio.h>
#include<string.h>
int main(){
char str1[20],str2[20];
printf ("Enter 1st string: ");
scanf("%s",str1);
printf ("Enter 2nd string: ");
scanf("%s",str2);
if(strcmp(str1,str2)==0)
printf ("Strings are equal");
else
printf("Strings are not equal");
return 0;
}

14.b) Write a C program to read and display the information of all the CO4 BTL 16
students in a class using array of structures. 3
Program:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Student {
char* name;
int roll_number;
int age;
double total_marks;
};
void main()
{
int i = 0;
struct Student student[5];
student[0].roll_number = 1;
student[0].name = "Anand";
student[0].age = 12;
student[0].total_marks = 78.50;
student[1].roll_number = 2;
student[1].name = "Babu";
student[1].age = 10;
student[1].total_marks = 56.84;
student[2].roll_number = 3;
student[2].name = "Daisy";
student[2].age = 11;
student[2].total_marks = 87.94;
student[3].roll_number = 4;
student[3].name = "Ganga";
student[3].age = 12;
student[3].total_marks = 89.78;
student[4].roll_number = 5;
student[4].name = "Ishwarya";
student[4].age = 13;
student[4].total_marks = 78.55;
printf("Student Records:\n\n");
for (i = 0; i < n; i++)
{
printf("\tName = %s\n", student[i].name);
printf("\tRoll Number = %d\n", student[i].roll_number);
printf("\tAge = %d\n", student[i].age);
printf("\tTotal Marks = %0.2f\n\n", student[i].total_marks);
}
getch();
}
Output:
Student Records:
Name = Anand
Roll Number = 1
Age = 12
Total Marks = 78.50
Name = Babu
Roll Number = 2
Age = 10
Total Marks = 56.84
Name = Daisy
Roll Number = 3
Age = 11
Total Marks = 87.94
Name = Ganga
Roll Number = 4
Age = 12
Total Marks = 89.78
Name = Ishwarya
Roll Number = 5
Age = 13
Total Marks = 78.55

15.a) Explain the inbuilt file handling functions in detail with suitable CO5 BTL 16
examples. 3
File Operations
One can perform following operations regarding files:
1. Creating a new file
2. Opening an existing file
3. Reading from and writing information to a file
4. Closing a file
Working with file
In order to work with file, you need to declare a pointer of type file. This
declaration is needed for communication between file and program.
FILE *fptr;
Opening a file
File can be opened with the help of fopen() function available in stdio.h
library file of C
The syntax for opening a file is
FILE *fptr = fopen("fileName","mode")
Here, fileName is a string literal, it refers the name of the file to be open
with it’s extension, if the file to be open is present in some other
directory, then have to specify full path. mode can have one of the
following options. .
Example:
fptr=fopen("C:\\TURBOC3\\program.txt","w");
Closing a File
File should be closed after its usage. File can be closed using fclose()
liberary function The syntax for closing a file is
fclose(file_pointer);
Here, file_pointer is the one which was created when the file was opened
using fopen() function.
Example:
fclose(fptr)
Text File Input Output (I/O)
In order to manipulate files we have to learn about File I/O i.e. how to
write data into a file and how to read data from a file. To read and write
file we use the functions fprintf() and fscanf().
Functions fprintf() and fscanf() are the file version of printf() and fscanf().
The only difference while using fprintf() and fscanf() is that, the first
argument is a pointer to FILE.
fprintf() - Writing to file
Example:
#include <stdio.h>
void main()
{
int n;
FILE *fptr;
fptr=fopen("C:\\TURBOC3\\sample.txt","w");
if(fptr==NULL){
printf("Cannot Open File!");
exit(1);
}
printf("Enter a Number: ");
scanf("%d",&n);
fprintf(fptr,"%d",n);
fclose(fptr);
}
This program read a number from user and stores in file. After you
compile and run this program, you can see a text file sample.txt created in
C:\\TURBOC3\\ path of your computer. When you open that file, you can
see the integer you entered. Similarly, fscanf() can be used to read data
from file.
fscanf() - Reading from file
#include <stdio.h>
void main()
{
int n;
FILE *fptr;
if ((fptr=fopen("C:\\TURBOC3\\sample.txt","r"))==NULL){
printf("Cannot Open File ");
exit(1);
}
fscanf(fptr,"%d",&n);
printf("Value in file is=%d",n);
fclose(fptr);
}
This program reads the integer present in the sample.txt file and prints it
onto the screen. Other unformatted I/O functions like fgetc(), fputc() ,
etc.. are used to read and write data in files.
fputc(), fputs()
The function fputc() writes the character value of the argument c to the
output stream referenced by fp. It returns the written character written on
success otherwise EOF if there is an error.
int fputc( int c, FILE *fp );
The function fputs() writes the string s to the output stream referenced by
fp. It returns a non-negative value on success, otherwise EOF is returned
in case of any error.
int fputs( const char *s, FILE *fp );
Example:
#include <stdio.h>
void main() {
FILE *fptr;
fptr = fopen("C:\\TURBOC3\\sample.txt", "w+");
fputs("Printing Using fputs", fptr);
fclose(fptr);
}
When the above program run, it creates a new file sample.txt in C:\\
TURBOC3\\ directory and writes the string "Printing Using fputs" to that
file.
fgetc(),fgets()
The fgetc() function reads a character from the input file referenced by fp.
The return value is the character read, or in case of any error, it returns
EOF.
int fgetc( FILE * fp );
The functions fgets() reads up to n-1 characters from the input stream
referenced by fp. It copies the read string into the buffer buf, appending a
null character to terminate the string.
If this function encounters a newline character '\n' or the end of the file
EOF before they have read the maximum number of characters, then it
returns only the characters read up to that point including the new line
character.
char *fgets( char *buf, int n, FILE *fp );
Example:
#include <stdio.h>
void main()
{
FILE *fptr;
char buff[255];
fptr = fopen("C:\\TURBOC3\\sample.txt", "r");
fgets(buff, 255, fptr);
printf("%s\n", buff );
fclose(ptr);
}
When the above program run, it reads the file created in the previous
program and produces the following result. Printing Using fputs
fread() and fwrite() – To read and write Binary file.
Functions fread() and fwrite() are used for reading from and writing to a
file on the disk respectively in case of binary files.
fwrite()
Function fwrite() takes four arguments, address of data to be written in
disk, size of data to be written in disk, number of such type of data and
pointer to the file where you want to write.
Syntax:
write(address_data,size_data,numbers_data,pointer_to_file);
Example :
#include <stdio.h>
struct marks
{
int m1, m2,m3,m4,m5;
};
void main()
{
int n;
struct marks m;
FILE *fptr;
if ((fptr = fopen("C:\\TURBOC3\\mark.bin","wb")) == NULL){
printf("File Cannot Open!");
exit(1);
}
printf("Enter 5 Students Marks\n");
for(n = 1; n <= 5; ++n)
{
printf("Enter English Mark of Student %d : ", n);
scanf("%d",&m.m1);
printf("Enter Math's Mark of Student %d : ", n);
scanf("%d",&m.m2);
printf("Enter Physics Mark of Student %d : ", n);
scanf("%d",&m.m3);
printf("Enter Chemistry Mark of Student %d : ", n);
scanf("%d",&m.m4);
printf("Enter Python Mark of Student %d : ", n);
scanf("%d",&m.m5);
fwrite(&m, sizeof(struct marks), 1, fptr);
}
fclose(fptr);
}
fread()
Function fread() also take 4 arguments similar to fwrite() function.
Syntax:
fread(address_data,size_data,numbers_data,pointer_to_file);
Example:
#include <stdio.h>
struct marks
{
int m1, m2,m3,m4,m5;
};
void main()
{
int n;
struct marks m;
FILE *fptr;
if ((fptr = fopen("C:\\TURBOC3\\mark.bin","rb")) == NULL){
printf("Cannot Open File !");
exit(1);
}
printf("Marks are\n");
for(n = 1; n <= 5; ++n)
{
fread(&m, sizeof(struct marks), 1, fptr);
printf("Student %d Marks : English: %d\t Maths : %d\t Physics: %d\t
Chemistry : %d\t
Python: %d\n",n, m.m1, m.m2, m.m3,m.m4,m.m5); }
fclose(fptr); }
fseek():
This function is used for seeking the pointer position in the file at the
specified byte.
Syntax:
fseek( file pointer, displacement, pointer position);
Where
file pointer ---- It is the pointer which points to the file.
displacement ---- It is positive or negative. This is the number of bytes
which are skipped backward (if negative) or forward( if positive) from the
current position.
This is attached with L because this is a long integer.
Pointer position:
This sets the pointer position in the file.
Value pointer position
0 Beginning of file.
1 Current position
2 End of file
Example:
1) fseek( p,10L,0)
0 means pointer position is on beginning of the file,from this statement
pointer position is skipped 10 bytes from the beginning of the file.
2)fseek( p,5L,1)
1 means current position of the pointer position.From this statement
pointer position is skipped 5 bytes forward from the current position.
3)fseek(p,-5L,1)
From this statement pointer position is skipped 5 bytes backward from the
current position
ftell()
This function returns the value of the current pointer position in the
file.The value is count from the beginning of the file.
Syntax:
ftell(fptr);
Where fptr is a file pointer.
rewind()
This function is used to move the file pointer to the beginning of the given
file.
Syntax:
rewind( fptr);
Where fptr is a file pointer.
Example
Program to read last ‘n’ characters of the file using appropriate file
functions (Here we using fseek() and fgetc()).

15.b) Interpret all “Mode of operations” performed on a File. CO5 BTL 16


Opening a file 3
File can be opened with the help of fopen() function available in stdio.h
library file of C
The syntax for opening a file is
FILE *fptr = fopen("fileName","mode")
Here, fileName is a string literal, it refers the name of the file to be open
with it’s extension, if the file to be open is present in some other
directory, then have to specify full path. mode can have one of the
following options.
Table: File Opening Modes
File Mode Meaning of Mode
r Open for reading. - If the file does not exist, fopen() returns NULL.
rb Open for reading in binary mode. - If the file does not exist, fopen()
returns NULL.
w Open for writing. - If the file exists, its contents are overwritten. If the
file does not exist, it will be created.
wb Open for writing in binary mode. - If the file exists, its contents are
overwritten. If the file does not exist, it will be created.
a Open for append. i.e, Data is added to end of file. - If the file does not
exists, it will be created.
ab Open for append in binary mode. i.e, Data is added to end of file. - If
the file does not exists, it will be created.
r+ Open for both reading and writing. - If the file does not exist, fopen()
returns NULL.
rb+ Open for both reading and writing in binary mode. - If the file does
not exist, fopen() returns NULL.
w+ Open for both reading and writing. - If the file exists, its contents are
overwritten. If the file does not exist, it will be created.
wb+ Open for both reading and writing in binary mode. - If the file exists,
its contents are overwritten. If the file does not exist, it will be created.
a+ Open for both reading and appending. - If the file does not exists, it
will be created.
ab+ Open for both reading and appending in binary mode. - If the file
does not exists, it will be created.
Example:
fptr=fopen("C:\\TURBOC3\\program.txt","w");
#include <stdio.h>
int main() {
FILE *file;
// Opening file for writing
file = fopen("example.txt", "w");
if (file == NULL) {
printf("Error opening file!\n");
return 1;
}
fprintf(file, "Hello, World!\n");
fclose(file);
file = fopen("example.txt", "r");
if (file == NULL) {
printf("Error opening file!\n");
return 1;
}
char content[100];
fgets(content, 100, file);
printf("Content read from file: %s\n", content);
fclose(file);
return 0;
}
*****************

You might also like