SlideShare ist ein Scribd-Unternehmen logo
1 von 28
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.
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("nntttWritten for smunn");
getch();
}
4. Write a program that accepts 15 different numbers and find the LCM and HCM.
Answer:-
#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("nntttWritten for smu.covertbay.comnn");
getch();
}


int lcmz(int e,int f)
{
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:-
#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("");
    }
}
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.
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
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(“tt STACK OPERATIONn”);
printf(“tt``````````n”);
printf(“tt 1:pushn”);
printf(“tt 2: popn”);
printf(“tt 3: dispayn”);
printf(“tt 4: exitnnn”);
printf(“tt enter the choice:”); scanf(“%d”, &choice);
switch(choice)
{
case 1: // push operation
printf(“nnEnter 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 emptyn”);
else
printf(“POP successful, Deleted item = %dn”, 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[])
{
if (*top == STACK_SIZE -1)
{
printf(“Stack overflown”);
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 emptyn”);
return;
}
printf(“nnntt content of the STACKnn”);
for(i=top; i>=0; i--)
{
printf(“ttt[%5d]n”, s[i]);
}
printf(“ttt------“);
}




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;
•   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.
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
}
}


    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
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? ");
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
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: %sn", st3);
printf("2nd copied string: %sn", st4);
printf("nntttWritten for smun");
getch();
}
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++; }
}
FILE *q;
q=fopen("test.txt","ab");
fwrite(&s,31,1,q);
fclose(q);


printf("nntShort form is saved in the file named test.txttn");
printf("nttWritten for smutn");
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
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)
   {
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);
}
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("nntMain Menu.........");
printf("nn1.Push");
printf("nn2.Pop");
printf("nn3.Exit");
do
{


printf("nntEnter Your Choice 1-3:");
scanf("%d",&opt);
switch(opt)
{
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:nn");
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("ntData Deleted From the Stack is:%dn",dt);
printf("ntAfter Deleting the Element from the stack is:nn");
disp(st,tos);
}
else
printf("nStack Empty,Deletio Not Possible:");
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:
   74
   Enter your choice 1-3:1
   Enter the element to be push:4


10. Write a C program to implement dequeues.
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.Insertn2.Deleten3.DisplaynEnter 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;
}
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");
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]);
}
}

Weitere ähnliche Inhalte

Was ist angesagt? (19)

Array Cont
Array ContArray Cont
Array Cont
 
Ch13
Ch13Ch13
Ch13
 
Lesson 1 overview
Lesson 1   overviewLesson 1   overview
Lesson 1 overview
 
4. SQL in DBMS
4. SQL in DBMS4. SQL in DBMS
4. SQL in DBMS
 
Structure & union
Structure & unionStructure & union
Structure & union
 
L6 structure
L6 structureL6 structure
L6 structure
 
Introduction to Data Structure : Pointer
Introduction to Data Structure : PointerIntroduction to Data Structure : Pointer
Introduction to Data Structure : Pointer
 
Lk module3
Lk module3Lk module3
Lk module3
 
Pointers and Structures
Pointers and StructuresPointers and Structures
Pointers and Structures
 
Structures and Pointers
Structures and PointersStructures and Pointers
Structures and Pointers
 
Function pointer
Function pointerFunction pointer
Function pointer
 
Dynamic memory allocation
Dynamic memory allocationDynamic memory allocation
Dynamic memory allocation
 
Presentation on c structures
Presentation on c   structures Presentation on c   structures
Presentation on c structures
 
6. R data structures
6. R data structures6. R data structures
6. R data structures
 
Chapter 2.datatypes and operators
Chapter 2.datatypes and operatorsChapter 2.datatypes and operators
Chapter 2.datatypes and operators
 
Unit 1
Unit  1Unit  1
Unit 1
 
Structures
StructuresStructures
Structures
 
Structures in c language
Structures in c languageStructures in c language
Structures in c language
 
arrays and pointers
arrays and pointersarrays and pointers
arrays and pointers
 

Andere mochten auch (9)

Bt0062
Bt0062Bt0062
Bt0062
 
Bt0065
Bt0065Bt0065
Bt0065
 
Tax Autumn Conference (09.12.10)
Tax Autumn Conference (09.12.10)Tax Autumn Conference (09.12.10)
Tax Autumn Conference (09.12.10)
 
