You are on page 1of 29

WEEK-1

WEEK-2

WEEK 3:

1. Write a C program to implement complex structures for the following operations.


A) Addition of Two complex numbers using structures.
B) Multiplication of Two complex numbers using structures.

A) Addition of Two complex numbers using structures.

PROGRAM

#include <stdio.h>
typedef struct complex
{
float real;
float imag;
} complex;
complex add(complex n1, complex n2);
int main()
{
complex n1, n2, result;
printf("For 1st complex number \n");
printf("Enter the real and imaginary parts: ");
scanf("%f %f", &n1.real, &n1.imag);
printf("\nFor 2nd complex number \n");
printf("Enter the real and imaginary parts: ");
scanf("%f %f", &n2.real, &n2.imag);
result = add(n1, n2);
printf("Sum = %.1f + %.1fi", result.real, result.imag);
return 0;
}
complex add(complex n1, complex n2)
{
complex temp;
temp.real = n1.real + n2.real;
temp.imag = n1.imag + n2.imag;
return (temp);
}
Output
For 1st complex number
Enter the real and imaginary parts: 2.1
-2.3
For 2nd complex number
Enter the real and imaginary parts: 5.6
23.2
Sum = 7.7 + 20.9i
Sample Viva Questions.

1.Write a Structure of a book (Name, author, book no, no of pages and price)?

typedef struct
{
char name[20], author[20];
int bookno,pages;
float price;
}BOOK;

2. What are the different ways a structure variable can be initialized?

Variable structure: struct{int x,y;}s1,s2;


Tagged structure:
struct ex
{
int x,y;
};
struct ex s1,s2;
Typedefined structure:
typedef struct
{
int x,y;
} EX;
EX s1,s2;

B) Multiplication of Two Complex numbers using Structures

PROGRAM

#include <stdio.h>
typedef struct complex
{
float real;
float imag;
} complex;
complex mul(complex n1, complex n2);
int main()
{
complex n1, n2, result;
printf("For 1st complex number \n");
printf("Enter the real and imaginary parts: ");
scanf("%f %f", &n1.real, &n1.imag);
printf("\nFor 2nd complex number \n");
printf("Enter the real and imaginary parts: ");
scanf("%f %f", &n2.real, &n2.imag);
result = mul(n1, n2);
printf("Product = %.1f + %.1fi", result.real, result.imag);
return 0;
}
complex mul(complex n1, complex n2)
{
complex temp;
 temp.real = a.real*b.real - a.img*b.img;
      temp.img = a.img*b.real + a.real*b.img;
return (temp);
}
Output
For 1st complex number
Enter the real and imaginary parts: 2
3
For 2nd complex number
Enter the real and imaginary parts: 4
5
Product = -7 + 22i

Sample Viva Questions.


1. How do you compare two structure variables?
By comparing individual members of the structure.
2. What is the difference between tagged structure and type defined structure?
Tagged structure:
struct ex
{
int x,y;
};
struct ex s1,s2;
Typedefined structure: (Typedef is used to give an alias name for the structure datatype)
typedef struct
{
int x,y;
} EX;
EX s1,s2;
WEEK 4:

1. Write a C program to implement arrays of structures?


PROGRAM

#include<stdio.h>
#include<string.h>
#define MAX 2
struct student
{
    char name[20];
    int roll_no;
    float marks;
};
int main()
{
    struct student arr_student[MAX];
    int i;
    for(i = 0; i < MAX; i++ )
    {
        printf("\nEnter details of student %d\n\n", i+1);
        printf("Enter name: ");
        scanf("%s", arr_student[i].name);
        printf("Enter roll no: ");
        scanf("%d", &arr_student[i].roll_no);
        printf("Enter marks: ");
        scanf("%f", &arr_student[i].marks);
    }
    printf("\n");
    printf("Name\tRoll no\tMarks\n");
    for(i = 0; i < MAX; i++ )
    {
        printf("%s\t%d\t%.2f\n", arr_student[i].name, arr_student[i].roll_no, arr_student[i].marks);
    }
    return 0;
}

