C Slow Learners ImpQues
C Slow Learners ImpQues
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.
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.
3. Definition section
The definition section defines all symbolic constants such using the #define directive.
Example: #define pi 3.14
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. 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
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
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
.
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
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;
};
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()
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));