Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
21 views30 pages

PPS II Mid Answers

The document provides an overview of bubble sort, linear search, matrix multiplication, passing 2-D arrays to functions, and string manipulation functions in C. It includes algorithms, example programs, and explanations of various concepts such as time complexity and pointer arithmetic. The content is structured to illustrate practical implementations and theoretical understanding of these programming techniques.

Uploaded by

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

PPS II Mid Answers

The document provides an overview of bubble sort, linear search, matrix multiplication, passing 2-D arrays to functions, and string manipulation functions in C. It includes algorithms, example programs, and explanations of various concepts such as time complexity and pointer arithmetic. The content is structured to illustrate practical implementations and theoretical understanding of these programming techniques.

Uploaded by

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

Sort the following 10 elements using bubble sort technique.

Write the algorithm for the


same.

85 53 96 35 27 87 37 12 90 23

Sorting is the process of arranging the data in some logical order. Bubble sort is an algorithm to
sort various linear data structures. The logical order can be ascending and descending. which each
pair of adjacent elements is compared and the elements are swapped if they are not in order. This
algorithm is not suitable for large data sets as its average and worst case complexity are of O(n2)
where n is the number of items. in the case of numeric values or dictionary order in the case of
alphanumeric values.
Algorithm:

Step 1: Start

Step 2: Read n, a[i] values as integers

Step 3: for i= 1 to n do increment i by 1

begin

for j= 0 to n - 1 increment j by 1

begin

if(a[j] > a[j + 1])

begin

t = a[j];

a[j] = a[j + 1];

a[j + 1] = t;

end

end

end

Step 4: for i: 0 to n
Print a[i]
Step 5: Stop

Time Complexity of Bubble Sort :

The complexity of sorting algorithm is depends upon the number of comparisons that
are made.
Total comparisons in Bubble sort is: n ( n – 1) / 2 ≈ n 2 – n
Best case : O (n2 )
Average case : O (n2 )
Worst case : O (n2)

Step1:
Comparing adjacent Elements
85 53 96 35 27 87 37 12 90 23

53 85 96 35 27 87 37 12 90 23

53 85 96 35 27 87 37 12 90 23

85 53 35 96 27 87 37 12 90 23

85 53 35 27 96 87 37 12 90 23

85 53 35 27 87 96 37 12 90 23

85 53 35 27 87 37 96 12 90 23

85 53 35 27 87 37 12 96 90 23

85 53 35 27 87 37 12 90 96 23

85 53 35 27 87 37 12 90 23 96
Step 2:
85 53 35 27 87 37 12 90 23 96

53 85 35 27 87 37 12 90 23 96

53 35 85 27 87 37 12 90 23 96

53 35 27 85 87 37 12 90 23 96
53 35 27 85 87 37 12 90 23 96

53 35 27 85 87 37 12 90 23 96

53 35 27 85 37 87 12 90 23 96

53 35 27 85 37 12 87 90 23 96

53 35 27 85 37 12 87 90 23 96

53 35 27 85 37 12 87 23 90 96

Step3:
53 35 27 85 37 12 87 23 90 96

35 53 27 85 37 12 87 23 90 96
35 27 53 85 37 12 87 23 90 96

35 27 53 85 37 12 87 23 90 96

53 35 27 37 12 85 87 23 90 96

53 35 27 37 12 85 87 23 90 96

53 35 27 37 12 85 23 87 90 96

Step4:
53 35 27 37 12 85 23 87 90 96

35 53 27 37 12 85 23 87 90 96
35 27 53 37 12 85 23 87 90 96

35 27 37 53 12 85 23 87 90 96

35 27 37 12 53 85 23 87 90 96

35 27 37 12 53 85 23 87 90 96

35 27 37 12 53 23 85 87 90 96
Step5:
27 35 37 12 53 23 85 87 90 96

27 35 37 12 53 23 85 87 90 96

27 35 12 37 53 23 85 87 90 96

27 35 12 37 53 23 85 87 90 96