B T0064
B T0064B T0064
B T0064
 
Iniciador 2010
Iniciador 2010Iniciador 2010
Iniciador 2010
 
Bt0070
Bt0070Bt0070
Bt0070
 
B T0066
B T0066B T0066
B T0066
 
B T0062
B T0062B T0062
B T0062
 
Bt0072
Bt0072Bt0072
Bt0072
 

Ähnlich wie B T0065

Abstract Data Types (a) Explain briefly what is meant by the ter.pdf
Abstract Data Types (a) Explain briefly what is meant by the ter.pdfAbstract Data Types (a) Explain briefly what is meant by the ter.pdf
Abstract Data Types (a) Explain briefly what is meant by the ter.pdfkarymadelaneyrenne19
 
CS 23001 Computer Science II Data Structures & AbstractionPro.docx
CS 23001 Computer Science II Data Structures & AbstractionPro.docxCS 23001 Computer Science II Data Structures & AbstractionPro.docx
CS 23001 Computer Science II Data Structures & AbstractionPro.docxfaithxdunce63732
 
Ds12 140715025807-phpapp02
Ds12 140715025807-phpapp02Ds12 140715025807-phpapp02
Ds12 140715025807-phpapp02Salman Qamar
 
Templates presentation
Templates presentationTemplates presentation
Templates presentationmalaybpramanik
 
Introduction to Data structure and algorithm.pptx
Introduction to Data structure and algorithm.pptxIntroduction to Data structure and algorithm.pptx
Introduction to Data structure and algorithm.pptxline24arts
 
Bsc cs ii dfs u-1 introduction to data structure
Bsc cs ii dfs u-1 introduction to data structureBsc cs ii dfs u-1 introduction to data structure
Bsc cs ii dfs u-1 introduction to data structureRai University
 
Presentation on c programing satcture
Presentation on c programing satcture Presentation on c programing satcture
Presentation on c programing satcture topu93
 
Bca ii dfs u-1 introduction to data structure
Bca ii dfs u-1 introduction to data structureBca ii dfs u-1 introduction to data structure
Bca ii dfs u-1 introduction to data structureRai University
 
Data structure and algorithm
Data structure and algorithmData structure and algorithm
Data structure and algorithmTrupti Agrawal
 
Introduction to Data Structure
Introduction to Data Structure Introduction to Data Structure
Introduction to Data Structure Prof Ansari
 
Data structures and algorithms short note (version 14).pd
Data structures and algorithms short note (version 14).pdData structures and algorithms short note (version 14).pd
Data structures and algorithms short note (version 14).pdNimmi Weeraddana
 

Ähnlich wie B T0065 (20)

Abstract Data Types (a) Explain briefly what is meant by the ter.pdf
Abstract Data Types (a) Explain briefly what is meant by the ter.pdfAbstract Data Types (a) Explain briefly what is meant by the ter.pdf
Abstract Data Types (a) Explain briefly what is meant by the ter.pdf
 
DS_PPT.pptx
DS_PPT.pptxDS_PPT.pptx
DS_PPT.pptx
 
Lecture 1 and 2
Lecture 1 and 2Lecture 1 and 2
Lecture 1 and 2
 
Data structures
Data structuresData structures
Data structures
 
CS 23001 Computer Science II Data Structures & AbstractionPro.docx
CS 23001 Computer Science II Data Structures & AbstractionPro.docxCS 23001 Computer Science II Data Structures & AbstractionPro.docx
CS 23001 Computer Science II Data Structures & AbstractionPro.docx
 
Ds12 140715025807-phpapp02
Ds12 140715025807-phpapp02Ds12 140715025807-phpapp02
Ds12 140715025807-phpapp02
 
Templates presentation
Templates presentationTemplates presentation
Templates presentation
 
Introduction to Data structure and algorithm.pptx
Introduction to Data structure and algorithm.pptxIntroduction to Data structure and algorithm.pptx
Introduction to Data structure and algorithm.pptx
 
Templates2
Templates2Templates2
Templates2
 
Bsc cs ii dfs u-1 introduction to data structure
Bsc cs ii dfs u-1 introduction to data structureBsc cs ii dfs u-1 introduction to data structure
Bsc cs ii dfs u-1 introduction to data structure
 
