MC0061 Q & Ans

35
Master of Computer Application (MCA) – Semester 1 MC0061 – Computer Programming “C Language” – 4 Credits (Book ID: B0678 & B0679) Assignment Set – 1 _________________________________________________________________ ____ Q. 1. Describe the features of a C program along with its block structure. Answer: Features of C Programming Language : 1 . Low Level Features : It is Closely Related to Lower level Language such as "Assembly Language" It is easy to write assembly codes in C 2 . Portability: C Programs are portable i.e they can be run on any Compiler with Little or no Modification Compiler and Preprocessor make it Possible for C Program to run it on Different PC 3 . Powerful Provides Wide verity of 'Data Types' Provides Wide verity of 'Functions' Provides useful Control & Loop Control Statements 4 . Bit Manipulation C Programs can be manipulated using bits It provides wide verity of bit manipulation Operators 5 . High Level Features : It is more User friendly as compare to Previous languages 6 . Modular Programming Modular programming is a software design technique that increases the extent to which software is composed of separate parts, called modules

Transcript of MC0061 Q & Ans

Page 1: MC0061 Q & Ans

Master of Computer Application (MCA) – Semester 1

MC0061 – Computer Programming “C Language” – 4 Credits

(Book ID: B0678 & B0679)

Assignment Set – 1

_____________________________________________________________________

Q. 1. Describe the features of a C program along with its block structure.

Answer:

Features of C Programming Language : 1 . Low Level Features :

It is Closely Related to Lower level Language such as "Assembly Language" It is easy to write assembly codes in C

2 . Portability: C Programs are portable i.e they can be run on any Compiler with Little or no

Modification Compiler and Preprocessor make it Possible for C Program to run it on Different PC

3 . Powerful Provides Wide verity of 'Data Types' Provides Wide verity of 'Functions' Provides useful Control & Loop Control Statements

4 . Bit Manipulation C Programs can be manipulated using bits It provides wide verity of bit manipulation Operators

5 . High Level Features : It is more User friendly as compare to Previous languages

6 . Modular Programming Modular programming is a software design technique that increases the extent to which

software is composed of separate parts, called modules C Program Consist of Different Modules that are integrated together to form complete

program7 . Efficient Use of Pointers

Pointers has direct access to memory. C Supports efficient use of pointer .

8 . More Efficient

Basic Structure of C Program

1. Documentation Section : It is set of Comment Lines It includes Title Of Program , Author Name Data Used Or Summary Information

2. Link Section :

Page 2: MC0061 Q & Ans

It is also called Header File Declaration Section It Links Compiler to Link Functions From System Library

3. Definition Section : Defines Symbolic Constants Eg. #define Count 10

4. Global Declaration Section : Variables that are accessed by one or more functions are called Global Variable Global Variables are declared in this Section. Global Variables are Always Declared outside of all Functions Has Prototype Declaration Of C Functions May Contain Function Definition

Page 3: MC0061 Q & Ans

5. Main Function Section : Declares all Variable variables used in Executable Section >Active Part of Program

Note : Program Execution begins at Opening Brase Program Execution ends at Closing Brase All Statements in C must ends with Semicolon

6. Subprogram Section : It has all User-defined Functions that are called in main User Defined Functions are generally placed immediately after main

Q. 2. Write a program in C to add first 10 odd numbers starting from 1.

Answer :

#include<stdio.h>#include<conio.h>

void main (){

int i,sum=0,count=0;for(i=1;count<=10;i=i+2,count++){

sum=sum+i;}printf(“Sum of First 10 odd numbers is %d”,sum);getch();

}

3. Explain the importance of operator precedence with a programming example.

Answer:

Operator precedence describes the order in which C reads expressions. For example, the expression a=4+b*2 contains two operations, an addition and a multiplication. Does the C compiler evaluate 4+b first, then multiply the result by 2, or does it evaluate b*2 first, then add 4 to the result? The operator precedence chart contains the answers. Operators higher in the chart have a higher precedence, meaning that the C compiler evaluates them first. Operators on the same line in the chart have the same precedence, and the "Associativity" column on the right gives their evaluation order.

