cds lab programs

Upload: raja-mohan-reddy

Post on 04-Apr-2018

224 views

Category:

Documents


0 download

TRANSCRIPT

  • 7/29/2019 CDS Lab Programs

    1/86

    CP LAB MANUAL (B.TECH I YEAR)

    COMPUTER PROGRAMMING Syllabus

    UNIT - IAlgorithm / pseudo code, flowchart, program development steps, structure of C program, A SimpleC program, identifiers, basic data types and sizes, Constants, variables, arithmetic, relational andlogical operators, increment and decrement operators, conditional operator, bit-wise operators,assignment operators, expressions, type conversions, conditional expressions, precedence and order of

    evaluation.

    UNIT IIInput-output statements, statements and blocks, if and switch statements, loops- while, do-while andfor statements, break, continue, goto and labels, programming examples.

    UNIT IIIDesigning structured programs, Functions, basics, parameter passing, storage classes- extern, auto,register, static, scope rules, block structure, user defined functions, standard library functions, recursivefunctions, header files, C preprocessor, example c programs.

    UNIT IVArrays- concepts, declaration, definition, accessing elements, storing elements, arrays and functions,two-dimensional and multi-dimensional arrays, applications of arrays. pointers- concepts, initialization of

    pointer variables, pointers and function arguments, address arithmetic, Character pointers and functions,pointers to pointers, pointers and multidimensional arrays, dynamic memory managements functions,command line arguments, c program examples.

    UNIT VDerived types- structures- declaration, definition and initialization of structures, accessing structures,nested structures, arrays of structures, structures and functions, pointers to structures, self referentialstructures, unions, typedef, bit fields, C program examples.

    UNIT VIInput and output concept of a file, text files and binary files, streams, standard I/o, Formatted I/o, fileI/o operations, error handling, C program examples.

    UNIT VIIIntroduction to data structures-Stacks and Queues, representing stacks and queues in C using arrays

    and linked lists.Implementation of Searching and sorting in C Linear and binary search methods, sorting Bubble sort,Quick Sort, merge sort.

    UNIT - VIIITrees- Binary trees, representation, traversals (Recursive) implemented in C, graphs- terminology,representation and basic operations on graphs.

    TEXT BOOKS :1. Computer science, A structured programming approach using C, B.A. Forouzan and R.F. Gilberg,

    Third edition, Thomson.2. DataStructures Using C A.S.Tanenbaum, Y. Langsam, and M.J. Augenstein, PHI/Pearson

    education.

    REFERENCES :1. C& Data structures P. Padmanabham, B.S. Publications.2. The C Programming Language, B.W. Kernighan, Dennis M.Ritchie,

    PHI/Pearson Education3. C Programming with problem solving, J.A. Jones & K. Harrow,

    dreamtech Press4. Programming in C Stephen G. Kochan, III Edition, Pearson Eductaion.5. Data Structures and Program Design in C, R.Kruse, C.L. Tondo, BP Leung, Shashi M, Second

    Edition, Pearson Education.

    Page 1 of 86

  • 7/29/2019 CDS Lab Programs

    2/86

    CP LAB MANUAL (B.TECH I YEAR)

    CONTENTS

    S.no Name of the Program PageNo

    1 A Fibonacci Sequence is defined as follows: the first and second terms inthe sequence are 0 and 1. Subsequent terms are found by adding the

    preceding two terms in the sequence. Write a C program to generate thefirst n terms of the sequence.

    2 Write a C program to generate all the prime numbers between 1 and n,where n is a value supplied by the user.

    3 Write a C program to find the sum of individual digits of a positiveinteger.

    4 Write a C program to calculate the following Sum:Sum=1-x2/2! +x4/4!-x6/6!+x8/8!-x10/10!

    5 Write a C program toe find the roots of a quadratic equation

    6 Write C programs that use both recursive and non-recursive functionsA) To find the factorial of a given integer.B) To find the GCD (greatest common divisor)of two given

    integers.

    C) To solve Towers of Hanoi problem.

    7 Write a C program, which takes two integer operands and one operatorform the user, performs the operation and then prints the result.(Consider the operators +,-,*,/,% and use Switch Statement)

    8 The total distance travelled by vehicle in t seconds is given by distance= ut+1/2at2 where u and a are the initial velocity (m/sec.) andacceleration (m/sec2). Write C program to find the distance travelled at

    regular intervals of time given the values of u and a. The programshould provide the flexibility to the user to select his own time intervals

    and repeat the calculations for different values of u and a.

    9 Write a C program that uses functions to perform the following:i)Addition of Two Matricesii)Multiplication of Two Matrices

    10 Write a C program to find both the larges and smallest number in a list ofintegers.

    11 Write a C program that uses functions to perform the followingoperations:A)To insert a sub-string in to given main string from a given

    position.B)To delete n Characters from a given position in a given string.

    12 Write a C program to determine if the given string is a palindrome ornot.

    Page 2 of 86

  • 7/29/2019 CDS Lab Programs

    3/86

    CP LAB MANUAL (B.TECH I YEAR)

    13 Write a C program that displays the position or index in the string Swhere the string T begins, or 1 if S doesnt contain T.

    14 Write a C program to count the lines, words and characters in a giventext.

    15 Write a C program to generate Pascals triangle.

    16 Write a C program to construct a pyramid of numbers.

    17 Write a C program to read in two numbers, x and n, and then computethe sum of this geometric progression:

    1+x+x2+x3+.+xn

    For example: if n is 3 and x is 5, then the program computes1+5+25+125.Print x,n, the sum Perform error checking. For example, the formuladoes not make sense for negative exponents if n is less than 0. Have

    your program print an error message if n

  • 7/29/2019 CDS Lab Programs

    4/86

    CP LAB MANUAL (B.TECH I YEAR)

    25 Write C programs that implement stack (its operations) usingA) Arrays B) Pointers

    26 Write C programs that implement Queue (its operations) usingA) Arrays B) Pointers

    27 Write a C program that uses Stack operations to perform the following:

    i) Converting infix expression into postfix expressionii) Evaluating the postfix expression

    28 Write a C program that uses functions to perform the following:i) Creating a Binary Tree of integersii) Traversing the above binary tree in preorder, inorder and

    postorder.

    29 Write C programs that use both recursive and non recursive functions toperform the following searching operations for a Key value in a given listof integers :

    A) Binary search B) Linear search

    30 Write C programs that implement the following sorting methods tosort a given list of integers in ascending order:

    A) Bubble sort B) Quick sort

    31 Write C programs that implement the following sorting methods to sorta given list of integers in ascending order:

    A) Insertion sort B)Merge sort

    32 Write C programs to implement A) Newton- Gregory forwardinterpolation. B) the Lagrange interpolation

    33 Write C programs to implement A) the linear regression andB) polynomial regression algorithms.

    34 Write C programs to implement A) Simpson methods. B) Trapezoidal

    Page 4 of 86

  • 7/29/2019 CDS Lab Programs

    5/86

    CP LAB MANUAL (B.TECH I YEAR)

    1

    * A Fibonacci Sequence is defined as follows: the first and second terms in the sequence

    are 0 and 1. Subsequent terms are found by adding the preceding two terms in the

    sequence. Write a C program to generatethe first n terms of the sequence. */

    #include

    void main(){int num1=0, num2=1,no,counter,fab;clrscr();

    printf("");printf("\n\n\n\t\tENTER LENGTH OF SERIES (N) : ");scanf("%d",&no);

    printf("\n\n\t\t\t");

    printf("\n\n\t\t%d %d",num1,num2);

    //LOOP WILL RUN FOR 2 TIME LESS IN SERIES AS THESE WAS PRINTED IN ADVANCEfor(counter = 1; counter

  • 7/29/2019 CDS Lab Programs

    6/86

    CP LAB MANUAL (B.TECH I YEAR)

    2/* Write a C program to generate all the prime numbers between 1 and n, where

    n is a value supplied by the user. */

    #include

    void main(){int no,counter,counter1,check;clrscr();printf("");printf("\n\n\n\t\t\tINPUT THE VALUE OF N: ");scanf("%d",&no);printf("\n\nTHE PRIME NO. SERIES B/W 1 TO %d : \n\n",no);

    for(counter = 1; counter 1 ; counter1--)if(counter%counter1 == 0){check++; // INCREMENT CHECK IF NO. IS NOT A PRIME NO.break;}if(check == 0)printf("%d\t",counter);

    }getch();}

    Page 6 of 86

  • 7/29/2019 CDS Lab Programs

    7/86

    CP LAB MANUAL (B.TECH I YEAR)

    3/* Write a C program to find the sum of individual digits of a positiveinteger.*/

    #include#include

    void main(){int num, k=1, sum=0;clrscr();printf("Enter the number whose digits are to be added:");scanf("%d",&num);

    while(num!=0){k=num%10;sum=sum+k;k=num/10;

    num=k;}printf("Sum of the digits:%d",sum);getch();}

    Page 7 of 86

  • 7/29/2019 CDS Lab Programs

    8/86

    CP LAB MANUAL (B.TECH I YEAR)

    4/* Write a C program to calculate the following Sum:

    Sum=1-x2/2! +x4/4!-x6/6!+x8/8!-x10/10!*/

    #include #include

    void main(){int counter,f_coun;float sum=0,x,power,fact;clrscr();

    printf("");printf("\n\n\tEQUATION SERIES : 1- X^2/2! + X^4/4! - X^6/6! + X^8/8! -X^10/10!");

    printf("\n\n\n\tENTER VALUE OF X : ");

    scanf("%f",&x);

    for(counter=0, power=0; power=1; f_coun--)

    fact *= f_coun;//EQ. FOR SUM SERIESsum=sum+(pow(-1,counter)*(pow(x,power)/fact));}

    printf("SUM : %f",sum);getch();

    }

    Page 8 of 86

  • 7/29/2019 CDS Lab Programs

    9/86

    CP LAB MANUAL (B.TECH I YEAR)

    5

    /* Write a C program toe find the roots of a quadratic equation. */

    #include

    #include#include

    void main(){float a,b,c,root1,root2;clrscr();printf("\n Enter values of a,b,c for finding roots of a quadratic eq:\n");scanf("%f%f%f",&a,&b,&c);

    /*checking condition*/if(b*b>4*a*c){

    root1=-b+sqrt(b*b-4*a*c)/2*a;root2=-b-sqrt(b*b-4*a*c)/2*a;printf("\n*****ROOTS ARE*****\n");printf("\n root1=%f\n root2=%f",root1,root2);}elseprintf("\n Imaginary Roots.");getch();}

    Page 9 of 86

  • 7/29/2019 CDS Lab Programs

    10/86

    CP LAB MANUAL (B.TECH I YEAR)

    6 A)

    /* Write C programs that use both recursive and non-recursive functionsTo find the factorial of a given integer.*/

    #include

    #include

    unsigned int recr_factorial(int n);unsigned int iter_factorial(int n);

    void main(){int n,i;long fact;clrscr();printf("Enter the number: ");scanf("%d",&n);

    if(n==0)printf("Factorial of 0 is 1\n");else{printf("Factorial of %d Using Recursive Function is

    %d\n",n,recr_factorial(n));printf("Factorial of %d Using Non-Recursive Function is

    %d\n",n,iter_factorial(n));}getch();

    }

    /* Recursive Function*/unsigned int recr_factorial(int n) {

    return n>=1 ? n * recr_factorial(n-1) : 1;}

    /* Non-Recursive Function*/unsigned int iter_factorial(int n) {

    int accu = 1;int i;for(i = 1; i

  • 7/29/2019 CDS Lab Programs

    11/86

    CP LAB MANUAL (B.TECH I YEAR)

    6 B)/* Write C programs that use both recursive and non-recursive functions

    To find the GCD (greatest common divisor) of two given integers.*/

    #include

    #include#include

    unsigned int GcdRecursive(unsigned m, unsigned n);unsigned int GcdNonRecursive(unsigned p,unsigned q);

    int main(void){int a,b,iGcd;clrscr();

    printf("Enter the two numbers whose GCD is to be found: ");scanf("%d%d",&a,&b);

    printf("GCD of %d and %d Using Recursive Function is%d\n",a,b,GcdRecursive(a,b));printf("GCD of %d and %d Using Non-Recursive Function is

    %d\n",a,b,GcdNonRecursive(a,b));

    getch();}

    /* Recursive Function*/unsigned int GcdRecursive(unsigned m, unsigned n){if(n>m)

    return GcdRecursive(n,m);

    if(n==0)return m;

    elsereturn GcdRecursive(n,m%n);

    }

    /* Non-Recursive Function*/unsigned int GcdNonRecursive(unsigned p,unsigned q){unsigned remainder;remainder = p-(p/q*q);

    if(remainder==0)return q;

    elseGcdRecursive(q,remainder);

    }

    Page 11 of 86

  • 7/29/2019 CDS Lab Programs

    12/86

    CP LAB MANUAL (B.TECH I YEAR)

    6 C)/* Write C programs that use both recursive and non-recursive functions

    To solve Towers of Hanoi problem.*/

    #include#include

    /* Non-Recursive Function*/void hanoiNonRecursion(int num,char sndl,char indl,char dndl){char stkn[100],stksndl[100],stkindl[100],stkdndl[100],stkadd[100],temp;int top,add;top=NULL;

    one:if(num==1){printf("\nMove top disk from needle %c to needle %c ",sndl,dndl);goto four;

    }

    two:top=top+1;stkn[top]=num;stksndl[top]=sndl;stkindl[top]=indl;stkdndl[top]=dndl;stkadd[top]=3;num=num-1;sndl=sndl;temp=indl;indl=dndl;dndl=temp;

    goto one;

    three:printf("\nMove top disk from needle %c to needle %c ",sndl,dndl);top=top+1;stkn[top]=num;stksndl[top]=sndl;stkindl[top]=indl;stkdndl[top]=dndl;stkadd[top]=5;num=num-1;temp=sndl;sndl=indl;indl=temp;

    dndl=dndl;

    goto one;

    four:if(top==NULL)return;

    num=stkn[top];sndl=stksndl[top];

    Page 12 of 86

  • 7/29/2019 CDS Lab Programs

    13/86

    CP LAB MANUAL (B.TECH I YEAR)

    indl=stkindl[top];dndl=stkdndl[top];add=stkadd[top];top=top-1;if(add==3)goto three;

    else if(add==5)goto four;

    }

    /* Recursive Function*/void hanoiRecursion( int num,char ndl1, char ndl2, char ndl3){

    if ( num == 1 ) {printf( "Move top disk from needle %c to needle %c.", ndl1, ndl2 );return;}

    hanoiRecursion( num - 1,ndl1, ndl3, ndl2 );printf( "Move top disk from needle %c to needle %c.", ndl1, ndl2 );

    hanoiRecursion( num - 1,ndl3, ndl2, ndl1 );}

    void main(){int no;clrscr();printf("Enter the no. of disks to be transferred: ");scanf("%d",&no);

    if(no

  • 7/29/2019 CDS Lab Programs

    14/86

    CP LAB MANUAL (B.TECH I YEAR)

    7/* Write a C program, which takes two integer operands and one operator form theuser,

    performs the operation and then prints the result.(Consider the operators +,-,*, /, % and use Switch Statement)

    */

    #include#include

    void main(){int a,b,res,ch;clrscr();printf("\t *********************");printf("\n\tMENU\n");printf("\t********************");printf("\n\t(1)ADDITION");printf("\n\t(2)SUBTRACTION");printf("\n\t(3)MULTIPLICATION");printf("\n\t(4)DIVISION");printf("\n\t(5)REMAINDER");printf("\n\t(0)EXIT");printf("\n\t********************");printf("\n\n\tEnter your choice:");scanf("%d",&ch);

    if(ch0){printf("Enter two numbers:\n");scanf("%d%d",&a,&b);}

    switch(ch){case 1:res=a+b;printf("\n Addition:%d",res);break;

    case 2:res=a-b;printf("\n Subtraction:%d",res);break;

    case 3:res=a*b;printf("\n Multiplication:%d",res);break;

    case 4:res=a/b;printf("\n Division:%d",res);break;

    case 5:

    Page 14 of 86

  • 7/29/2019 CDS Lab Programs

    15/86

    CP LAB MANUAL (B.TECH I YEAR)

    res=a%b;printf("\n Remainder:%d",res);break;

    case 0:printf("\n Choice Terminated");exit();break;

    default:printf("\n Invalid Choice");}getch();}

    Page 15 of 86

  • 7/29/2019 CDS Lab Programs

    16/86

    CP LAB MANUAL (B.TECH I YEAR)

    8)/* The total distance travelled by vehicle in 't' seconds is given by distance= ut+1/2at2 where 'u' and 'a' are the initial velocity (m/sec.) and acceleration(m/sec2).

    Write C program to find the distance travelled at regular intervals of timegiven the values of 'u' and 'a'. The program should provide the flexibility to

    the user to select his own time intervals and repeat the calculations fordifferent values of 'u' and 'a'. */

    #include #include

    void main(){int tim_intrval, counter,time;float accl, distance=0, velos;clrscr();printf("");

    printf("\n\n\n\t\t\tNO OF TIME INTERVALS : ");scanf("%d",&tim_intrval);

    for(counter = 1; counter

  • 7/29/2019 CDS Lab Programs

    17/86

    CP LAB MANUAL (B.TECH I YEAR)

    9)/* Write a C program that uses functions to perform the following:

    i) Addition of Two Matricesii) Multiplication of Two Matrices */

    #include

    void main(){int ch,i,j,m,n,p,q,k,r1,c1,a[10][10],b[10][10],c[10][10];clrscr();printf("************************************");printf("\n\t\tMENU");printf("\n**********************************");printf("\n[1]ADDITION OF TWO MATRICES");printf("\n[2]MULTIPLICATION OF TWO MATRICES");printf("\n[0]EXIT");printf("\n**********************************");printf("\n\tEnter your choice:\n");scanf("%d",&ch);

    if(ch0){printf("Valid Choice\n");}

    switch(ch){case 1:printf("Input rows and columns of A & B Matrix:");scanf("%d%d",&r1,&c1);printf("Enter elements of matrix A:\n");for(i=0;i

  • 7/29/2019 CDS Lab Programs

    18/86

    CP LAB MANUAL (B.TECH I YEAR)

    scanf("%d%d",&p,&q);if(n==p){printf("matrices can be multiplied\n");printf("resultant matrix is %d*%d\n",m,q);printf("Input A matrix\n");read_matrix(a,m,n);printf("Input B matrix\n");/*Function call to read the matrix*/read_matrix(b,p,q);/*Function for Multiplication of two matrices*/printf("\n =====Matrix Multiplication=====\n");for(i=0;i

  • 7/29/2019 CDS Lab Programs

    19/86

    CP LAB MANUAL (B.TECH I YEAR)

    {for(j=0;j

  • 7/29/2019 CDS Lab Programs

    20/86

    CP LAB MANUAL (B.TECH I YEAR)

    10/* Write a C program to find both the largest and smallest number in a list of integers*/

    main( ){

    float largest(float a[ ], int n);

    float value[4] = {2.5,-4.75,1.2,3.67};printf("%f\n", largest(value,4));

    }

    float largest(float a[], int n)

    {int i;

    float max;

    max = a[0];

    for(i = 1; i < n; i++)if(max < a[i])

    max = a[i];return(max);

    }

    Page 20 of 86

  • 7/29/2019 CDS Lab Programs

    21/86

    CP LAB MANUAL (B.TECH I YEAR)

    11 A)/* Write a C program that uses functions to perform the following operations:

    To insert a sub-string in to given main string from a given position.*/

    #include

    #include #include

    void main(){char a[10];char b[10];char c[10];int p=0,r=0,i=0;int t=0;int x,g,s,n,o;clrscr();

    puts("Enter First String:");

    gets(a);puts("Enter Second String:");gets(b);printf("Enter the position where the item has to be inserted: ");scanf("%d",&p);r = strlen(a);n = strlen(b);i=0;

    // Copying the input string into another arraywhile(i

  • 7/29/2019 CDS Lab Programs

    22/86

    CP LAB MANUAL (B.TECH I YEAR)

    11 B/* Write a C program that uses functions to perform the following operations:

    To delete n Characters from a given position in a given string.*/

    #include

    #include #include

    void delchar(char *x,int a, int b);

    void main(){

    char string[10];int n,pos,p;clrscr();

    puts("Enter the string");gets(string);printf("Enter the position from where to delete");scanf("%d",&pos);printf("Enter the number of characters to be deleted");scanf("%d",&n);delchar(string, n,pos);getch();

    }

    // Function to delete n charactersvoid delchar(char *x,int a, int b){if ((a1)

  • 7/29/2019 CDS Lab Programs

    23/86

    CP LAB MANUAL (B.TECH I YEAR)

    12/* Write a C program to determine if the given string is a palindrome or not */

    #include#include

    enum Boolean{false,true};enum Boolean IsPalindrome(char string[]){int left,right,len=strlen(string);enum Boolean matched=true;if(len==0)return 0;left=0;right=len-1;

    /* Compare the first and last letter,second & second last & so on */while(left

  • 7/29/2019 CDS Lab Programs

    24/86

    CP LAB MANUAL (B.TECH I YEAR)

    14

    /* Write a C program to count the lines, words and characters in a given text*/

    Program#include

    main()

    {char line[81], ctr;

    int i,c,

    end = 0,

    characters = 0,words = 0,

    lines = 0;

    printf("KEY IN THE TEXT.\n");

    printf("GIVE ONE SPACE AFTER EACH WORD.\n");printf("WHEN COMPLETED, PRESS 'RETURN'.\n\n");

    while( end == 0){

    /* Reading a line of text */

    c = 0;

    while((ctr=getchar()) != '\n')line[c++] = ctr;

    line[c] = '\0';

    /* counting the words in a line */if(line[0] == '\0')

    break ;

    else{

    words++;

    for(i=0; line[i] != '\0';i++)if(line[i] == ' ' || line[i] == '\t')

    words++;

    }

    /* counting lines and characters */lines = lines +1;

    characters = characters + strlen(line);

    }printf ("\n");

    printf("Number of lines = %d\n", lines);

    printf("Number of words = %d\n", words);printf("Number of characters = %d\n", characters);

    }

    Output

    KEY IN THE TEXT.

    Page 24 of 86

  • 7/29/2019 CDS Lab Programs

    25/86

    CP LAB MANUAL (B.TECH I YEAR)

    GIVE ONE SPACE AFTER EACH WORD.

    WHEN COMPLETED, PRESS 'RETURN'.

    Admiration is a very short-lived passion.Admiration involves a glorious obliquity of vision.

    Always we like those who admire us but we do not

    like those whom we admire.Fools admire, but men of sense approve.

    Number of lines = 5

    Number of words = 36Number of characters = 205

    Page 25 of 86

  • 7/29/2019 CDS Lab Programs

    26/86

    CP LAB MANUAL (B.TECH I YEAR)

    13/* Write a C program that displays the position or index in the string S

    where the string T begins, or - 1 if S doesn't contain T.*/

    #include#include#include

    void main(){char s[30], t[20];char *found;clrscr();

    /* Entering the main string */puts("Enter the first string: ");gets(s);

    /* Entering the string whose position or index to be displayed */puts("Enter the string to be searched: ");gets(t);

    /*Searching string t in string s */found=strstr(s,t);if(found)printf("Second String is found in the First String at %d position.\n",found-

    s);elseprintf("-1");

    getch();}

    Page 26 of 86

  • 7/29/2019 CDS Lab Programs

    27/86

    CP LAB MANUAL (B.TECH I YEAR)

    15/* Write a C program to generate Pascal's triangle. */

    #include#include

    void main(){int bin,p,q,r,x;clrscr();bin=1;q=0;

    printf("Rows you want to input:");scanf("%d",&r);

    printf("\nPascal's Triangle:\n");

    while(q0;--p)printf(" ");for(x=0;x

  • 7/29/2019 CDS Lab Programs

    28/86

    CP LAB MANUAL (B.TECH I YEAR)

    16 /* Write a C program to construct a pyramid of numbers. */

    #include#include

    void main(){int num,i,y,x=35;clrscr();printf("\nEnter the number to generate the pyramid:\n");scanf("%d",&num);

    for(y=0;y

  • 7/29/2019 CDS Lab Programs

    29/86

    CP LAB MANUAL (B.TECH I YEAR)

    17/*Write a C program to read in two numbers, x and n, and then compute the sum ofthis geometric progression:1+x+x2+x3+.+xn For example: if n is 3 and x is 5, then the program computes1+5+25+125. Print x, n, the sum Perform error checking. For example, the

    formula does not make sense for negative exponents - if n is less than 0. Haveyour program print an error message if n

  • 7/29/2019 CDS Lab Programs

    30/86

    CP LAB MANUAL (B.TECH I YEAR)

    18/* 2s complement of a number is obtained by scanning it from right to left andcomplementing all the bits after the first appearance of a 1. Thus 2scomplement of 11100 is 00100. Write a C program to find the 2s complement of a

    binary number.*/

    #include #include

    void complement (char *a);void main(){char a[16];int i;clrscr();printf("Enter the binary number");gets(a);for(i=0;a[i]!='\0'; i++){if (a[i]!='0' && a[i]!='1'){printf("The number entered is not a binary number. Enter the correct

    number");exit(0);}}complement(a);getch();}void complement (char *a){int l, i, c=0;

    char b[16];l=strlen(a);for (i=l-1; i>=0; i--){if (a[i]=='0')b[i]='1';elseb[i]='0';}for(i=l-1; i>=0; i--){if(i==l-1){if (b[i]=='0')b[i]='1';else{b[i]='0';c=1;}}else{

    Page 30 of 86

  • 7/29/2019 CDS Lab Programs

    31/86

    CP LAB MANUAL (B.TECH I YEAR)

    if(c==1 && b[i]=='0'){b[i]='1';c=0;}else if (c==1 && b[i]=='1'){b[i]='0';c=1;}}}b[l]='\0';printf("The 2's complement is %s", b);}

    Page 31 of 86

  • 7/29/2019 CDS Lab Programs

    32/86

    CP LAB MANUAL (B.TECH I YEAR)

    19 * Write a C program to convert a Roman numeral to its decimal equivalent. */

    #include#include#include

    #include

    void main(){

    int *a,len,i,j,k;char *rom;

    clrscr();

    printf("Enter the Roman Numeral:");scanf("%s",rom);

    len=strlen(rom);

    for(i=0;i0;i--){

    if(a[i]>a[i-1])k=k-a[i-1];else if(a[i]==a[i-1] || a[i]

  • 7/29/2019 CDS Lab Programs

    33/86

    CP LAB MANUAL (B.TECH I YEAR)

    20/* Write a C program that uses functions to perform the following operations:

    i) Reading a complex number

    ii) Writing a complex numberiii) Addition of two complex numbersiv) Multiplication of two complex numbers

    (Note: represent complex number using a structure.) */

    #include#include

    void arithmetic(int opern);

    struct comp{

    double realpart;

    double imgpart;};

    void main(){

    int opern;clrscr();printf("\n\n \t\t\t***** MAIN MENU *****");printf("\n\n Select your option: \n 1 : ADD\n 2 : MULTIPLY\n 0 : EXIT

    \n\n\t\t Enter your Option [ ]\b\b");

    scanf("%d",&opern);

    switch(opern)

    {case 0:

    exit(0);case 1:case 2:

    arithmetic(opern);default:

    main();}

    }

    void arithmetic(int opern)

    {

    struct comp w1, w2, w;

    printf("\n Enter two Complex Numbers (x+iy):\n Real Part of FirstNumber:");

    scanf("%lf",&w1.realpart);printf("\n Imaginary Part of First Number:");scanf("%lf",&w1.imgpart);printf("\n Real Part of Second Number:");

    Page 33 of 86

  • 7/29/2019 CDS Lab Programs

    34/86

    CP LAB MANUAL (B.TECH I YEAR)

    scanf("%lf",&w2.realpart);printf("\n Imaginary Part of Second Number:");scanf("%lf",&w2.imgpart);

    switch(opern){

    /*addition of complex number*/case 1:

    w.realpart = w1.realpart+w2.realpart;w.imgpart = w1.imgpart+w2.imgpart;break;

    /*multiplication of complex number*/case 2:

    w.realpart=(w1.realpart*w2.realpart)-(w1.imgpart*w2.imgpart);w.imgpart=(w1.realpart*w2.imgpart)+(w1.imgpart*w2.realpart);break;

    }

    if (w.imgpart>0)printf("\n Answer = %lf+%lfi",w.realpart,w.imgpart);

    elseprintf("\n Answer = %lf%lfi",w.realpart,w.imgpart);

    getch();main();

    }

    Page 34 of 86

  • 7/29/2019 CDS Lab Programs

    35/86

    CP LAB MANUAL (B.TECH I YEAR)

    21/* Write a C program which copies one file to another.*/

    #include #include

    #include

    void main(int argc, char *argv[]){FILE *fs,*ft;char ch;clrscr();if(argc!=3){puts("Invalid number of arguments.");exit(0);}fs = fopen(argv[1],"r");if(fs==NULL){puts("Source file cannot be opened.");exit(0);}ft = fopen(argv[2],"w");if (ft==NULL){puts("Target file cannot be opened.");fclose(fs);exit(0);}while(1){

    ch=fgetc(fs);if (ch==EOF)break;elsefputc(ch,ft);}fclose(fs);fclose(ft);getch();

    }

    Page 35 of 86

  • 7/29/2019 CDS Lab Programs

    36/86

    CP LAB MANUAL (B.TECH I YEAR)

    22/* Write a C program to reverse the first n characters in a file.(Note: The file name and n are specified on the command line.)*/

    #include #include #include #include

    void main(int argc, char *argv[]){char a[15];char s[20];char n;int k;int j=0;int i;int len;FILE *fp;

    if(argc!=3){puts("Improper number of arguments.");exit(0);}fp = fopen(argv[1],"r");if(fp == NULL){puts("File cannot be opened.");exit(0);}

    k=*argv[2]-48;n = fread(a,1,k,fp);a[n]='\0';len=strlen(a);for(i=len-1;i>=0;i--){s[j]=a[i];printf("%c",s[j]);j=j+1;

    }s[j+1]='\0';getch();}

    Page 36 of 86

  • 7/29/2019 CDS Lab Programs

    37/86

    CP LAB MANUAL (B.TECH I YEAR)

    23/* Write a program to create a linear linked list interactively and print outthe list and the total number of items in the list. */

    #include #include #define NULL 0

    struct linked_list{

    int number;struct linked_list *next;

    };typedef struct linked_list node; /* node type defined */

    main(){

    node *head;void create(node *p);

    int count(node *p);void print(node *p);head = (node *)malloc(sizeof(node));create(head);printf("\n");printf(head);printf("\n");printf("\nNumber of items = %d \n", count(head));

    }void create(node *list){

    printf("Input a number\n");printf("(type -999 at end): ");scanf("%d", &list -> number); /* create current node */

    if(list->number == -999){

    list->next = NULL;}

    else /*create next node */{

    list->next = (node *)malloc(sizeof(node));create(list->next); */ Recursion occurs */

    }return;

    }

    void print(node *list){

    if(list->next != NULL){printf("%d-->",list ->number); /* print current item */

    if(list->next->next == NULL)

    printf("%d", list->next->number);

    print(list->next); /* move to next item */

    Page 37 of 86

  • 7/29/2019 CDS Lab Programs

    38/86

    CP LAB MANUAL (B.TECH I YEAR)

    }return;

    }

    int count(node *list){

    if(list->next == NULL)return (0);

    elsereturn(1+ count(list->next));

    }

    Output

    Input a number(type -999 to end); 60Input a number(type -999 to end); 20Input a number(type -999 to end); 10

    Input a number(type -999 to end); 40Input a number(type -999 to end); 30Input a number(type -999 to end); 50Input a number(type -999 to end); -999

    60 -->20 -->10 -->40 -->30 -->50 --> -999

    Number of items = 6

    /* Write a function for deleting an item from linked list */

    node *delete(node *head){

    node *find(node *p, int a);int key; /* item to be deleted */node *n1; /* pointer to node preceding key node */node *p; /* temporary pointer */printf("\n What is the item (number) to be deleted?");scanf("%d", &key);

    if(head->number == key) /* first node to be deleted) */{

    p = head->next; /* pointer to 2nd node in list */free(head); /* release space of key node */head = p; /* make head to point to 1st node */

    }else{

    n1 = find(head, key);if(n1 == NULL)

    Page 38 of 86

  • 7/29/2019 CDS Lab Programs

    39/86

    CP LAB MANUAL (B.TECH I YEAR)

    printf("\n key not found \n");else /* delete key node */{

    p = n1->next->next; /* pointer to the nodefollowing the keynode */

    free(n1->next); /* free key node */n1->next = p; /* establish link */

    }}return(head);

    }/* USE FUNCTION find() HERE */

    /* Write a function for inserting an item into a linked list */

    node *insert(node *head){

    node *find(node *p, int a);node *new; /* pointer to new node */node *n1; /* pointer to node preceding key node */int key;int x; /* new item (number) to be inserted */

    printf("Value of new item?");scanf("%d", &x);printf("Value of key item ? (type -999 if last) ");scanf("%d", &key);

    if(head->number == key) /* new node is first */{

    new = (node *)malloc(size of(node));new->number = x;new->next = head;head = new;

    }else /* find key node and insert new node */{ /* before the key node */

    n1 = find(head, key); /* find key node */

    if(n1 == NULL)printf("\n key is not found \n");

    else /* insert new node */{new = (node *)malloc(sizeof(node));new->number = x;new->next = n1->next;n1->next = new;}

    }

    Page 39 of 86

  • 7/29/2019 CDS Lab Programs

    40/86

    CP LAB MANUAL (B.TECH I YEAR)

    return(head);}node *find(node *lists, int key){

    if(list->next->number == key) /* key found */return(list);

    else

    if(list->next->next == NULL) /* end */return(NULL);

    elsefind(list->next, key);

    }

    /* Write a program for creation of sorted list from a given list of numbers */

    #include #include #define NULL 0

    struct linked_list{

    int number;struct linked_list *next;

    };typedef struct linked_list node;

    main (){

    int n;node *head = NULL;void print(node *p);node *insert_Sort(node *p, int n);

    printf("Input the list of numbers.\n");printf("At end, type -999.\n");scanf("%d",&n);

    while(n != -999){

    if(head == NULL) /* create 'base' node */

    {head = (node *)malloc(sizeof(node));head ->number = n;head->next = NULL;

    }

    else /* insert next item */{

    head = insert_sort(head,n);

    Page 40 of 86

  • 7/29/2019 CDS Lab Programs

    41/86

    CP LAB MANUAL (B.TECH I YEAR)

    }scanf("%d", &n);

    }printf("\n");print(head);print("\n");

    }node *insert_sort(node *list, int x){

    node *p1, *p2, *p;p1 = NULL;p2 = list; /* p2 points to first node */

    for( ; p2->number < x ; p2 = p2->next){

    p1 = p2;

    if(p2->next == NULL){

    p2 = p2->next; /* p2 set to NULL */

    break; /* insert new node at end */}

    }

    /* key node found */p = (node *)malloc(sizeof(node)); /* space for new node */p->number = x; /* place value in the new node */p->next = p2; /* link new node to key node */if (p1 == NULL)

    list = p; /* new node becomes the first node */else

    p1->next = p; /* new node inserted after 1st node */return (list);

    }void print(node *list){

    if (list == NULL)printf("NULL");

    else{

    printf("%d-->",list->number);print(list->next);

    }return;

    }

    Output

    Input the list of number.At end, type -999.80 70 50 40 60 -99940-->50-->60-->70-->80 -->NULLInput the list of number.At end, type -999.40 70 50 60 80 -99940-->50-->60-->70-->80-->NULL

    Page 41 of 86

  • 7/29/2019 CDS Lab Programs

    42/86

    CP LAB MANUAL (B.TECH I YEAR)

    24/* Write a C program that uses functions to perform the following operations ondoubly linked list.:

    i) Creation ii) Insertion iii) Deletion iv) Traversal in both ways */

    #include "stdio.h"#include "alloc.h"

    typedef struct dubll{int data;struct dubll *leftlink,*rightlink;}*DUBLL;

    DUBLL high,temp_node,low,last,pntr;int flag=0;

    DUBLL NodeAlloc();DUBLL Search(int,int);

    void CreateItem();void AppendItem();void PrintItem();void DeleteItem();DUBLL Search(int item,int flag);DUBLL NodeAlloc();void InsertItem();

    void main(void){int choice,Item;high=NULL;while(1){clrscr();printf("\n \t\t\t***** M A I N M E N U *****\n\n");printf("\n 1: Create Linked List \n 2: Append a Node to the List \n 3:

    Traverse the List \n 4: Delete a Node from the List \n 5: Search a Node \n 6:Insert a Node to the List \n 7: Close \n\n\t\t Enter your Option [ ]\b\b");scanf("%d",&choice);switch(choice){case 1:

    CreateItem();puts("\nPress any key to go back to main menu.");

    getch();

    break;case 2:

    AppendItem();break;

    case 3:PrintItem();puts("\nPress any key to go back to main menu.");getch();

    break;case 4:

    Page 42 of 86

  • 7/29/2019 CDS Lab Programs

    43/86

    CP LAB MANUAL (B.TECH I YEAR)

    DeleteItem();break;

    case 5:printf("Find an Item: ");scanf("%d",&Item);temp_node=Search(Item,0);if(temp_node){

    puts("The item is available in the Linked List.");}else

    {puts("The item is not found in the Linked List.");}getch();

    break;case 6:

    InsertItem();break;

    case 7:

    exit();default:

    puts("Invalid choice.");puts("\nPress any key to go back to main menu.");

    getch();break;

    }}

    }

    /* Function to Create the list*/

    void CreateItem(){

    if(high==NULL){printf("\n --Creating the list--");temp_node=NodeAlloc();printf("\n Enter starting data (as integer value) :");scanf("%d",&temp_node->data);high=temp_node;}else{ printf("\n List already created @ %d with %d as data.",high,high-

    >data);}}

    /* Function to Append items to the list*/void AppendItem()

    {low=high;if(high==NULL){CreateItem();

    }else{temp_node=NodeAlloc();printf("\n Enter Item (in integer) :");

    Page 43 of 86

  • 7/29/2019 CDS Lab Programs

    44/86

    CP LAB MANUAL (B.TECH I YEAR)

    scanf("%d",&temp_node->data);temp_node->rightlink=NULL;

    while(low->rightlink!=NULL)low=low->rightlink;low->rightlink=temp_node;temp_node->leftlink=low;last=low->rightlink;

    }}

    /* Function to Traverse the list both ways and print the data*/void PrintItem(){

    DUBLL temp_node;if(high==NULL){printf("\n List is not available. Please create a list first.");getch();

    CreateItem();}temp_node=high;last=low->rightlink;printf("\n--Printing The List In Forward direction--\n");

    while(temp_node!=NULL) //In forward direction{printf("\t %d",temp_node->data);temp_node = temp_node->rightlink;}

    printf("\n");printf("\n--Printing The List In Backward direction--\n");

    temp_node=high;if(temp_node->rightlink==NULL){printf("%d",temp_node->data);return; }

    while(last!=NULL) //In backward direction{printf("\t %d",last->data);last = last->leftlink;}

    }

    /* Function to Delete items of the list*/void DeleteItem(){int value;DUBLL temp_node;

    if(high==NULL){printf("\n List is not available. Please create a list first.");getch();CreateItem();

    }printf("\n Item to delete :");scanf("%d",&value);pntr=Search(value,1);pntr->leftlink->rightlink=pntr->rightlink;

    Page 44 of 86

  • 7/29/2019 CDS Lab Programs

    45/86

    CP LAB MANUAL (B.TECH I YEAR)

    pntr->rightlink->leftlink=pntr->leftlink;temp_node=pntr;free(temp_node);}

    /* Function to Search an item from the list*/DUBLL Search(int item,int flag){

    temp_node = high;if(high==NULL){printf("\n List is not available. Please create a list first.");getch();CreateItem();

    }while(temp_node!=NULL){if(temp_node->data==item ){if(flag==0)

    {return(1);

    }else{return(temp_node);}

    }temp_node=temp_node->rightlink;}

    }

    /* Function to Allocate nodes*/

    DUBLL NodeAlloc(){DUBLL tmep_node;tmep_node=malloc(sizeof(struct dubll));if(tmep_node==NULL){printf("\n No memory available. Node allocation cannot be done.");}tmep_node->rightlink=tmep_node->leftlink=NULL;

    return(tmep_node);}

    /* Function to Insert items in the middle of the list*/void InsertItem()

    {int node;DUBLL temp_node;

    if(high==NULL){printf("\n List is not available. Please create a list first.");getch();CreateItem();

    }

    Page 45 of 86

  • 7/29/2019 CDS Lab Programs

    46/86

    CP LAB MANUAL (B.TECH I YEAR)

    temp_node=NodeAlloc();printf("Position At which node to be inserted: ___ & New Item Value: ___ ");scanf("%d",&node);scanf("%d",&temp_node->data);pntr=Search(node,1);

    if(pntr->rightlink==NULL){printf("\n The operation is not possible.");getch();return;}

    temp_node->leftlink=pntr; //creating link to new nodetemp_node->rightlink=pntr->rightlink;

    pntr->rightlink->leftlink=temp_node;pntr->rightlink=temp_node;

    printf("\n Item has been Inserted.");getch();

    }

    Page 46 of 86

  • 7/29/2019 CDS Lab Programs

    47/86

    CP LAB MANUAL (B.TECH I YEAR)

    25 A)/* Write C programs that implement stack (its operations) using i) Arrays */

    #include#include

    int st_arr[20];int t=-1;

    void push_ele(int ele);int pop_ele();void display_ele();

    void main(){char choice,num1=0,num2=0;while(1){clrscr();

    printf("======================================");printf("\n\t\t MENU ");printf("\n======================================");printf("\n[1] Using Push Function");printf("\n[2] Using Pop Function");printf("\n[3] Elements present in Stack");printf("\n[4] Exit\n");printf("\n\tEnter your choice: ");fflush(stdin);scanf("%c",&choice);

    switch(choice-'0'){

    case 1:{printf("\n\tElement to be pushed: ");scanf("%d",&num1);push_ele(num1);break;}

    case 2:{num2=pop_ele(1);printf("\n\tElement to be popped: %d\n\t",num2);getch();

    break;}

    case 3:{display_ele();getch();break;}

    Page 47 of 86

  • 7/29/2019 CDS Lab Programs

    48/86

    CP LAB MANUAL (B.TECH I YEAR)

    case 4:exit(1);break;

    default:printf("\nYour choice is invalid.\n");break;

    }}

    }

    /*Implementing the push() function. */void push_ele(int ele){if(t==99){printf("STACK is Full.\n");getch();exit(1);

    }

    st_arr[++t]=ele;}

    /*Implementing the pop() function. */int pop_ele(){int ele1;if(t==-1){printf("\n\tSTACK is Empty.\n");getch();exit(1);

    }return(st_arr[t--]);

    }

    /*Implementing display() function. */void display_ele(){int k;printf("\n\tElements present in the stack are:\n\t");for(k=0;k

  • 7/29/2019 CDS Lab Programs

    49/86

    CP LAB MANUAL (B.TECH I YEAR)

    *t;int i;

    void push_ele(int j);int pop_ele();void display_ele();

    void main(){char choice,num1=0,num2=0;int i;while(1){clrscr();printf("======================================");printf("\n\t\t MENU ");printf("\n======================================");printf("\n[1] Using Push Function");printf("\n[2] Using Pop Function");

    printf("\n[3] Elements present in Stack");printf("\n[4] Exit\n");printf("\n\tEnter your choice: ");fflush(stdin);scanf("%c",&choice);

    switch(choice-'0'){case 1:{printf("\n\tElement to be pushed:");scanf("%d",&num1);push_ele(num1);break;}

    case 2:{num2=pop_ele(1);printf("\n\tElement to be popped: %d\n\t",num2);getch();break;}

    case 3:{printf("\n\tElements present in the stack are:\n\t");

    display_ele();getch();break;}

    case 4:exit(1);break;

    default:

    Page 49 of 86

  • 7/29/2019 CDS Lab Programs

    50/86

    CP LAB MANUAL (B.TECH I YEAR)

    printf("\nYour choice is invalid.\n");break;

    }}

    }

    /*Inserting the elements using push function*/void push_ele(int j){struct st_point *m;m=(struct st_point*)malloc(sizeof(struct st_point));m->ele=j;m->l=t;t=m;return;

    }

    /*Removing the elements using pop function*/int pop_ele(){

    if(t==NULL){printf("\n\STACK is Empty.");getch();exit(1);

    }else{int i=t->ele;t=t->l;return (i);

    }return 0;}

    /*Displaying the elements */void display_ele(){struct st_point *pointer=NULL;pointer=t;while(pointer!=NULL){printf("%d\t",pointer->ele);pointer=pointer->l;

    }}

    Page 50 of 86

  • 7/29/2019 CDS Lab Programs

    51/86

    CP LAB MANUAL (B.TECH I YEAR)

    26 A)/* Write C programs that implement Queue (its operations) using i) Arrays */

    #include#include#include#define size 10#define true 1#define false 0

    struct q_arr{int f,r;int num;int a[size];

    };

    void init(struct q_arr* queue);int e_que(struct q_arr* queue);

    int f_que(struct q_arr* queue);int add_ele(struct q_arr* queue,int);int rem_ele(struct q_arr* queue);void display_ele(struct q_arr* queue);

    /*main function*/void main(){int ele,k;int ch;

    struct q_arr *queue = (struct q_arr*)malloc(sizeof(struct q_arr));init(queue);

    while(1){clrscr();printf("\n\n****IMPLEMENTATION OF QUEUE USING ARRAYS****\n");printf("============================================");printf("\n\t\tMENU\n");printf("============================================");printf("\n\t[1] To insert an element");printf("\n\t[2] To remove an element");printf("\n\t[3] To display all the elements");printf("\n\t[4] Exit");printf("\n\n\t Enter your choice: ");scanf("%d",&ch);

    switch(ch){case 1:{printf("\nElement to be inserted:");scanf("%d",&ele);add_ele(queue,ele);break;}

    Page 51 of 86

  • 7/29/2019 CDS Lab Programs

    52/86

    CP LAB MANUAL (B.TECH I YEAR)

    case 2:{if(!e_que(queue)){k=rem_ele(queue);printf("\n%d element is removed\n",k);getch();

    }else{printf("\tQueue is Empty. No element can be removed.");getch();

    }break;}

    case 3:{display_ele(queue);

    getch();break;}

    case 4:exit(0);

    default:printf("\tInvalid Choice.");getch();break;

    }}

    }/*end main*/

    void init(struct q_arr* queue){queue->f = 0;queue->r = -1;queue->num = 0;

    }

    /* Function to check is the queue is empty*/int e_que(struct q_arr* queue){if(queue->num==0)

    return true;return false;

    }

    /* Function to check if the queue is full*/int f_que(struct q_arr* queue){if(queue->num == size)return true;return false;

    Page 52 of 86

  • 7/29/2019 CDS Lab Programs

    53/86

    CP LAB MANUAL (B.TECH I YEAR)

    }

    /* Function to add an element to the queue*/int add_ele(struct q_arr* queue,int j){if(f_que(queue))return false;

    if(queue->r == size - 1)queue->r = -1;queue->a[++queue->r] = j;queue->num++;return true;

    }

    /* Function to remove an element of the queue*/int rem_ele(struct q_arr* queue){int j;if(e_que(queue))

    return -9999;j = queue->a[queue->f++];if(queue->f == size)queue->f = 0;queue->num--;return j;

    }

    /* Function to display the queue*/void display_ele(struct q_arr* queue){int j;if(e_que(queue)){printf("Queue is Empty. No records to display.");return;

    }printf("\nElements present in the Queue are: ");for(j=queue->f;jr;j++)printf("%d\t",queue->a[j]);printf("\n");

    }

    Page 53 of 86

  • 7/29/2019 CDS Lab Programs

    54/86

    CP LAB MANUAL (B.TECH I YEAR)

    26 B) /* Write C programs that implement Queue (its operations) using ii)Pointers */

    #define true 1#define false 0

    #include#include#include

    struct q_point{int ele;struct q_point* n;

    };

    struct q_point *f_ptr = NULL;

    int e_que(void);void add_ele(int);int rem_ele(void);void show_ele();

    /*main function*/void main(){int ele,choice,j;while(1){clrscr();printf("\n\n****IMPLEMENTATION OF QUEUE USING POINTERS****\n");printf("==============================================");printf("\n\t\t MENU\n");printf("==============================================");printf("\n\t[1] To insert an element");printf("\n\t[2] To remove an element");printf("\n\t[3] To display all the elements");printf("\n\t[4] Exit");printf("\n\n\tEnter your choice:");scanf("%d", &choice);

    switch(choice){case 1:

    {printf("\n\tElement to be inserted:");scanf("%d",&ele);add_ele(ele);getch();break;}

    case 2:{

    Page 54 of 86

  • 7/29/2019 CDS Lab Programs

    55/86

    CP LAB MANUAL (B.TECH I YEAR)

    if(!e_que()){j=rem_ele();printf("\n\t%d is removed from the queue",j);getch();

    }else{printf("\n\tQueue is Empty.");getch();

    }break;}

    case 3:show_ele();getch();break;

    case 4:

    exit(1);break;

    default:printf("\n\tInvalid choice.");getch();break;

    }

    }}

    /* Function to check if the queue is empty*/int e_que(void){if(f_ptr==NULL)return true;return false;

    }

    /* Function to add an element to the queue*/void add_ele(int ele){struct q_point *queue = (struct q_point*)malloc(sizeof(struct q_point));queue->ele = ele;queue->n = NULL;if(f_ptr==NULL)

    f_ptr = queue;else{struct q_point* ptr;ptr = f_ptr;for(ptr=f_ptr ;ptr->n!=NULL; ptr=ptr->n);ptr->n = queue;

    }}

    Page 55 of 86

  • 7/29/2019 CDS Lab Programs

    56/86

    CP LAB MANUAL (B.TECH I YEAR)

    /* Function to remove an element from the queue*/int rem_ele(){struct q_point* queue=NULL;if(e_que()==false){int j = f_ptr->ele;queue=f_ptr;f_ptr = f_ptr->n;free (queue);return j;

    }else{printf("\n\tQueue is empty.");return -9999;

    }}

    /* Function to display the queue*/

    void show_ele(){struct q_point *ptr=NULL;ptr=f_ptr;if(e_que()){printf("\n\tQUEUE is Empty.");return;

    }else{printf("\n\tElements present in Queue are:\n\t");while(ptr!=NULL){printf("%d\t",ptr->ele);ptr=ptr->n;

    }}

    }

    Page 56 of 86

  • 7/29/2019 CDS Lab Programs

    57/86

    CP LAB MANUAL (B.TECH I YEAR)

    27/* Write a C program that uses Stack operations to perform the following:

    i) Converting infix expression into postfix expressionii) Evaluating the postfix expression */

    #include#include

    int st[100];int st_top=-1;

    int cal(char post[]);void in_post(char in[]);void push_item(int it);int pop_item();int st_ISP(char t);int st_ICP(char t);

    /*main function*/

    void main(){char in[100],post[100];clrscr();printf("\n\tEnter the Infix Expression: ");gets(in);in_post(in);getch();

    }/*end main*/

    void push_item(int it){if(st_top==99){printf("\n\n\t*STACK is Full*");getch();exit(1);

    }st[++st_top]=it;

    }

    int pop_item(){int it;if(st_top==-1){

    getch();}return(st[st_top--]);

    }

    /*Function for converting an infix expression to a postfix expression. */void in_post(char in[]){int x=0,y=0,z,result=0;char a,c, post[100];

    Page 57 of 86

  • 7/29/2019 CDS Lab Programs

    58/86

    CP LAB MANUAL (B.TECH I YEAR)

    char t;push_item('\0');t=in[x];while(t!='\0'){if(isalnum(t))/*For checking whether the value in t is an alphabet or number. */{post[y]=t;y++;

    }else if(t=='('){push_item('(');

    }else if(t==')'){while(st[st_top]!='('){c=pop_item();

    post[y]=c;y++;}

    c=pop_item();}else{while(st_ISP(st[st_top])>=st_ICP(t)){c=pop_item();post[y]=c;y++;}push_item(t);

    }x++;t=in[x];

    }

    while(st_top!=-1){c=pop_item();post[y]=c;y++;

    }printf("\n\tThe Postfix Expression is:");

    for(z=0;z

  • 7/29/2019 CDS Lab Programs

    59/86

    CP LAB MANUAL (B.TECH I YEAR)

    else if(a=='n' || a=='N'){exit(0);

    }}

    /*Determining priority of inside elements*/int st_ISP(char t){switch(t){case '(':return (10);case ')':return (9);case '+':return (7);case '-':return (7);case '*':return (8);case '/':return (8);case '\0':return (0);default: printf("Expression is invalid.");break;

    }return 0;

    }

    /*Determining priority of approaching elements*/int st_ICP(char t){switch(t){

    case '(':return (10);case ')':return (9);case '+':return (7);case '-':return (7);case '*':return (8);case '/':return (8);case '\0':return (0);default: printf("Expression is invalid.");break;

    }return 0;

    }

    /*Evaluating the result of postfix expression*/int cal(char post[]){int m,n,x,y,j=0,len;

    len=strlen(post);while(j

  • 7/29/2019 CDS Lab Programs

    60/86

    CP LAB MANUAL (B.TECH I YEAR)

    m=pop_item();n=pop_item();

    switch(post[j]){case '+':x=n+m;break;case '-':x=n-m;break;case '*':x=n*m;break;case '/':x=n/m;break;}push_item(x);

    }j++;

    }if(st_top>0){

    printf("Number of Operands are more than Operators.");exit(0);

    }else{y=pop_item();return (y);

    }return 0;

    }

    Page 60 of 86

  • 7/29/2019 CDS Lab Programs

    61/86

    CP LAB MANUAL (B.TECH I YEAR)

    28/* Write a C program that uses functions to perform the following:

    i) Creating a Binary Tree of integersii) Traversing the above binary tree in preorder, inorder and postorder. */

    #include#include #include

    struct treenode{int ele;struct treenode *l_child, *r_child;

    };

    struct treenode *insert_node(struct treenode *t,int a);void TraverseInorder(struct treenode *t);void TraversePreorder(struct treenode *t);void TraversePostorder(struct treenode *t);

    /*main function*/void main(){struct treenode *root_node = NULL;int num,value;int choice;

    clrscr();

    printf("----------------------------------------------------\n");printf("\t\t\tMENU\n");printf("-----------------------------------------------------\n");printf("[1] Create a Binary Tree and Use Inorder Traversal\n");printf("[2] Create a Binary Tree and Use Preorder Traversal\n");printf("[3] Create a Binary Tree and Use Postorder Traversal\n");printf("-----------------------------------------------------\n");printf("Enter your choice:");scanf("%d",&choice);

    if(choice>0 & choice 0){

    printf("\n\nEnter the data value:");scanf("%d",&value);root_node = insert_node(root_node,value);

    }

    switch(choice){case 1:

    printf("\n\nBinary tree using Inorder Traversal : ");TraverseInorder(root_node);

    Page 61 of 86

  • 7/29/2019 CDS Lab Programs

    62/86

    CP LAB MANUAL (B.TECH I YEAR)

    getch();break;

    case 2:printf("\n\nBinary tree using Preorder Traversal : ");TraversePreorder(root_node);getch();break;

    case 3:printf("\n\nBinary tree using Postorder Traversal : ");TraversePostorder(root_node);getch();break;

    default:printf("Invalid Choice");break;

    }}

    }/*end main*/

    /* Function to create a Binary Tree of integers data */struct treenode *insert_node(struct treenode *t,int a){struct treenode *temp_node1,*temp_node2;if(t == NULL){

    t = (struct treenode *) malloc(sizeof(struct treenode));if(t == NULL){printf("Value cannot be allocated.\n");exit(0);}t->ele = a;t->l_child=t->r_child=NULL;

    }else{temp_node1 = t;

    while(temp_node1 != NULL){temp_node2 = temp_node1;if( temp_node1 ->ele > a)temp_node1 = temp_node1->l_child;

    elsetemp_node1 = temp_node1->r_child;}if( temp_node2->ele > a){temp_node2->l_child = (struct treenode*)malloc(sizeof(struct treenode));temp_node2 = temp_node2->l_child;if(temp_node2 == NULL){printf("Value cannot be allocated.\n");

    Page 62 of 86

  • 7/29/2019 CDS Lab Programs

    63/86

    CP LAB MANUAL (B.TECH I YEAR)

    exit(0);}temp_node2->ele = a;temp_node2->l_child=temp_node2->r_child = NULL;

    }else{

    temp_node2->r_child = (struct treenode*)malloc(sizeof(struct treenode));

    temp_node2 = temp_node2->r_child;if(temp_node2 == NULL){printf("Value cannot be allocated.\n");exit(0);

    }temp_node2->ele = a;temp_node2->l_child=temp_node2->r_child = NULL;

    }}return(t);

    }

    /* Function for Traversing the binary tree in inorder. */void TraverseInorder(struct treenode *t){if(t != NULL){TraverseInorder(t->l_child);printf("%d\t",t->ele);in_order(t->r_child);}}

    /* Function for Traversing the binary tree in preorder. */void TraversePreorder(struct treenode *t){if(t != NULL){printf("%d\t",t->ele);TraversePreorder(t->l_child);TraversePreorder(t->r_child);}

    }

    /* Function for Traversing the binary tree in postorder. */void TraversePostorder(struct treenode *t){

    if(t != NULL){TraversePostorder(t->l_child);TraversePostorder(t->r_child);printf("%d\t",t->ele);}}

    Page 63 of 86

  • 7/29/2019 CDS Lab Programs

    64/86

    CP LAB MANUAL (B.TECH I YEAR)

    29 B)

    /* Write C programs that use both recursive and non recursive functions toperform the following searching operations for a Key value in a given list ofintegers : ii) Binary search*/

    #include #define MAX_LEN 10

    /* Non-Recursive function*/void b_search_nonrecursive(int l[],int num,int ele){

    int l1,i,j, flag = 0;l1 = 0;i = num-1;while(l1

  • 7/29/2019 CDS Lab Programs

    65/86

    CP LAB MANUAL (B.TECH I YEAR)

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

    void print_list(int l[],int n){

    int i;for(i=0;i

  • 7/29/2019 CDS Lab Programs

    66/86

    CP LAB MANUAL (B.TECH I YEAR)

    } getch(); }29 A)/* Write C programs that use both recursive and non recursive functionsto perform the following searching operation for a Key value in a given list ofintegers :i) Linear search */

    #include #define MAX_LEN 10

    void l_search_recursive(int l[],int num,int ele);void l_search(int l[],int num,int ele);void read_list(int l[],int num);void print_list(int l[],int num);

    void main(){

    int l[MAX_LEN], num, ele;int ch;

    clrscr();

    printf("======================================================");printf("\n\t\t\tMENU");printf("\n=====================================================");printf("\n[1] Linary Search using Recursion method");printf("\n[2] Linary Search using Non-Recursion method");printf("\n\nEnter your Choice:");scanf("%d",&ch);

    if(ch0){printf("Enter the number of elements :");scanf("%d",&num);read_list(l,num);printf("\nElements present in the list are:\n\n");print_list(l,num);printf("\n\nElement you want to search:\n\n");scanf("%d",&ele);

    switch(ch){case 1:printf("\n**Recursion method**\n");

    l_search_recursive(l,num,ele);getch();break;

    case 2:printf("\n**Non-Recursion method**\n");l_search_nonrecursive(l,num,ele);getch();break;

    }}getch();

    }/*end main*/

    Page 66 of 86

  • 7/29/2019 CDS Lab Programs

    67/86

    CP LAB MANUAL (B.TECH I YEAR)

    /* Non-Recursive method*/void l_search_nonrecursive(int l[],int num,int ele){

    int j, f=0;for(j=0;j

  • 7/29/2019 CDS Lab Programs

    68/86

    CP LAB MANUAL (B.TECH I YEAR)

    30 A)

    /* Write C programs that implement the following sorting methods to sorta given list of integers in ascending order: i) Bubble sort */

    #include #define MAX 10

    void swapList(int *m,int *n){

    int temp;temp = *m;*m = *n;*n = temp;

    }

    // Function for Bubble Sortvoid bub_sort(int list[], int n){

    int i,j;for(i=0;i

  • 7/29/2019 CDS Lab Programs

    69/86

    CP LAB MANUAL (B.TECH I YEAR)

    30 B)/* Write C program that implement the following sorting methodsto sort a given list of integers in ascending order: ii) Quick sort */

    #include #define MAX 10

    void swap(int *m,int *n){

    int temp;temp = *m;*m = *n;*n = temp;

    }int get_key_position(int x,int y ){

    return((x+y) /2);

    }

    // Function for Quick Sortvoid quicksort(int list[],int m,int n){

    int key,i,j,k;if( m < n){

    k = get_key_position(m,n);swap(&list[m],&list[k]);key = list[m];i = m+1;j = n;while(i

  • 7/29/2019 CDS Lab Programs

    70/86

    CP LAB MANUAL (B.TECH I YEAR)

    // Function to print the datavoid print_data(int list[],int n){

    int j;for(j=0;j

  • 7/29/2019 CDS Lab Programs

    71/86

    CP LAB MANUAL (B.TECH I YEAR)

    31 A)

    /* Write C program that implement the following sorting methodsto sort a given list of integers in ascending order: i) Insertion sort */

    #include#include

    void inst_sort(int []);

    void main(){int num[5],count;clrscr();printf("\nEnter the Five Elements to sort:\n");

    for (count=0;count

  • 7/29/2019 CDS Lab Programs

    72/86

    CP LAB MANUAL (B.TECH I YEAR)

    31 B)

    /* Write C program that implement the following sorting methods to sort a givenlist of integers in ascending order:ii) Merge sort */

    #include #include

    #define MAX_ARY 10

    void merge_sort(int x[], int end, int start);

    int main(void) {int ary[MAX_ARY];int j = 0;

    printf("\n\nEnter the elements to be sorted: \n");for(j=0;j

  • 7/29/2019 CDS Lab Programs

    73/86

    CP LAB MANUAL (B.TECH I YEAR)

    executing[j] = x[end + j];

    mrg1 = 0;mrg2 = mid - end + 1;

    for(j = 0; j < size; j++) {if(mrg2

  • 7/29/2019 CDS Lab Programs

    74/86

    CP LAB MANUAL (B.TECH I YEAR)

    32 B)/* Write C program to implement the Newton- Gregory forward interpolation.*/

    #include#include#define MaxN 100#define Order_of_diff 4

    void main (){float arr_x[MaxN+1], arr_y[MaxN+1], numerator=1.0, denominator=1.0, x, y, p, h,diff_table[MaxN+1][Order_of_diff+1];int i,j,n,k;clrscr();

    printf("Enter the value of n \n");scanf("%d",&n);printf("Enter the values of x and y");

    for(i=0; i

  • 7/29/2019 CDS Lab Programs

    75/86

    CP LAB MANUAL (B.TECH I YEAR)

    33 A)

    /* Write C program to implement the linear regression algorithm. */

    #include#include#include#include

    float mean(float *a, int n);void deviation(float *a, float mean, int n, float *d, float *S);

    void main(){

    float a[20],b[20],dx[20],dy[20];float sy=0,sx=0,mean_x=0,mean_y=0,sum_xy=0;float corr_coff=0,reg_coff_xy=0, reg_coff_yx=0;char type_coff[7];

    int n=0,i=0;

    clrscr();

    printf("Enter the value of n: ");scanf("%d",&n);printf("Enter the values of x and y:\n");for(i=0;i

  • 7/29/2019 CDS Lab Programs

    76/86

    CP LAB MANUAL (B.TECH I YEAR)

    float mean(float *a, int n){

    float sum=0, i=0;for(i=0;i

  • 7/29/2019 CDS Lab Programs

    77/86

    CP LAB MANUAL (B.TECH I YEAR)

    34 A)

    /* Write C program to implement Simpson method. */

    #include#include#include

    char postfix[80];float stack[80];char stack1[80];int top=-1,top1=-1;float eval(char postfix[], float x1);void infix_postfix(char infix[]);

    main(){float x0, xn, h, s,e1,e2, e3;char exp[80], arr[80];int i,n,l=0;

    clrscr();printf("\nEnter an expression: ");gets(exp);puts("Enter x0, xn and number of sub-intervals: ");scanf("%f%f%d", &x0, &xn, &n);h=(xn-x0)/n;if(exp[0]=='l'&& exp[1]=='o'&& exp[2]=='g'){

    l=strlen(exp);for(i=0;i

  • 7/29/2019 CDS Lab Programs

    78/86

    CP LAB MANUAL (B.TECH I YEAR)

    exit(0);}else{top++;stack[top]=item;

    }return;}/*Removing the operands from a stack. */float pop(){float item;if(top==-1)

    {printf("\n\tThe stack is empty\n\t");getch();}item=stack[top];top--;

    return (item);}void push1(char item){if(top1==79){printf("\n\tThe stack is full");getch();exit(0);

    }else{top1++;stack1[top1]=item;

    }return;}/*Removing the operands from a stack. */char pop1(){char item;if(top1==-1){printf("\n\tThe stack1 is empty\n\t");getch();

    }item=stack1[top1];

    top1--;return (item);}/*Converting an infix expression to a postfix expression. */void infix_postfix(char infix[]){int i=0,j=0,k;char ch;char token;for(i=0;i

  • 7/29/2019 CDS Lab Programs

    79/86

    CP LAB MANUAL (B.TECH I YEAR)

    postfix[i]=' ';push1('?');i=0;token=infix[i];while(token!='\0'){if(isalnum(token)){postfix[j]=token;j++;

    }else if(token=='('){push1('(');

    }else if(token==')'){while(stack1[top1]!='('){ch=pop1();

    postfix[j]=ch;j++;

    }ch=pop1();}else{while(ISPriority(stack1[top1])>=ICP(token)){ch=pop1();postfix[j]=ch;j++;}

    push1(token);}i++;token=infix[i];}while(top1!=0){ch=pop1();postfix[j]=ch;j++;}postfix[j]='\0';}

    /*Determining the priority of elements that are placed inside the stack. */int ISPriority(char token){switch(token){case '(':return (0);case ')':return (9);case '+':return (7);case '-':return (7);case '*':return (8);

    Page 79 of 86

  • 7/29/2019 CDS Lab Programs

    80/86

    CP LAB MANUAL (B.TECH I YEAR)

    case '/':return (8);case '?':return (0);default: printf("Invalid expression");}return 0;}

    /*Determining the priority of elements that are approaching towards the stack.*/int ICP(char token){switch(token){case '(':return (10);case ')':return (9);case '+':return (7);case '-':return (7);case '*':return (8);case '/':return (8);case '\0':return (0);

    default: printf("Invalid expression");}

    return 0;}/*Calculating the result of expression, which is converted in postfix notation.*/float eval(char p[], float x1){float t1,t2,k,r;int i=0,l;l=strlen(p);while(i

  • 7/29/2019 CDS Lab Programs

    81/86

    CP LAB MANUAL (B.TECH I YEAR)

    push(k);}i++;}if(top>0){printf("You have entered the operands more than the operators");exit(0);}else{r=pop();return (r);}return 0;}

    Page 81 of 86

  • 7/29/2019 CDS Lab Programs

    82/86

    CP LAB MANUAL (B.TECH I YEAR)

    34 B)/* Write C program to implement Trapezoidal method.*/

    #include#include#include

    char postfix[80];float stack[80];char stack1[80];int top=-1,top1=-1;

    float eval(char postfix[], float x1);void infix_postfix(char infix[]);

    main(){float x0, xn, h, s,e1,e2;char exp[80], arr[80];int i,n,l=0;

    clrscr();printf("\nEnter an expression: ");gets(exp);puts("Enter x0, xn and number of subintervals");scanf("%f%f%d", &x0, &xn, &n);h=(xn-x0)/n;if(exp[0]=='l'&& exp[1]=='o'&& exp[2]=='g'){l=strlen(exp);for(i=0;i

  • 7/29/2019 CDS Lab Programs

    83/86

    CP LAB MANUAL (B.TECH I YEAR)

    }else{top++;stack[top]=item;}return;}/*Removing the operands from a stack. */float pop(){float item;if(top==-1){printf("\n\tThe stack is empty\n\t");getch();

    }item=stack[top];top--;return (item);

    }void push1(char item){if(top1==79){printf("\n\tThe stack is full");getch();exit(0);

    }else{top1++;stack1[top1]=item;}return;}/*Removing the operands from a stack. */char pop1(){char item;if(top1==-1){printf("\n\tThe stack1 is empty\n\t");getch();}item=stack1[top1];top1--;

    return (item);}

    /*Converting an infix expression to a postfix expression. */void infix_postfix(char infix[]){int i=0,j=0,k;char ch;char token;for(i=0;i

  • 7/29/2019 CDS Lab Programs

    84/86

    CP LAB MANUAL (B.TECH I YEAR)

    postfix[i]=' ';push1('?');i=0;token=infix[i];while(token!='\0'){if(isalnum(token)){postfix[j]=token;j++;}else if(token=='('){push1('(');}else if(token==')'){while(stack1[top1]!='('){ch=pop1();

    postfix[j]=ch;j++;

    }ch=pop1();}else{

    while(ISPriority(stack1[top1])>=ICP(token)){ch=pop1();

    /*Assigning the popped element into the postfix array. */postfix[j]=ch;j++;

    }push1(token);}i++;token=infix[i];}while(top1!=0){ch=pop1();postfix[j]=ch;j++;}postfix[j]='\0';

    }

    int ISPriority(char token){switch(token){case '(':return (0);case ')':return (9);case '+':return (7);case '-':return (7);

    Page 84 of 86

  • 7/29/2019 CDS Lab Programs

    85/86

    CP LAB MANUAL (B.TECH I YEAR)

    case '*':return (8);case '/':return (8);case '?':return (0);default: printf("Invalid expression");break;}return 0;}/*Determining the priority of elements that are approaching towards the stack.*/int ICP(char token){switch(token){

    case '(':return (10);case ')':return (9);case '+':return (7);case '-':return (7);case '*':return (8);case '/':return (8);

    case '\0':return (0);default: printf("Invalid expression");break;

    }return 0;}/*Calculating the result of expression, which is converted in postfix notation.*/float eval(char p[], float x1){float t1,t2,k,r;int i=0,l;l=strlen(p);while(i

  • 7/29/2019 CDS Lab Programs

    86/86

    CP LAB MANUAL (B.TECH I YEAR)

    default: printf("\n\tInvalid expression");break;}push(k);}i++;}if(top>0){printf("You have entered the operands more than the operators");exit(0);}else{r=pop();return (r);}return 0;}