0% found this document useful (0 votes)
8 views19 pages

C Slow Learners ImpQues

This document outlines important topics for a C programming course, focusing on key concepts such as assignment vs. comparison operators, enumeration constants, programming paradigms, and the structure of a C program. It covers decision-making statements, looping statements, arrays, string handling functions, and sorting/searching algorithms. Each section includes definitions, examples, and explanations to aid slow learners in understanding the material.

Uploaded by

jamila
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)
8 views19 pages

C Slow Learners ImpQues

This document outlines important topics for a C programming course, focusing on key concepts such as assignment vs. comparison operators, enumeration constants, programming paradigms, and the structure of a C program. It covers decision-making statements, looping statements, arrays, string handling functions, and sorting/searching algorithms. Each section includes definitions, examples, and explanations to aid slow learners in understanding the material.

Uploaded by

jamila
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/ 19

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

CS3251: PROGRAMMING IN C
Important Topics for Slow Learners
UNIT – 1
Part – A
1. What is the difference between a=5 and a==5 in C?
 a= 5 means the value 5 of the RHS is assigned to the LHS variable x . Here = is the
assignment operator.
 But x == 5, == this is the relational (comparison) operator. Here it checks whether the value
of RHS is equal to the value of LHS and this expression returns a boolean value as a result. It
is the equality operation.

2. How to Create Enumeration Constant?


 An enum is defined by using the 'enum' keyword in C, and the use of a comma separates the
constants within.
 The basic syntax of defining an enum is:
enum enum_name{int_const1, int_const2, int_const3, …. int_constN};

3. Define Programming Paradigm?


 Programming paradigms are different ways or styles in which a given program or
programming language can be organized.
 It is a way to classify programming languages based on their features. Languages can be
classified into multiple paradigms.

4. What is the importance of keywords in C?
o Keywords are reserved identifiers
o They performs a specific task , specifies the data type
o Keyword can not be used as an identifier
 Ex: for , if , int

5. Define External Storage Classes?
 The extern storage class is used to give a reference of a global variable that is visible to ALL
the program files.
 When you use 'extern', keyword the variable cannot be initialized however, it points the
variable name at a storage location that has been previously defined.

Part – B
1. Describe the Structure of a C Program with an Example?
1. Documentation section
The documentation section consists of a set of comment lines giving:
 The name of the program,
 The author and
 Other details, which the programmer would like to use later.

2. Link section (Preprocessor statement)


 The link section provides instructions to the compiler to link functions from the system
library such as using the #include directive.
Example: #include<stdio.h>, #include<conio.h>

3. Definition section
 The definition section defines all symbolic constants such using the #define directive.
Example: #define pi 3.14

4. Global declaration section:


 There are some variables that are used in more than one function.
 Such variables are called global variables and are declared in the global declaration section
 that is outside of all the functions.This section also declares all the user-defined functions.

5. main () function section


 Every C program must have one main function section.
 We can also use int or main with the main ().
 The void main() specifies that the program will not return any value.
 The int main() specifies that the program can return integer type data.
 This section contains two parts declaration part and executable part.
i) Declaration part:
 The declaration part declares all the variables used in the executable part.

ii) Executable part:


 There is at least one statement in the executable part.
 These two parts must appear between the opening and closing braces.
 The program execution begins at the opening brace and ends at the closing brace.

6. Subprogram section
If the program is a multi-function program then the subprogram section contains all the user-defined
functions that are called in the main () function.User-defined functions are generally placed
immediately after the main () function.

2. Explain about decision making or Conditional branching Statements in C?


Decision making statements in a programming language help the programmer to transfer the
control from one part to other part of the program. Program control is transferred from one
point to another based on the result of some condition.

Decision making statements are also called as conditional statements in C.


Conditional Statements in C are:
1. if statement 3. Nested if-else statement
2. if-else statement 4. If … else if ladder
1. if Statement
if - statement is used to test a condition or Boolean expression(logical expression Eg:- ( x>y),
(x==y), (x!=y)). If the condition is true then the if block statements will be executed.
The if statement contains a logical expression using which data is compared and a decision is
made based on the result of comparison.