Operator Precedence Chart

Page 4: MC0061 Q & Ans

Operator Type Operator AssociativityPrimary Expression Operators () [] . -> expr++ expr-- left-to-rightUnary Operators * & + - ! ~ ++expr --expr (typecast) sizeof right-to-left

Binary Operators

* / %

left-to-right

+ ->> <<< > <= >=== !=&^|&&||

Ternary Operator ?: right-to-leftAssignment Operators = += -= *= /= %= >>= <<= &= ^= |= right-to-leftComma , left-to-right

The following program illustrates the effect of presence of parenthesis in expressions.

.main () { float a, b, c x, y, z; a = 9; b = 12; c = 3; x = a – b / 3 + c * 2 – 1; y = a – b / (3 + c) * (2 – 1); z = a – ( b / (3 + c) * 2) – 1; printf (“x = %fn”,x); printf (“y = %fn”,y); printf (“z = %fn”,z); }

output

x = 10.00 y = 7.00 z = 4.00

Q. 4. Using input and output functions in C, write a program to accept a string of

characters

Page 5: MC0061 Q & Ans

Answer :

/*String.c string variable*/ #include < stdio.h > main() { char month[15]; printf (“Enter the string”); gets (month); printf (“The string entered is %s”, month); }

5. Write a C program to demonstrate the usage of gets() and puts() function.

Answer:

gets reads a complete line of text into a string until a end-of-file (EOF) is encountered. It is the responsibility of the programmer to ensure that the string which receives the input text read by gets is large enough.

puts displays a string onto the standard output or terminal and follows it with a newline character.

#include <stdio.h>

main (){char answer[256];puts("Enter your name");while((gets(answer))!= NULL)printf("Hello " %s, answer);}

Q. 6. Write a program in C to demonstrate the concept of using pointers on two – dimensional arrays.Answer :An array is actually very much like pointer. We can declare the arrays first element as a[0] or as

int *a because a[0] is an address and *a is also an address the form of declaration is equivalent.

The difference is pointer is a variable and can appear on the left of the assignment operator that

is lvalue. The array name is constant and cannot appear as the left side of assignment operator.

An example program:

Page 6: MC0061 Q & Ans

#include <stdio.h>#include <stdlib.h>

main(){long mat[5][5], **ptr;

mat[0][0] = 3;ptr = (long **)mat;

printf(" mat %p \n", mat);printf(" ptr %p \n", ptr);printf(" mat[0][0] %d \n", mat[0][0]);printf(" &mat[0][0] %p \n", &mat[0][0]);printf(" &ptr[0][0] %p \n", &ptr[0][0]);

return;}

The output is: mat 7FDF6310 ptr 7FDF6310 mat[0][0] 3 &mat[0][0] 7FDF6310 &ptr[0][0] 3

7. Write a program to demonstrate the concept of arrays of structures.Answer:

It is possible to define a array of structures for example if we are maintaining information of all the students in the college and if 100 students are studying in the college. We need to use an array than single variables. We can define an array of structures as shown in the following example:

structure information { int id_no; char name[20]; char address[20]; char combination[3]; int age; } student[100];

An array of structures can be assigned initial values just as any other array can. Remember that

Page 7: MC0061 Q & Ans

each element is a structure that must be assigned corresponding initial values as illustrated below.

#include <stdio.h> { struct info { int id_no; char name[20]; char address[20]; char combination[3]; int age; } struct info std[100]; int I,n; printf(“Enter the number of students”); scanf(“%d”,&n); printf(“ Enter Id_no,name address combination agem”); for(I=0;I < n;I++) scanf(%d%s%s%s%d”,&std[I].id_no,std[I].name,std[I].address,std[I].combination,&std[I].age); printf(“n Student information”); for (I=0;I< n;I++) printf(“%d%s%s%s%dn”, ”,std[I].id_no,std[I].name,std[I].address,std[I].combination,std[I].age);

}