DS_PPT.ppt
DS_PPT.pptDS_PPT.ppt
DS_PPT.ppt
 
Data structure
 Data structure Data structure
Data structure
 
Presentation on c programing satcture
Presentation on c programing satcture Presentation on c programing satcture
Presentation on c programing satcture
 
Python for beginners
Python for beginnersPython for beginners
Python for beginners
 
Bca ii dfs u-1 introduction to data structure
Bca ii dfs u-1 introduction to data structureBca ii dfs u-1 introduction to data structure
Bca ii dfs u-1 introduction to data structure
 
Data structure and algorithm
Data structure and algorithmData structure and algorithm
Data structure and algorithm
 
Introduction to Data Structure
Introduction to Data Structure Introduction to Data Structure
Introduction to Data Structure
 
Data structures and algorithms short note (version 14).pd
Data structures and algorithms short note (version 14).pdData structures and algorithms short note (version 14).pd
Data structures and algorithms short note (version 14).pd
 
Cs341
Cs341Cs341
Cs341
 
UNIT 1.pptx
UNIT 1.pptxUNIT 1.pptx
UNIT 1.pptx
 

Mehr von Simpaly Jha

Mehr von Simpaly Jha (6)

Bt0071
Bt0071Bt0071
Bt0071
 
Bt0068
Bt0068Bt0068
Bt0068
 
Shree Ganesh
Shree GaneshShree Ganesh
Shree Ganesh
 
Bt0064
Bt0064Bt0064
Bt0064
 
Bt0066
Bt0066Bt0066
Bt0066
 
Shree Ganesha!!!!!!!!!!!!!!!!!
Shree Ganesha!!!!!!!!!!!!!!!!!Shree Ganesha!!!!!!!!!!!!!!!!!
Shree Ganesha!!!!!!!!!!!!!!!!!
 

B T0065

  • 1. 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.
  • 2. 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("nntttWritten for smunn"); getch(); } 4. Write a program that accepts 15 different numbers and find the LCM and HCM. Answer:-
  • 3. #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("nntttWritten for smu.covertbay.comnn"); getch(); } int lcmz(int e,int f)
  • 4. { 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:-
  • 5. #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(""); } }
  • 6. 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.
  • 7. 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
  • 8. 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(“tt STACK OPERATIONn”); printf(“tt``````````n”); printf(“tt 1:pushn”);
  • 9. printf(“tt 2: popn”); printf(“tt 3: dispayn”); printf(“tt 4: exitnnn”); printf(“tt enter the choice:”); scanf(“%d”, &choice); switch(choice) { case 1: // push operation printf(“nnEnter 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 emptyn”); else printf(“POP successful, Deleted item = %dn”, 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[]) {
  • 10. if (*top == STACK_SIZE -1) { printf(“Stack overflown”); 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 emptyn”); return; } printf(“nnntt content of the STACKnn”); for(i=top; i>=0; i--) { printf(“ttt[%5d]n”, s[i]); }
  • 11. printf(“ttt------“); } 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;
  • 12. 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.
  • 13. 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
  • 14. } } 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
  • 15. 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? ");
  • 16. 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
  • 17. 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: %sn", st3); printf("2nd copied string: %sn", st4); printf("nntttWritten for smun"); getch(); }
  • 18. 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++; } }
  • 19. FILE *q; q=fopen("test.txt","ab"); fwrite(&s,31,1,q); fclose(q); printf("nntShort form is saved in the file named test.txttn"); printf("nttWritten for smutn"); 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
  • 20. 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) {
  • 21. 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);
  • 22. } 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("nntMain Menu........."); printf("nn1.Push"); printf("nn2.Pop"); printf("nn3.Exit"); do { printf("nntEnter Your Choice 1-3:"); scanf("%d",&opt); switch(opt)
  • 23. { 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:nn"); 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("ntData Deleted From the Stack is:%dn",dt); printf("ntAfter Deleting the Element from the stack is:nn"); disp(st,tos); } else printf("nStack Empty,Deletio Not Possible:");
  • 24. 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: 74 Enter your choice 1-3:1 Enter the element to be push:4 10. Write a C program to implement dequeues.
  • 25. 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.Insertn2.Deleten3.DisplaynEnter 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;
  • 26. } 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");
  • 27. 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]);
  • 28. } }