Expected Output:
Enter details of student 1 
Enter name: Jim
Enter roll no: 1
Enter marks: 44
Enter details of student 2
Enter name: Tim
Enter roll no: 2
Enter marks: 76
Name Roll no Marks
Jim 1 44.00
Tim 2 76.00
Sample Viva Questions.

1. Give an example of nested structure.

     struct student_college_detail


{
    int college_id;
    char college_name[50];
};
struct student_detail
{
    int id;
    char name[20];
    float percentage;
    struct student_college_detail clg_data; // structure within structure
}stu_data;
 

2. What are the different ways of accessing the structure members using structure variable?

Using structure variable(dot operator) and pointer to structure(indirect selection operator).

2. Write a C program to implement bit fields in C?

PROGRAM

#include<stdio.h>
struct time{
unsigned int hours: 5; // Size restricted to 5 bits
unsigned int minutes:6; // Size restricted to 6 bits
unsigned int seconds:6; // Size restricted to 6 bits
};
int main()
{
struct time t = {11, 30, 10}; // Here t is an object of the structure time
printf("Welcome to Data Structures!\n\n");
printf("The time is %d : %d : %d\n", t.hours, t.minutes, t.seconds);
printf("The size of time is %ld bytes.\n", sizeof(struct time));
return 0;
}
Output:
Welcome to Data Structures!

The time is 02:31:25


The size of time is 4 bytes
Sample Viva Questions.

1. scanf() cannot be used for bit fields. Justify.


Bits cannot have addresses.

2. union add
{
int a:2;
char b:9;
}a1;
main()
{ printf(“%d”, sizeof(a1));
}
What is the output of the above code?

Error. Width of b exceeds its size.

WEEK 5:

1. Write a C Program to store the information (name, roll no, and branch) of a student
using unions.

PROGRAM

#include <stdio.h>
typedef union
{
struct student
{
char name[50];
int roll;
float marks;
} s;
}u;
int main() {
printf("Enter information:\n");
printf("Enter name: ");
scanf("%s",u. s.name);
printf("Enter roll number: ");
scanf("%d", &u.s.roll);
printf("Enter marks: ");
scanf("%f", &u.s.marks);
printf("Displaying Information:\n");
printf("Name: ");
printf("%s",u. s.name);
printf("Roll number: %d\n", u.s.roll);
printf("Marks: %.1f\n",u. s.marks);
return 0;
}
Output
Enter information:
Enter name: XYZ
Enter roll number: 23
Enter marks: 34.5
Displaying Information:
Name: XYZ
Roll number: 23
Marks: 34.5

Sample Viva Questions.

1. How memory allocations in bit fields differ from structures?


Bit fields are used to use memory efficiently when we know that the value of a field or group of
fields will never exceed a limit or is within a small range.

2. What are the disadvantages of unions over structures?


Only the last entered data can be stored in the union. It overwrites the data previously stored in the
union.
2. Write a C program to implement inter function communication by passing
pointers to a structure.

PROGRAM

#include <stdio.h>
typedef struct Complex
{
float real;
float imag;
} complex;
void addNumbers(complex c1, complex c2, complex *result);
int main()
{
complex c1, c2, result;
printf("For first number,\n");
printf("Enter real part: ");
scanf("%f", &c1.real);
printf("Enter imaginary part: ");
scanf("%f", &c1.imag);
printf("For second number, \n");
printf("Enter real part: ");
scanf("%f", &c2.real);
printf("Enter imaginary part: ");
scanf("%f", &c2.imag);
addNumbers(c1, c2, &result);
printf("\nresult.real = %.1f\n", result.real);
printf("result.imag = %.1f", result.imag);
return 0;
}
void addNumbers(complex c1, complex c2, complex *result)
{
result->real = c1.real + c2.real;
result->imag = c1.imag + c2.imag;
}
Output
For first number,
Enter real part: 1.1
Enter imaginary part: -2.4
For second number,
Enter real part: 3.4
Enter imaginary part: -3.2
result.real = 4.5
result.imag = -5.6

Sample Viva Questions.

1. Can a pointer variable be declared as a member of structure if yes? Explain.


Structure may contain the Pointer variable as member. Pointers are used to store the address of
memory location. They can be de-referenced by ‘*’ operator.
Example :
struct Sample
{
int *ptr; //Stores address of integer Variable
char *name; //Stores address of Character String
}s1;