27 35 12 37 23 53 85 87 90 96
Step6
27 35 12 37 23 53 85 87 90 96

27 12 35 37 23 53 85 87 90 96

27 12 35 37 23 53 85 87 90 96

27 12 35 23 37 53 85 87 90 96

Step7:
27 12 35 23 37 53 85 87 90 96

12 27 35 23 37 53 85 87 90 96

12 27 35 23 37 53 85 87 90 96

12 27 23 35 37 53 85 87 90 96

Step8:
12 27 23 35 37 53 85 87 90 96
12 27 23 35 37 53 85 87 90 96
12 23 27 35 37 53 85 87 90 96

Write a program for searching a key element in the array using Linear Search method.

Linear search in C to find whether a number is present in an array. If it's present, then at what
location it occurs. It is also known as a sequential search. It is straightforward and works as
follows: we compare each element with the element to search until we find it or the list ends.

Program:

#include<stdio.h>
int main()
{
int i, a[20], n, key, flag = 0;
printf("Enter the size of an array \n");
scanf("%d", &n);
printf("Enter the array elements");
for(i = 0; i < n; i++)
{
scanf("%d", &a[i]);
}
printf("Enter the key elements");
scanf("%d", &key);
for(i = 0; i < n; i++)
{
if(a[i] == key)
{
flag = 1;
break;
}}
if(flag == 1)
printf("The key elements is found at location %d", i);
else
printf("The key element is not found in the array");
return 0;
}

Write a program to perform multiplication of matrices of order m by p and p by n.

#include<stdio.h>
int main()
{
int a[20][20],b[20][20],c[20][20];
int m,n,p,i,j,k;
printf("Enter rows and columns of matrix A\n");
scanf("%d%d",&m,&p);
printf("Enter rows and columns of matrix B\n");
scanf("%d%d",&n,&p);
if(n!=p)
{
printf("Matrix multiplication not possible\n");
return 0;
}
printf("Enter elements of matrix A\n");
for(i=0;i<m;i++)
{
for(j=0;j<p;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("Enter elements of matrix B\n");
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
scanf("%d",&b[i][j]);
}
}
for(i=0;i<n;i++)
{
for(j=0;j<p;j++)
{
c[i][j]=0;
for(k=0;k<n;k++)
{
c[i][j]=c[i][j]+a[i][k]*b[k][j];
}
}
}
printf("Product of two matrices is\n");
for(i=0;i<m;i++)
{
for(j=0;j<p;j++)
{
printf("%d\n",c[i][j]);
}
}
}

How to pass a 2-D array to Function? Explain with example program.


When we need to pass an entire array to a function, we can pass the name of the array. Entire array
is always passed by reference to the function. Following are the rules to pass 2-D array in a
function :
The rules are simple.
 The function must be called by passing only the array name.
 In the function definition, we must indicate that the array has two dimensions by
including two sets of brackets.
 The size of the second dimension must be specified.
 The prototype declaration should be similar to the function header.

Example:

#include <stdio.h>
const int M = 3;
const int N = 3;

void print(int arr[M][N])


{
int i, j;
for (i = 0; i < M; i++)
for (j = 0; j < N; j++)
printf("%d ", arr[i][j]);
}

int main()
{
int arr[][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
print(arr);
return 0;
}
Illustrate the use of any five String manipulation functions using programs?

C supports a number of string handling functions. All of these built-in functions are
aimed atPerforming various operations on strings and they are defined in the header file
string.h

strlen( )

This function is used to find the length of the string excluding the NULL character. In
other words, this function is used to count the number of characters in a string. Its
syntax is as follows:

syntax:

int cse_c(string)
Example: char str1[ ] = “WELCOME”;

int n;

n = strlen(str1);

Program:

#include<stdio.h>
#include<string.h>
int main()
{
char string1[50];
int length;
printf("\n Enter any string:");
gets(string1);
length=strlen(string1);
printf("\n The length of string=%d",length);
}

ii). strcpy( )

