Published on

Only for SMU student

If any one read this message plz contact as per the given Email ID

Published in: Education
No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide


  1. 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 = 601. What do you mean by data types? Explain.Answe:- Data type is essential when we define a variable. Because when variable is definedwe must maintain the data type along with the variable so that it possible to allocate thememory space. et us consider the analogous example of cooking. At the time of defined acontainer we must define its capacity. If it is large enough, then space is wasted and if is smallthan 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 type2. 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. 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. 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. 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;elsee=f;f=rem;}}5. Distinguish library functions and user defined functions.Answer:- Unit 5 (Library function = predefined function | user defined function = definedby user)6. Write a program to illustrate the usage of pointers with arrays and functions.Answer:-
  5. 5. #include <stdio.h>#define ROWS 3#define COLS 4void 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. 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 structuresthat have similar behavior; or for certain data types of one or more programming languagesthat have similar semantics. An abstract data type is defined indirectly, only by the operationsthat 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, thatinserts some data item into the structure, and pop, that extracts an item from it; with theconstraint that each pop always returns the most recently pushed item that has not beenpopped yet. When analyzing the efficiency of algorithms that use stacks, one may also specifythat both operations take the same time no matter how many items have been pushed into thestack, and that the stack uses a constant amount of storage for each element.
  7. 7. Abstract data types are purely theoretical entities, used (among other things) to simplify thedescription of abstract algorithms, to classify and evaluate data structures, and to formallydescribe the type systems of programming languages. However, an ADT may be implementedby 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: themodules interface declares procedures that correspond to the ADT operations, sometimeswith comments that describe the constraints. This information hiding strategy allows theimplementation 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 adata type as well as the functions that operate on these objects. There are no standardconventions for defining them. A broad division may be drawn between "imperative" and"functional" definition styles Imperative abstract data type definitionsIn the "imperative" view, which is closer to the philosophy of imperative programminglanguages, an abstract data structure is conceived as an entity that is mutable — meaning thatit may be in different states at different times. Some operations may change the state of theADT; therefore, the order in which operations are evaluated is important, and the sameoperation on the same entities may have different effects if executed at different times — justlike the instructions of a computer, or the commands and procedures of an imperativelanguage. To underscore this view, it is customary to say that the operations are executed orapplied, rather than evaluated. The imperative style is often used when describing abstractalgorithms.Functional ADT definitionsAnother way to define an ADT, closer to the spirit of functional programming, is to considereach state of the structure as a separate entity. In this view, any operation that modifies theADT is modeled as a mathematical function that takes the old state as an argument, andreturns the new state as part of the result. Unlike the "imperative" operations, these functionshave no side effects. Therefore, the order in which they are evaluated is immaterial, and the
  8. 8. same operation applied to the same arguments (including the same input states) will alwaysreturn 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 ofstoring 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_SIZE5void main(){void push(int,int*,int*);int pop(int*,int*);void display(int,int*);int topint s[10]int tem;int choice;top= -1;for (.’.’){clrscr();printf(“tt STACK OPERATIONn”);printf(“tt``````````n”);printf(“tt 1:pushn”);
  9. 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 operationprintf(“nnEnter the item to be inserted:”); scanf(“%d”, &item)’push(item, &top, s);continue;case 2: // pop operationitem = pop(&top, s);if(item == 0)printf(“stack is emptyn”);elseprintf(“POP successful, Deleted item = %dn”, item);break;case 3: // displaydisplay(top, s);break;case 4: // exit from programexit(0);default:printf(“invalid input – Try Again”);}getch();}}void push(int item, int *top, int s[]){
  10. 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. 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 typeListNode 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. 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 theinformation field of a node, and some modify the structure of the list, by changing how thenodes 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. 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. 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. Its very hard toupgrade as well as understand when goto is used in code. Some time ago it was a bigdiscussion about it. Many professional programmers have agreed that goto caused a lot ofproblems. Nowadays goto is almost not used in professional projects. another view:You shouldnt "avoid it" so much as know when to use it and when to use another way. Usedimproperly it makes code unreadable and hard to maintain, which is why beginners are taughtnot to use it (beginners would use it improperly and never learn to use loops :p ). Example of
  15. 15. the proper usage would be exiting multiple levels of nested loops..while(...){while(...){while(...){if (something) goto end;}}}end://rest of the codeBut 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. 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; treturn 0;} 5. Write a user defined function which is equivalent of strlen().Answer:- The library function are common required functions groped together and stored infiles 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 madeover the turbo C compiler version 3.0. there are 101 header files in the compiler. Some header
  17. 17. files and some functions are given below which are commonly used. Before we used anylibrary 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. 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. 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. 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. 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. 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. 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");}elseprintf("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);}elseprintf("nStack Empty,Deletio Not Possible:");
  24. 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:410. Write a C program to implement dequeues.
  25. 25. Answer:#include < stdio.h >#include < conio.h >#define MAX 3int 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. 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;elserear++;queue[rear]=item;}int del(){int item;if(front==-1){printf("QUEUE EMPTY");
  27. 27. return -1;}item=queue[front];if(front==rear){front=-1;rear=-1;}else if(front==MAX-1)front=0;elsefront++;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. 28. }}