2. If…else Statement
The if…else statement evaluates test expression and will execute body of if only when test
condition is True. If the condition is False, body of else is executed.
3. Nested if-else statement
We can have an if...else statement inside another if…else statement. This is called nesting in
Computer programming
4. If … else if ladder

 This is used to check multiple conditions. If condition-1 is false, then it checks the condition-
2 of the else if block, if this is also false then it checks the condition-3 of the next else if block
and so on. If all the given conditions are false then it execute the else block.
 Among the several if…else if block only one block is executed accordingly to the condition.
Example-1 (program to find out the greater number)
#include<stdio.h>
void main(){
int a, b;
a=30;
b=90;
if(b > a)
printf("b is greater than a");
if(a> b)
printf("a is greater than b");
}
Output: b is greater than

3. Illustrate the purpose of Looping Statements with Example?

Different types of looping statements in C are:


1. For
2. While
3. Do While
1. For loop
 A for loop is used for iterating over a sequence of statements.
 To iterate over a series of statements for loop uses three parameters like initial value of the
 iterating variable, Condition for exit of loop and increment or decrement statement.
Example:
for (i = 1; i < 11; i++)
{
printf("%d ", i);
}
Execution of for loop:

 The initialization statement is executed only once.


 Then, the test expression /condition is evaluated. If the test expression is evaluated to false,
 The for loop is terminated. However, if the test expression is evaluated to true, statements
inside the body of the for loop are executed, and the expression is updated by executing the
increment/decrement statement.
2. While Loop
A while loop statement in Python programming language repeatedly executes one or more
target statements as long as a given condition is true.
Execution of while loop:

 The while loop evaluates the testExpression inside the parentheses ().
 If testExpression is true, statements inside the body of while loop are executed.
 Then, testExpression is evaluated again.
 The process goes on until testExpression is evaluated to false.
 If test Expression is false, the loop terminates.
3. do...while loop

 The do..while loop is similar to the while loop with one important difference.
 The body of do...while loop is executed at least once. Only then, the test expression is
evaluated.
 It is a type of exit control loop statement.
Program to add numbers until the user enters zero:
#include <stdio.h>
void main() {
int number, sum = 0;
do { Output
printf("Enter a number: "); Enter a number: 25
scanf("%d", &number); Enter a number: 15
sum += number; Enter a number: 20
} while(number != 0); Enter a number: 30
printf("Sum = %d",sum); Enter a number: 0
} Sum = 9
UNIT- 2
Part – A

1. Define Array and types of Array?


 Array is a collection of similar type of values
 All values are stored in continuous memory locations
 All values share a common name
 Linear data structure. The elements are organized in a sequential order.
i)One Dimensional Array
ii)Two Dimensional Array
2. How to create a two dimentional array?
Two Dimensional Arrays can be thought of as an array of arrays or as a matrix
consisting of rows and columns.
Syntax: data_type array_name[i][j];
Example: int A[10][20];

3. How to initialize a string?Give an Example?


 C does not have a String type to easily create string variables.
 Instead of,must use the char type and create an array of characters to make a string:
char greetings[] = "Hello World!";
 Note that you have to use double quotes ( " " ).
4. Name any two library functions for handling string
strlen() – finds the length of a string. It returns an integer value. It counts the no. of
characters except null character & returns the count
strlen(str)
strcpy() – copies the source string into destination string. So, the source string should
be enough to store the destination string.
strcpy(source,destination)
5. What are the different ways of Initializing an Array?
There are two different kinds of ways to Initializing an Array.
1.Compile Time Initialization
2.RunTime Initialization
Part- B

1. Describe the following functions with examples. (4+4+4+4)