This function is used to copy one string to the other.

Its syntax is as follows:

Strcpy(str1,str2);

where string1 and string2 are one-dimensional character arrays.This function copies the
content of string2 to string1.

Program:

#include<stdio.h>
#include<string.h> int main( )
{
char string1[30],string2[30];
printf("\n Enter first string:");
gets(string1);
printf("\n Enter second string:");
gets(string2);
strcpy(string2,string1);
printf("\n First string=%s",string1);
printf("\n Second string=%s",string2);
}
(iii). strcmp ( )

This function compares two strings character by character (ASCII comparison) and
returns one of three values {-1,0,1}. The numeric difference is „0‟ if strings are equal .If
it is negative string1is alphabetically above string2 .If it is positive string2 is alphabetically
above string1.

Its syntax is as follows:

int strcmp(string1,string2);
Program:
#include<stdio.h>
#include<string.h>
main()
{
char string1[30],string2[15];
int x;
printf(“\n Enter first string:”);
gets(string1);
printf(“\n Enter second string:”);
gets(string2);

x=strcmp(string1,string2);
if(x==0)
printf(“\n Both strings are
equal”); else if(x>0)
printf(“\n First string is bigger”);
else
printf(“\n Second string is bigger”);
}

iv). strcat ( )

This function is used to concatenate two strings. i.e., it appends one string at the end of
thespecified string. Its syntax as follows:
strcat(string1,string2);
where string1 and string2 are one-dimensional character arrays. This function joins two
strings together. In other words, it adds the string2 to string1 and the string1 contains the
final concatenated string.
E.g., string1 contains prog and string2 contains ram, then string1 holds program after
execution of the strcat() function.

#include<stdio.h>
#include<string.h>
main()
{

char string1[30],string2[15];
printf(“\n Enter first string:”);
gets(string1);
printf(“\n Enter second string:”);
gets(string2);
strcat(string1,string2);
printf(“\n Concatenated string=%s”,string1);
}
strrev( ):

strrev( ) function reverses a given string in C language. Syntax for strrev( ) function is given
below.
char *strrev(char *string);

Program:

#include <stdio.h>
#include <string.h>
int main() {
char string[100];
char ch, *ptr;
printf("Enter any string\n");
gets(string);
printf("Enter any character to search\n");
scanf("%c", &ch);
ptr = strchr(string, ch);
if(NULL == ptr){
printf("'%c' not found in string \"%s\"\n", ch, string);
} else {
printf("String after %c is \"%s\"\n", ch, ptr);
}
return(0);
}

Explain about pointer arithmetic using suitable examples?


Pointer arithmetic is a set of operations that can be performed on pointers, which are
variables that store memory addresses. These operations are different from traditional
mathematical calculations because they are performed in the context of memory addresses
and the data types they point to.
Some of the operations are done by the pointer in C language. Some of the operations are :

 Increment/Decrement of a Pointer

 Addition of integer to a pointer

 Subtraction of integer to a pointer

 Comparison of pointers

Increment/Decrement of a Pointer
Increment: When you increment a pointer in C, it moves to the next memory location based on
the size of the data it points to.

For example, if you have an integer pointer and you increment it, it will jump to the next integer-
sized space in memory (usually 4 bytes). The same applies to float pointers; they move by the size
of a float (typically 4 bytes) when incremented. This way, pointers stay aligned with the data they
point to.

Decrement: When a pointer is decremented in C, it moves backward by an amount equal to the


size of the data type it is pointing to. Your examples illustrate this effectively:

 If you have an integer pointer and you decrement it, it moves back by 4 bytes (assuming a
standard 4-byte integer on most systems).
 If you have a float pointer and you decrement it, it also moves back by 4 bytes (assuming a
standard 4-byte float).

Addition of Integer to Pointer

When you add an integer to a pointer, the integer value is first multiplied by the size of the data
type to which the pointer points, and then the result is added to the pointer’s address.

example:

 You have an integer pointer storing the address 1000.

 When you add the integer 5 to it with the expression ptr = ptr + 5, the final address stored
