Top Banner
August 2010 Bachelor of Science in Information Technology (BScIT) – Semester 1/ Diploma in Information Technology (DIT) – Semester 1 BT0065 – C Programming and Data Structures – 3 Credits (Book ID: B0949) Assignment Set – 1 (60 Marks) Answer all questions 10 x 6 = 60 1. What do you mean by data types? Explain. Answe:- Data type is essential when we define a variable. Because when variable is defined we must maintain the data type along with the variable so that it possible to allocate the memory space. et us consider the analogous example of cooking. At the time of defined a container we must define its capacity. If it is large enough, then space is wasted and if is small than data can be overflowed. In C language, there are four Data Type. a) Primary or fundamental data type b) User defined data type c) Derived data type d) Empty data type 2. Write an algorithm to print all even numbers in descending order and draw the flowchart. Answer:- Flowchart to print all even numbers in descending order from 100 till 2.
34

Bt0065

May 17, 2015

Download

Education

Simpaly Jha

Only for SMU student

If any one read this message plz contact as per the given Email ID
[email protected]
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Bt0065

August 2010

Bachelor of Science in Information Technology (BScIT) – Semester 1/

Diploma in Information Technology (DIT) – Semester 1

BT0065 – C Programming and Data Structures – 3 Credits

(Book ID: B0949)

Assignment Set – 1 (60 Marks)

Answer all questions 10 x 6 = 60

1. What do you mean by data types? Explain.

Answe:- Data type is essential when we define a variable. Because when variable is defined

we must maintain the data type along with the variable so that it possible to allocate the

memory space. et us consider the analogous example of cooking. At the time of defined a

container we must define its capacity. If it is large enough, then space is wasted and if is small

than data can be overflowed.

In C language, there are four Data Type.

a) Primary or fundamental data type

b) User defined data type

c) Derived data type

d) Empty data type

2. Write an algorithm to print all even numbers in descending order and draw the flowchart.

Answer:- Flowchart to print all even numbers in descending order from 100 till 2.

Page 2: Bt0065

3. Write a C program to add all numbers between 100 and 200 that contain the digit 5.

Answer:-

#include <stdio.h>

#include <conio.h>

main(void)

{

int t=0,a=101,b=0,c=100;

for(;a<=200;a++)

{

b=a-c;

if(b%10==5||b/10==5)

t+=a;

}

printf("\nSum of the numbers is %d",t);

printf("\n\n\t\t\tWritten for smu\n\n");       

getch();

}

4. Write a program that accepts 15 different numbers and find the LCM and HCM.

Answer:-

Page 3: Bt0065

#include <stdio.h>

#include <conio.h>

int hcmz(int,int);

int lcmz(int,int);

main(void)

{

int num[14],c=15,v,max,min;

printf("Enter 15 numbers:\n");

           

for(v=0;v<c;v++)

scanf("%d",&num[v]);

min=num[0];

for(v=1;v<c;v++)

min=hcmz(min,num[v]);

printf("\nHCM is %d",min);

max=num[0];

for(v=1;v<c;v++)

max=lcmz(max,num[v]);

printf("\nLCM is %d",max);

printf("\n\n\t\t\tWritten for smu.covertbay.com\n\n");          

getch();

}

int lcmz(int e,int f)

Page 4: Bt0065

{

int lcm;

lcm = e*f/hcmz(e,f);

return lcm;

}

int hcmz(int e,int f)

{

int dump,rem;

if(e<f)

{

dump=e;

e=f;

f=dump;

}   

while(1)

{

rem=e%f;

if(rem==0)

return f;

else

e=f;

f=rem;

}

}

5. Distinguish library functions and user defined functions.

Answer:- Unit 5 (Library function = predefined function | user defined function = defined

by user)

6. Write a program to illustrate the usage of pointers with arrays and functions.

Answer:-

Page 5: Bt0065

#include <stdio.h>

#define ROWS 3

#define COLS 4

void print(int rows, int cols, int *matrix);

int main(int argc, char *argv[]) {

    int a[ROWS*COLS], i;

    /* initialize */

    for (i = 0; i < ROWS*COLS; i++) {

        a[i] = i+1;

    }

    /* display */

    print(ROWS,COLS,a);

    return 0;

}