2. What is the purpose of indirect selection operator in C?


To access the member of a structure using a pointer.
WEEK 6:

1. Write a c program to implement singly linked list for the following operations.
a) Insertion b)Deletion c)Search

PROGRAM

#include<stdio.h>
#include<stdlib.h>
struct linked_list
{
int number;
struct linked_list *next;
};
typedef struct linked_list node;
node *head=NULL, *last=NULL;
void create_linked_list();
void print_linked_list();
void insert_at_last(int value);
void insert_at_first(int value);
void insert_after(int key, int value);
void delete_item(int value);
void search_item(int value);
int main()
{
int key, value;
//Create a linked list
printf("Create Linked List\n");
create_linked_list();
print_linked_list();
//Insert value at last position to existing Linked List
printf("\nInsert new item at last\n");
scanf("%d", &value);
insert_at_last(value);
print_linked_list();
//Insert value at first position to existing Linked List
printf("\nInsert new item at first\n");
scanf("%d", &value);
insert_at_first(value);
print_linked_list();
//Insert value after a defined value to existing Linked List
printf("\nEnter a KEY (existing item of List), after that you want to insert a value\n");
scanf("%d", &key);
printf("\nInsert new item after %d KEY\n", key);
scanf("%d", &value);
insert_after(key, value);
print_linked_list();
//Search an item from Linked List
printf("\nEnter an item to search it from List\n");
scanf("%d", &value);
search_item(value);
//Delete value from List
printf("\nEnter a value, which you want to delete from list\n");
scanf("%d", &value);
delete_item(value);
print_linked_list();
return 0;
}

void create_linked_list()
{
int val;
while(1)
{
printf("Input a number. (Enter -1 to exit)\n");
scanf("%d", &val);
if(val==-1)
break;
insert_at_last(val);
}
}
void insert_at_last(int value)
{
node *temp_node;
temp_node = (node *) malloc(sizeof(node));
temp_node->number=value;
temp_node->next=NULL;
//For the 1st element
if(head==NULL)
{
head=temp_node;
last=temp_node;
}
else
{
last->next=temp_node;
last=temp_node;
}
}

void insert_at_first(int value)