in ptr will be calculated as follows: 1000 + sizeof(int) * 5, which is equal to 1020.

Subtraction of Integer to Pointer

When you subtract an integer from a pointer, the integer value is first multiplied by the size of the
data type to which the pointer points, and then the result is subtracted from the pointer’s address.

example:

 You have an integer pointer storing the address 1000.

 When you subtract the integer 5 from it with the expression ptr = ptr - 5, the final address
stored in ptr will be calculated as follows: 1000 - sizeof(int) * 5, which is equal to 980.

#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);

p=p-3;

printf("After subtract 3: Address of p variable is %u \n",p);

return 0;

}
Write a program to reverse a given string without using built-in function strrev( ).

#include <stdio.h>
#include<string.h>
void main()
{
char s[10],d[10];
int len,i,flag;
printf("enter the data into s: ");
gets(s);
len=strlen(s);
for(i=0;i<len;i++)
{
if(s[i]!=s[len-i-1])
{
flag=1;
break;
}
}
if(flag==0)
{
printf("yes");
}
else{
printf("no");
}
}

Write a C program for exchanging of two values using Call by reference mechanism.

#include<stdio.h>
void swap(int *,int *) ; // function declaration
void main(){
int num1, num2 ;
num1 = 10 ;
num2 = 20 ;
printf("\nBefore swap: num1 = %d, num2 = %d", num1, num2) ;
swap(&num1, &num2) ; // calling function
printf("\nAfter swap: num1 = %d, num2 = %d", num1, num2);
}
void swap(int *a, int *b) // called function
{
int temp ;
temp = *a ;
*a = *b ;
*b = temp ;
}
How to create array of strings? Explain with suitable example
 An array is essentially a collection of elements. And the data types for all elements
must be the same and stored at the contiguous memory location. Similarly, an array of
strings means a collection of several strings.
1-D Array Of Strings:
 String is a one-dimensional array of characters which is terminated by delimiter \0
(null). Thus, C uses variable-length delimited strings in programs.
Syntax:

data_type arrayName [Size ] = “String” char