(i) strlen() (ii) strcpy() (iii)strcat() (iv)strcmp()
The group of characters, digits, & symbols enclosed within double quotes is called as
Strings. Every string is terminated with the NULL (‘\0’) character.
E.g. “INDIA” is a string. Each character of string occupies 1 byte of memory. The last
character is always ‘\0’.
Declaration:
String is always declared as character arrays.
Syntax: char stringname*size+;
E.g. char a*20+;
Initialization:
We can use 2 ways for initializing.
i.By using string constant
E.g. char str*6+= “Hello”;
ii.By using initialisation list
E.g. char str*6+=,‘H’, ‘e’, ‘l’, ;l’, ;o’, ‘\0’-;
1. strlen() function
It is used to find the length of a string. The terminating character (‘\0’) is not counted.
Syntax: variable = strlen(string_name);
E.g.
s= “welcome”;
strlen(s)
-> returns the length of string s as 7.
2. strcpy() function
It copies the source string to the destination string
Syntax : strcpy ( destination, source);
E.g.
s1=“hai”;
s2= “welcome”;
strcpy(s1,s2); -> s2 is copied to s1. i.e. s1=welcome
3. strcat() function
It concatenates a second string to the end of the first string.
Syntax: strcat( firststring, secondstring );
E.g.
s1=“good ”;
s2= “ evening”;
strcat(s1,s2); -> s2 is joined with s1. Now s1 is good evening.
4. strcmp() function
It is used to compare 2 strings.
Syntax: varaible=strcmp(string1,string2);
 If the first string is greater than the second string a positive number is returned.
 If the first string is less than the second string a negative number is returned.
 If the first and the second string are equal 0 is returned.
2. Write a C program to sort the n numbers using selection sort?
Selection sort is a sorting algorithm that selects the smallest element from an unsorted
list in each iteration and places that element at the beginning of the unsorted list.
Example: arr[] = {20, 12, 10, 15, 2}

1. Set the first element as minimum.


2. Compare minimum with the second element. If the second element is smaller than
minimum, assign the second element as minimum. Compare minimum with the third
element. Again, if the third element is smaller, then assign third element as minimum
otherwise do nothing. The process goes on until the last element.
3. After each iteration, minimum is placed in the front of the unsorted list. By swapping
theparticular position element with the minimum.
4. For each iteration, indexing starts from the first unsorted element. Step 1 to 3 are repeated
until all the elements are placed at their correct positions.

Selection Sort Algorithm:


selectionSort(array, size) array[i] = temp;
repeat (size - 1) times }
set the first unsorted element as the }
minimum void main()
for each of the unsorted elements {
if element < currentMinimum int data[] = {20, 12, 10, 15, 2};
set element as new minimum int size = sizeof(data)/sizeof(data[0]);
swap minimum with first unsorted printf("Array before sorting:\n");
position for (int i = 0; i < size; ++i)
end selectionSort {
Program: printf("%d ", data[i]);
#include <stdio.h> }
void selectionSort(int array[] , int size) printf("\nArray After sorting:\n");
{ selectionSort(data, size);
int temp; for (int i = 0; i < size; ++i)
for (int i = 0; i < size - 1; i++) {
{ printf("%d ", data[i]);
int minindx = i; }
for (int j = i + 1; j < size; j++) }
{ Output:
if (array[j] < array[minindx]) Array before sorting:
minindx = j; 20 12 10 15 2
} Array After sorting:
temp = array[minindx]; 2 10 12 15 20
array[minindx] = array[i];

3. Develop a C program to search an element from the array? Using binary search algorithm?
Searching is an operation in which a given list is searched for a particular value. If the value is
found its position is returned.
Types of searching:
1. Linear Search
2. Binary Search
Binary Search:

 If a list is already sorted then we can easily find the element using binary search.
 It uses divide and conquer technique.
Binary search follows the divide and conquer approach in which the list is divided into two
halves, and the item is compared with the middle element of the list. If the match is found
then, the location of the middle element is returned. Else, if searching element is less than
middle element, search the left half else search the right half. Repeat these processes again.
 Binary search is faster than the linear search. Its time complexity is O(log(n)), while that of
the linear search is O(n). However, the list should be in ascending/descending order.
Algorithm:
Step 1: START.
Step 2: Accept the sorted array
Step 3: Accept key to be searched.
Step 4: first=0.
Step 5: last=n-1.
Step 6: mid= (first + last) / 2.
Step 7:If k(mid)==key then Display “Record found at position mid” then go to step 10.
Step 8: If key<k(mid) then bottom=mid-1 else, top=mid+1.
Step 9: If top<=bottom then go to step 5.
Step 10: Display “Record not found”.
Step 11: STOP.
Program: printf("%d is present at index %d.\n",
#include<stdio.h> s_elemet, middle+1);
void main() break;
{ }
int i, first, last, middle, n, s_elemet, else
array[100]; last = middle - 1;
printf("Enter number of elements: "); middle = (first + last)/2;
scanf("%d",&n); }
printf("Enter %d numbers:\n", n); if (first > last)
for (i = 0; i < n; i++) printf("Not found! %d is not present in
scanf("%d",&array[i]); the list.\n", s_elemet);
printf("Enter the value to find: "); }
scanf("%d", &s_elemet); OUTPUT:
first = 0; Enter number of elements:5
last = n - 1; Enter 5 numbers:
middle = (first+last)/2; 25
while (first <= last) 15
{ 35
if (array[middle] < s_elemet) 40
first = middle + 1; 10
else if (array[middle] == s_elemet) Enter the value to find: 40
{ 40 is present at index 4
UNIT- 3
Part – A
1. What is the difference between Pass-by-value & Pass-by-reference?

Pass-by-value Pass-by-reference
Copy of actual arguments are passed Address of actual arguments are
passed
Changes to formal arguments doesn’t Changes to formal arguments
reflect to actual argument reflect to actual argument
Need more memory Saves memory space

2. Define recursion or recursive function?


 Recursion is a process by which a function calls itself.
 Recursive function is a function that calls itself.
3. List out any 4 math functions
 pow(x,y) : used to find power of value of xy .Returns a double value
 log10(x) : used to find natural logarithmic value of x
 sqrt(x) : used to find square root vale of x
 sin(x) : returns sin value of x
4. Define pointer. How will you declare it?
 A pointer is a variable that stores the memory address of another variable as its value.
A pointer variable points to a data type (like int ) of the same type, and is created with
the * operator.
 The pointer in c language can be declared using * (asterisk symbol). It is also known
as indirection pointer used to dereference a pointer.
5. What is a void pointer and a null pointer?
 A null pointer is a kind of pointer that does not point to any memory location. If you
declare a pointer and do not initializes it, then there is a possibility of data getting
leaked or accessed by other programs.
 A void pointer is a generic pointer that has the ability to store the address of a variable
of any data type by using the indirection operator with proper typecasting.
PART – B
1. Explain the Parameter passing: Pass by value, Pass by reference with Example?
 There are different ways in which parameter data can be passed into functions.
 Let us assume that a function B() is called from another function A().
 In this case A is called the “calling function (caller)” and B is called the “called
function(callee)”. Also, the arguments which A sends to B are called actual arguments and
theparameters of B are called formal arguments. Important ways of Parameter Passing are
i. Pass By Value
ii. Pass by reference
i)Pass By Value:
C always uses 'pass by value' to pass arguments to functions (another term is 'call by value’).
Pass by value means that a copy of the actual parameter’s value is made in memory, i.e.
Features:

nt in the calling code.

.
ii). Pass by reference:
Pass by reference (also called pass by address) means to pass the reference of an argument in
the calling function to the corresponding formal parameter of the called function so that a
copy of the address of the actual parameter is made in memory, i.e.
Features

(reference) is passed to the callee


.
Example:
#include<stdio.h>
void incrementCount(int *count)//pass by reference
{
*count=*count+1;
printf("\nvalue of count in callee function: %d",*count);
}
void main()
{
int count=0;
printf("Pass by reference\n");
incrementCount(&count);
printf("\nvalue of count in caller function: %d",count);
}
Output
Pass by reference
value of count in callee function: 1
value of count in caller function: 1
2. Binary Search using recursive functions Or (Explain about Recursion)?
 Recursion is a common programming concept. It means that a function calls itself.
 This has the benefit of meaning that you can loop through data to reach a result.
 Recursive function: A function is said to be a recursive function if it calls itself.
 There are two types of Recursion:
i. Direct Recursion
ii. Indirect Recursion
Problem Solution:
1. We will be having an array of numbers, we just need to find out the whether the element is
present in an array or not.
2. It can be done using Binary Search by recursion or iteration methods. Here in this problem
we will do it using recursion.
3. The basic idea behind Binary Search is that the array in which it is applied upon should be
sorted. It divides the whole array into two halves and proceeds to look for the key in
suitable part of divided array.
4. Worst case time complexity of Binary Search it is O(log n). The Best case time complexity
of Binary Search is O(1). The only condition for implementing Binary Search is that the
array should be sorted.
Binary Search program using recursive functions:
#include <stdio.h> if (list[mid] == key)
void binary_search(int [], int, int, int); {
int main() printf("Key found in position
{ %d\n",mid+1);
int key, n, i; }
int list[25]; else if (list[mid] > key)
printf("Enter size of a list: "); {
scanf("%d", &n); binary_search(list, lo, mid - 1,
printf("Enter elements in sorted order\n"); key);
for(i = 0; i < n; i++) }
{ else if (list[mid] < key)
scanf("%d",&list[i]); {
} binary_search(list, mid + 1, hi,
printf("\n"); key);
printf("Enter key to search: "); }
scanf("%d", &key); }
binary_search(list, 0, n, key); Output
} Enter size of a list: 5
void binary_search(int list[], int lo, int hi, Enter elements in sorted order
int key) 10
{ 40
int mid; 90
if (lo > hi) 110
{ 150
printf("Number not found\n"); Enter key to search: 90
return; Key found in position 3
}
mid = (lo + hi) / 2;
3. Explain in detail about Pointers and Pointer operators?
 The Pointer is a variable that stores address of another variable. A pointer can also be
used to refer to another pointer function.
 A pointer can be incremented/decremented, i.e., to point to the next/ previous memory
location.
 The purpose of pointer is to save memory space and achieve faster execution time.
 The general form of a pointer variable declaration is
Operators in pointers

1. Referencing operator: A pointer variable is made to refer to an object. Reference


operator(&) is used for this. Reference operator is also known as address of (&) operator.
Example:
int *ip; //pointer to an integer
double *dp; // pointer to a double
float *fp; //pointer to a float
char *ch //pointer to a character

2. Dereferencing operator
The object referenced by a pointer can be indirectly accessed by dereferencing the pointer.
Dereferencing operator (*) is used for this .This operator is also known as indirection
operator or value- at-address.
Example:
float a=12.5;
float *p;
p=&a;
printf(“%u”,p);
Here p will be assigned with address of variable a.

Example program:
#include<stdio.h>
void main()
{
int x, y, z;
int *p1, *p2;
x=10;
y=20;
p1=&x;
p2=&y;
z= *p1 + *p2
printf(“%d “, z);
printf(“%d “, p1);
printf(“%d “,*p1);
printf(“%d “,&p2);
}
UNIT- 4
Part – A
1. Define self-referential structure?
 A structure is said to be self-referential structure if it contains a pointer to its same structure
type. This self-referential structure is used to create linked list nodes.
Example:
struct node
{
int value;
struct node * next;
};

2. What is the use of typedef?


 typedef is a user defined data type. It is used to define a new data type.
Syntax: typedef old-type new-type
Example:
typedef int I;
void main()
{
I a=2,b=3;
printf(“%d”,a+b);
}

3. What is Linked List? & List out its types


 Linked list is a collection of nodes. A node consists of a value and a next field. The next field
points next node in the list. The types of linked lists are,
 singly linked list – node has 2 fields, value & next link
 Doubly linked list – node has 3 fields, value, previous link & forward link
 Circularly linked list – the next field of last node points first node of the list

4. How to create a node in singly liked list?


 In C language, a linked list can be implemented using structure and pointers.
struct LinkedList
{
int data;
struct LinkedList *next;
};
 The above definition is used to create every node in the list.
 The data field stores the element and the next is a pointer to store the address of the next
node.

5. What is register storage in storage class?


 The scope of register variables is within the function block where it is defined.
 The frequently accessed variables are stored in the CPU register since the access time is less
and makes our program run faster.
PART – B
1. Explain in detail about Nested structures with Example?
 A nested structure in C is a structure within structure. One structure can be declared
inside another structure in the same way structure members are declared inside a
structure.
 There are two ways to define nested structure in C
i. By separate structure ii. By embedded structure
i) By separate structure :
Here we can create 2 structures, but depended structure should be used inside the
main structure as a member.
Syntax:
struct name1 struct name2
{ {
member_1; member_1;
member_2; member_2;
member_n; struct name1 var1;
}; } var2;
ii) By embedded structure
The embedded structure enables us to declare the structure inside the structure. Hence, it
requires less line of codes but it cannot be used in multiple data structures.
Syntax: member_1;
struct name1 member_2;
{ .
member_1; member_n;
member_2; } var1;
struct name2 member_n;
{ }var2;

Example:
#include<stdio.h> printf("Enter employee information?\n");
struct address
{ scanf("%s %s %d %s", & emp.name, &
char city[20]; emp.addr.city, &emp.addr.pin,&
int pin; emp.addr.phone);
char phone[14]; printf("Printing the employee
}; information....\n");
struct employee
{ printf("name: %s\n City: %s\n Pincode:
char name[20]; %d\n Phone: %s", emp.name,
struct address addr; emp.addr.city,
}; emp.addr.pin, emp.addr.phone);
void main ()
{ }
struct employee emp;
2.Explain in detail about Self-referential structures or (singly linked list)?
 Self Referential structures are those structures that have one or more pointers which point to
the same type of structure, as their member.
 Structures pointing to the same type of structures are self-referential in nature.
Types of Self Referential Structures
i. Self Referential Structure with Single Link
ii. Self Referential Structure with Multiple Links
i. Self Referential Structure with Single Link:
 These structures can have only one self-pointer as their member.
 The following example will show us how to connect the objects of a self-referential structure
with the single link and access the corresponding data members.
Example: ob1.data2 = 20;
#include <stdio.h> struct node ob2;
struct node { ob2.link = NULL;
int data1; ob2.data1 = 30;
char data2; ob2.data2 = 40;
struct node* link; ob1.link = &ob2;
}; printf("%d", ob1.link->data1);
void main() printf("\n%d", ob1.link->data2);
{ }
struct node ob1; Output
ob1.link = NULL; 30 40
ob1.data1 = 10;
ii. Self Referential Structure with Multiple Links:
 Self referential structures with multiple links can have more than one self-pointers.
 Manycomplicated data structures can be easily constructed using these structures. Such
structures can easily connect to more than one nodes at a time.
Example:
#include <stdio.h> ob1.next_link = &ob2;
struct node { ob2.next_link = &ob3;
int data; ob2.prev_link = &ob1;
struct node* prev_link; ob3.prev_link = &ob2;
struct node* next_link; }; printf("%d\t", ob1.data);
void main() { printf("%d\t", ob1.next_link->data);
struct node ob1; printf("%d\n", ob1.next_link->next_link->data);
ob1.prev_link = NULL; printf("%d\t", ob2.prev_link->data);
ob1.next_link = NULL; printf("%d\t", ob2.data);
ob1.data = 10; printf("%d\n", ob2.next_link->data);
struct node ob2; printf("%d\t", ob3.prev_link->prev_link->data);
ob2.prev_link = NULL; printf("%d\t", ob3.prev_link->data);
ob2.next_link = NULL; printf("%d", ob3.data);
ob2.data = 20; }
struct node ob3; Output
ob3.prev_link = NULL; 10 20 30
ob3.next_link = NULL; 10 20 30
ob3.data = 30; 10 20 30
3. What is Dynamic Memory Allocation? Explain various C functions that are used for it?
 Dynamic memory allocation refers to the process of manual memory management (allocation
and deallocation).
 Sometimes the size of the array you declared may be insufficient. To solve this issue, allocate
memory manually during run-time. This is known as dynamic memory allocation in C.
 Before learning above functions, let's understand the difference between static memory
allocation and dynamic memory allocation.
1. malloc():
 The name "malloc" stands for memory allocation.
 The malloc() function reserves a block of memory of the specified number of bytes. And, it
returns a pointer of void which can be casted into pointers of any form.
Syntax of malloc() : ptr = (castType*) malloc(size);
Example: ptr = (float*) malloc(100 * sizeof(float));
 The above statement allocates 400 bytes of memory. It's because the size of float is 4 bytes.
And, the pointer ptr holds the address of the first byte in the allocated memory.

2. calloc():
 The name "calloc" stands for contiguous allocation.
 The calloc() function allocates multiple blocks of requested memory.
 The malloc() function allocates memory and leaves the memory uninitialized, whereas the
calloc() function allocates memory and initializes all bits to zero.
Syntax of malloc(): ptr = (castType*)calloc(n, size);
Example: ptr = (float*) calloc(5, sizeof(float));
 In the above statement, we are allocating an float array of size 5 at run-time and assigning it
to an integer pointer ptr, ptr will store the address of the very first element of the allocated array.

3.realloc():
 If the dynamically allocated memory using malloc() or calloc() is not sufficient, we can
reallocate the memory by realloc() function.
Syntax of realloc(): ptr = realloc(ptr, newSize);
Example: ptr1=realloc(ptr1,5,size(int))
Here, ptr is reallocated with a new size of 20 bytes.
4. free():
 The memory occupied by malloc() or calloc() functions must be released by calling free()
function. Otherwise, it will consume memory until program exit.
Syntax of free(): free( pointer );

Example : free(ptr1);

 In the above statement, we are deallocating memory block(s) pointed by a pointer ptr1 in the
Memory.
UNIT- 5
Part – A
1. List out the basic file Operations?
1. Creating a new file – fopen() with attributes as “a” or “a+” or “w” or “w+”
2. Opening an existing file – fopen()
3. Reading from file – fscanf() or fgets()
4. Writing to a file – fprintf() or fputs()
5. Moving to a specific location in a file – fseek(), rewind()
6. Closing a file – fclose()

2. What is sequential access?


 Read and write operation is done sequentially, starting from the beginning of the file.
 The file pointer cannot be moved to any desired position.
 The file pointer can move to next byte after reading the previous byte.

3. Define EOF & feof()?


 Bothe EOF & feof() are used to check whether the file pointer is at the end of
the file content.
 EOF indicates "end of file".The value of EOF is -1 .
 feof() : The function feof() is used to check the end of file after EOF. It tests
the end of file indicator. It returns non-zero value if successful otherwise, zero.

4. Compare fseek() and ftell() Function?


fseek and ftell are routines that permit repositioning of a file.
fseek() ftell()
fseek can use this saved offset value to ftell returns a file's current position as
reposition the file to that same place for an offset of so many bytes from the
reading. beginning of the file

Syntax: fseek(filepointer,offset,position); Syntax: offset= ftell(file pointer);

5. What is the use of rewind() functions?


In C, the rewind() function returns the file position indicator to the beginning of
the file. It takes a file pointer as input and moves the indicator to the beginning of the file,
allowing data to be read once more from the beginning.

Part – B
1. Explain the various file accessing policies in language C with appropriate programs?
Here are two main ways a file can be processed:
i)Sequential Access
ii)Random Access
i) Sequential Access:
 In this type of file, the data are kept sequentially. To read last record of the file, it is expected
to read all the records before that particular record. It takes more time for accessing the
records.
 A Sequential file is characterized by the fact that individual data items are arranged serially in
a sequence, one after another.
Example: fscanf(cfPtr, "%d %s %lf", &account, &name,
#include <stdio.h> &balance);
#include <stdlib.h> while (!feof(cfPtr))
void main() {
{ printf("%-10d%-10s%.2f\n", account, name,
int account; balance);
char name[30]; fscanf(cfPtr, "%d %s %lf", &account, name,
double balance; &balance);
FILE *cfPtr; }
cfPtr = fopen("E:\\clients.txt", "r"); fclose(cfPtr);
if (cfPtr == NULL) }
{ Output
printf("File could not be opened"); Account Name Balance
exit(0); 100 Jones 9023.00
} 200 Frank 234.00
printf("%-10s%-10s%s\n", "Account", "Name", 300 Mano 29023.00
"Balance"); 400 Bala 2344.00.

ii)Random Access:
 In this type of file, the data can be read and modified randomly. If it is desired to read the last
record of a file, directly the same record can be read. It takes less access time.
The functions used to randomly access a record stored in a file are
1. fseek()
2. ftell()
3. rewind()

1.fseek() :
 It is used to reposition a data stream.
Syntax: fseek( file pointer, offset value , position);
The position value should have one of the following values (defined in stdio.h):
i. SEEK_SET : to perform input or output on offset bytes from start of the file
ii. SEEK_CUR : to perform input or output on offset bytes from the current position in the file
iii. SEEK_END : to perform input or output on offset bytes from the end of the file
Example: fseek(fp, 5, 0); fseek(fp, -5, 2);
2. ftell()
 The ftell function is used to know the current position of file pointer. It is at this position at
whichthe next I/O will be performed. The ftell() is defined in stdio.h.
Syntax: ftell (file pointer);
Example: x=ftell(fp);
3. rewind()
 rewind() is used to adjust the position of file pointer so that the next I/O operation will take
place at the beginning of the file. Syntax: rewind(file pointer); Example: rewind( fp);
Example program for random access of file:
#include<stdio.h> while(!feof(fp))
void main () {
{ c = fgetc(fp);
FILE *fp; printf("%c", c);
int c; }
fp = fopen("file.txt","w+"); fclose(fp);
fputs("This is our class room", fp); }
fseek( fp, 12, 0 ); Output:
fputs("C programming LAB ", fp); The current position of the file pointer is:
printf("The current position of the file 30
pointer is: %ld\n", ftell(fp)); The current position of the file pointer is: 0
rewind(fp); This is our C programming Lab
printf("The current position of the file
pointer is: %ld\n", ftell(fp));

2. Explain about command line argument with suitable example?


 It is possible to pass some values from the command line to your C programs when they are
executed. These values are called command line arguments.
 To support command line argument, you need to change the structure of main() function as
given below.
The command line arguments are handled using main() function arguments.
 Here, argc counts the number of arguments. It counts the file name as the first argument.
 argv[] is a pointer array which points to each argument passed to the program. It
should be noted that argv[0] holds the name of the program itself.
 argv[1] is a pointer to the first command line argument supplied,
 argv[2] is a pointer to the second command line argument supplied, and so on.
Example :
#include <stdio.h> Step-4: Enter the name of the program as the
#include <conio.h> first argument and followed by remaining
void main(int argc, char *argv[]) arguments one by one separated by space.
{ Example:
int i; E:\>program_name hello 100 200
if( argc >= 1 ) Output
{ The arguments supplied are:
printf("The arguments supplied are:\n"); The argument number [1] is program_name
for(i = 0; i < argc; i++) The argument number [2] is hello
{ The argument number [3] is 100
printf("The argument number [%d] is %s\n", The argument number [4] is 200
i+1,argv[i]); } } }
Run this program from command line by
following the bellow steps:
Step-1: compile the program
Step-2: Type cmd in the windows run prompt.
Step-3: Open the directory where the c
program is stored

You might also like