8. Write a program to accept 10 integers and print it in reverse order using linked lists.Answer :

#include<stdio.h>

#include<stdlib.h>

struct list

{

    int num;

    struct list *next;

};

typedef struct list node;

void init(node* record)

{

    record->next=NULL;

Page 8: MC0061 Q & Ans

}

void addnode(node* record,int d)

{

    node* fresh;

    fresh=(node *)malloc(sizeof(node));

    fresh->num=d;

    fresh->next=record->next;

    record->next=fresh;

}

void print(node *record)

{

    node* temp;

    temp=(node *)malloc(sizeof(node));

    for(temp=record->next;temp;temp=temp->next)

        printf(" %d",temp->num);

}

void reverse(node* record)

{

    node* temp;node* temp1;node* temp2;

    temp=(node *)malloc(sizeof(node));

    temp1=(node *)malloc(sizeof(node));

    temp2=(node *)malloc(sizeof(node));

    temp=record;temp1=temp->next;temp2=temp1->next;

    temp->next->next=NULL;

    while(temp2!=NULL)

    {

        temp=temp1;

        temp1=temp2;

        temp2=temp1->next;

        temp1->next=temp;

    }

Page 9: MC0061 Q & Ans

    record->next=temp1;

}

int main(void)

{

    node* start;

    node* start1;

    start=(node *) malloc(sizeof(node));

    init(start);

    int i=0;

    for(i=10;i>=0;i--)

        addnode(start,i);

    print(start);

    reverse(start);

    printf("n");

    print(start);

    return 0;

}

Page 10: MC0061 Q & Ans

Master of Computer Application (MCA) – Semester 1

MC0061 – Computer Programming “C Language”

(Book ID: B0678 & B0679)

Assignment Set – 2

_____________________________________________________________________

Q.1. Explain the following by writing example programs demonstrating their usage:

goto statement

if…else statement

Answer:1. goto Statement

goto statement is a jump statements and is perhaps the most controversial feature in C. Goto in unstructured language such as basic was indispensable and the soul of the programming language but in a structured language they are criticized beyond limit. The critics say that due to other jump statements in c goto is not all required and more over it destroys the structure of your program and make it unreadable. But on other hand goto statement of C provides some very powerfull programming options in very complicated situation. This tutorial will take an neutral stand in such an argument and neither recommend nor discourage use of goto.

Goto is used for jumping from one point to another point in your function. You can not jump from one function to another. Jump points or way points for goto are marked by label statements. Label statement can be anywhere in the function above or below the goto statement. Special situation in which goto find use is deeply nested loops or if - else ladders.

General form of goto statement is -..goto label1;..label1 :.label2 :..goto label2; #include <stdio.h>int main (void)// Print value 0 to 9{a = 1; loop:; // label stamentprintf ("\n%d",a);

Page 11: MC0061 Q & Ans

a++;if (a < 10) goto loop ; // jump statement retrun 0;}

2. if - else Statement

if - else statement is a selection statement. It selects one piece of code for execution among two on basis of a outcome of a conditonal logic. The piece of code being refer here can be a s tament, a block statement or even a empty statement depending upon the logic of your program.

General form of if - else statement is : if (condition) statement;else statement;else block here is optional.

Conditon here evaluates to true or false ie. zero or non-zero in c respectively.It can be any valid data type which can be interpreted by C compiler as 1 or 0. If the code evaluates to be true the one assosiated with if is executed otherwise one associated with else is executed. Hence the if - else statment helps the programmer in controlling the flow of statements in his program. The important thing to note is code of if and else block are inversely related in logic ie. either code of if block or code of else block will be executed never both.

Also in a professionally written code if the variable alone is able to control the condtion using a comparison is considered a bad style. For example say i an integer variable can attain any value then this value can be directly interpreted as zero or non-zero and is sufficient to control the loop. In this case conditons like (i == 0) or (i != 0) are considered bad programming style and should be avoided.