str[6]=”Hello”
Program:
#include<stdio.h>
int main()
{
char str[8];
printf("Enter a String: "); scanf("%s", &str);
printf("%s", str);
}
2-D array of Strings:
An array of strings is a two-dimensional array of character-type arrays where each character
array (string) is null-terminated..
Syntax:
data_type arrayName [size1][size2] = {string1, string2, ..., string

char strings [no_of_strings] [max_size_of_each_string];


A two-dimensional array of character types, where the first subscript is the total number of
strings and the second subscript is the maximum size of each string.
To initialize an array of strings, you need to provide the multiple strings inside the double
quotes separated by the commas.
Example:
char city[4][12] = { "Chennai", "Kolkata", "Mumbai", "New Delhi" };
Program:
#include <stdio.h>
int main ()
{
char subjects [5][15] = {
"English", "Mathematics", "PPS","BEEE", "ED" };
for (int i = 0; i < 5; i++){
printf("%s\n", subjects[i]);
}
return 0;
}
Write a C program to find the sum of array elements using Pointers.
#include <stdlib.h>
#include<stdio.h>
int main(void)
{
int n,i,*a,sum=0;
printf("Enter size of array:");
scanf("%d",&n);
a=calloc(sizeof(int),n);
printf("Enter %d Elements:",n);
for(i=0;i<n;i++)
{
scanf("%d",a+i);
}
for(i=0;i<n;i++)

{
sum=sum+*(a+i);
}
printf("The sum of Array is: %d",sum);
return 0;
}

Write a C program to find substring in a given string?


#include <stdio.h>
#include <string.h>
int main()
{
char S1[50], S2[15];
int index, i, l1, l2, j, max;
printf("Enter String :--> ");
gets(S1);
printf("Enter Substring :--> ");
gets(S2);
l1 = strlen(S1);
l2 = strlen(S2);
max = l1 - l2;
for(i = 0;i <= max; i++)
{
if(strncmp(S1 + i, S2, l2) == 0)
break;
}
if(i <= max)
printf("\nSubstring is located at index --> %d", i);
else
printf("\nSubstring not found");
return 0;
}
Contrast calloc( ) and malloc( ) functions?

S.No. malloc() calloc()

malloc() is a function that creates one calloc() is a function that assigns a specified number of
1. block of memory of a fixed size. blocks of memory to a single variable.

2. malloc() only takes one argument calloc() takes two arguments.

3. malloc() is faster than calloc. calloc() is slower than malloc()

4. malloc() has high time efficiency calloc() has low time efficiency

malloc() is used to indicate memory calloc() is used to indicate contiguous memory


5. allocation allocation

6. Syntax : void* malloc(size_t size); Syntax : void* calloc(size_t num, size_t size);

malloc() does not initialize the memory to


calloc() initializes the memory to zero
7. zero
S.No. malloc() calloc()

malloc() does not add any extra memory


calloc() adds some extra memory overhead
8. overhead

Develop C program to find the grades of students using structures?


#include<stdio.h>
#include<string.h>
struct stud
{
char nam[20];
int obtain_mark;
int per;
char grad[5];
};
struct stud s[5];
int i;
int main()
{
for(i=1; i<=5; i++)
{
printf("Enter %d student name : ",i);
scanf("%s",&s[i].nam);
printf("Enter %d student obtained marks = ",i);
scanf("%d",&s[i].obtain_mark);
fflush(stdin);
}
for(i=1; i<=5; i++)
s[i].per=s[i].obtain_mark/5;
for(i=1; i<=5; i++)
{
if(s[i].per>=80)
{
strcpy(s[i].grad,"A");
}
else if(s[i].per>=60){
strcpy(s[i].grad,"B");
}
else if(s[i].per>=50){
strcpy(s[i].grad,"C");
}
else if(s[i].per>=40){
strcpy(s[i].grad,"D");
}
else
strcpy(s[i].grad,"F");
}
for(i=1; i<=5; i++)
{
printf("\n%d student %s has obtained grade %s ",i,s[i].nam,s[i].grad);
}
return 0;
}
Compare and contrast Structure and Union with an example
Parameters Structure Union
A structure is declared using the A union is declared using the "union"
Keyword
"struct" keyword keyword
All the structure members have a All the members share the same memory
Memory
unique memory location. location.
Stores distinct values for all the
Value Stores same values for all the members
members
The sum of the sizes of all the members
Size The size of the largest member of the union
of a structure
Initialization of Multiple members can be initialized at
Only one member can be initialized at a time
member variables the same time
You can access individual members at a
Accessing Members You can access only one member at a time
time
It's used to store one of the many available
Data types It's used for storing various data types
data types.
Change in the value of one member will
Change in the value of any member
Altering values affect the value of other members in the
does not affect other member's value
union.
Write C program using pointer to a structure to initialize members of a structure.
#include<stdio.h>
struct student
{
char name[10];
char dept[5];
int htno;
};
int main()
{
struct student *ptr,s;
ptr=&s;
printf("Enter name name:\n");
gets(ptr->name);
printf("Enter dept:\n");
gets(ptr->dept);
printf("Enter hall ticket no:\n");
scanf("%d",&ptr->htno);
printf("Name=%s\n",ptr->name);
printf("Dept=%s\n",ptr->dept);
printf("Hallticket no=%d\n",ptr->htno);
}

Develop a C program to create file and copy the content of that file into another?
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fptr1, *fptr2;
char filename[100];
int c;
printf("Enter the filename to open for reading: ");
scanf("%s", filename);
// Open one file for reading
fptr1 = fopen(filename, "r");
if (fptr1 == NULL)
{
printf("Cannot open file %s\n", filename);
exit(1);
}
printf("Enter the filename to open for writing: ");
scanf("%s", filename);

// Open another file for writing


fptr2 = fopen(filename, "w");
if (fptr2 == NULL)
{
printf("Cannot open file %s\n", filename);
exit(1);
}
// Read contents from file
while ((c = fgetc(fptr1)) != EOF)
{
fputc(c, fptr2);
}
printf("Contents copied to %s\n", filename);
fclose(fptr1);
fclose(fptr2);
return 0;
}