{
node *temp_node = (node *) malloc(sizeof(node));
temp_node->number=value;
temp_node->next = head;
head = temp_node;
}
void insert_after(int key, int value)
{
node *myNode = head;
int flag = 0;
while(myNode!=NULL)
{
if(myNode->number==key)
{
node *newNode = (node *) malloc(sizeof(node));
newNode->number = value;
newNode->next = myNode->next;
myNode->next = newNode;
printf("%d is inserted after %d\n", value, key);
flag = 1;
break;
}
else
myNode = myNode->next;
}
if(flag==0)
printf("Key not found!\n");
}
void delete_item(int value)
{
node *myNode = head, *previous=NULL;
int flag = 0;
while(myNode!=NULL)
{
if(myNode->number==value)
{
if(previous==NULL)
head = myNode->next;
else
previous->next = myNode->next;
printf("%d is deleted from list\n", value);
flag = 1;
free(myNode); //need to free up the memory to prevent memory leak
break;
}
previous = myNode;
myNode = myNode->next;
}
if(flag==0)
printf("Key not found!\n");
}
void search_item(int value)
{
node *searchNode = head;
int flag = 0;
while(searchNode!=NULL)
{
if(searchNode->number==value)
{
printf("%d is present in this list. Memory address is %d\n", value, searchNode);
flag = 1;
break;
}
else
searchNode = searchNode->next;
}
if(flag==0)
printf("Item not found\n");
}
void print_linked_list()
{
printf("\nYour full linked list is\n");
node *myList;
myList = head;
while(myList!=NULL)
{
printf("%d ", myList->number);
myList = myList->next;
}

Sample Viva Questions.

1. What is a linear list? How memory is allocated for a node ?


Linear Linked list is the default linked list and a linear data structure in which data is not stored
in contiguous memory locations but each data node is connected to the next data node via a
pointer, hence forming a chain.
NODE * p=(NODE*)malloc(sizeof(NODE));
2. What is NULL Pointer? Explain it with syntax.

A pointer which points to nothing is called a NULL pointer; int *p=NULL;


WEEK 7:
1. Write a c program to sort the elements using selection sort.

PROGRAM

#include <stdio.h>
int main()
{
  int array[100], n, c, d, position, t;
  printf("Enter number of elements\n");
  scanf("%d", &n);
  printf("Enter %d integers\n", n);
  for (c = 0; c < n; c++)
    scanf("%d", &array[c]);
  for (c = 0; c < (n - 1); c++) // finding minimum element (n-1) times
  {
    position = c;
    for (d = c + 1; d < n; d++)
    {
      if (array[position] > array[d])
        position = d;
    }
    if (position != c)
    {
      t = array[c];
      array[c] = array[position];
      array[position] = t;
    }
  }
  printf("Sorted list in ascending order:\n");
  for (c = 0; c < n; c++)
    printf("%d\n", array[c]);
  return 0;
}
Output:
Enter number of elements
5
Enter 5integers
46381
Sorted list in ascending order:
13468
Sample Viva Questions.

1. What are the asymptotic notations?


Asymptotic Notations are languages that allow us to analyze an algorithm's running time by
identifying its behavior as the input size for the algorithm increases.

2. An array contains the following elements 65, 25 ,12 ,22, 11. What is the output at 3rd pass
using selection sort.

11,12,22,25,65
2. Write a C program to sort the elements using Quick sort.
PROGRAM
#include<stdio.h>
void quicksort(int [10],int,int);

int main(){
int x[20],size,i;
printf("\nEnter size of the array: ");
scanf("%d",&size);
printf("\nEnter %d elements: ",size);
for(i=0;i<size;i++)
scanf("%d",&x[i]);
quicksort(x,0,size-1);
printf("\nSorted elements: ");
for(i=0;i<size;i++)
printf(" %d",x[i]);
getch();
return 0;
}
void quicksort(int x[10],int first,int last){
int pivot,j,temp,i;
if(first<last){
pivot=first; i=first; j=last;
while(i<j){
while(x[i]<=x[pivot]&&i<last)
i++;
while(x[j]>x[pivot])
j--;
if(i<j){
temp=x[i]; x[i]=x[j]; x[j]=temp;
}
}
temp=x[pivot];
x[pivot]=x[j];
x[j]=temp;
quicksort(x,first,j-1);
quicksort(x,j+1,last);
}
}

Output:
Enter number of elements
5
Enter the integers
46381
Te sorted array is
13468

Sample Viva Questions.

1. What is the difference between selection and bubble sorting techniques?


Selection sort selects the smallest element and swaps it with the first element of the
unsorted list.
Bubble sort compares adjacent elements and swaps if previous element is bigger than the
next element.

2. No of passes required for sorting the following elements using bubble sort. 5, 1, 4 ,28, 9, 76

5
WEEK 8:

1. Write a c program to sort the elements using Insertion sort.


PROGRAM

#include<stdio.h>
void main( )
{
int
a[10],i,j,k,n;
printf("How many elements you want to sort?\n");
scanf("%d",&n);
printf("\nEnter the Elements into an array:\n");
for (i=0;i<n;i++)
scanf("%d",&a[i]);
for(i=1;i<n;i++)
{
k=a[i];
for(j= i-1; j>=0 && k<a[j]; j--)
a[j+1]=a[j];
a[j+1]=k;
}
printf("\n\n Elements after sorting: \n");
for(i=0;i<n;i++)

printf("%d\n", a[i]);

OUTPUT:
How many elements you want to sort ? :
6

Enter elements for an array : 78 23 45 8 32 36


After Sorting the elements are : 8 23 32 36 45 78

A list of sorted elements now : 8 23 32 36 45 78

Sample Viva Questions

1. What is the time complexity of Insertion Sort for an unsorted list?


O(n2)

2. If the list is already sorted, what is the time complexity of insertion sort?
O(n)

16
2. Write a C program to search an element in a list of elements using linear search. If the element
found display the position, otherwise print “element not present”

PROGRAM

#include<stdio.h>
int linear(int [ ],int,int);
void main( )
{
int a[20], pos = -1, n, k, i;
printf("\nEnter the n value:");
scanf("%d",&n);
printf("\nEnter elements for an array:");
for(i=0; i<n ;i++)
scanf("%d",&a[i]);
printf("\nEnter the element to be searched:");
scanf("%d",&k);
pos=linear(a,n,k);
if(pos != -1)
printf("\n Search successful element found at position %d",pos);
Else
printf("\n Search unsuccessful, element not found");
getchar( );
}
int linear(int a[ ],int n,int k)
{
int i;
for(i=0;i<n;i++)
{

f(a[i]==k)
return(i);
}
return -1;
}
Output:-
Enter the n value : 5
Enter elements for an array : 11 2 23 14 55
Enter the element to be searched : 14
Search successful element found at position : 3

17
Sample Viva Questions.

1. What is the best and worst case time complexity of Linear Search Algorithm?
O(1) and O(n)

2. When can a linear search be used?

When the elements are unsorted.

WEEK 9:
1. Write a C program to search an element in a list of elements using Binary search. If
the element found display the position, otherwise print “element not present”.

PROGRAM

#include<stdio.h>
int bsearch(int [ ],int,int);
void main( )
{
int a[20],pos,n,k,i;
printf("\nEnter the n value:");
scanf("%d",&n);
printf("\nEnter elements for an array:");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("\nEnter the key value:");
scanf("%d",&k);
pos=bsearch(a,n,k);
if(pos!= -1)
printf("Search successful, element found at position %d",pos);
else
printf("Search unsuccessful, element not found");
}
int bsearch(int a[ ],int n, int k)
{
int lb=0,ub,mid;
ub=n-1;
while(ub>=l)
{
mid=(lb+ub)/2;
i(k<a[mid])
ub=mid-1;

18
else if(k>a[mid])
lb=mid+1;
else if(k==a[mid])
return(mid);
}
return -1;
}

OUTPUT

Enter ‗n‘ value : 67

Enter elements for an array : 35 10 32 25 84 55 78


Enter the element to be
searched : 25
Search successful, Element found at
Position : 3

Sample Viva Questions.

1. What is the time complexity of binary search algorithm?


O(log n)

2. State the differences between Linear search and binary search


A linear search scans one item at a time, without jumping to any item. In contrast, binary
search cuts down your search to half as soon as you find the middle of a sorted list.
In linear search, the worst case complexity is O(n), where binary search making O(log n)
comparisons.
Time taken to search elements keep increasing as the number of elements is increased when
searching through linear process. But binary search compresses the searching period by dividing
the whole array into two half.

19
WEEK 10:

1. Write a C program convert infix to postfix notation and postfix evaluation using stack

PROGRAM

#include<stdio.h>
char stack[20];
int top = -1;
void push(char x)
{
    stack[++top] = x;
}
 char pop()
{
    if(top == -1)
        return -1;
    else
        return stack[top--];
}
 int priority(char x)
{
    if(x == '(')
        return 0;
    if(x == '+' || x == '-')
        return 1;
    if(x == '*' || x == '/')
        return 2;
}
 main()
{
    char exp[20];
    char *e, x;
    printf("Enter the expression :: ");
    scanf("%s",exp);
    e = exp;
    while(*e != '\0')
    {
        if(isalnum(*e))
            printf("%c",*e);
        else if(*e == '(')
            push(*e);
        else if(*e == ')')
        {
            while((x = pop()) != '(')
                printf("%c", x);
        }

20
        else
        {
            while(priority(stack[top]) >= priority(*e))
                printf("%c",pop());
            push(*e);
        }
        e++;
    }
    while(top != -1)
    {
        printf("%c",pop());
    }
}
 
OUTPUT:
Enter the expression :: a+b*c
abc*+

Enter the expression :: (a+b)*c+(d-a)


ab+c*da-+

Sample Viva Questions.

1. Convert the expression a+b-c*d/e into post fix notation


ab+cd*e/-

2. What are the stack applications?

Recursive functions, infix to postfix conversion, postfix evaluation

21
WEEK 11:

1. Write a C program implement Queue using arrays for the following operations.
i) Enqueue ii) Dequeue iii) Peek iv) Display
PROGRAM