Here is a code showing the if - else statement in action –// Code showing if - else statement in action.#include <stdio.h>#include <string.h>void onlyif (char value[]);{ if ( !strcmp (value,"Password")// Strcmp functions return zero if string passed are same. { printf ("\nRight"); }}void ifandelse (char value []);{ if ( !strcmp (value,"Password") { printf ("\nRight"); } else

Page 12: MC0061 Q & Ans

{ printf ("\nWrong"); }}int main (){ char value [1000]; printf ("Enter Password : "); scanf ("%s", value); return 0;}

One property of if -else statement is that they can be nested. This means that if statement can be target of another if statement.

General representation of nested if in C can be -

if (condition1) statement1; if (condition2) statement2; if (condition 3) statement3; ............. n levels; else statement n+1 else statement n+2else statement n+3

Another popular variant of if-else statement is if-else ladder in this we create a series of generally one level deep. It has a special property that when any one of the condition statement is found to be true only statement associate with the if having that condition true is executed and all other statements in the ladder are by-passed. If none of the conditions evaluate to be true then the final statement associated with else is executed if present. Also it is recommended to use standard indentation pattern.General representation of nested if in C can be -

if (condition1) statement1elseif (condition2) statement2else..... n heightif (condition n+1) statement n+1else if (condition n+2) statement n+2elsestatement n+3 // Final Statement

Page 13: MC0061 Q & Ans

Q. 2. Write a program to print a set of 9 integers in a matrix format using nested for loops.Answer: #include<stdio.h>#include<conio.h>#define MAX 3void main(){

int i,k, a1[MAX][MAX],j;printf("Enter element for a");for(i=0;i<MAX;i++){

for(j=0;j<MAX;j++){

scanf("%d",&a1[i][j]);}

}

printf("Array in matrix form");for(i=0;i<MAX;i++){

for(j=0;j<MAX;j++){

printf("%d\t",a3[i][j]);}printf("\n");

}

getch();}

Q. 3. A 5-digit positive integer is entered through the keyboard, write a function to calculate sum of digits of the 5-digit number: (a) Without using recursion

(b) Using recursion

Answer:(a). Without recursion

#include<stdio.h>#include<conio.h>

int add(int num){

int sum=0,rem,i,j,n;for(i=num;i!=0;i=i/10)

Page 14: MC0061 Q & Ans

{rem =i%10;sum=sum+rem;

}return sum;

}

void main(){

int num,sum;printf(“enter five digit number”);scanf(“%d”,&num);sum=add(num);printf(“Sum of Digit is %d”,sum);getch();

}

(b) With recursion

#include<stdio.h>#include<conio.h>

int add(int num){

if(num==0)return num;

else{

rem=num%10;return rem+add(n/10);

}}

void main(){

int num,sum;printf(“enter five digit number”);scanf(“%d”,&num);sum=add(num);printf(“Sum of Digit is %d”,sum);getch();

}

Page 15: MC0061 Q & Ans

Q. 4. Write a program in C to perform matrix multiplications on integers.

Answer:

#include<stdio.h>#include<conio.h>#define MAX 3void main(){

int i,k,a3[MAX][MAX],a1[MAX][MAX],j,a2[MAX][MAX];printf("Enter element for a1");for(i=0;i<MAX;i++)

for(j=0;j<MAX;j++)scanf("%d",&a1[i][j]);

printf("Enter element for a2");for(i=0;i<MAX;i++)

for(j=0;j<MAX;j++)scanf("%d",&a2[i][j]);

for(i=0;i<MAX;i++){

for(j=0;j<MAX;j++){

a3[i][j]=0;for(k=0;k<MAX;k++){

a3[i][j] +=a1[i][k]*a2[k][j];}

}}printf("Array MAX");for(i=0;i<MAX;i++){

for(j=0;j<MAX;j++){

printf("%d\t",a3[i][j]);}printf("\n");

} getch();}