Explain the file operation functions. And illustrate with examples


A file is a container in computer storage devices which is used for storing output or information
permanently in the form of a sequence of bytes on the disk. A File can be used to store a large
volume of persistent data.
File Built-in Function (or) File Built-in Methods
In c provides basic functions and methods necessary to manipulate files by default. You
can do most of the file manipulation using a file object.
 Open a file
 Read or write (perform operation)
 Close the filee
Opening or Creating a file in C
Before making changes to a file, you will have to open it first. You can use the fopen() function
for that. You can also create a new file using the fopen() function.
Syntax of fopen():-
ile_pointer_name = fopen("filename", "mode");
fopen() function accepts two parameters:-
filename:- Name of the file which you want to open or create. If it is stored at some specific
location then you must provide the full path of the file.
mode:- The mode in which you want to open the file.
Example:
include<stdio.h>
void main()
{
FILE *fptr;
fptr=fopen("abc.txt","r");
printf("%s", fptr);
}

Read or write (perform operation)

a) getc(); It is used to read characters from file that has been opened for read operation.

Syntax: C=gets (file pointer)

This statement reads a character from file pointed to by file pointer and assign to c. It returns an
end-of-file marker EOF, when end of file as been reached

b) fscanf();

This function is similar to that of scanf function except that it works on files.

Syntax: fscanf (fp, ”control string”, list);

Example fscanf(f1,”%s%d”,str,&num)
The above statement reads string type data and integer types data from file.

c) getw();

This function reads an integer from file.


Syntax: getw (file pointer);

d) fgets():

This function reads a string from a file pointed by a file pointer. It also copies the string to a
memory location referred by an array.

Syntax: fgets(string,no of bytes,filepointer);

e) fread():

This function is used for reading an entire structure block from a given file.

Syntax: fread(&struct_name,sizeof(struct_name),1,filepointer);

Writing data to a file:

To write into a file, following C functions are used

a. putc(): This function writer a character to a file that has been opened in write mode.

Syntax: This statement writes the character contained in character variable c into a file whose
pointer is fp.

b. fprintf(): This function performs function, similar to that of printf.

Syntax: fprintf(f1,”%s,%d”,str,num);

C. putw(): It writes an integer to a file.

Syntax: putw (variable, fp);

d) fputs(): This function writes a string into a file pointed by a file pointer.

Synatax: fputs(string,filepointer);

e) fwrite(): This function is used for writing an entire block structure to a given file.

Syntax: fwrite(&struct_name,sizeof(struct_name),1,filepointer);
Closing a file:

 A file is closed as soon as all operations on it have been completed.

 Library function for closing a file is fclose(file pointer);


 Example: fclose(fp); This statement closes a file pointed by file pointer fp.

 Or fcloseall(), to close all opened files at a time

Syntax:

fclose(file_pointer_name);

#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
FILE *fptr;
char str[100];
fptr=fopen("ABC.TXT","r");
printf("%d\n",fptr);
do
{
fscanf(fptr,"%s",str);
printf("%s ",str);
}
while(!feof(fptr));
fclose(fptr);
}

Explain the command line arguments. Demonstrate with examples


In C programming language, command line arguments are the data values that are passed from
command line to our program. Using command line arguments we can control the program
execution from the outside of the program. Generally, all the command line arguments are handled
by the main() method.
Syntax:
returnType_Function (*pointer_name) ( list_of_arguments)
 int main(char *argv[] , int argc)
 char *argv[ ] - It is a character pointer array used to store the actual values of command
line arguments are passed from the command line.
 int argc - It is an integer argument used to store the count of command line arguments are