#include<stdio.h>
#include<conio.h>
#define n 5
void main()
{
    int queue[n],ch=1,front=0,rear=0,i,j=1,x=n;
    //clrscr();
    printf("Queue using Array");
    printf("\n1.Insertion \n2.Deletion \n3.Display \n4.Exit");
    while(ch)
    {
        printf("\nEnter the Choice:");
        scanf("%d",&ch);
        switch(ch)
        {
        case 1:
            if(rear==x)
                printf("\n Queue is Full");
            else
            {
                printf("\n Enter no %d:",j++);
                scanf("%d",&queue[rear++]);
            }
            break;
        case 2:
            if(front==rear)
            {
                printf("\n Queue is empty");
            }
            else
            {
                printf("\n Deleted Element is %d",queue[front++]);
                x++;
            }
            break;
        case 3:
            printf("\n Queue Elements are:\n ");
            if(front==rear)
                printf("\n Queue is Empty");
            else
            {
                for(i=front; i<rear; i++)
                {
22
                    printf("%d",queue[i]);
                    printf("\n");
                }
                break;
            case 4:
                exit(0);
            default:
                printf("Wrong Choice: please see the options");
            }
        }
    }
    getch();
}
 OUTPUT:
Queue using Array
1.Insertion
2.Deletion
3.Display
4.Exit
Enter the Choice:1
Enter no 1:10
Enter the Choice:1
Enter no 2:54
Enter the Choice:1
Enter no 3:98
Enter the Choice:1
Enter no 4:234
Enter the Choice:3
Queue Elements are:
10
54
98
234