Q. 5. Describe the following concepts with the help of suitable code snippets:a. Global Variables

b. Static Variables

c. External Variables

Page 16: MC0061 Q & Ans

Answer :

Static Variables: static is the default storage class for global variables. The two variables below (count and

road) both have a static storage class.

static int Count; int Road;

{ printf("%d\n", Road); }

static variables can be 'seen' within all functions in this source file. At link time, the static variables defined here will not be seen by the object modules that are brought in.

static can also be defined within a function. If this is done the variable is initalised at run time but is not reinitalized when the function is called. This inside a function static variable retains its value during vairous calls.

void func(void); static count=10; /* Global variable - static is the default */ main() { while (count--) { func(); } } void func( void ) { static i = 5; i++; printf("i is %d and count is %d\n", i, count); } This will produce following result i is 6 and count is 9 i is 7 and count is 8 i is 8 and count is 7 i is 9 and count is 6 i is 10 and count is 5 i is 11 and count is 4 i is 12 and count is 3 i is 13 and count is 2 i is 14 and count is 1 i is 15 and count is 0

Page 17: MC0061 Q & Ans

(B) External Variable

Extern is used to give a reference of a global variable that is visible to ALL the program files. When you use 'extern' the variable cannot be initalized as all it does is point the variable name at a storage location that has been previously defined.

When you have multiple files and you define a global variable or function which will be used in other files also, then extern will be used in another file to give reference of defined variable or function. Just for understanding extern is used to decalre a global variable or function in another files.

File 1: main.c

int count=5;

main() { write_extern(); }

File 2: write.c

void write_extern(void);

extern int count;

void write_extern(void) { printf("count is %i\n", count); }

Q. 6. Explain with suitable code examples, various possible file operations in C language.

Answer:

C supports a number of functions that have the ability to perform basic file operations, which include: 1. Naming a file 2. Opening a file 3. Reading from a file 4. Writing data into a file 5. Closing a file

Real life situations involve large volume of data and in such cases, the console oriented I/O operations pose two major problems

It becomes cumbersome and time consuming to handle large volumes of data through terminals.

Page 18: MC0061 Q & Ans

The entire data is lost when either the program is terminated or computer is turned off therefore it is necessary to have more flexible approach where data can be stored on the disks and read whenever necessary, without destroying the data. This method employs the concept of files to store data.

File operation functions in C:

Function Name

Operation

fopen() Creates a new file for use Opens a new existing file for use

fclose Closes a file which has been opened for usegetc() Reads a character from a fileputc() Writes a character to a filefprintf() Writes a set of data values to a filefscanf() Reads a set of data values from a filegetw() Reads a integer from a fileputw() Writes an integer to the filefseek() Sets the position to a desired point in the fileftell() Gives the current position in the filerewind() Sets the position to the begining of the file

Defining and opening a file:

If we want to store data in a file into the secondary memory, we must specify certain things about the file to the operating system. They include the fielname, data structure, purpose. The general format of the function used for opening a file is FILE *fp; fp=fopen(“filename”,”mode”);

The first statement declares the variable fp as a pointer to the data type FILE. As stated earlier, File is a structure that is defined in the I/O Library. The second statement opens the file named filename and assigns an identifier to the FILE type pointer fp.R open the file for read only. W open the file for writing only. A open the file for appending data to it.

Closing a file: The input output library supports the function to close a file; it is in the following format. fclose(file_pointer);

A file must be closed as soon as all operations on it have been completed. This would close the file associated with the file pointer. Observe the following program.

FILE *p1 *p2; p1=fopen (“Input”,”w”);

Page 19: MC0061 Q & Ans

p2=fopen (“Output”,”r”); …. … fclose(p1); fclose(p2) The above program opens two files and closes them after all operations on them are completed, once a file is closed its file pointer can be reversed on other file.