passed from the command line.
Properties of Command-Line arguments in C:-
 argv[0] prints the name of the program.
 argv[1] prints the first argument which is provided by the user.
 argv[argc] is a null pointer.
 Always passed to the main() function.
 Command Line Arguments are passed by the user from the terminal.
 It is used to control programs from the outside.
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) // command line arguments
{
if(argc!=5)
{
printf("Arguments passed through command line " \ "not equal to 5");
return 1;
}
printf("\n Program name : %s \n", argv[0]);
printf("1st arg : %s \n", argv[1]);
printf("2nd arg : %s \n", argv[2]);
printf("3rd arg : %s \n", argv[3]);
printf("4th arg : %s \n", argv[4]);
printf("5th arg : %s \n", argv[5]);
return 0;
}
Describe for following with example
1. fseek()
2. ftell()
3. rewind()
Fseek():
The C library function fseek() sets the file position of the stream to a given offset. The pointer
associated with the file is moved to that offset.
Syntax
int fseek(FILE *fp, long int offset, int pos)
 where, fp – file pointer
 offset – Number of bytes/characters to be offset/moved from whence/the current file
pointer position
 pos – This is the current file pointer position from where offset is added.
 Below 3 constants are used to specify this.
 SEEK_END: End of the file.
 SEEK_SET: Beginning of the file.
 SEEK_CUR: Current position of the file pointer
include< stdio.h >
#include<conio.h>
#include< string.h >
FILE *ptr;
void main()
{
int length;
char str[30]=”Hello! My name is Rajveer.”;
char str2[7]=”Yashraj”;
clrscr();
ptr=fopen(“c:\\test3.txt”,”w”);
fputs(str,ptr);
length=strlen(str2);
fseek(ptr,(ftell(ptr)-length)-1,SEEK_SET);
fputs(str2,ptr);
fclose(ptr);
getch();
}
ftell() Function in C
ftell() function in C is used to find the position of the file pointer from the start of the file.
The syntax of ftell() is:
Syntax:
int ftell(FILE *fp)
Program:
#include<stdio.h>
#include<conio.h>
FILE *ptr;
void main()
{
int length;
char str[20]=”Have a nice day!”;
char str2[20];
clrscr();
ptr=fopen(“c:\\test2.txt”,”w”);
fputs(str,ptr);
fclose(ptr);
ptr=fopen(“c:\\test2.txt”,”r”);
fgets(str2,sizeof(str2),ptr);
printf(“%s\n”,str2);
length=ftell(ptr);
printf(“File length=%d\n”,length);
rewind(ptr);
length=ftell(ptr);
printf(“File length=%d\n”,length);
fclose(ptr);
getch();
}
rewind()
rewind function is used to move file pointer position to the beginning of the file.
Syntax:
rewind(fp);
rewind(cse-c);
Explain self referential structures with an examples ?
A structure definition which includes at least one member as a pointer to the same structure is
known as self-referential structure. It can be linked together to form useful data structures
such as lists, queues, stacks and trees. It is terminated with a NULL pointer (0).
The syntax for using the self referential structure as follows,
struct tag_name
{
Type1 member1;
Type2 member2;
……….
struct tag_name *next;
};
How to access Accessing Structure Members
Accessing Structure Members with Pointer To access the member variable using a pointer to
a structure variable we can use arrow operator(->). We can access member variable by using
pointer variable followed by an arrow operator and then the name of the member variable. To
access a member variable of structure using variable identifier we use dot(.) operator whereas
we use arrow(->) operator to access member variable using structure pointer.
Syntax:
employee_ptr->salary
#include <stdio.h>
struct my_structure {
char name[20];
int number;
int rank;
};
int main()
{
employee_ptr->salary;
struct my_structure variable = {"StudyTonight", 35, 1};
struct my_structure *ptr;
ptr = &variable;
printf("NAME: %s\n", ptr->name);
printf("NUMBER: %d\n", ptr->number);
printf("RANK: %d", ptr->rank);
return 0;
}

You might also like