Enter the Choice:2


Deleted Element is 10
Enter the Choice:3
Queue Elements are:
54
98
234

Enter the Choice:4

23
Sample Viva Questions.

1. What is the difference between Stack and Queue?

Stack follows the principle of LIFO( last in first out) and queue follows the principle of FIFO
(first in first out).

2. What is the initial values of Front and Rear elements of a Queue?

Front=0, rear=n-1

WEEK 12:

1. Write a C program open a new file and implement the following I/O functions
a. fprintf(), fscanf()
b. getw(), putw()
c. getc(), putc()

A. fprintf(), fscanf()

PROGRAM

#include <stdio.h>
int main()
{ int i, sum2=0;
FILE *f2;
f2 = fopen("data3.txt","w");
for(i=1;i<5;i++) /* write integers to files in binary and text format*/
fprintf(f2,"%d\n",i);
fclose(f2);
f2 = fopen("data3.txt","r");
while(fscanf(f2,"%d",&i)!=EOF)
{
sum2+=i;
printf("text file: i=%d\n",i);
}
fprintf(stdout,"text sum=%d\n",sum2);
fclose(f2);
}

Output:
Text file: i=1
Text file: i=2
Text file: i=3
Text file: i=4
Text sum=10

24
Sample Viva Questions.

1. Write the syntax for printf() and fprintf() functions.

int printf(const char *format , list of arguments);


int fprintf(FILE * stream, const char *format , list of arguments);

2. What are the application areas of fprintf() function?


fprintf is used to print content in file instead of stdout console.

B. getw() and putw()

Objective:
Student will be able to understand the concept of Files
Outcome:
Student gains the ability to learn how to manipulate data in a file using file I/O as per
the requirements.
PROGRAM

#include <stdio.h>
main()
{
int i,sum1=0;
FILE *f1;
f1 = fopen("data1.txt","w");
for(i=10;i<5;i++)
{
putw(i,f1);
}
fclose(f1);
f1 = fopen("data1.txt","r");
while((i=getw(f1))!=EOF)
{
sum1+=i;
printf("binary file: i=%d\n",i);
}
printf("binary sum=%d",sum1);
fclose(f1);
}

Output:
Binary file: i=1
Binary file: i=2
Binary file: i=3
Binary file: i=4
Binary sum=10

25
Sample Viva Questions.

1. What is the difference between scanf( ) and getw( ) functions and why are they used?
scanf is used to read any type of input from the keyboard whereas getw reads only
integers.

2. What is the difference between printf( ) and putw( ) functions and why are they used?
printf is used to print any type of data to the monitor whereas putw displays only
integers.

C. getc( ) and putc( )

PROGRAM