The getc and putc functions are analogous to getchar and putchar functions and handle one character at a time. The putc function writes the character contained in character variable c to the file associated with the pointer fp1. ex putc(c,fp1); similarly getc function is used to read a character from a file that has been open in read mode. c=getc(fp2).

The program shown below displays use of a file operations. The data enter through the keyboard and the program writes it. Character by character, to the file input. The end of the data is indicated by entering an EOF character, which is control-z. the file input is closed at this signal.

#include< stdio.h > main() { file *f1; printf(“Data input output”); f1=fopen(“Input”,”w”); /*Open the file Input*/ while((c=getchar())!=EOF) /*get a character from key board*/ putc(c,f1); /*write a character to input*/ fclose(f1); /*close the file input*/ printf(“nData outputn”); f1=fopen(“INPUT”,”r”); /*Reopen the file input*/ while((c=getc(f1))!=EOF) printf(“%c”,c); fclose(f1); }

The getw and putw functions:

These are integer-oriented functions. They are similar to get c and putc functions and are used to read and write integer values. These functions would be usefull when we deal with only integer data. The general forms of getw and putw are:

putw(integer,fp); getw(fp);

The fprintf & fscanf functions:

The fprintf and fscanf functions are identical to printf and scanf functions except that they work on files. The first argument of theses functions is a file pointer which specifies the file to be used. The general form of fprintf is

Page 20: MC0061 Q & Ans

fprintf(fp,”control string”, list);

Where fp id a file pointer associated with a file that has been opened for writing. The control string is file output specifications list may include variable, constant and string.

fprintf(f1,%s%d%f”,name,age,7.5);

Here name is an array variable of type char and age is an int variable The general format of fscanf is

fscanf(fp,”controlstring”,list);

This statement would cause the reading of items in the control string.

Example:

fscanf(f2,”5s%d”,item,&quantity”);

Like scanf, fscanf also returns the number of items that are successfully read.

/*Program to handle mixed data types*/ #include< stdio.h > main() { FILE *fp; int num,qty,I; float price,value; char item[10],filename[10]; printf(“Input filename”); scanf(“%s”,filename); fp=fopen(filename,”w”); printf(“Input inventory datann”0; printf(“Item namem number price quantityn”); for I=1;I< =3;I++) { fscanf(stdin,”%s%d%f%d”,item,&number,&price,&quality); fprintf(fp,”%s%d%f%d”,itemnumber,price,quality); } fclose (fp); fprintf(stdout,”nn”); fp=fopen(filename,”r”); printf(“Item name number price quantity value”); for(I=1;I< =3;I++) { fscanf(fp,”%s%d%f%d”,item,&number,&prince,&quality); value=price*quantity”);

Page 21: MC0061 Q & Ans

fprintf(“stdout,”%s%d%f%d%dn”,item,number,price,quantity,value); } fclose(fp); }

Random access to files:

Sometimes it is required to access only a particular part of the and not the complete file. This can be accomplished by using the following function:

1 > fseek

fseek function:

The general format of fseek function is a s follows:

fseek(file pointer,offset, position);

Q. 7. Describe the following:

Self Referential structures

Unions

Answer:

(a) Union

Unions like structure contain members whose individual data types may differ from one another. However the members that compose a union all share the same storage area within the computers memory where as each member within a structure is assigned its own unique storage area. Thus unions are used to conserve memory. They are useful for application involving multiple members. Where values need not be assigned to all the members at any one time. Like structures union can be declared using the keyword union as follows:

union item { int m; float p; char c; } code;

this declares a variable code of type union item. The union contains three members each with a different data type. However we can use only one of them at a time. This is because if only one location is allocated for union variable irrespective of size. The compiler allocates a piece of storage that is large enough to access a union member we can use the same syntax that we use to access structure members. That is

Page 22: MC0061 Q & Ans

code.m code.p code.c

are all valid member variables. During accessing we should make sure that we are accessing the member whose value is currently stored. For example a statement such as

code.m=456; code.p=456.78; printf(“%d”,code.m);

Would produce erroneous result.