void print(int rows, int cols, int *matrix) {

    int i, j, *p = matrix;

   

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

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

            printf("%3d",*(p + (i * cols) + j)));

        }

        puts("");

    }

}

Page 6: Bt0065

7. Write a program that reads numbers from a file and find the largest and smallest among

them.

Answer:-

#include<stdio.h>

#include<lib.h>

void main(void)

{

FILE *fp;

int i;

clrscr();

while(!eof(fp))

{

a[i]=fgetc(fp);

i++

getch();

}

8. What do you mean by Abstract Data Type?

Answer:- an abstract data type is a mathematical model for a certain class of data structures

that have similar behavior; or for certain data types of one or more programming languages

that have similar semantics. An abstract data type is defined indirectly, only by the operations

that may be performed on it and by mathematical constraints on the effects (and possibly cost)

of those operations.

For example, an abstract stack data structure could be defined by two operations: push, that

inserts some data item into the structure, and pop, that extracts an item from it; with the

constraint that each pop always returns the most recently pushed item that has not been

popped yet. When analyzing the efficiency of algorithms that use stacks, one may also specify

that both operations take the same time no matter how many items have been pushed into the

stack, and that the stack uses a constant amount of storage for each element.

Page 7: Bt0065

Abstract data types are purely theoretical entities, used (among other things) to simplify the

description of abstract algorithms, to classify and evaluate data structures, and to formally

describe the type systems of programming languages. However, an ADT may be implemented

by specific data types or data structures, in many ways and in many programming languages;

or described in a formal specification language. ADTs are often implemented as modules: the

module's interface declares procedures that correspond to the ADT operations, sometimes

with comments that describe the constraints. This information hiding strategy allows the

implementation of the module to be changed without disturbing the client programs.

An Abstract Data type is defined as a mathematical model of the data objects that make up a

data type as well as the functions that operate on these objects. There are no standard

conventions for defining them. A broad division may be drawn between "imperative" and

"functional" definition styles Imperative abstract data type definitions

In the "imperative" view, which is closer to the philosophy of imperative programming

languages, an abstract data structure is conceived as an entity that is mutable — meaning that

it may be in different states at different times. Some operations may change the state of the

ADT; therefore, the order in which operations are evaluated is important, and the same

operation on the same entities may have different effects if executed at different times — just

like the instructions of a computer, or the commands and procedures of an imperative

language. To underscore this view, it is customary to say that the operations are executed or

applied, rather than evaluated. The imperative style is often used when describing abstract

algorithms.

Functional ADT definitions

Another way to define an ADT, closer to the spirit of functional programming, is to consider

each state of the structure as a separate entity. In this view, any operation that modifies the

ADT is modeled as a mathematical function that takes the old state as an argument, and

returns the new state as part of the result. Unlike the "imperative" operations, these functions

have no side effects. Therefore, the order in which they are evaluated is immaterial, and the

Page 8: Bt0065

same operation applied to the same arguments (including the same input states) will always

return the same results (and output states).

In the functional view, in particular, there is no way (or need) to define an "abstract variable"

with the semantics of imperative variables (namely, with fetch and store operations). Instead of

storing values into variables, one passes them as arguments to functions.

9. Write a program to implement the stack operations using arrays.

Answer:-

#include<stdio.h>

#include<process.h>

#define STACK_SIZE5

void main()

{

void push(int,int*,int*);

int pop(int*,int*);

void display(int,int*);

int top

int s[10]

int tem;

int choice;

top= -1;

for (.’.’)

{

clrscr();

printf(“\t\t STACK OPERATION\n”);

printf(“\t\t``````````\n”);

printf(“\t\t 1:push\n”);

Page 9: Bt0065

printf(“\t\t 2: pop\n”);

printf(“\t\t 3: dispay\n”);

printf(“\t\t 4: exit\n\n\n”);

printf(“\t\t enter the choice:”); scanf(“%d”, &choice);

switch(choice)

{

case 1: // push operation

printf(“\n\nEnter the item to be inserted:”); scanf(“%d”, &item)’

push(item, &top, s);

continue;

case 2: // pop operation

item = pop(&top, s);

if(item == 0)

printf(“stack is empty\n”);

else

printf(“POP successful, Deleted item = %d\n”, item);

break;

case 3: // display

display(top, s);

break;

case 4: // exit from program

exit(0);

default:

printf(“invalid input – Try Again”);

}

getch();

}

}

void push(int item, int *top, int s[])

{

Page 10: Bt0065

if (*top == STACK_SIZE -1)

{

printf(“Stack overflow\n”);

getch(); return;

}

s[++(*top)] = item;

}

int pop(int *top, int s[])

{

int item;

if(*top == -1)

{

return 0;

}

item = s[(*top)--};

return item;

}

void display(int top, int s[])

{

int I;

if(top == -1)

{

printf(“stack is empty\n”);

return;

}

printf(“\n\n\n\t\t content of the STACK\n\n”);

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

{

printf(“\t\t\t[%5d]\n”, s[i]);

}

Page 11: Bt0065

printf(“\t\t\t------“);

}

10. Explain the operations that can be performed on linked list.

Answer:- The operations that can be performed on a linked list are...

1. Insert an element or list.

2. Delete an element or list.

3. Read an element or list.

4. Modify an element or list.

5. Search for the first or next occurence of an element.

Suppose that we have already created a linked list in memory, and that a variable lis of type

ListNode contains a reference to the first element of the list.

We can perform various operations on such a list. The most common operations are:

checking whether the list is empty;

accessing a node to modify it or to obtain the information in it;

traversing the list to access all elements (e.g., to print them, or to find some specific

element);

determining the size (i.e., the number of elements) of the list;

Page 12: Bt0065

inserting or removing a specific element (e.g., the first one, the last one, or one with a

certain value);

creating a list by reading the elements from an input stream;

converting a list to and from an array, string, etc.

Note that some of the operations above do not modify the list at all, some modify only the

information field of a node, and some modify the structure of the list, by changing how the

nodes are connected to each other. We will realize each operation through a static method:

The method takes as one of its parameters a reference to the first node of the list.

If the method modifies the list, it also returns a reference to the first node of the

modified list as its return value.

Page 13: Bt0065

August 2010

Bachelor of Science in Information Technology (BScIT) – Semester 1/

Diploma in Information Technology (DIT) – Semester 1

BT0065 – C Programming and Data Structures – 3 Credits

(Book ID: B0949)

Assignment Set – 2 (60 Marks)

Answer all questions 10 x 6 = 60

1. What is the difference between pre increment and post increment operator?

Answer:- Pre increment means that if you have for instance a loop:

{

...

for (int i = 1; i<10; ++i)

{

// the index i before the first iteration equals 1

...

// the index i after the first iteration equals 2

}

}

Post increment

{

...

for (int i = 1; i<10; i++)

{

// the index i after before the iteration equals 2

...

// the index i after the first iteration equals 3

Page 14: Bt0065

}

}

2. Write an algorithm to print the factorial of a given number and then draw the flowchart.

Answer:-

Step I Start

Step II Input A,B

Step III C = 0

Step IV C = A+B

Step V Print C

Step VI End

Start

Input A,B

C=0

C= A+B

Print C

End

3. Why should we avoid ‘goto’ statement?

Answer:- goto tends to get messy if you have to use more then one of them. It's very hard to

upgrade as well as understand when goto is used in code. Some time ago it was a big

discussion about it. Many professional programmers have agreed that goto caused a lot of

problems. Nowadays goto is almost not used in professional projects. another view:

You shouldn't "avoid it" so much as know when to use it and when to use another way. Used

improperly it makes code unreadable and hard to maintain, which is why beginners are taught

not to use it (beginners would use it improperly and never learn to use loops :p ). Example of

Page 15: Bt0065

the proper usage would be exiting multiple levels of nested loops..

while(...){

while(...){

while(...){

if (something) goto end;

}}}

end:

//rest of the code

But it can still be avoided. In this example, by using a flag.

flag=1;

while(...&&flag){

while (...&&flag){

while(...&&flag){

if (something) flag=0;

}}}

4. Write a program to sort the elements of an array in the ascending order.

Answer:-

#include<stdio.h>

#include <conio.h>

int main(void)

{

int item[100];

int a, b, t;

int count;

/* read in numbers */

printf("How many numbers? ");

Page 16: Bt0065

scanf("%d", &count);

for(a = 0; a < count; a++)

scanf("%d", &item[a]);

/* now, sort them using a bubble sort */

for(a = 1; a < count; ++a)

for(b = count-1; b >= a; --b) {

/* compare adjacent elements */

if(item[ b - 1] > item[ b ]) {

/* exchange elements */

t = item[ b - 1];

item[ b - 1] = item[ b ];

item[ b ] = t;

}

}

/* display sorted list */

for(t=0; t

return 0;

}

5. Write a user defined function which is equivalent of strlen().

Answer:- The library function are common required functions groped together and stored in

files called library. The library functions are present on disk in the most of the compilers.

According to the compiler version the library functions varies. Here the discussion in made

over the turbo C compiler version 3.0. there are 101 header files in the compiler. Some header

Page 17: Bt0065

files and some functions are given below which are commonly used. Before we used any

library function, we must open the respective header file.

Syntax for file inclusion:

#include<header file name>

OR

#include “header file name”

6. Write a C program to copy two strings using pointers.

Answer:

#include <stdio.h>

#include <conio.h>

void cpy(char *d, char *s);

main(void){

char st1[31],st2[31],st3[31],st4[31];

        

printf("Enter 1st string: ");

gets(st1);

printf("Enter 2nd string: ");

gets(st2);

      

cpy(st3, st1);

cpy(st4, st2);

printf("\n1st copied string: %s\n", st3);

printf("2nd copied string: %s\n", st4);

printf("\n\n\t\t\tWritten for smu\n");

getch();

}

Page 18: Bt0065

void cpy(char *d, char *s)

{

while(*s)

*d++ = *s++;

*d = '\0';

}

7. Write a program to accept name and store the name in its short form (e.g. Sikkim

Manipal University should be stored as SMU).

Answer:

#include <stdio.h>

#include <conio.h>

main(void)

{

char a[31]="";

char s[31]="";

char p=' ';

int c=1,v=0;

printf("Enter here: ");

gets(a);

s[0]=a[0];

for(;v<100;v++)

{

if(a[v]==p)

{ s[c]=a[v+1];

c++; }

}

Page 19: Bt0065

       

FILE *q;               

q=fopen("test.txt","ab");

fwrite(&s,31,1,q);

fclose(q);

        

printf("\n\n\tShort form is saved in the file named test.txt\t\n");

printf("\n\t\tWritten for smu\t\n");

getch();

}

8. What is a Data Structure? Explain.

Answer: In computer science, a data structure is a way of storing data in a computer

so that it can Be used efficiently. Often a carefully chosen data structure will allow the

most efficient Algorithm to be used. The choice of the data structure often begins from

the choice of an Abstract data type. A well-designed data structure allows a variety of

critical operations to Be performed, using as few resources, both execution time and

memory space, as Possible. Data structures are implemented using the data types,

references and operations On them provided by a programming language .Different

kinds of data structures are suited to different kinds of applications, and some Are

highly specialized to certain tasks. For example, B-trees are particularly well-suited for

implementation of databases, while routing tables rely on networks of machines to

Function.

Common data structures:

Array

Stacks

Queues

Linked lists

Trees

Graphs

Page 20: Bt0065

A data structure is a specialized format for organizing and storing data. General data

Structure types include the array, the file, the record, the table, the tree, and so on. Any

data structure is designed to organize data to suit a specific purpose so that it can be

accessed and worked with in appropriate ways. In computer programming, a data

structure may be selected or designed to store data for the purpose of working on it

with various algorithms.

Different kinds of data structures are suited to different kinds of applications, and some

are highly specialized to certain tasks. For example, B-trees are particularly well-suited

for implementation of databases, while networks of machines rely on routing tables to

function.

In the design of many types of computer program, the choice of data structures is a

primary design consideration. Experience in building large systems has shown that the

difficulty of implementation and the quality and performance of the final result depends

heavily on choosing the best data structure. After the data structures are chosen, the

algorithms to be used often become relatively obvious. Sometimes things work in the

opposite direction data structures are chosen because certain key tasks have

algorithms that work best with particular data structures. In either case, the choice of

appropriate data structures is crucial.

9. Write a program to implement stack with POP and PUSH operations.

Answer: #include <stdio.h>

#include <conio.h>

void push(int st[],int data,int &top);

void disp(int st[],int &top);

int pop(int st[],int &top);

int flg=0;

int top=-1,tos=-1;

int st[50];

void push(int st[],int data,int &top)

{

Page 21: Bt0065

if(top==50-1)

flg=0;

else

{

flg=1;

top++;

st[top]=data;

}

}

int pop(int st[],int &top)

{

int pe;

if(top==-1)

{

pe=0;

flg=0;

}

else

{

flg=1;

pe=st[top];

top--;

}

return(pe);

Page 22: Bt0065

}

void disp(int st[],int &top)

{

int i;

if(top==-1)

{

printf("\nStack is Empty");

}

else

{

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

printf("\t%d",st[i]);

}

}

void main()

{

int dt,opt;

int q=0;

clrscr();

printf("This Program Is Used to Perform PUSH & POP operations On Stack");

printf("\n\n\tMain Menu.........");

printf("\n\n1.Push");

printf("\n\n2.Pop");

printf("\n\n3.Exit");

do

{

printf("\n\n\tEnter Your Choice 1-3:");

scanf("%d",&opt);

switch(opt)

Page 23: Bt0065

{

case 1:

printf("\nEnter the Element to be Push:");

scanf("%d",&dt);

push(st,dt,tos);

if(flg==1)

{

printf("\nAfter Inserting the Element, Stack is:\n\n");

disp(st,tos);

if(tos==50-1)

printf("\nStack is Now Full");

}

else

printf("\nStack Overflow Insertion Not Possible");

break;

case 2:

dt=pop(st,tos);

if(flg==1)

{

printf("\n\tData Deleted From the Stack is:%d\n",dt);

printf("\n\tAfter Deleting the Element from the stack is:\n\n");

disp(st,tos);

}

else

printf("\nStack Empty,Deletio Not Possible:");

Page 24: Bt0065

break;

case 3:

q=1;

break;

default:printf("\nWrong Choice Enter 1-3 Only");

}

}while(q!=1);

}

OUTPUT

Main Menu.........

1.push

2.pop

3.exit

Enter your choice 1-3:1

Enter the element to be push:4

After inserting the elements,stack is:

4

Enter your choice 1-3:1

Enter the element to be push:7

After inserting the elements,stack is:

7 4

Enter your choice 1-3:1

Enter the element to be push:4

10. Write a C program to implement dequeues.

Page 25: Bt0065

Answer:

#include < stdio.h >

#include < conio.h >

#define MAX 3

int queue[MAX],front,rear;

void main()

{

void insert(int);

int del();

void display();

int choice,item;

char ch;

clrscr();

front=-1;

rear=-1;

do

{

printf("\n1.Insert\n2.Delete\n3.Display\nEnter ur choice(1-3):");

scanf("%d",&choice);

switch(choice)

{

case 1: printf("\nEnter item:");

scanf("%d",&item);

insert(item);

break;

case 2: item=del();

printf("\nDeleted item is %d",item);

break;

case 3: display();

break;

Page 26: Bt0065

}

printf("\nDo u wish to continue(y/n):");

fflush(stdin);

scanf("%c",&ch);

}while(ch=='y' || ch=='Y');

getch();

}

void insert(int item)

{

if(rear+1==front||front==0 && rear==MAX-1)

{

printf("QUEUE is FULL");

return;

}

if(front==-1 && rear==-1)

front=0;

if(rear==MAX-1)

rear=0;

else

rear++;

queue[rear]=item;

}

int del()

{

int item;

if(front==-1)

{

printf("QUEUE EMPTY");

Page 27: Bt0065

return -1;

}

item=queue[front];

if(front==rear)

{

front=-1;

rear=-1;

}

else if(front==MAX-1)

front=0;

else

front++;

return item;

}

void display()

{

int i;

printf("The Queue is:");

if(rear > front)

{

for(i=front;i < =rear;i++)

printf("%3d",queue[i]);

}

else

{

for(i=front;i < =MAX-1;i++)

printf("%3d",queue[i]);

for(i=0;i < = rear;i++)

printf("%3d",queue[i]);

Page 28: Bt0065

}

}