#include <stdio.h>
int main()
{
   char ch;
   FILE *fp;
   if (fp = fopen("test.c", "r"))
   {
     ch = getc(fp);
     while (ch != EOF)
     {
        putc(ch, stdout);
        ch = getc(fp);
     }
     fclose(fp);
     return 0;
}}

Sample Viva Questions.

1. What is the difference between getchar( ) and getc( ) functions in C?


The key difference between getc and getchar is that the getc is used to read a character
from an input stream such as a file or standard input while getchar is to read a character
from standard input.
2. What is the difference between putchar( ) and putc( ) functions in C?
The key difference between putc and putchar is that the putc is used to display a
character to an output stream such as a file or standard output while putchar is to display
a character to standard output.
WEEK 13:

1. Write a C program to copy data from one file to another.

PROGRAM
26
#include<stdio.h>
int main()
{
char ch;
FILE *fp,*fp1;
fp1=fopen("data.txt","w");
if(fp=fopen("file1.c","r"))
{
ch = getc(fp);
while(ch != EOF)
{
putc(ch,fp1);
ch = getc(fp);
}
fclose(fp);
fclose(fp1);
printf("Data copied successfully \n");
return 0;
}
}
Output: Data copied successfully

Sample Viva Questions.


1. What is the difference between “r+” and “r” modes with respect to files?
When a file is opened in r+ mode , it can be read from and also written into using
file positioning functions.
When a file is opened in r mode,it can only be read from.

2. What are the differences between text and binary files?


A text file contains textual information in the form of alphabets, digits and special
characters or symbols. A binary file contains bytes or a compiled version of a text
file.

2. Write a C program to merge two files, using command line arguments

PROGRAM

#include<stdio.h>
int main(int argc,char *argv[])
{
char ch;
FILE *fp,*fp1;
fp1=fopen(argv[1],"a");
if(fp=fopen(argv[2],"r"))
{
ch = getc(fp);
while(ch != EOF)
{
putc(ch,fp1);
27
ch = getc(fp);
}
fclose(fp);
printf(“Files merged\n”):
return 0;
}
}

Output: Files merged


Sample Viva Questions.

1. What are the arguments passed to the main function in C?


Argument count , argument vector and environment variable.

2. Why should argc be of type int and argv of type char? Explain.

argc contains the number of arguments passed and argv stores the arguments passed
to the main function.

WEEK 14:

Write a C program to implement multi file programming for basic arithmetic


operations

PROGRAM

vi mainprg.c
#include<stdio.h>
#include"arith.h"
int main()
{
int a,b,c;
printf("Enter the values of a and b\n");
scanf("%d%d",&a,&b);
c=add(a,b);
printf("The sum of %d + %d = %d\n",a,b,c);
c=sub(a,b);
printf("The difference of %d - %d = %d\n",a,b,c);
c=mul(a,b);
printf("The product of %d * %d = %d\n",a,b,c);
c=div(a,b);
printf("The quotient of %d / %d = %d\n",a,b,c);
printf("END OF MULTIFILE PROGRAMMING\n");
return 0;
}
vi add.c
#include"arith.h"

28
int add(int x,int y)
{
return x+y;
}
vi sub.c
#include"arith.h"
int sub(int x,int y)
{
return x-y;
}
vi mul.c
#include"arith.h"
int mul(int x,int y)
{
return x*y;
}
vi div.c
#include"arith.h"
int div(int x,int y)
{
return x/y;
}
Create object file
[faculty@localhost ~]$ cc -c add.c
[faculty@localhost ~]$ cc -c sub.c
[faculty@localhost ~$ cc -c mul.c
[faculty@localhost ~]$ cc -c div.c
Compiling and linking all files
[faculty@localhost ~]$ cc mainprg.c add.o sub.o mul.o div.o
[faculty@localhost ~]$./a.out

Sample Viva Questions.

1. How can a global variable be used in multi file programming?


Using the keyword extern.

2. What are the advantages of multi file programming in C?


If we write code for a module in a separate document, we can use that function in
multiple programs. It increases reusability of the code. If we want to change
anything in a class, we will only have to change it in that particularly document and
the change will be automatically reflected in all the documents referring to this
document.

29

You might also like