In effect a union creates a storage location that can be used by one of its members at a time. When a different number is assigned a new value the new value supercedes the previous members value. Unions may be used in all places where a structure is allowed. The notation for accessing a union member that is nested inside a structure remains the same as for the nested structure.

(b) Self referential Structure

A self-referential structure is one of the data structures which refer to the pointer to (points) to another structure of the same type. For example, a linked list is supposed to be a self-referential data structure. The next node of a node is being pointed, which is of the same struct type. For example,

typedef struct listnode {void *data;struct listnode *next;} linked_list;

A self referential structure is used to create data structures like linked lists, stacks, etc. Following is an example of this kind of structure:

struct struct_name{       datatype datatypename;       struct_name * pointer_name;}; 

Q. 8. Describe with the help of suitable coding example, the implementation of circular queues.

Answer :

Page 23: MC0061 Q & Ans

Circular queue:

 In a circular queue, after rear reaches the end of the queue, it can be reset to zero. This helps in refilling the empty spaces in between.

This article contains the code for implementing a circular queue using ADT. Here, we demonstrate all the functions that can be performed in a circular queue.

CODE:#include"stdio.h"#include"stdlib.h"typedef struct qrec { int *a; int front,rear,cap,size; }*queue;

queue makeempty(queue q) { q->rear=-1; q->front=-1; return q; }

queue createqueue(int max) { queue q; q=(queue)malloc(sizeof(struct qrec)); q->a=(int*)malloc(sizeof(int)*max); makeempty(q); q->cap=max; return q; }

int isfull(queue q) {

Page 24: MC0061 Q & Ans

return q->rear==q->cap-1 && q->front==0 || q->front==q->rear+1; }

int isempty(queue q) { return q->front==-1; }

void enqueue(queue q,int x) { if(isfull(q)) printf("\n Overflow"); else { q->rear=(q->rear+1)%(q->cap); q->a[q->rear]=x; if(q->front==-1) q->front=0; } }

int dequeue(queue q) { if(isempty(q)) printf("\n Underflow"); else { if(q->rear==q->front) makeempty(q); else { q->front=(q->front+1)%(q->cap); return q->a[q->front]; } } }

int front(queue q) { if(isempty(q)) printf("\n Underflow"); else return q->a[q->front]; }

int frontanddelete(queue q)

Page 25: MC0061 Q & Ans

{ int p; if(isempty(q)) { printf("underflow"); return 0; } else { p=front(q); dequeue(q); return p; } } void display(queue q) { int i; printf("\n CONTENTS"); for(i=q->front;i!=q->rear;i=(i+1)%q->cap) printf("\t%d",q->a[i]); printf("\t%d",q->a[i]); } int main() { int m,b,c; queue q;

printf("\nEnter the max size"); scanf("%d",&m); q=createqueue(m); printf("\n MENU\n1.Enqueue\n2.Dequeue\n3.Front\n4.Front and delete\n5.Exit"); while(1) { printf("\n ENTER UR CHOICE"); scanf("%d",&b); switch(b) { case 1: printf("\n Enter a no"); scanf("%d",&c); enqueue(q,c); display(q); break; case 2:dequeue(q); printf("\n Deq"); display(q);

Page 26: MC0061 Q & Ans

break; case 3:printf("\n Front value is %d",front(q)); display(q); break; case 4:frontanddelete(q); display(q); break; case 5:exit(0); break; default:printf("\n Invalid option"); break; } }

}

IMPLEMENTATION:

1.Initially,the maximum no.of elements to be stored in the queue is obtained from the user.

2.A circular queue is created by dynamically allocating memory using createqueue() function.

3.Then, choices are provided to the user from which one can choose the operation to be performed.

4.A switch case is made use of in this code. Depending upon the choice entered by the user,the corresponding operations are performed.

5.After each operation,the display() function is called so that the user can better understand the implementation.

6.If the user enters a number that has not been specified in the cases, the default case is executed and the program terminates.