SlideShare a Scribd company logo
1 of 75
Download to read offline
SrinivasReddyAmedapu@yahoo.com

         Computer Programming Lab Solutions
                                   (as per JNTU Hyderabad Syllabus)

Prepared by

Srinivas Reddy Amedapu
Full Time Research Scholar, CSE Department,
NATIONAL INSTITUTE OF TECHNOLOGY, TRICHY, TAMIL NADU,
Date: February 01, 2013, Phone: 08220 172 182 (TN), 09490 456 987 (AP),
Email: SrinivasReddyAmedapu@yahoo.com
-----------------------------------------------------------------------------------------------------------------------

Week I (a) Write a program to find the sum of individual digits of a positive integer.
#include<stdio.h>
void main()
{
       int num,d,sum,temp;

        printf("nEnter a positive integer : ");
        scanf("%d",&num);
        temp=num;
        sum=0;
        while(num)
        {
                d=num%10;
                sum=sum+d;
                num/=10;
        }
        printf("nSum of digits of %d is %d",temp,sum);
}

Enter a positive integer : 1234

Sum of digits of 1234 is 10




Srinivas Reddy Amedapu, Full Time Research Scholar, CSE Department
NATIONAL INSTITUTE OF TECHNOLOGY, TRICHY, TAMIL NADU                                                                1
SrinivasReddyAmedapu@yahoo.com
Week I (b) 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 generate the first n terms of the sequence.
#include<stdio.h>
void main()
{
       int f1,f2,f3,n,i;

        printf("nHow many Fibonacci Sequence numbers you want? ");
        scanf("%d",&n);
        f1=0, f2=1;
        printf("nThe follwing are %d Fibonacci Numbersn",n);
        for(i=1;i<=n;i++)
        {
                printf(" %d",f1);
                f3=f1+f2;
                f1=f2;
                f2=f3;
        }
}

How many Fibonacci Sequence numbers you want? 11

The follwing are 11 Fibonacci Numbers
0 1 1 2 3 5 8 13 21 34 55

Week I (c) Write a C program to generate all the prime numbers between 1 and n, where n is a value
supplied by the user.
#include<stdio.h>
void main()
{
       int i,n,num,j;

        printf("nEnter upper limit for prime numbers : ");
        scanf("%d",&n);
        printf("nPrime numbers between 1 and %d aren1",n);
        for(i=1;i<=n;i++)
        {
                num=i;
                for(j=2;j<num;j++)
                        if(num%j==0)
                                break;
                if(j==num)
                        printf(" %d",num);
        }
}
Enter upper limit for prime numbers : 55
Prime numbers between 1 and 55 are
1 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53
Srinivas Reddy Amedapu, Full Time Research Scholar, CSE Department
NATIONAL INSTITUTE OF TECHNOLOGY, TRICHY, TAMIL NADU                                              2
SrinivasReddyAmedapu@yahoo.com
Week 2 (a) Write a C program to calculate the following Sum:
Sum=1-x2/2!+x4/4!-x6/6!+x8/8!-x10/10!
#include<stdio.h>
void main()
{
       float sum,term;
       int n,x,i;

        printf("nSequence is 1-x^2/2!+x^4/4-x^6/6!+x^8/8!-x^10/10! . . .");
        printf("nHow many terms you want to calculate in the sequence");
        printf("nEnter x and n valuesn");
        scanf("%d%d",&x,&n);
        term=1.0;
        for(i=1;i<=n;i++)
        {
                sum=sum+term;
                term=-term*x*x/((i*2)*(i*2-1));
        }
        printf("nSum=%8.2f",sum);
}

Sequence is 1-x^2/2!+x^4/4-x^6/6!+x^8/8!-x^10/10! . . .
How many terms you want to calculate in the sequence
Enter x and n values
34
Sum= -1.14

Sequence is 1-x^2/2!+x^4/4-x^6/6!+x^8/8!-x^10/10! . . .
How many terms you want to calculate in the sequence
Enter x and n values
47
Sum= -0.65




Week 2 (b) Write a C program to find the roots of a quadratic equation.
#include<math.h>
#include<stdio.h>
void main()
{
       int a,b,c,descr;
       float r1,r2;

        printf("nQuadratic equation program");
        printf("nEnter a,b and c valuesn");
        scanf("%d%d%d",&a,&b,&c);
        descr=b*b-4*a*c;
Srinivas Reddy Amedapu, Full Time Research Scholar, CSE Department
NATIONAL INSTITUTE OF TECHNOLOGY, TRICHY, TAMIL NADU                                              3
SrinivasReddyAmedapu@yahoo.com
        if(descr==0)
        {
                printf("nRoots are equal");
                r1=r2=-b/(2.0*a);
                printf("nRoot1=Root2=%5.2f",r1);
        }
        else
        {
                if(descr>0)
                {
                        printf("nRoots are unequal");
                        r1=(-b+sqrt(descr))/(2.0*a);
                        r2=(-b-sqrt(descr))/(2.0*a);
                        printf("nRoot1=%5.2f",r1);
                        printf("nRoot2=%5.2f",r2);
                }
                else
                        printf("nRoots are imaginary");
        }
}

Quadratic equation program
Enter a,b and c values
121

Roots are equal
Root1=Root2=-1.00


Quadratic equation program
Enter a,b and c values
1 -1 -6

Roots are unequal
Root1= 3.00
Root2=-2.00
Quadratic equation program
Enter a,b and c values
123

Roots are imaginary




Srinivas Reddy Amedapu, Full Time Research Scholar, CSE Department
NATIONAL INSTITUTE OF TECHNOLOGY, TRICHY, TAMIL NADU                                            4
SrinivasReddyAmedapu@yahoo.com
Week 3 (a) Write C programs that use both recursive and non-recursive functions
   (i)      To find the factorial of a given integer.
Non-Recursive
#include<stdio.h>
void main()
{
       int num,fact;
       int factorial();

        printf("nEnter a positive integer: ");
        scanf("%d",&num);
        fact=factorial(num);
        printf("nFactorial of %d is %d",num,fact);
}

int factorial(int n)
{
        int i,f;

        f=1;
        for(i=1;i<=n;i++)
                f=f*i;
        return f;
}

Enter a positive integer: 5
Factorial of 5 is 120

Enter a positive integer: 7
Factorial of 7 is 5040

Enter a positive integer: 6
Factorial of 6 is 720



Recursive
#include<stdio.h>
void main()
{
       int num,fact;
       int factorial();

        printf("nEnter a positive integer: ");
        scanf("%d",&num);
        fact=factorial(num);
        printf("nFactorial of %d is %d",num,fact);
}

Srinivas Reddy Amedapu, Full Time Research Scholar, CSE Department
NATIONAL INSTITUTE OF TECHNOLOGY, TRICHY, TAMIL NADU                                            5
SrinivasReddyAmedapu@yahoo.com
int factorial(int n)
{
        int f;

        if(n<=1)
                return 1;
        else
                f=n*factorial(n-1);
        return f;
}

Enter a positive integer: 7
Factorial of 7 is 5040

Enter a positive integer: 5
Factorial of 5 is 120

Enter a positive integer: 6
Factorial of 6 is 720



Week 3 (a) Write C programs that use both recursive and non-recursive functions
    (ii)     To find the GCD (greatest common divisor) of two given integers.
Non-Recursive
#include<stdio.h>
void main()
{
         int a,b,val;
         int GCD();

        printf("nEnter two positive integersn");
        scanf("%d%d",&a,&b);
        val=GCD(a,b);
        printf("nGCD of %d and %d is %d",a,b,val);
}
int GCD(int x,int y)
{
      int temp;

        while(x%y!=0)
        {
                temp=x%y;
                x=y;
                y=temp;
        }
        return y;
}

Srinivas Reddy Amedapu, Full Time Research Scholar, CSE Department
NATIONAL INSTITUTE OF TECHNOLOGY, TRICHY, TAMIL NADU                                            6
SrinivasReddyAmedapu@yahoo.com
Enter two positive integers
24 16
GCD of 24 and 16 is 8

Enter two positive integers
35 275
GCD of 35 and 275 is 5



Non-Recursive Solution 2
#include<stdio.h>
void main()
{
       int a,b,val;
       int GCD();

        printf("nEnter two positive integersn");
        scanf("%d%d",&a,&b);
        val=GCD(a,b);
        printf("nGCD of %d and %d is %d",a,b,val);
}
int GCD(int x,int y)
{
      int i,temp;

        if(x>y)
        {
                  temp=x;
                  x=y;
                  y=temp;
        }
        for(i=y;i>=1;i--)
                if(x%i==0&&y%i==0)
                       break;
        return i;
}

Enter two positive integers
24 16
GCD of 24 and 16 is 8

Enter two positive integers
78 24
GCD of 78 and 24 is 6




Srinivas Reddy Amedapu, Full Time Research Scholar, CSE Department
NATIONAL INSTITUTE OF TECHNOLOGY, TRICHY, TAMIL NADU                                            7
SrinivasReddyAmedapu@yahoo.com
Recursive
#include<stdio.h>
void main()
{
       int a,b,val,temp;
       int GCD();

        printf("nEnter two positive integersn");
        scanf("%d%d",&a,&b);
        val=GCD(a,b);
        printf("nGCD of %d and %d is %d",a,b,val);
}

int GCD(int x,int y)
{
      int g,temp;

        if(x%y!=0)
               GCD(y,x%y);
        else
               return y;
}

Enter two positive integers
78 25
GCD of 78 and 25 is 1

Enter two positive integers
78 24
GCD of 78 and 24 is 6



Week 3 (a) Write C programs that use both recursive and non-recursive functions
iii) To solve Towers of Hanoi problem.


Week 4 a) 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 time given 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 for
different values of ‘u’ and ‘a’.




Srinivas Reddy Amedapu, Full Time Research Scholar, CSE Department
NATIONAL INSTITUTE OF TECHNOLOGY, TRICHY, TAMIL NADU                                                8
SrinivasReddyAmedapu@yahoo.com
Week 4 (b) Write a C program, which takes two integer operands and one operator from the user,
performs the operation and then prints the result. (Consider the operators +, -, *, /, % and use
Switch Statement)
#include<stdio.h>
void main()
{
       int a,b,val;
       char op;

        printf("nEnter two integers and operatorn");
        scanf("%d%d %c",&a,&b,&op);
        switch(op)
        {
                case '+': val=a+b;
                           break;
                case '-': val=a-b;
                           break;
                case '*': val=a*b;
                           break;
                case '/': val=a/b;
                           break;
                case '%': val=a%b;
                           break;
        }
        printf("n %d %c %d = %d",a,op,b,val);
}
Enter two integers and operator
10 12 +
 10 + 12 = 22
Enter two integers and operator
10 12 -
 10 - 12 = -2
Enter two integers and operator
10 12 *
 10 * 12 = 120
Enter two integers and operator
22 5 /
 22 / 5 = 4
Enter two integers and operator
22 5 %
 22 % 5 = 2




Srinivas Reddy Amedapu, Full Time Research Scholar, CSE Department
NATIONAL INSTITUTE OF TECHNOLOGY, TRICHY, TAMIL NADU                                            9
SrinivasReddyAmedapu@yahoo.com
Week 5 (a) Write a C program to find both the largest and smallest number in a list of integers.
#include<stdio.h>
void main()
{
       int x[100],n,i,large,small;

        printf("nHow many values you want to enter into an array? ");
        scanf("%d",&n);
        printf("nEnter %d integersn",n);
        for(i=0;i<n;i++)
                scanf("%d",&x[i]);
        large=x[0];
        small=x[0];
        for(i=1;i<n;i++)
        {
                if(large<x[i])
                        large=x[i];
                if(small>x[i])
                        small=x[i];
        }
        printf("nArray values aren");
        for(i=0;i<n;i++)
                printf(" %d",x[i]);
        printf("nLargest = %d",large);
        printf("nSmallest = %d",small);
}

How many values you want to enter into an array? 7
Enter 7 integers
33 22 77 99 66 11 55

Array values are
33 22 77 99 66 11 55
Largest = 99
Smallest = 11


Week 5 (b) Write a C program that uses functions to perform the following:
               i)     Addition of Two Matrices
#include<stdio.h>
void main()
{
       int a[20][20],b[20][20],c[20][20];
       int m1,m2,m3,n1,n2,n3;
       void read2D(),print2D(),add();

        printf("nEnter size of matrix A : ");
        scanf("%d%d",&m1,&n1);
        read2D(a,m1,n1);
Srinivas Reddy Amedapu, Full Time Research Scholar, CSE Department
NATIONAL INSTITUTE OF TECHNOLOGY, TRICHY, TAMIL NADU                                                10
SrinivasReddyAmedapu@yahoo.com
        printf("nEnter size of matrix B: ");
        scanf("%d%d",&m2,&n2);
        read2D(b,m2,n2);
        add(a,m1,n1,b,m2,n2,c,&m3,&n3);
        printf("nMatrix An");
        print2D(a,m1,n1);
        printf("nMatrix Bn");
        print2D(b,m2,n2);
        printf("nMatrix Cn");
        print2D(c,m3,n3);
}
void add(int a[20][20],int m1,int n1, int b[20][20],int m2,int n2,int c[20][20],int *mp,int *np)
{
       int i,j;

        if(m1!=m2||n1!=n2)
        {
                printf("nAddition of matrices is not possible");
                exit(0);
        }
        for(i=0;i<m1;i++)
                for(j=0;j<n1;j++)
                         c[i][j]=a[i][j]+b[i][j];
        *mp=m1;
        *np=n1;
}

void print2D(int x[20][20],int m,int n)
{
       int i,j;

        printf("nContents of matrix aren");
        for(i=0;i<m;i++)
        {
                printf("n");
                for(j=0;j<n;j++)
                        printf("%5d",x[i][j]);
        }
}

void read2D(int x[20][20],int m,int n)
{
       int i,j;

        printf("nEnter values into %d X %d matrixn",m,n);
        for(i=0;i<m;i++)
                for(j=0;j<n;j++)
                        scanf("%d",&x[i][j]);
}
Srinivas Reddy Amedapu, Full Time Research Scholar, CSE Department
NATIONAL INSTITUTE OF TECHNOLOGY, TRICHY, TAMIL NADU                                                11
SrinivasReddyAmedapu@yahoo.com
Enter size of matrix A : 3 4
Enter values into 3 X 4 matrix
1234
1234
1234
Enter size of matrix B: 3 4
Enter values into 3 X 4 matrix
1111
2222
3333

Matrix A
Contents of matrix are
  1 2 3 4
  1 2 3 4
  1 2 3 4



Matrix B
Contents of matrix are
  1 1 1 1
  2 2 2 2
  3 3 3 3
Matrix C
Contents of matrix are
  2 3 4 5
  3 4 5 6
  4 5 6 7


Enter size of matrix A : 2 3
Enter values into 2 X 3 matrix
123
456
Enter size of matrix B: 2 2
Enter values into 2 X 2 matrix
11
22
Addition of matrices is not possible




Srinivas Reddy Amedapu, Full Time Research Scholar, CSE Department
NATIONAL INSTITUTE OF TECHNOLOGY, TRICHY, TAMIL NADU                                            12
SrinivasReddyAmedapu@yahoo.com
Week 5 (b) Write a C program that uses functions to perform the following:
            ii)    Multiplication of Two Matrices

#include<stdio.h>
void main()
{
       int a[20][20],b[20][20],c[20][20];
       int m1,m2,m3,n1,n2,n3;
       void read2D(),print2D(),multiply();

        printf("nEnter size of matrix A : ");
        scanf("%d%d",&m1,&n1);
        read2D(a,m1,n1);
        printf("nEnter size of matrix B: ");
        scanf("%d%d",&m2,&n2);
        read2D(b,m2,n2);
        multiply(a,m1,n1,b,m2,n2,c,&m3,&n3);

        printf("nMatrix An");
        print2D(a,m1,n1);
        printf("nMatrix Bn");
        print2D(b,m2,n2);
        printf("nMatrix A x Bn");
        print2D(c,m3,n3);
}

void multiply(int a[20][20],int m1,int n1, int b[20][20],int m2,int n2,int c[20][20],int *mp,int *np)
{
      int i,j,k;

        if(n1!=m2)
        {
                printf("nMultiplication of matrices is not possible");
                exit(0);
        }
        for(i=0;i<m1;i++)
        {
                for(j=0;j<n2;j++)
                {
                         c[i][j]=0;
                         for(k=1;k<n1;k++)
                                 c[i][j]=c[i][j]+a[i][k]*b[k][j];
                }
        }
        *mp=m1;
        *np=n2;
}


Srinivas Reddy Amedapu, Full Time Research Scholar, CSE Department
NATIONAL INSTITUTE OF TECHNOLOGY, TRICHY, TAMIL NADU                                                    13
SrinivasReddyAmedapu@yahoo.com
void print2D(int x[20][20],int m,int n)
{
       int i,j;

        printf("nContents of matrix aren");
        for(i=0;i<m;i++)
        {
                printf("n");
                for(j=0;j<n;j++)
                        printf("%5d",x[i][j]);
        }
}

void read2D(int x[20][20],int m,int n)
{
       int i,j;

        printf("nEnter values into %d X %d matrixn",m,n);
        for(i=0;i<m;i++)
                for(j=0;j<n;j++)
                        scanf("%d",&x[i][j]);
}

Enter size of matrix A : 2 4
Enter values into 2 X 4 matrix
1234
1111
Enter size of matrix B: 4 1
Enter values into 4 X 1 matrix
1234

Matrix A
Contents of matrix are

  1 2 3 4
  1 1 1 1
Matrix B
Contents of matrix are
  1
  2
  3
  4
Matrix A x B
Contents of matrix are
 29
  9



Srinivas Reddy Amedapu, Full Time Research Scholar, CSE Department
NATIONAL INSTITUTE OF TECHNOLOGY, TRICHY, TAMIL NADU                                            14
SrinivasReddyAmedapu@yahoo.com
Enter size of matrix A : 2 4
Enter values into 2 X 4 matrix
1234
5678

Enter size of matrix B: 2 3
Enter values into 2 X 3 matrix
444
777
Multiplication of matrices is not possible

Enter size of matrix A : 3 4
Enter values into 3 X 4 matrix
1234
5678
9 10 11 12
Enter size of matrix B: 4 5
Enter values into 4 X 5 matrix
11111
22222
33333
44444

Matrix A
Contents of matrix are

  1 2 3 4
  5 6 7 8
  9 10 11 12
Matrix B
Contents of matrix are
  1 1 1 1 1
  2 2 2 2 2
  3 3 3 3 3
  4 4 4 4 4
Matrix A x B
Contents of matrix are

 29 29 29 29 29
 65 65 65 65 65
 101 101 101 101 101




Srinivas Reddy Amedapu, Full Time Research Scholar, CSE Department
NATIONAL INSTITUTE OF TECHNOLOGY, TRICHY, TAMIL NADU                                            15
SrinivasReddyAmedapu@yahoo.com
Week 6
a) Write a C program that uses functions to perform the following operations:
i) To insert a sub-string in to a given main string from a given position.
ii) To delete n Characters from a given position in a given string.
b) Write a C program to determine if the given string is a palindrome or not

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

#include<stdio.h>
void main()
{
       char str[500],sub[100];
       int n1,n2,i,j,loc;

        printf("nEnter main string: ");
        scanf("%s",str);
        printf("nEnter sub string: ");
        scanf("%s",sub);
        printf("nEnter position: ");
        scanf("%d",&loc);

        printf("nMain string: %s",str);
        printf("nSub string: %s",sub);

        n1=strlen(str);
        n2=strlen(sub);

        if(loc>n1)
        {
                printf("nPosition is out of range");
                exit(0);
        }

        for(i=n1;i>=loc;i--)
               str[i+n2]=str[i];

        j=0;
        while(sub[j])
        {
               str[loc+j]=sub[j];
               j++;
        }

        printf("nMain string: %s",str);
        printf("nSub string: %s",sub);
}



Srinivas Reddy Amedapu, Full Time Research Scholar, CSE Department
NATIONAL INSTITUTE OF TECHNOLOGY, TRICHY, TAMIL NADU                                            16
SrinivasReddyAmedapu@yahoo.com
INPUT/OUTPUT

Enter main string: JntuHyderabad
Enter sub string: ASReddy
Enter position: 4

Main string: JntuHyderabad
Sub string: ASReddy

Main string: JntuASReddyHyderabad
Sub string: ASReddy



Enter main string: AravindReddyJNTUH
Enter sub string: 12011U0502
Enter position: 12

Main string: AravindReddyJNTUH
Sub string: 12011U0502

Main string: AravindReddy12011U0502JNTUH
Sub string: 12011U0502


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


#include<stdio.h>
void main()
{
       char str[500];
       int n,i,loc;

        printf("nEnter a string: ");
        scanf("%s",str);
        printf("nEnter number of characters to be deleted: ");
        scanf("%d",&n);
        printf("nEnter position from which deletion should be done: ");
        scanf("%d",&loc);

        if(loc+n>strlen(str))
        {
                printf("nDeletion not possible");
                printf("nToo many characters from the given location");
                exit(0);
        }


Srinivas Reddy Amedapu, Full Time Research Scholar, CSE Department
NATIONAL INSTITUTE OF TECHNOLOGY, TRICHY, TAMIL NADU                                              17
SrinivasReddyAmedapu@yahoo.com
        i=loc;
        while(str[i+n])
        {
                str[i]=str[i+n];
                i++;
        }
        str[i]=str[i+n];
        printf("nString after deletion: %s",str);

}

INPUT/OUTPUT

Enter a string: AravindReddyJNTU
Enter number of characters to be deleted: 5
Enter position from which deletion should be done: 7

String after deletion: AravindJNTU


Enter a string: AravindReddyNarmetta12011U0502
Enter number of characters to be deleted: 8
Enter position from which deletion should be done: 12

String after deletion: AravindReddy12011U0502


b) Write a C program to determine if the given string is a palindrome or not

#include<stdio.h>
#include<string.h>
void main()
{
       char str[500];
       int n,i;

        printf("nEnter a string: ");
        scanf("%s",str);

        n=strlen(str);
        for(i=0;i<n/2;i++)
                if(str[i]!=str[n-i-1])
                         break;
        if(i==n/2)
                printf("n%s is palindrome",str);
        else
                printf("n%s is not palindrome",str);
}

Srinivas Reddy Amedapu, Full Time Research Scholar, CSE Department
NATIONAL INSTITUTE OF TECHNOLOGY, TRICHY, TAMIL NADU                                            18
SrinivasReddyAmedapu@yahoo.com
Enter a string: madam
madam is palindrome

Enter a string: aravind
aravind is not palindrome

Enter a string: aravindnivara
aravindnivara is palindrome

Enter a string: jntutnj
jntutnj is palindrome

Enter a string: JNTUH
JNTUH is not palindrome


Week 7
a) 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.
b) Write a C program to count the lines, words and characters in a given text.

#include<stdio.h>
void main()
{
       char str[500],sub[100];
       int n1,n2,i,j,loc;

        printf("nEnter main string: ");
        scanf("%s",str);
        printf("nEnter sub string: ");
        scanf("%s",sub);

        i=0;
        while(str[i])
        {
                j=0;
                while(str[i+j]&&sub[j]&&str[i+j]==sub[j])
                        j++;
                if(sub[j]==NULL)
                        break;
                i=i+1;
        }
        if(sub[j]==NULL)
                printf("nSub string available at %d location",i+1);
        else
                printf("nSub String not available : %d",-1);
}


Srinivas Reddy Amedapu, Full Time Research Scholar, CSE Department
NATIONAL INSTITUTE OF TECHNOLOGY, TRICHY, TAMIL NADU                                                19
SrinivasReddyAmedapu@yahoo.com
INPUT/OUTPUT

Enter main string: AravindReddy
Enter sub string: Reddy
Sub string available at 8 location

Enter main string: AravindJNTUcse
Enter sub string: JNTU
Sub string available at 8 location

Enter main string: SrinivasReddy
Enter sub string: vas
Sub string available at 6 location

Enter main string: FirstYear
Enter sub string: irt
Sub String not available : -1



Week 7 (b) Write a C program to count the lines, words and characters in a given text.

Week 8 (a) Write a program to generate Pascal’s triangle.
First Model using Arrays
#include<stdio.h>
void main()
{
       int x[50][50],i,j,spaces,l,n;

        printf("nThis is a program to generate Pascal triangle");
        printf("nHow many lines you want : ");
        scanf("%d",&n);
        for(i=0;i<n;i++)
                for(j=0;j<=i;j++)
                        if(j==0||j==i)
                                x[i][j]=1;
                        else
                                x[i][j]=x[i-1][j-1]+x[i-1][j];
        spaces=36;
        for(i=0;i<n;i++)
        {
                printf("nn");
                for(l=0;l<=spaces;l++)
                        printf(" ");
                for(j=0;j<=i;j++)
                        printf("%4d",x[i][j]);
                spaces=spaces-2;
        }
}
Srinivas Reddy Amedapu, Full Time Research Scholar, CSE Department
NATIONAL INSTITUTE OF TECHNOLOGY, TRICHY, TAMIL NADU                                            20
SrinivasReddyAmedapu@yahoo.com
This is a program to generate Pascal triangle
How many lines you want : 7

                                                     1

                                            1                  1

                                   1                 2                1

                          1                 3                  3           1

                 1                 4                 6                4          1

        1                 5                 10                 10          5            1

1                6                 15                20               15         6            1




Second Model Without Arrays

#include<stdio.h>
void main()
{
        int i,j,l,n,ncr,spaces;

        printf("nEnter number of lines to be printed: ");
        scanf("%d",&n);
        spaces=38;
        for(i=0;i<=n;i++)
        {
                 printf("nn");
                 for(l=1;l<=spaces;l++)
                          printf(" ");

                 for(j=0;j<=i;j++)
                 {
                          if(j==0||j==i)
                                   ncr=1;
                          else
                                   ncr=fact(i)/(fact(i-j)*fact(j));
                          printf("%4d",ncr);
                 }
                 spaces=spaces-2;
        }
}

Srinivas Reddy Amedapu, Full Time Research Scholar, CSE Department
NATIONAL INSTITUTE OF TECHNOLOGY, TRICHY, TAMIL NADU                                                      21
SrinivasReddyAmedapu@yahoo.com
int fact(int n)
{
         int i,f=1;

         for(i=1;i<=n;i++)
                  f=f*i;
         return f;
}

INPUT/OUTPUT

Enter number of lines to be printed: 5

                                                 1

                                         1               1

                                 1               2                   1

                             1           3               3               1

                  1              4               6                   4         1

         1                   5           10              10              5            1




Week 8 (b) Write a C program to construct a pyramid of numbers.
(i)
#include<stdio.h>
void main()
{
       int i,j,l,n,sp;

         printf("nHow many lines you want ? ");
         scanf("%d",&n);
         sp=35;
         for(i=1;i<=n;i++)
         {
                 printf("n");
                 for(l=1;l<sp;l++)
                         printf(" ");
                 for(j=1;j<=i;j++)
                         printf("%4d",1);
                 sp=sp-2;
         }
}

Srinivas Reddy Amedapu, Full Time Research Scholar, CSE Department
NATIONAL INSTITUTE OF TECHNOLOGY, TRICHY, TAMIL NADU                                                    22
SrinivasReddyAmedapu@yahoo.com
How many lines you want ? 7

                               1
                              1 1
                             1 1 1
                            1 1 1 1
                           1 1 1 1 1
                          1 1 1 1 1 1
                         1 1 1 1 1 1 1




(ii)
#include<stdio.h>
void main()
{
       int i,j,k,l,n,spaces;

        clrscr();
        printf("nThis is a dymand pattern program");
        printf("nEnter n value ");
        scanf("%d",&n);
        spaces=36;

        for(i=1;i<=n;i++)
        {
                printf("n");
                for(l=1;l<=spaces;l++)
                        printf(" ");
                for(j=1;j<=i;j++)
                        printf("%4d",i);
                spaces-=2;
        }
        spaces=spaces+4;
        for(i=n-1;i>=1;i--)
        {
                printf("n");
                for(l=1;l<=spaces;l++)
                        printf(" ");
                for(j=1;j<=i;j++)
                        printf("%4d",i);
                spaces+=2;
        }
}




Srinivas Reddy Amedapu, Full Time Research Scholar, CSE Department
NATIONAL INSTITUTE OF TECHNOLOGY, TRICHY, TAMIL NADU                                            23
SrinivasReddyAmedapu@yahoo.com
This is a dymand pattern program
Enter n value 7

                                     1
                                    2 2
                                   3 3 3
                                  4 4 4 4
                                5 5 5 5 5
                               6 6 6 6 6 6
                              7 7 7 7 7 7 7
                               6 6 6 6 6 6
                                 5 5 5 5 5
                                  4 4 4 4
                                   3 3 3
                                    2 2
                                     1
(iii)
void main()
{
      int i,j,k,l,n,spaces;

        printf("nThis is a dymand pattern program");
        printf("nEnter n value ");
        scanf("%d",&n);
        spaces=36;
        for(i=1;i<=n;i++)
        {
                printf("n");
                for(l=1;l<=spaces;l++)
                        printf(" ");
                for(j=1;j<=i;j++)
                        printf("%4d",j);
                for(j=i-1;j>=1;j--)
                        printf("%4d",j);
                spaces-=4;
        }
        spaces=spaces+8;
        for(i=n-1;i>=1;i--)
        {
                printf("n");
                for(l=1;l<=spaces;l++)
                        printf(" ");
                for(j=1;j<=i;j++)
                        printf("%4d",j);
                for(j=i-1;j>=1;j--)
                        printf("%4d",j);
                spaces+=4;
        }
}
Srinivas Reddy Amedapu, Full Time Research Scholar, CSE Department
NATIONAL INSTITUTE OF TECHNOLOGY, TRICHY, TAMIL NADU                                            24
SrinivasReddyAmedapu@yahoo.com
This is a dymand pattern program
Enter n value 7
                                 1
                               1 2 1
                             1 2 3 2 1
                           1 2 3 4 3 2 1
                         1 2 3 4 5 4 3 2            1
                       1 2 3 4 5 6 5 4 3            2 1
                     1 2 3 4 5 6 7 6 5 4             3 2 1
                       1 2 3 4 5 6 5 4 3            2 1
                         1 2 3 4 5 4 3 2            1
                           1 2 3 4 3 2 1
                             1 2 3 2 1
                               1 2 1
                                 1



Some more patterns


void main()
{
      int i,j,n;

            printf("nThis is a pattern program");
            printf("nEnter how many lines you want : ");
            scanf("%d",&n);
            for(i=1;i<=n;i++)                            //Program done by Srinivas Reddy Amedapu
            {                                      //SrinivasReddyAmedapu@yahoo.com
                    printf("n");                                // 9490 456 987
                    for(j=1;j<=i;j++)
                            printf("%4d",j);
            }
}

This is a pattern program
Enter how many lines you want : 7

    1
    1   2
    1   2   3
    1   2   3   4
    1   2   3   4 5
    1   2   3   4 5 6
    1   2   3   4 5 6 7



Srinivas Reddy Amedapu, Full Time Research Scholar, CSE Department
NATIONAL INSTITUTE OF TECHNOLOGY, TRICHY, TAMIL NADU                                                25
SrinivasReddyAmedapu@yahoo.com
void main()
{
      int i,j,n;

            printf("nThis is a pattern program");
            printf("nEnter how many lines you want : ");
            scanf("%d",&n);
            for(i=1;i<=n;i++)
            {
                    printf("n");
                    for(j=1;j<=i;j++)
                            printf("%4d",i);
            }
}

This is a pattern program
Enter how many lines you want : 7

    1
    2   2
    3   3   3
    4   4   4   4
    5   5   5   5 5
    6   6   6   6 6 6
    7   7   7   7 7 7 7


                                         //Program done by Srinivas Reddy Amedapu
                                             //SrinivasReddyAmedapu@yahoo.com
void main()                                             // 9490 456 987
{
      int i,j,n,x;

            printf("nThis is a pattern program");
            printf("nEnter how many lines you want : ");
            scanf("%d",&n);
            x=1;
            for(i=1;i<=n;i++)
            {
                    printf("n");
                    for(j=1;j<=i;j++)
                    {
                            printf("%4d",x);
                            x=x+1;
                    }
            }
}


Srinivas Reddy Amedapu, Full Time Research Scholar, CSE Department
NATIONAL INSTITUTE OF TECHNOLOGY, TRICHY, TAMIL NADU                                              26
SrinivasReddyAmedapu@yahoo.com
This is a pattern program
Enter how many lines you want : 7

    1
    2    3
    4    5 6
    7    8 9 10
    11   12 13 14 15
    16   17 18 19 20 21
    22   23 24 25 26 27 28


void main()
{
      int i,j,n,x;

           printf("nThis is a pattern program");
           printf("nEnter how many lines you want : ");
           scanf("%d",&n);
           x=n*(n+1)/2;
           for(i=1;i<=n;i++)
           {
                   printf("n");
                   for(j=1;j<=i;j++)
                   {
                           printf("%4d",x);
                           x=x-1;
                   }
           }
}                                                                    //Program done by Srinivas Reddy Amedapu
                                                                        //SrinivasReddyAmedapu@yahoo.com
This is a pattern program                                                           // 9490 456 987
Enter how many lines you want : 7

    28
    27   26
    25   24 23
    22   21 20 19
    18   17 16 15 14
    13   12 11 10 9 8
    7    6 5 4 3 2 1




Srinivas Reddy Amedapu, Full Time Research Scholar, CSE Department
NATIONAL INSTITUTE OF TECHNOLOGY, TRICHY, TAMIL NADU                                                            27
SrinivasReddyAmedapu@yahoo.com
void main()
{
      int i,j,n,x;

            printf("nThis is a pattern program");
            printf("nEnter how many lines you want : ");
            scanf("%d",&n);
            x=n;
            for(i=1;i<=n;i++)
            {
                    printf("n");
                    for(j=1;j<=i;j++)
                            printf("%4d",x);
                    x=x-1;
            }
}

This is a pattern program
Enter how many lines you want : 7

    7
    6   6
    5   5   5
    4   4   4   4
    3   3   3   3 3
    2   2   2   2 2 2
    1   1   1   1 1 1 1

                                                                     //Program done by Srinivas Reddy Amedapu
                                                                         //SrinivasReddyAmedapu@yahoo.com
void main()                                                                         // 9490 456 987
{
      int i,j,n,x;

            printf("nThis is a pattern program");
            printf("nEnter how many lines you want : ");
            scanf("%d",&n);
            x=n;
            for(i=1;i<=n;i++)
            {
                    printf("n");
                    x=n-i+1;
                    for(j=1;j<=i;j++)
                    {
                            printf("%4d",x);
                            x=x+1;
                    }
            }
}
Srinivas Reddy Amedapu, Full Time Research Scholar, CSE Department
NATIONAL INSTITUTE OF TECHNOLOGY, TRICHY, TAMIL NADU                                                            28
SrinivasReddyAmedapu@yahoo.com
This is a pattern program
Enter how many lines you want : 7

    7
    6   7
    5   6   7
    4   5   6   7
    3   4   5   6 7
    2   3   4   5 6 7
    1   2   3   4 5 6 7



void main()
{
      int i,j,n,x;

            printf("nThis is a pattern program");                   //Program done by Srinivas Reddy Amedapu
            printf("nEnter how many lines you want : ");               //SrinivasReddyAmedapu@yahoo.com
            scanf("%d",&n);                                                               // 9490 456 987
            x=n;
            for(i=1;i<=n;i++)
            {
                    printf("n");
                    x=n;
                    for(j=1;j<=i;j++)
                    {
                            printf("%4d",x);
                            x=x-1;
                    }
            }
}


This is a pattern program
Enter how many lines you want : 7

    7
    7   6
    7   6   5
    7   6   5   4
    7   6   5   4 3
    7   6   5   4 3 2
    7   6   5   4 3 2 1




Srinivas Reddy Amedapu, Full Time Research Scholar, CSE Department
NATIONAL INSTITUTE OF TECHNOLOGY, TRICHY, TAMIL NADU                                                            29
SrinivasReddyAmedapu@yahoo.com
void main()
{
      int i,j,n,l,spaces;

        printf("nThis is a pattern program");
        printf("nEnter how many lines you want : ");
        scanf("%d",&n);
        spaces=25;
        for(i=n;i>=1;i--)
        {
                printf("n");
                for(l=1;l<=spaces;l++)                               //Program done by Srinivas Reddy Amedapu
                        printf(" ");                                      //SrinivasReddyAmedapu@yahoo.com
                for(j=1;j<=i;j++)                                                         // 9490 456 987
                        printf("%4d",j);
                spaces=spaces+4;
        }
}

This is a pattern program
Enter how many lines you want : 7

                                            1 2 3 4 5 6 7
                                               1 2 3 4 5 6
                                                  1 2 3 4 5
                                                   1 2 3 4
                                                      1 2 3
                                                       1 2
                                                         1
void main()
{
      int i,j,n;

        printf("nThis is a pattern program");
        printf("nEnter how many lines you want : ");
        scanf("%d",&n);
        for(i=n;i>=1;i--)
        {
                printf("n");
                for(j=1;j<=i;j++)
                        printf("%4d",i);
        }
}




Srinivas Reddy Amedapu, Full Time Research Scholar, CSE Department
NATIONAL INSTITUTE OF TECHNOLOGY, TRICHY, TAMIL NADU                                                            30
SrinivasReddyAmedapu@yahoo.com
This is a pattern program
Enter how many lines you want : 7

    7    7   7   7 7 7 7
    6    6   6   6 6 6
    5    5   5   5 5
    4    4   4   4
    3    3   3
    2    2
    1




void main()
{
      int i,j,n,x;                                                   //Program done by Srinivas Reddy Amedapu
                                                                          //SrinivasReddyAmedapu@yahoo.com
             printf("nThis is a pattern program");                                  // 9490 456 987
             printf("nEnter how many lines you want : ");
             scanf("%d",&n);
             for(i=n;i>=1;i--)
             {
                     printf("n");
                     x=i*(i+1)/2-i;
                     for(j=1;j<=i;j++)
                     {
                             x=x+1;
                             printf("%4d",x);
                     }
             }
}


This is a pattern program
Enter how many lines you want : 7

    22   23 24 25 26 27 28
    16   17 18 19 20 21
    11   12 13 14 15
    7    8 9 10
    4    5 6
    2    3
    1




Srinivas Reddy Amedapu, Full Time Research Scholar, CSE Department
NATIONAL INSTITUTE OF TECHNOLOGY, TRICHY, TAMIL NADU                                                            31
SrinivasReddyAmedapu@yahoo.com
void main()
{
      int i,j,n,x,diff,temp;

        printf("nThis is a pattern program");
        printf("nEnter how many lines you want : ");
        scanf("%d",&n);
        temp=0;
        diff=n;
        for(i=n;i>=1;i--)
        {
                printf("n");
                temp=temp+diff;                                      //Program done by Srinivas Reddy Amedapu
                diff=diff-1;                                              //SrinivasReddyAmedapu@yahoo.com
                x=temp;                                                              // 9490 456 987
                for(j=1;j<=i;j++)
                {
                        printf("%4d",x);
                        x=x-1;
                }
        }
}

This is a pattern program
Enter how many lines you want : 7
  7 6 5 4 3 2 1
 13 12 11 10 9 8
 18 17 16 15 14
 22 21 20 19
 25 24 23
 27 26
 28

void main()
{
      int i,j,n,x;

        printf("nThis is a pattern program");
        printf("nEnter how many lines you want : ");
        scanf("%d",&n);
        x=1;
        for(i=n;i>=1;i--)
        {
                printf("n");
                for(j=1;j<=i;j++)
                        printf("%4d",x);
                x=x+1;
        }
}
Srinivas Reddy Amedapu, Full Time Research Scholar, CSE Department
NATIONAL INSTITUTE OF TECHNOLOGY, TRICHY, TAMIL NADU                                                            32
SrinivasReddyAmedapu@yahoo.com
This is a pattern program
Enter how many lines you want : 7

    1   1   1   1 1 1 1
    2   2   2   2 2 2                                                //Program done by Srinivas Reddy Amedapu
    3   3   3   3 3                                                     //SrinivasReddyAmedapu@yahoo.com
    4   4   4   4                                                                   // 9490 456 987
    5   5   5
    6   6
    7



void main()
{
      int i,j,n,x;

            printf("nThis is a pattern program");
            printf("nEnter how many lines you want : ");
            scanf("%d",&n);
            for(i=n;i>=1;i--)
            {
                    printf("n");
                    x=n;
                    for(j=1;j<=i;j++)
                    {
                            printf("%4d",x);
                            x=x-1;
                    }
            }
}



This is a pattern program
Enter how many lines you want : 7

    7   6   5   4 3 2 1
    7   6   5   4 3 2
    7   6   5   4 3
    7   6   5   4
    7   6   5
    7   6
    7




Srinivas Reddy Amedapu, Full Time Research Scholar, CSE Department
NATIONAL INSTITUTE OF TECHNOLOGY, TRICHY, TAMIL NADU                                                            33
SrinivasReddyAmedapu@yahoo.com
void main()
{
      int i,j,n,x;

        clrscr();
        printf("nThis is a pattern program");                       //Program done by Srinivas Reddy Amedapu
        printf("nEnter how many lines you want : ");                    //SrinivasReddyAmedapu@yahoo.com
        scanf("%d",&n);                                                                   // 9490 456 987
        for(i=n;i>=1;i--)
        {
                printf("n");
                x=n-i+1;
                for(j=1;j<=i;j++)
                {
                        printf("%4d",x);
                        x=x+1;
                }
        }
}

This is a pattern program
Enter how many lines you want : 7

  1 2 3 4 5 6 7
  2 3 4 5 6 7
  3 4 5 6 7
  4 5 6 7
  5 6 7
  6 7
  7
void main()
{
      int i,j,n,l,spaces,x;

        printf("nThis is a pattern program");
        printf("nEnter how many lines you want : ");
        scanf("%d",&n);
        spaces=35;
        x=1;
        for(i=1;i<=n;i++)
        {
                printf("n");
                for(l=1;l<=spaces;l++)
                        printf(" ");
                for(j=1;j<=i;j++)                                    //Program done by Srinivas Reddy Amedapu
                {                                                        //SrinivasReddyAmedapu@yahoo.com
                        printf("%4d",x);                                                  // 9490 456 987
                        x=x+1;
                }
Srinivas Reddy Amedapu, Full Time Research Scholar, CSE Department
NATIONAL INSTITUTE OF TECHNOLOGY, TRICHY, TAMIL NADU                                                            34
SrinivasReddyAmedapu@yahoo.com
                spaces=spaces-2;
        }
}
This is a pattern program
Enter how many lines you want : 4

                         1
                        2 3
                       4 5 6
                      7 8 9 10

void main()
{
      int i,j,n,l,spaces;

        printf("nThis is a pattern program");
        printf("nEnter how many lines you want : ");
        scanf("%d",&n);
        spaces=35;
        for(i=1;i<=n;i++)
        {
                printf("n");
                for(l=1;l<=spaces;l++)
                        printf(" ");
                for(j=1;j<=i*2-1;j++)
                        printf("%4d",i);
                spaces=spaces-4;
        }
}

This is a pattern program
Enter how many lines you want : 4

                                                         1
                                                       2 2 2
                                                     3 3 3 3 3
                                                   4 4 4 4 4 4 4


void main()
{
      int i,j,n,l,spaces;

        printf("nThis is a pattern program");                       //Program done by Srinivas Reddy Amedapu
        printf("nEnter how many lines you want : ");                    //SrinivasReddyAmedapu@yahoo.com
        scanf("%d",&n);                                                                   // 9490 456 987
        spaces=35;
        for(i=1;i<=n;i++)
        {
Srinivas Reddy Amedapu, Full Time Research Scholar, CSE Department
NATIONAL INSTITUTE OF TECHNOLOGY, TRICHY, TAMIL NADU                                                            35
SrinivasReddyAmedapu@yahoo.com
                printf("n");
                for(l=1;l<=spaces;l++)
                        printf(" ");
                for(j=1;j<=i;j++)
                        printf("%4d",j);
                for(j=i-1;j>=1;j--)
                        printf("%4d",j);
                spaces=spaces-4;
        }
}

This is a pattern program
Enter how many lines you want : 4

                                                         1
                                                       1 2 1
                                                     1 2 3 2 1
                                                   1 2 3 4 3 2 1




Week 9
Write a C program to read in two numbers, x and n, and then compute the sum of this geometric
progression: 1+x+x2+x3+………….+xn. For example: if n is 3 and x is 5, then the program computes
1+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. Have your program print an error message if n<0,
then go back and read in the next pair of numbers of without computing the sum. Are any values of x
also illegal ? If so, test for them too.




Week 10
a) 2’s complement of a number is obtained by scanning it from right to left and complementing all
the bits after the first appearance of a 1. Thus 2’s complement of 11100 is 00100. Write a C program
to find the 2’s complement of a binary number.
b) Write a C program to convert a Roman numeral to its decimal equivalent.




Srinivas Reddy Amedapu, Full Time Research Scholar, CSE Department
NATIONAL INSTITUTE OF TECHNOLOGY, TRICHY, TAMIL NADU                                              36
SrinivasReddyAmedapu@yahoo.com
Week 11
Write a C program that uses functions to perform the following operations:
i) Reading a complex number
ii) Writing a complex number
iii) Addition of two complex numbers
iv) Multiplication of two complex numbers
(Note: represent complex number using a structure.)

struct complex
{
        int real;
        int imag;
};
void main()
{
        struct complex c1,c2,c3,c4;
        void read(),display();
        struct complex add(),mult();

        read(&c1);
        read(&c2);

        printf("nEntered complex numbers aren");
        display(c1);
        display(c2);

        c3=add(c1,c2);
        c4=mult(c1,c2);

        printf("nAddition of two complex numbersn");
        display(c3);

        printf("nMultiplication of two complex numbersn");
        display(c4);
}
void read(struct complex *p)
{
       printf("nEnter Complex number (real imaginary)");
       scanf("%d%d",&p->real,&p->imag);
}


void display(struct complex c)
{
       printf("nComplex number is ");
       printf("n%d %di",c.real,c.imag);
}


Srinivas Reddy Amedapu, Full Time Research Scholar, CSE Department
NATIONAL INSTITUTE OF TECHNOLOGY, TRICHY, TAMIL NADU                                            37
SrinivasReddyAmedapu@yahoo.com
struct complex add(struct complex x, struct complex y)
{
        struct complex z;

        z.real=x.real+y.real;
        z.imag=x.imag+y.imag;
        return z;
}


struct complex mult(struct complex x, struct complex y)
{
        struct complex z;

        z.real=x.real*y.real-x.imag*y.imag;
        z.imag=x.imag*y.real+x.real*y.imag;
        return z;
}

Enter Complex number (real imaginary)2 3
Enter Complex number (real imaginary)4 7

Enter complex numbers are
Complex number is
2 3i
Complex number is
4 7i

Addition of two complex numbers
Complex number is
6 10i

Multiplication of two complex numbers
Complex number is
-13 26i




Srinivas Reddy Amedapu, Full Time Research Scholar, CSE Department
NATIONAL INSTITUTE OF TECHNOLOGY, TRICHY, TAMIL NADU                                            38
SrinivasReddyAmedapu@yahoo.com
Week 12
a) Write a C program which copies one file to another.

#include<stdio.h>
void main(int argc,char* argv[])
{
       FILE *fp1,*fp2;
       char ch;

        if(argc!=3)
        {
                printf("nUse Command Properly");
                printf("nCommand SourceFileName TargetFileName");
                exit(0);
        }

        fp1=fopen(argv[1],"r");
        if(fp1==NULL)
        {
               printf("nSource File Not Existing");
               exit(1);
        }

        fp2=fopen(argv[2],"w");
        ch=fgetc(fp1);
        while(ch!=EOF)
        {
                fputc(ch,fp2);
                ch=fgetc(fp1);
        }
        printf("nFile Copied");
        fclose(fp1);
        fclose(fp2);
}


C:TCBIN>dir asrc*.*
Volume in drive C has no label.
Volume Serial Number is 60A8-805B

Directory of C:TCBIN

01/05/2013 11:46 PM          485 ASRCPY.BAK
01/05/2013 11:46 PM          485 ASRCPY.C
01/05/2013 11:46 PM        12,280 ASRCPY.EXE
                   5 File(s)     15,883 bytes
                   0 Dir(s) 36,109,975,552 bytes free


Srinivas Reddy Amedapu, Full Time Research Scholar, CSE Department
NATIONAL INSTITUTE OF TECHNOLOGY, TRICHY, TAMIL NADU                                            39
SrinivasReddyAmedapu@yahoo.com
C:TCBIN>asrcpy asrcpy.c aravind.c
File Copied

C:TCBIN>asrcpy sss.c yyy.c
Source File Not Existing

C:TCBIN>asrcpy asrcpy.c yy.c zz.c
Use Command Properly
Command SourceFileName TargetFileName

C:TCBIN>asrcpy aravind.c jntuh.c
File Copied

C:TCBIN>dir jnt*.*
Volume in drive C has no label.
Volume Serial Number is 60A8-805B

Directory of C:TCBIN

01/05/2013 11:49 PM          485 JNTUH.C
                   1 File(s)       485 bytes
                   0 Dir(s) 36,109,844,480 bytes free

C:TCBIN>exit




b) 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<stdio.h>
void main(int argc,char* argv[])
{
       FILE *fp;
       int n,n2;
       char ch;

        n=atoi(argv[2]);
        n2=n;
        fp=fopen(argv[1],"r");
        fseek(fp,n+1,0);
        while(n>0)
        {
               fseek(fp,-2,1);
               ch=fgetc(fp);
               printf("%c",ch);
               n=n-1;
        }
Srinivas Reddy Amedapu, Full Time Research Scholar, CSE Department
NATIONAL INSTITUTE OF TECHNOLOGY, TRICHY, TAMIL NADU                                            40
SrinivasReddyAmedapu@yahoo.com
        fseek(fp,n2,0);
        ch=fgetc(fp);
        while(ch!=EOF)
        {
                printf("%c",ch);
                ch=fgetc(fp);
        }
        fclose(fp);
}
INPUT/OUTPUT

C:TCBIN>type text.dat
This is Srinivas Reddy Amedapu, Full Time Research Scholar at NIT Trichy, TN.

C:TCBIN>asrfile4 text.dat 25
mA yddeR savinirS si sihTedapu, Full Time Research Scholar at NIT Trichy, TN.

C:TCBIN>asrfile4 text.dat 66
TIN ta ralohcS hcraeseR emiT lluF ,upademA yddeR savinirS si sihTTrichy, TN.

C:TCBIN>asrfile4 text.dat 45
seR emiT lluF ,upademA yddeR savinirS si sihTearch Scholar at NIT Trichy, TN.


C:TCBIN>type aravind.dat
I am Aravind Reddy Ravula, studying B.Tech(+MBA) First Year, JNTU Hyderabad.

C:TCBIN>asrfile4 aravind.dat 35
gniyduts ,aluvaR yddeR dnivarA ma I B.Tech(+MBA) First Year, JNTU Hyderabad.

C:TCBIN>asrfile4 aravind.dat 55
tsriF )ABM+(hceT.B gniyduts ,aluvaR yddeR dnivarA ma IYear, JNTU Hyderabad.
C:TCBIN>exit

Week 13
a) Write a C programme to display the contents of a file.

#include<stdio.h>
void main(int argc,char* argv[])
{
       FILE *fp;
       char ch;

        if(argc!=2)
        {
                printf("nUse Command Properly");
                printf("nCommand FileName");
                exit(0);
        }
Srinivas Reddy Amedapu, Full Time Research Scholar, CSE Department
NATIONAL INSTITUTE OF TECHNOLOGY, TRICHY, TAMIL NADU                                            41
SrinivasReddyAmedapu@yahoo.com
        fp=fopen(argv[1],"r");
        if(fp==NULL)
        {
               printf("nSource File Not Existing");
               exit(1);
        }

        ch=fgetc(fp);
        while(ch!=EOF)
        {
                printf("%c",ch);
                ch=fgetc(fp);
        }
        fclose(fp);
}

C:TCBIN>asrtype yy.c

Source File Not Existing
C:TCBIN>asrtype simple.c
void main()
{
         printf("nWelcome to JNTU--Aravind Reddy CSE");
}
C:TCBIN>asrtype simple.c asrtype.c

Use Command Properly
Command FileName
C:TCBIN>exit



b) Write a C programme to merge two files into a third file ( i.e., the contents of the first file followed
by those of the second are put in the third file)


#include<stdio.h>
void main(int argc,char* argv[])
{
       FILE *fp1,*fp2,*fp3;
       char ch;

        if(argc!=4)
        {
                printf("nUse Command Properly");
                printf("nCommand SourceFileName1 SourceFileName2 TargetFileName");
                exit(0);
        }

Srinivas Reddy Amedapu, Full Time Research Scholar, CSE Department
NATIONAL INSTITUTE OF TECHNOLOGY, TRICHY, TAMIL NADU                                                    42
SrinivasReddyAmedapu@yahoo.com
        fp1=fopen(argv[1],"r");
        if(fp1==NULL)
        {
               printf("nSource File1 Not Existing");
               exit(1);
        }

        fp3=fopen(argv[3],"w");
        ch=fgetc(fp1);
        while(ch!=EOF)
        {
                fputc(ch,fp3);
                ch=fgetc(fp1);
        }
        fclose(fp1);

        fp2=fopen(argv[2],"r");
        if(fp2==NULL)
        {
               printf("nSource File 2 Not Existing");
               fclose(fp3);
               exit(2);
        }

        ch=fgetc(fp2);
        while(ch!=EOF)
        {
                fputc(ch,fp3);
                ch=fgetc(fp2);
        }
        fclose(fp2);
        fclose(fp3);
}




INPUT/OUTPUT


C:TCBIN>asrmerg simple.c hworld.c aravind.c


C:TCBIN>type simple.c
void main()
{
        printf("nWelcome to JNTU--Aravind Reddy CSE");
}

Srinivas Reddy Amedapu, Full Time Research Scholar, CSE Department
NATIONAL INSTITUTE OF TECHNOLOGY, TRICHY, TAMIL NADU                                            43
SrinivasReddyAmedapu@yahoo.com
C:TCBIN>type hworld.c
#include<stdio.h>
void main()
{
         printf("nHello World!");
         printf("nThis is Aravind Reddy");
         printf("nRoll No. 12011U0502, CSE");
}

C:TCBIN>type aravind.c
void main()
{
         printf("nWelcome to JNTU--Aravind Reddy CSE");
}
#include<stdio.h>
void main()
{
         printf("nHello World!");
         printf("nThis is Aravind Reddy");
         printf("nRoll No. 12011U0502, CSE");
}

C:TCBIN>exit



Week 14
Write a C program that uses functions to perform the following operations on singly linked list.:
i) Creation ii) Insertion iii) Deletion iv) Traversal

#include<stdio.h>
#include<alloc.h>

struct node
{
        int data;
        struct node *link;
};

typedef struct node* nodeptr;

void main()
{
      int val,pos;
      nodeptr list;
      nodeptr create();
      void print(),insertnth(nodeptr*,int,int);
      int deletenth(nodeptr*,int);

Srinivas Reddy Amedapu, Full Time Research Scholar, CSE Department
NATIONAL INSTITUTE OF TECHNOLOGY, TRICHY, TAMIL NADU                                                44
SrinivasReddyAmedapu@yahoo.com
        list=create();
        print(list);
        printf("nEnter Element to be inserted and position : ");
        scanf("%d%d",&val,&pos);
        insertnth(&list,val,pos);
        print(list);
        printf("nWhich position node you want to delete? ");
        scanf("%d",&pos);
        val=deletenth(&list,pos);
        printf("nDeleted node value is %d",val);
        print(list);
}
int deletenth(nodeptr *lp,int pos)
{
        int val=-1;
        nodeptr p,q,r;
        if(*lp==NULL)
                printf("nLinked List is empty, delete not possible");
        else
        {
                p=*lp;
                if(pos==1)
                {
                    *lp=p->link;
                    val=p->data;
                    free(p);
                }
                else
                {
                        pos=pos-2;
                        while(p&&pos)
                        {
                               p=p->link;
                               pos=pos-1;
                        }
                        if(p)
                        {
                               q=p->link;
                               p->link=q->link;
                               val=q->data;
                               free(q);
                        }
                        else
                               printf("nLess nodes than given node number");
                }
        }
        return val;
}
Srinivas Reddy Amedapu, Full Time Research Scholar, CSE Department
NATIONAL INSTITUTE OF TECHNOLOGY, TRICHY, TAMIL NADU                                             45
SrinivasReddyAmedapu@yahoo.com
void insertnth(nodeptr *lp,int val,int pos)
{
       nodeptr p,q,r;
       nodeptr getnode();

        q=getnode();
        q->data=val;
        q->link=NULL;
        if(*lp==NULL)
               *lp=q;
        else
        {
               p=*lp;
               pos=pos-1;
               while(p&&pos)
               {
                      r=p;
                      p=p->link;
                      pos=pos-1;
               }
               q->link=r->link;
               r->link=q;
        }
}


nodeptr create()
{
       int val;
       nodeptr p,q,r;
       nodeptr getnode();

        printf("nEnter 0 (zero) to stopn");
        scanf("%d",&val);
        p=getnode();
        r=p;
        while(val)
        {
                 q=getnode();
                 q->data=val;
                 p->link=q;
                 p=q;
                 scanf("%d",&val);
        }
        p->link=NULL;
        p=r->link;
        free(r);
        return p;
}
Srinivas Reddy Amedapu, Full Time Research Scholar, CSE Department
NATIONAL INSTITUTE OF TECHNOLOGY, TRICHY, TAMIL NADU                                            46
SrinivasReddyAmedapu@yahoo.com
void print(nodeptr p)
{
       printf("nContents of Linked List aren");
       while(p)
       {
               printf(" %d",p->data);
               p=p->link;
       }
}


nodeptr getnode()
{
       nodeptr p;

        p=(nodeptr)malloc(sizeof(struct node));
        return p;
}


INPUT/OUTPUT

Enter 0 (zero) to stop
11 22 33 44 55 66 77 88 99 0

Contents of Linked List are
 11 22 33 44 55 66 77 88 99

Enter Element to be inserted and position : 678 6
Contents of Linked List are
 11 22 33 44 55 678 66 77 88 99

Which position node you want to delete? 3
Deleted node value is 33
Contents of Linked List are
 11 22 44 55 678 66 77 88 99




Srinivas Reddy Amedapu, Full Time Research Scholar, CSE Department
NATIONAL INSTITUTE OF TECHNOLOGY, TRICHY, TAMIL NADU                                            47
SrinivasReddyAmedapu@yahoo.com
Week 15
Write C programs that implement stack (its operations) using
i) Arrays ii) Pointers

Arrays

#include<stdio.h>
#define MAX 100

void main()
{
      int stack[MAX],top=-1,val,op;
      void push(),display(),options();
      int pop();

         clrscr();
         options();
         while(1)
         {
                 printf("nSelect option : ");
                 scanf("%d",&op);
                 switch(op)
                 {
                         case 1: printf("nEnter value to be pushed : ");
                                 scanf("%d",&val);
                                 push(stack,&top,val);
                                 break;
                         case 2: val=pop(stack,&top);
                                 printf("nValue poped is %d",val);
                                 break;
                         case 3: display(stack,top);
                                 break;
                         case 4: exit(0);
                                 break; //optional ie, non reachable code
                         default:options();
                                 break; //optional, last case
                 }
         }
}
void push(int stk[],int *tp,int val)
{
       if(*tp==MAX-1)
               printf("nStack full, %d not inserted",val);
       else
       {
               *tp=*tp+1;
               stk[*tp]=val;
       }
}
Srinivas Reddy Amedapu, Full Time Research Scholar, CSE Department
NATIONAL INSTITUTE OF TECHNOLOGY, TRICHY, TAMIL NADU                                                   48
SrinivasReddyAmedapu@yahoo.com
int pop(int stk[],int *tp)
{
        int val=-1;

        if(*tp==-1)
                printf("nStack empty, no value deleted");
        else
        {
                val=stk[*tp];
                *tp=*tp-1;
        }
        return val;
}


void display(int stk[],int top)
{
       int i;

        printf("nContents of Stack aren");
        for(i=top;i>=0;i--)
                printf("ntt%4d",stk[i]);
}


void options()
{
       printf("nAvailable optons aren");
       printf("ntt0. Options");
       printf("ntt1. Push");
       printf("ntt2. Pop");
       printf("ntt3. Display");
       printf("ntt4. Exit");
}

INPUT/OUTPUT

Available optons are
       0. Options
       1. Push
       2. Pop
       3. Display
       4. Exit

Select option : 1
Enter value to be pushed : 11

Select option : 1
Enter value to be pushed : 99
Srinivas Reddy Amedapu, Full Time Research Scholar, CSE Department
NATIONAL INSTITUTE OF TECHNOLOGY, TRICHY, TAMIL NADU                                            49
SrinivasReddyAmedapu@yahoo.com
Select option : 1
Enter value to be pushed : 88

Select option : 3
Contents of Stack are
         88
         99
         11

Select option : 2
Value poped is 88

Select option : 2
Value poped is 99

Select option : 2
Value poped is 11

Select option : 2
Stack empty, no value deleted
Value poped is -1

Select option : 4


Pointers

#include<stdio.h>

struct node
{
        int data;
        struct node *link;
};
typedef struct node* nodeptr;

void main()
{
      int op,val;
      nodeptr sp=NULL;
      void push(),display(),options();
      int pop();

        clrscr();
        options();
        while(1)
        {
                printf("nSelect option : ");
                scanf("%d",&op);
Srinivas Reddy Amedapu, Full Time Research Scholar, CSE Department
NATIONAL INSTITUTE OF TECHNOLOGY, TRICHY, TAMIL NADU                                            50
SrinivasReddyAmedapu@yahoo.com
                switch(op)
                {
                       case 1: printf("nEnter value to be pushed : ");
                               scanf("%d",&val);
                               push(&sp,val);
                               break;
                       case 2: val=pop(&sp);
                               printf("nValue poped is %d",val);
                               break;
                       case 3: display(sp);
                               break;
                       case 4: exit(0);
                               break; //optional ie, non reachable code
                       default:options();
                               break; //optional, last case
                }
        }
}

void push(nodeptr *spp,int val)
{
       nodeptr p;
       nodeptr getnode();

        p=getnode();
        p->data=val;
        p->link=*spp;
        *spp=p;
}
int pop(nodeptr *spp)
{
        int val=-1;
        nodeptr p;

        if(*spp==NULL)
                printf("nStack Empty");
        else
        {
                p=*spp;
                *spp=p->link;
                val=p->data;
                free(p);
        }
        return val;
}




Srinivas Reddy Amedapu, Full Time Research Scholar, CSE Department
NATIONAL INSTITUTE OF TECHNOLOGY, TRICHY, TAMIL NADU                                                 51
SrinivasReddyAmedapu@yahoo.com
void display(nodeptr p)
{
       printf("nContents of Stack aren");
       while(p)
       {
               printf("nt%4d",p->data);
               p=p->link;
       }
}

void options()
{
       printf("nAvailable optons aren");
       printf("nt0. Options");
       printf("nt1. Push");
       printf("nt2. Pop");
       printf("nt3. Display");
       printf("nt4. Exit");
}

nodeptr getnode()
{
       nodeptr p;

        p=(nodeptr)malloc(sizeof(struct node));
        return p;
}

INPUT/OUTPUT

Available optons are
       0. Options
       1. Push
       2. Pop
       3. Display
       4. Exit

Select option : 1
Enter value to be pushed : 11

Select option : 1
Enter value to be pushed : 22

Select option : 1
Enter value to be pushed : 44

Select option : 2
Value poped is 44

Srinivas Reddy Amedapu, Full Time Research Scholar, CSE Department
NATIONAL INSTITUTE OF TECHNOLOGY, TRICHY, TAMIL NADU                                            52
SrinivasReddyAmedapu@yahoo.com
Select option : 3
Contents of Stack are
                22
                11

Select option : 2
Value poped is 22

Select option : 2
Value poped is 11

Select option : 2
Stack Empty
Value poped is -1

Select option : 4



Week 16
Write C programs that implement Queue (its operations) using
i) Arrays ii) Pointers

Arrays

#include<stdio.h>
#define MAX 100

void main()
{
      int val,op;
      int queue[MAX],front=0,rear=-1;
      int delet();
      void insert(),display(),options();

         options();
         while(1)
         {
                printf("nSelect option: ");
                scanf("%d",&op);
                switch(op)
                {
                        case 1: printf("nEnter value to be inserted: ");
                                  scanf("%d",&val);
                                  insert(queue,&rear,val);
                                  break;
                        case 2: val=delet(queue,&front,rear);
                                  printf("nDeleted value is %d",val);
                                  break;
Srinivas Reddy Amedapu, Full Time Research Scholar, CSE Department
NATIONAL INSTITUTE OF TECHNOLOGY, TRICHY, TAMIL NADU                                                   53
SrinivasReddyAmedapu@yahoo.com
                         case 3: display(queue,front,rear);
                                   break;
                         case 4: exit(0);
                                   break;
                         default: options();
                                   break;
                 }
        }
}


int delet(int q[],int *fp,int r)
{
        int val=-1;

        if(*fp>r)
                printf("nQueue empty");
        else
        {
                val=q[*fp];
                *fp=*fp+1;
        }
        return val;
}


void insert(int q[],int *rp,int val)
{
       if(*rp==MAX-1)
                printf("nQueue full");
       else
       {
                *rp=*rp+1;
                q[*rp]=val;
       }
}


void display(int q[],int f,int r)
{
       int i;

        printf("nContents of queue are:n");
        for(i=f;i<=r;i++)
                printf(" %d",q[i]);
}



Srinivas Reddy Amedapu, Full Time Research Scholar, CSE Department
NATIONAL INSTITUTE OF TECHNOLOGY, TRICHY, TAMIL NADU                                            54
SrinivasReddyAmedapu@yahoo.com
void options()
{
       printf("nAvailable operations");
       printf("nt1. Insert");
       printf("nt2. Delete");
       printf("nt3. Display");
       printf("nt4. Exit");
}


Available operations
         1. Insert
         2. Delete
         3. Display
         4. Exit

Select option: 1
Enter value to be inserted: 11

Select option: 1
Enter value to be inserted: 66

Select option: 1
Enter value to be inserted: 88

Select option: 3
Contents of queue are:
11 66 88

Select option: 2
Deleted value is 11

Select option: 4



Pointers

#include<stdio.h>
#define MAX 100

struct node
{
        int data;
        struct node *link;
};
typedef struct node* nodeptr;


Srinivas Reddy Amedapu, Full Time Research Scholar, CSE Department
NATIONAL INSTITUTE OF TECHNOLOGY, TRICHY, TAMIL NADU                                            55
SrinivasReddyAmedapu@yahoo.com
void main()
{
      int val,op;
      nodeptr front=NULL,rear=NULL;
      int delet();
      void insert(),display(),options();

        options();
        while(1)
        {
               printf("nSelect option: ");
               scanf("%d",&op);
               switch(op)
               {
                       case 1: printf("nEnter value to be inserted: ");
                                 scanf("%d",&val);
                                 insert(&front,&rear,val);
                                 break;
                       case 2: val=delet(&front,&rear);
                                 printf("nDeleted value is %d",val);
                                 break;
                       case 3: display(front);
                                 break;
                       case 4: exit(0);
                                 break;
                       default: options();
                                 break;
               }
        }
}


int delet(nodeptr *fp,nodeptr *rp)
{
        int val=-1;
        nodeptr p;

        if(*fp==NULL)
                printf("nQueue is Empty");
        else
        {
                p=*fp;
                val=p->data;
                *fp=p->link;
                if(*fp==NULL)
                        *rp=NULL;
        }
        return val;
}
Srinivas Reddy Amedapu, Full Time Research Scholar, CSE Department
NATIONAL INSTITUTE OF TECHNOLOGY, TRICHY, TAMIL NADU                                                  56
SrinivasReddyAmedapu@yahoo.com
void insert(nodeptr *fp,nodeptr *rp,int val)
{
       nodeptr p;
       nodeptr getnode();

        p=getnode();
        p->data=val;
        p->link=NULL;
        if(*rp==NULL)
               *fp=*rp=p;
        else
        {
               (*rp)->link=p;
               *rp=p;
        }
}


void display(nodeptr p)
{
       printf("nContents of queue are:n");
       while(p)
       {
               printf(" %d",p->data);
               p=p->link;
       }
}


void options()
{
       printf("nAvailable operations");
       printf("nt1. Insert");
       printf("nt2. Delete");
       printf("nt3. Display");
       printf("nt4. Exit");
}



nodeptr getnode()
{
       nodeptr p;

        p=(nodeptr)malloc(sizeof(struct node));
        return p;
}


Srinivas Reddy Amedapu, Full Time Research Scholar, CSE Department
NATIONAL INSTITUTE OF TECHNOLOGY, TRICHY, TAMIL NADU                                            57
SrinivasReddyAmedapu@yahoo.com
Available operations
         1. Insert
         2. Delete
         3. Display
         4. Exit

Select option: 1
Enter value to be inserted: 11

Select option: 1
Enter value to be inserted: 12

Select option: 1
Enter value to be inserted: 14

Select option: 2
Deleted value is 11

Select option: 3
Contents of queue are:
12 14

Select option: 2
Deleted value is 12

Select option: 2
Deleted value is 14

Select option: 2
Queue is Empty
Deleted value is -1

Select option: 3
Contents of queue are:

Select option: 4




Srinivas Reddy Amedapu, Full Time Research Scholar, CSE Department
NATIONAL INSTITUTE OF TECHNOLOGY, TRICHY, TAMIL NADU                                            58
SrinivasReddyAmedapu@yahoo.com
Week 17
Write a C program that uses Stack operations to perform the following:
i) Converting infix expression into postfix expression
ii) Evaluating the postfix expression

Converting infix expression into postfix expression

#include<math.h>
#include<stdio.h>
#include<alloc.h>
#include<conio.h>
struct node
{
        char data;
        struct node* link;
};
typedef struct node* nodeptr;

void main()
{
      char in[100],post[100];
      int i,j;
      nodeptr sp=NULL;
      void push();
      char pop();

        printf("nEnter valid infix expression");
        printf("nThis program will work for + - * / % ^ operatorsn");
        scanf("%s",in);
        i=0,j=0;
        while(in[i])
        {
                if(in[i]>='a'&&in[i]<='z')
                {
                         post[j]=in[i];
                         j++;
                }
                else
                {
                         if(in[i]=='+'||in[i]=='-'||in[i]=='*'
                                  ||in[i]=='/'||in[i]=='%'||in[i]=='^')
                         {
                                  while(sp&&compare(in[i],sp->data)<=0)
                                  {
                                           post[j]=pop(&sp);
                                           j++;
                                  }
                                  push(&sp,in[i]);
                         }
Srinivas Reddy Amedapu, Full Time Research Scholar, CSE Department
NATIONAL INSTITUTE OF TECHNOLOGY, TRICHY, TAMIL NADU                                                 59
SrinivasReddyAmedapu@yahoo.com
                         else
                         {
                                 printf("nInvalid Symbol in the expression");
                                 exit(0);
                         }
                }
                i++;
        }
        while(sp)
        {
                post[j]=pop(&sp);
                j++;
        }
        post[j]='0';
        printf("nInfix expression: %s",in);
        printf("nPostfix expression: %s",post);
}

int compare(char sym1,char sym2)
{
       int diff;

        diff=priority(sym1)-priority(sym2);
        return diff;
}

int priority(char sym)
{
        int p;

        switch(sym)
        {
               case '+':
               case '-': p=1;
                                 break;
                case '*':
                case '/': p=2;
                                 break;
                case '%': p=3;
                                 break;
                case '^': p=4;
                                 break;
        }
        return p;
}




Srinivas Reddy Amedapu, Full Time Research Scholar, CSE Department
NATIONAL INSTITUTE OF TECHNOLOGY, TRICHY, TAMIL NADU                                                 60
SrinivasReddyAmedapu@yahoo.com
char pop(nodeptr *spp)
{
       int val=-1;
       nodeptr p;

        p=*spp;
        *spp=p->link;
        val=p->data;
        free(p);
        return(val);
}

void push(nodeptr *spp,char val)
{
       nodeptr p;
       nodeptr getnode();

        p=getnode();
        p->data=val;
        p->link=*spp;
        *spp=p;
}

nodeptr getnode()
{
       nodeptr p;

        p=(nodeptr)malloc(sizeof(struct node)); // malloc -> alloc.h included
        return p;
}

INPUT/OUTPUT

Enter valid infix expression
This program will work for + - * / % ^ operators
a+b*c/d-e%f^g
Infix expression: a+b*c/d-e%f^g
Postfix expression: abc*d/+efg^%-

Enter valid infix expression
This program will work for + - * / % ^ operators
a+b@
Invalid Symbol in the expression

Enter valid infix expression
This program will work for + - * / % ^ operators
a+b%c-d/f+g^h+i*j
Infix expression: a+b%c-d/f+g^h+i*j
Postfix expression: abc%+df/-gh^+ij*+
Srinivas Reddy Amedapu, Full Time Research Scholar, CSE Department
NATIONAL INSTITUTE OF TECHNOLOGY, TRICHY, TAMIL NADU                                               61
SrinivasReddyAmedapu@yahoo.com
Evaluating the postfix expression

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

struct node
{
        int data;
        struct node* link;
};
typedef struct node* nodeptr;

void main()
{
      int i,val,val1,val2,temp;
      char post[100];
      nodeptr sp=NULL;
      int evaluate(),pop();
      void push();

        printf("nEnter postfix expressionn");
        scanf("%s",post);
        i=0;
        while(post[i])
        {
                if(post[i]>='0'&&post[i]<='9')
                {
                        temp=post[i]-'0';
                        push(&sp,temp);
                }
                else
                {
                        if(post[i]=='+'||post[i]=='-'||post[i]=='*'
                                ||post[i]=='/'||post[i]=='^')
                        {
                                val2=pop(&sp);
                                val1=pop(&sp);
                                if(val1==-1||val2==-1)
                                {
                                         printf("nExpression Error");
                                         exit(0);
                                }
                                val=evaluate(val1,val2,post[i]);
                                push(&sp,val);
                        }


Srinivas Reddy Amedapu, Full Time Research Scholar, CSE Department
NATIONAL INSTITUTE OF TECHNOLOGY, TRICHY, TAMIL NADU                                                62
SrinivasReddyAmedapu@yahoo.com
                         else
                         {
                                 printf("nInvalid Symbol");
                                 exit(1);
                         }
                }
                i=i+1;
        }
        val=pop(&sp);
        printf("n%s = %d",post,val);
        getch(); // getch -> conio.h included
}

int evaluate(int a,int b,char sym)
{
        int val;

        switch(sym)
        {
                case '+': val=a+b; break;
                case '-': val=a-b; break;
                case '*': val=a*b; break;
                case '/': val=a/b; break;
                case '^': val=pow(a,b); // pow -> math.h is included
        }
        return val;
}

int pop(nodeptr *spp)
{
        int val=-1;
        nodeptr p;

        p=*spp;
        *spp=p->link;
        val=p->data;
        free(p);
        return(val);
}
void push(nodeptr *spp,int val)
{
       nodeptr p;
       nodeptr getnode();

        p=getnode();
        p->data=val;
        p->link=*spp;
        *spp=p;
}
Srinivas Reddy Amedapu, Full Time Research Scholar, CSE Department
NATIONAL INSTITUTE OF TECHNOLOGY, TRICHY, TAMIL NADU                                              63
SrinivasReddyAmedapu@yahoo.com
nodeptr getnode()
{
       nodeptr p;

        p=(nodeptr)malloc(sizeof(struct node)); // malloc -> alloc.h included
        return p;
}

INPUT/OUTPUT

Enter postfix expression
23+

23+ = 5


Enter postfix expression
45+63/-42^+

45+63/-42^+ = 23


Enter postfix expression
45*

45* = 20

Week 18
Write a C program that implements the following sorting methods to sort a given list of integers in
ascending
order
i) Bubble sort
ii) Selection sort

Bubble Sort

#include<stdio.h>
#define MAX 100
void main()
{
       int arr[MAX],n,temp,i,j;
       void read1D(),print1D(),bubble();

        printf("nEnter number of terms: ");
        scanf("%d",&n);
        read1D(arr,n);
        bubble(arr,n);
        print1D(arr,n);
}
Srinivas Reddy Amedapu, Full Time Research Scholar, CSE Department
NATIONAL INSTITUTE OF TECHNOLOGY, TRICHY, TAMIL NADU                                                  64
SrinivasReddyAmedapu@yahoo.com
void bubble(int a[],int n)
{
       int i,j,temp;

        for(i=0;i<n-1;i++)
        {
                for(j=0;j<n-i-1;j++)
                        if(a[j]>a[j+1])
                        {
                                temp=a[j];
                                a[j]=a[j+1];
                                a[j+1]=temp;
                        }
        }
}

void read1D(int arr[],int n)
{
       int i;

        printf("nEnter %d valuesn",n);
        for(i=0;i<n;i++)
                scanf("%d",&arr[i]);
}

void print1D(int arr[],int n)
{
       int i;

        printf("nValues of array are:n");
        for(i=0;i<n;i++)
                printf(" %d",arr[i]);
}


Enter number of terms: 7
Enter 7 values
11 66 33 99 88 22 44

Values of array are:
11 22 33 44 66 88 99


Enter number terms: 12
Enter 12 values
22 88 33 77 100 222 777 123 876 456 767 121

Values of array are:
22 33 77 88 100 121 123 222 456 767 777 876
Srinivas Reddy Amedapu, Full Time Research Scholar, CSE Department
NATIONAL INSTITUTE OF TECHNOLOGY, TRICHY, TAMIL NADU                                            65
SrinivasReddyAmedapu@yahoo.com
Week 18 Write a C program that implements the following sorting methods to sort a given list of
integers in ascending order
ii) Selection sort


Week 19
Write C programs that use both recursive and non recursive functions to perform the following
searching operations for a Key value in a given list of integers :
i) Linear search ii) Binary search

Iterative Linear Search

#include<stdio.h>
void main()
{
       int arr[100],n,val,loc;
       void read1D();
       int lsearch();

        printf("nHowmany elements you want to enter? ");
        scanf("%d",&n);
        read1D(arr,n);

        printf("nEnter element to be searched: ");
        scanf("%d",&val);

        loc=lsearch(arr,n,val);
        printf("n%d availabel at %d location",val,loc);
}

int lsearch(int arr[],int n,int val)
{
        int i;

        for(i=0;i<n;i++)
                if(arr[i]==val)
                         return i;
        return -1;
}

void read1D(int arr[],int n)
{
       int i;

        printf("nEnter %d values:n",n);
        for(i=0;i<n;i++)
                scanf("%d",&arr[i]);
}

Srinivas Reddy Amedapu, Full Time Research Scholar, CSE Department
NATIONAL INSTITUTE OF TECHNOLOGY, TRICHY, TAMIL NADU                                              66
SrinivasReddyAmedapu@yahoo.com
INPUT/OUTPUT

Howmany elements you want to enter? 1
Enter 1 values:
1
Enter element to be searched: 1
1 availabel at 0 location

Howmany elements you want to enter? 8
Enter 8 values:
11 55 33 77 89 98 22 66
Enter element to be searched: 89
89 availabel at 4 location

Howmany elements you want to enter? 12
Enter 12 values:
12 56 89 65 32 11 66 44 99 92 23 48
Enter element to be searched: 10
10 availabel at -1 location

Howmany elements you want to enter? 5
Enter 5 values:
12345
Enter element to be searched: 3
3 availabel at 2 location




Iterative Binary Search

#include<stdio.h>
void main()
{
       int arr[100],n,val,loc;
       void read1D();
       int bsearch();

        printf("nHowmany elements you want to enter? ");
        scanf("%d",&n);
        read1D(arr,n);

        printf("nEnter element to be searched: ");
        scanf("%d",&val);

        loc=bsearch(arr,0,n-1,val);
        printf("n%d availabel at %d location",val,loc);
}

Srinivas Reddy Amedapu, Full Time Research Scholar, CSE Department
NATIONAL INSTITUTE OF TECHNOLOGY, TRICHY, TAMIL NADU                                            67
SrinivasReddyAmedapu@yahoo.com
int bsearch(int arr[],int lb,int ub,int val)
{
        int mid;

        while(lb<=ub)
        {
                mid=(lb+ub)/2;
                if(arr[mid]==val)
                        return mid;
                else
                        if(arr[mid]<val)
                                lb=mid+1;
                        else
                                ub=mid-1;
        }
        return -1;
}

void read1D(int arr[],int n)
{
       int i;

        printf("nEnter %d values:n",n);
        for(i=0;i<n;i++)
                scanf("%d",&arr[i]);
}


INPUT/OUTPUT

Howmany elements you want to enter? 7
Enter 7 values:
11 33 45 67 88 90 112
Enter element to be searched: 88
88 availabel at 4 location

Howmany elements you want to enter? 5
Enter 5 values:
1 4 7 9 15
Enter element to be searched: 6
6 availabel at -1 location

Howmany elements you want to enter? 10
Enter 10 values:
11 14 17 25 28 45 47 56 67 78
Enter element to be searched: 56
56 availabel at 7 location


Srinivas Reddy Amedapu, Full Time Research Scholar, CSE Department
NATIONAL INSTITUTE OF TECHNOLOGY, TRICHY, TAMIL NADU                                            68
SrinivasReddyAmedapu@yahoo.com
Recursive Binary Search

#include<stdio.h>
void main()
{
       int arr[100],n,val,loc;
       void read1D();
       int bsearch();

        printf("nHowmany elements you want to enter? ");
        scanf("%d",&n);
        read1D(arr,n);

        printf("nEnter element to be searched: ");
        scanf("%d",&val);

        loc=bsearch(arr,0,n-1,val);
        printf("n%d availabel at %d location",val,loc);
}

int bsearch(int a[],int low,int high,int key)
{
        int mid;

        if(low<=high)
        {
               mid=(low+high)/2;
               if(a[mid]==key)
                        return mid;
               else if(key<a[mid])
                        return bsearch(a,low,mid-1,key);
               else if(key>a[mid])
                        return bsearch(a,mid+1,high,key);
        }
        else
               return -1;
}

void read1D(int arr[],int n)
{
       int i;

        printf("nEnter %d values:n",n);
        for(i=0;i<n;i++)
                scanf("%d",&arr[i]);
}



Srinivas Reddy Amedapu, Full Time Research Scholar, CSE Department
NATIONAL INSTITUTE OF TECHNOLOGY, TRICHY, TAMIL NADU                                            69
SrinivasReddyAmedapu@yahoo.com
Howmany elements you want to enter? 5
Enter 5 values:
11 22 33 44 55
Enter element to be searched: 22
22 availabel at 1 location

Howmany elements you want to enter? 7
Enter 7 values:
12 23 34 45 56 67 78
Enter element to be searched: 66
66 availabel at -1 location

Howmany elements you want to enter? 10
Enter 10 values:
10 20 30 40 50 60 70 80 90 100
Enter element to be searched: 80
80 availabel at 7 location




Week 20
Write C program that implement the Quick sort method to sort a given list of integers in ascending
order:

#include<stdio.h>
#define MAX 100
int split(int*,int,int);
void getdata(int arr[],int n);
void display(int arr[],int n);
int main()
{

        int arr[MAX],i,n;
        void quicksort(int*,int,int);

        printf("nEnter the total number of elements: ");
        scanf("%d",&n);

        getdata(arr,n);
        quicksort(arr,0,n-1);
        display(arr,n);

        return 0;
}



Srinivas Reddy Amedapu, Full Time Research Scholar, CSE Department
NATIONAL INSTITUTE OF TECHNOLOGY, TRICHY, TAMIL NADU                                             70
SrinivasReddyAmedapu@yahoo.com
void getdata(int arr[],int n)
{
       int i;

        printf("nEnter the elements which to be sort:n");
        for(i=0;i<n;i++)
                scanf("%d",&arr[i]);
}

void display(int arr[],int n)
{
       int i;

        printf("nAfter merge sorting elements are:n");
        for(i=0;i<n;i++)
                printf("%d ",arr[i]);
}

void quicksort(int a[],int lower,int upper)
{
         int i ;
         if(upper>lower)
         {
                 i=split(a,lower,upper);
                 quicksort(a,lower,i-1);
                 quicksort(a,i+1,upper);
         }
}
int split(int x[10],int lower,int upper)
{
         int pivot,j,temp,i;

        pivot=lower;
        i=lower;
        j=upper;

        while(i<j)
        {
               while(x[i]<=x[pivot]&&i<upper)
                       i++;
               while(x[j]>x[pivot])
                       j--;
               if(i<j)
               {
                       temp=x[i];
                       x[i]=x[j];
                       x[j]=temp;
               }
        }
Srinivas Reddy Amedapu, Full Time Research Scholar, CSE Department
NATIONAL INSTITUTE OF TECHNOLOGY, TRICHY, TAMIL NADU                                            71
C and Data Structures
C and Data Structures
C and Data Structures
C and Data Structures

More Related Content

What's hot

Data structure new lab manual
Data structure  new lab manualData structure  new lab manual
Data structure new lab manual
SANTOSH RATH
 
Numerical analysis
Numerical analysisNumerical analysis
Numerical analysis
Vishal Singh
 
Chapter 8 c solution
Chapter 8 c solutionChapter 8 c solution
Chapter 8 c solution
Azhar Javed
 
C Prog. - Strings (Updated)
C Prog. - Strings (Updated)C Prog. - Strings (Updated)
C Prog. - Strings (Updated)
vinay arora
 

What's hot (18)

C program
C programC program
C program
 
Critical buckling load geometric nonlinearity analysis of springs with rigid ...
Critical buckling load geometric nonlinearity analysis of springs with rigid ...Critical buckling load geometric nonlinearity analysis of springs with rigid ...
Critical buckling load geometric nonlinearity analysis of springs with rigid ...
 
DAA Lab File C Programs
DAA Lab File C ProgramsDAA Lab File C Programs
DAA Lab File C Programs
 
All important c programby makhan kumbhkar
All important c programby makhan kumbhkarAll important c programby makhan kumbhkar
All important c programby makhan kumbhkar
 
Lab manual data structure (cs305 rgpv) (usefulsearch.org) (useful search)
Lab manual data structure (cs305 rgpv) (usefulsearch.org)  (useful search)Lab manual data structure (cs305 rgpv) (usefulsearch.org)  (useful search)
Lab manual data structure (cs305 rgpv) (usefulsearch.org) (useful search)
 
Data structure new lab manual
Data structure  new lab manualData structure  new lab manual
Data structure new lab manual
 
C Programming
C ProgrammingC Programming
C Programming
 
Basic c programs updated on 31.8.2020
Basic c programs updated on 31.8.2020Basic c programs updated on 31.8.2020
Basic c programs updated on 31.8.2020
 
Numerical analysis
Numerical analysisNumerical analysis
Numerical analysis
 
C Prog - Array
C Prog - ArrayC Prog - Array
C Prog - Array
 
CS6311- PROGRAMMING & DATA STRUCTURE II LABORATORY
CS6311- PROGRAMMING & DATA STRUCTURE II LABORATORYCS6311- PROGRAMMING & DATA STRUCTURE II LABORATORY
CS6311- PROGRAMMING & DATA STRUCTURE II LABORATORY
 
C Programming lab
C Programming labC Programming lab
C Programming lab
 
Chapter 8 c solution
Chapter 8 c solutionChapter 8 c solution
Chapter 8 c solution
 
C programs
C programsC programs
C programs
 
Mech nacp lab
Mech nacp labMech nacp lab
Mech nacp lab
 
Data Structure Project File
Data Structure Project FileData Structure Project File
Data Structure Project File
 
Ada file
Ada fileAda file
Ada file
 
C Prog. - Strings (Updated)
C Prog. - Strings (Updated)C Prog. - Strings (Updated)
C Prog. - Strings (Updated)
 

Similar to C and Data Structures

C Prog - Pointers
C Prog - PointersC Prog - Pointers
C Prog - Pointers
vinay arora
 
Practical write a c program to reverse a given number
Practical write a c program to reverse a given numberPractical write a c program to reverse a given number
Practical write a c program to reverse a given number
Mainak Sasmal
 
Practical write a c program to reverse a given number
Practical write a c program to reverse a given numberPractical write a c program to reverse a given number
Practical write a c program to reverse a given number
Mainak Sasmal
 

Similar to C and Data Structures (20)

Srinivas Reddy Amedapu, CPDS, CP Lab, JNTU Hyderabad
Srinivas Reddy Amedapu, CPDS, CP Lab, JNTU HyderabadSrinivas Reddy Amedapu, CPDS, CP Lab, JNTU Hyderabad
Srinivas Reddy Amedapu, CPDS, CP Lab, JNTU Hyderabad
 
Progr3
Progr3Progr3
Progr3
 
C Prog - Pointers
C Prog - PointersC Prog - Pointers
C Prog - Pointers
 
DSC program.pdf
DSC program.pdfDSC program.pdf
DSC program.pdf
 
C Programming Example
C Programming ExampleC Programming Example
C Programming Example
 
Cpds lab
Cpds labCpds lab
Cpds lab
 
Practical write a c program to reverse a given number
Practical write a c program to reverse a given numberPractical write a c program to reverse a given number
Practical write a c program to reverse a given number
 
Practical write a c program to reverse a given number
Practical write a c program to reverse a given numberPractical write a c program to reverse a given number
Practical write a c program to reverse a given number
 
Let us C (by yashvant Kanetkar) chapter 3 Solution
Let us C   (by yashvant Kanetkar) chapter 3 SolutionLet us C   (by yashvant Kanetkar) chapter 3 Solution
Let us C (by yashvant Kanetkar) chapter 3 Solution
 
Common problems solving using c
Common problems solving using cCommon problems solving using c
Common problems solving using c
 
Lab. Programs in C
Lab. Programs in CLab. Programs in C
Lab. Programs in C
 
C lab
C labC lab
C lab
 
C programs Set 2
C programs Set 2C programs Set 2
C programs Set 2
 
C faq pdf
C faq pdfC faq pdf
C faq pdf
 
'C' language notes (a.p)
'C' language notes (a.p)'C' language notes (a.p)
'C' language notes (a.p)
 
SaraPIC
SaraPICSaraPIC
SaraPIC
 
C-programs
C-programsC-programs
C-programs
 
C Programming Example
C Programming Example C Programming Example
C Programming Example
 
programs
programsprograms
programs
 
Basic C Programming Lab Practice
Basic C Programming Lab PracticeBasic C Programming Lab Practice
Basic C Programming Lab Practice
 

C and Data Structures

  • 1. SrinivasReddyAmedapu@yahoo.com Computer Programming Lab Solutions (as per JNTU Hyderabad Syllabus) Prepared by Srinivas Reddy Amedapu Full Time Research Scholar, CSE Department, NATIONAL INSTITUTE OF TECHNOLOGY, TRICHY, TAMIL NADU, Date: February 01, 2013, Phone: 08220 172 182 (TN), 09490 456 987 (AP), Email: SrinivasReddyAmedapu@yahoo.com ----------------------------------------------------------------------------------------------------------------------- Week I (a) Write a program to find the sum of individual digits of a positive integer. #include<stdio.h> void main() { int num,d,sum,temp; printf("nEnter a positive integer : "); scanf("%d",&num); temp=num; sum=0; while(num) { d=num%10; sum=sum+d; num/=10; } printf("nSum of digits of %d is %d",temp,sum); } Enter a positive integer : 1234 Sum of digits of 1234 is 10 Srinivas Reddy Amedapu, Full Time Research Scholar, CSE Department NATIONAL INSTITUTE OF TECHNOLOGY, TRICHY, TAMIL NADU 1
  • 2. SrinivasReddyAmedapu@yahoo.com Week I (b) 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 generate the first n terms of the sequence. #include<stdio.h> void main() { int f1,f2,f3,n,i; printf("nHow many Fibonacci Sequence numbers you want? "); scanf("%d",&n); f1=0, f2=1; printf("nThe follwing are %d Fibonacci Numbersn",n); for(i=1;i<=n;i++) { printf(" %d",f1); f3=f1+f2; f1=f2; f2=f3; } } How many Fibonacci Sequence numbers you want? 11 The follwing are 11 Fibonacci Numbers 0 1 1 2 3 5 8 13 21 34 55 Week I (c) Write a C program to generate all the prime numbers between 1 and n, where n is a value supplied by the user. #include<stdio.h> void main() { int i,n,num,j; printf("nEnter upper limit for prime numbers : "); scanf("%d",&n); printf("nPrime numbers between 1 and %d aren1",n); for(i=1;i<=n;i++) { num=i; for(j=2;j<num;j++) if(num%j==0) break; if(j==num) printf(" %d",num); } } Enter upper limit for prime numbers : 55 Prime numbers between 1 and 55 are 1 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 Srinivas Reddy Amedapu, Full Time Research Scholar, CSE Department NATIONAL INSTITUTE OF TECHNOLOGY, TRICHY, TAMIL NADU 2
  • 3. SrinivasReddyAmedapu@yahoo.com Week 2 (a) Write a C program to calculate the following Sum: Sum=1-x2/2!+x4/4!-x6/6!+x8/8!-x10/10! #include<stdio.h> void main() { float sum,term; int n,x,i; printf("nSequence is 1-x^2/2!+x^4/4-x^6/6!+x^8/8!-x^10/10! . . ."); printf("nHow many terms you want to calculate in the sequence"); printf("nEnter x and n valuesn"); scanf("%d%d",&x,&n); term=1.0; for(i=1;i<=n;i++) { sum=sum+term; term=-term*x*x/((i*2)*(i*2-1)); } printf("nSum=%8.2f",sum); } Sequence is 1-x^2/2!+x^4/4-x^6/6!+x^8/8!-x^10/10! . . . How many terms you want to calculate in the sequence Enter x and n values 34 Sum= -1.14 Sequence is 1-x^2/2!+x^4/4-x^6/6!+x^8/8!-x^10/10! . . . How many terms you want to calculate in the sequence Enter x and n values 47 Sum= -0.65 Week 2 (b) Write a C program to find the roots of a quadratic equation. #include<math.h> #include<stdio.h> void main() { int a,b,c,descr; float r1,r2; printf("nQuadratic equation program"); printf("nEnter a,b and c valuesn"); scanf("%d%d%d",&a,&b,&c); descr=b*b-4*a*c; Srinivas Reddy Amedapu, Full Time Research Scholar, CSE Department NATIONAL INSTITUTE OF TECHNOLOGY, TRICHY, TAMIL NADU 3
  • 4. SrinivasReddyAmedapu@yahoo.com if(descr==0) { printf("nRoots are equal"); r1=r2=-b/(2.0*a); printf("nRoot1=Root2=%5.2f",r1); } else { if(descr>0) { printf("nRoots are unequal"); r1=(-b+sqrt(descr))/(2.0*a); r2=(-b-sqrt(descr))/(2.0*a); printf("nRoot1=%5.2f",r1); printf("nRoot2=%5.2f",r2); } else printf("nRoots are imaginary"); } } Quadratic equation program Enter a,b and c values 121 Roots are equal Root1=Root2=-1.00 Quadratic equation program Enter a,b and c values 1 -1 -6 Roots are unequal Root1= 3.00 Root2=-2.00 Quadratic equation program Enter a,b and c values 123 Roots are imaginary Srinivas Reddy Amedapu, Full Time Research Scholar, CSE Department NATIONAL INSTITUTE OF TECHNOLOGY, TRICHY, TAMIL NADU 4
  • 5. SrinivasReddyAmedapu@yahoo.com Week 3 (a) Write C programs that use both recursive and non-recursive functions (i) To find the factorial of a given integer. Non-Recursive #include<stdio.h> void main() { int num,fact; int factorial(); printf("nEnter a positive integer: "); scanf("%d",&num); fact=factorial(num); printf("nFactorial of %d is %d",num,fact); } int factorial(int n) { int i,f; f=1; for(i=1;i<=n;i++) f=f*i; return f; } Enter a positive integer: 5 Factorial of 5 is 120 Enter a positive integer: 7 Factorial of 7 is 5040 Enter a positive integer: 6 Factorial of 6 is 720 Recursive #include<stdio.h> void main() { int num,fact; int factorial(); printf("nEnter a positive integer: "); scanf("%d",&num); fact=factorial(num); printf("nFactorial of %d is %d",num,fact); } Srinivas Reddy Amedapu, Full Time Research Scholar, CSE Department NATIONAL INSTITUTE OF TECHNOLOGY, TRICHY, TAMIL NADU 5
  • 6. SrinivasReddyAmedapu@yahoo.com int factorial(int n) { int f; if(n<=1) return 1; else f=n*factorial(n-1); return f; } Enter a positive integer: 7 Factorial of 7 is 5040 Enter a positive integer: 5 Factorial of 5 is 120 Enter a positive integer: 6 Factorial of 6 is 720 Week 3 (a) Write C programs that use both recursive and non-recursive functions (ii) To find the GCD (greatest common divisor) of two given integers. Non-Recursive #include<stdio.h> void main() { int a,b,val; int GCD(); printf("nEnter two positive integersn"); scanf("%d%d",&a,&b); val=GCD(a,b); printf("nGCD of %d and %d is %d",a,b,val); } int GCD(int x,int y) { int temp; while(x%y!=0) { temp=x%y; x=y; y=temp; } return y; } Srinivas Reddy Amedapu, Full Time Research Scholar, CSE Department NATIONAL INSTITUTE OF TECHNOLOGY, TRICHY, TAMIL NADU 6
  • 7. SrinivasReddyAmedapu@yahoo.com Enter two positive integers 24 16 GCD of 24 and 16 is 8 Enter two positive integers 35 275 GCD of 35 and 275 is 5 Non-Recursive Solution 2 #include<stdio.h> void main() { int a,b,val; int GCD(); printf("nEnter two positive integersn"); scanf("%d%d",&a,&b); val=GCD(a,b); printf("nGCD of %d and %d is %d",a,b,val); } int GCD(int x,int y) { int i,temp; if(x>y) { temp=x; x=y; y=temp; } for(i=y;i>=1;i--) if(x%i==0&&y%i==0) break; return i; } Enter two positive integers 24 16 GCD of 24 and 16 is 8 Enter two positive integers 78 24 GCD of 78 and 24 is 6 Srinivas Reddy Amedapu, Full Time Research Scholar, CSE Department NATIONAL INSTITUTE OF TECHNOLOGY, TRICHY, TAMIL NADU 7
  • 8. SrinivasReddyAmedapu@yahoo.com Recursive #include<stdio.h> void main() { int a,b,val,temp; int GCD(); printf("nEnter two positive integersn"); scanf("%d%d",&a,&b); val=GCD(a,b); printf("nGCD of %d and %d is %d",a,b,val); } int GCD(int x,int y) { int g,temp; if(x%y!=0) GCD(y,x%y); else return y; } Enter two positive integers 78 25 GCD of 78 and 25 is 1 Enter two positive integers 78 24 GCD of 78 and 24 is 6 Week 3 (a) Write C programs that use both recursive and non-recursive functions iii) To solve Towers of Hanoi problem. Week 4 a) 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 time given 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 for different values of ‘u’ and ‘a’. Srinivas Reddy Amedapu, Full Time Research Scholar, CSE Department NATIONAL INSTITUTE OF TECHNOLOGY, TRICHY, TAMIL NADU 8
  • 9. SrinivasReddyAmedapu@yahoo.com Week 4 (b) Write a C program, which takes two integer operands and one operator from the user, performs the operation and then prints the result. (Consider the operators +, -, *, /, % and use Switch Statement) #include<stdio.h> void main() { int a,b,val; char op; printf("nEnter two integers and operatorn"); scanf("%d%d %c",&a,&b,&op); switch(op) { case '+': val=a+b; break; case '-': val=a-b; break; case '*': val=a*b; break; case '/': val=a/b; break; case '%': val=a%b; break; } printf("n %d %c %d = %d",a,op,b,val); } Enter two integers and operator 10 12 + 10 + 12 = 22 Enter two integers and operator 10 12 - 10 - 12 = -2 Enter two integers and operator 10 12 * 10 * 12 = 120 Enter two integers and operator 22 5 / 22 / 5 = 4 Enter two integers and operator 22 5 % 22 % 5 = 2 Srinivas Reddy Amedapu, Full Time Research Scholar, CSE Department NATIONAL INSTITUTE OF TECHNOLOGY, TRICHY, TAMIL NADU 9
  • 10. SrinivasReddyAmedapu@yahoo.com Week 5 (a) Write a C program to find both the largest and smallest number in a list of integers. #include<stdio.h> void main() { int x[100],n,i,large,small; printf("nHow many values you want to enter into an array? "); scanf("%d",&n); printf("nEnter %d integersn",n); for(i=0;i<n;i++) scanf("%d",&x[i]); large=x[0]; small=x[0]; for(i=1;i<n;i++) { if(large<x[i]) large=x[i]; if(small>x[i]) small=x[i]; } printf("nArray values aren"); for(i=0;i<n;i++) printf(" %d",x[i]); printf("nLargest = %d",large); printf("nSmallest = %d",small); } How many values you want to enter into an array? 7 Enter 7 integers 33 22 77 99 66 11 55 Array values are 33 22 77 99 66 11 55 Largest = 99 Smallest = 11 Week 5 (b) Write a C program that uses functions to perform the following: i) Addition of Two Matrices #include<stdio.h> void main() { int a[20][20],b[20][20],c[20][20]; int m1,m2,m3,n1,n2,n3; void read2D(),print2D(),add(); printf("nEnter size of matrix A : "); scanf("%d%d",&m1,&n1); read2D(a,m1,n1); Srinivas Reddy Amedapu, Full Time Research Scholar, CSE Department NATIONAL INSTITUTE OF TECHNOLOGY, TRICHY, TAMIL NADU 10
  • 11. SrinivasReddyAmedapu@yahoo.com printf("nEnter size of matrix B: "); scanf("%d%d",&m2,&n2); read2D(b,m2,n2); add(a,m1,n1,b,m2,n2,c,&m3,&n3); printf("nMatrix An"); print2D(a,m1,n1); printf("nMatrix Bn"); print2D(b,m2,n2); printf("nMatrix Cn"); print2D(c,m3,n3); } void add(int a[20][20],int m1,int n1, int b[20][20],int m2,int n2,int c[20][20],int *mp,int *np) { int i,j; if(m1!=m2||n1!=n2) { printf("nAddition of matrices is not possible"); exit(0); } for(i=0;i<m1;i++) for(j=0;j<n1;j++) c[i][j]=a[i][j]+b[i][j]; *mp=m1; *np=n1; } void print2D(int x[20][20],int m,int n) { int i,j; printf("nContents of matrix aren"); for(i=0;i<m;i++) { printf("n"); for(j=0;j<n;j++) printf("%5d",x[i][j]); } } void read2D(int x[20][20],int m,int n) { int i,j; printf("nEnter values into %d X %d matrixn",m,n); for(i=0;i<m;i++) for(j=0;j<n;j++) scanf("%d",&x[i][j]); } Srinivas Reddy Amedapu, Full Time Research Scholar, CSE Department NATIONAL INSTITUTE OF TECHNOLOGY, TRICHY, TAMIL NADU 11
  • 12. SrinivasReddyAmedapu@yahoo.com Enter size of matrix A : 3 4 Enter values into 3 X 4 matrix 1234 1234 1234 Enter size of matrix B: 3 4 Enter values into 3 X 4 matrix 1111 2222 3333 Matrix A Contents of matrix are 1 2 3 4 1 2 3 4 1 2 3 4 Matrix B Contents of matrix are 1 1 1 1 2 2 2 2 3 3 3 3 Matrix C Contents of matrix are 2 3 4 5 3 4 5 6 4 5 6 7 Enter size of matrix A : 2 3 Enter values into 2 X 3 matrix 123 456 Enter size of matrix B: 2 2 Enter values into 2 X 2 matrix 11 22 Addition of matrices is not possible Srinivas Reddy Amedapu, Full Time Research Scholar, CSE Department NATIONAL INSTITUTE OF TECHNOLOGY, TRICHY, TAMIL NADU 12
  • 13. SrinivasReddyAmedapu@yahoo.com Week 5 (b) Write a C program that uses functions to perform the following: ii) Multiplication of Two Matrices #include<stdio.h> void main() { int a[20][20],b[20][20],c[20][20]; int m1,m2,m3,n1,n2,n3; void read2D(),print2D(),multiply(); printf("nEnter size of matrix A : "); scanf("%d%d",&m1,&n1); read2D(a,m1,n1); printf("nEnter size of matrix B: "); scanf("%d%d",&m2,&n2); read2D(b,m2,n2); multiply(a,m1,n1,b,m2,n2,c,&m3,&n3); printf("nMatrix An"); print2D(a,m1,n1); printf("nMatrix Bn"); print2D(b,m2,n2); printf("nMatrix A x Bn"); print2D(c,m3,n3); } void multiply(int a[20][20],int m1,int n1, int b[20][20],int m2,int n2,int c[20][20],int *mp,int *np) { int i,j,k; if(n1!=m2) { printf("nMultiplication of matrices is not possible"); exit(0); } for(i=0;i<m1;i++) { for(j=0;j<n2;j++) { c[i][j]=0; for(k=1;k<n1;k++) c[i][j]=c[i][j]+a[i][k]*b[k][j]; } } *mp=m1; *np=n2; } Srinivas Reddy Amedapu, Full Time Research Scholar, CSE Department NATIONAL INSTITUTE OF TECHNOLOGY, TRICHY, TAMIL NADU 13
  • 14. SrinivasReddyAmedapu@yahoo.com void print2D(int x[20][20],int m,int n) { int i,j; printf("nContents of matrix aren"); for(i=0;i<m;i++) { printf("n"); for(j=0;j<n;j++) printf("%5d",x[i][j]); } } void read2D(int x[20][20],int m,int n) { int i,j; printf("nEnter values into %d X %d matrixn",m,n); for(i=0;i<m;i++) for(j=0;j<n;j++) scanf("%d",&x[i][j]); } Enter size of matrix A : 2 4 Enter values into 2 X 4 matrix 1234 1111 Enter size of matrix B: 4 1 Enter values into 4 X 1 matrix 1234 Matrix A Contents of matrix are 1 2 3 4 1 1 1 1 Matrix B Contents of matrix are 1 2 3 4 Matrix A x B Contents of matrix are 29 9 Srinivas Reddy Amedapu, Full Time Research Scholar, CSE Department NATIONAL INSTITUTE OF TECHNOLOGY, TRICHY, TAMIL NADU 14
  • 15. SrinivasReddyAmedapu@yahoo.com Enter size of matrix A : 2 4 Enter values into 2 X 4 matrix 1234 5678 Enter size of matrix B: 2 3 Enter values into 2 X 3 matrix 444 777 Multiplication of matrices is not possible Enter size of matrix A : 3 4 Enter values into 3 X 4 matrix 1234 5678 9 10 11 12 Enter size of matrix B: 4 5 Enter values into 4 X 5 matrix 11111 22222 33333 44444 Matrix A Contents of matrix are 1 2 3 4 5 6 7 8 9 10 11 12 Matrix B Contents of matrix are 1 1 1 1 1 2 2 2 2 2 3 3 3 3 3 4 4 4 4 4 Matrix A x B Contents of matrix are 29 29 29 29 29 65 65 65 65 65 101 101 101 101 101 Srinivas Reddy Amedapu, Full Time Research Scholar, CSE Department NATIONAL INSTITUTE OF TECHNOLOGY, TRICHY, TAMIL NADU 15
  • 16. SrinivasReddyAmedapu@yahoo.com Week 6 a) Write a C program that uses functions to perform the following operations: i) To insert a sub-string in to a given main string from a given position. ii) To delete n Characters from a given position in a given string. b) Write a C program to determine if the given string is a palindrome or not To insert a sub-string in to a given main string from a given position. #include<stdio.h> void main() { char str[500],sub[100]; int n1,n2,i,j,loc; printf("nEnter main string: "); scanf("%s",str); printf("nEnter sub string: "); scanf("%s",sub); printf("nEnter position: "); scanf("%d",&loc); printf("nMain string: %s",str); printf("nSub string: %s",sub); n1=strlen(str); n2=strlen(sub); if(loc>n1) { printf("nPosition is out of range"); exit(0); } for(i=n1;i>=loc;i--) str[i+n2]=str[i]; j=0; while(sub[j]) { str[loc+j]=sub[j]; j++; } printf("nMain string: %s",str); printf("nSub string: %s",sub); } Srinivas Reddy Amedapu, Full Time Research Scholar, CSE Department NATIONAL INSTITUTE OF TECHNOLOGY, TRICHY, TAMIL NADU 16
  • 17. SrinivasReddyAmedapu@yahoo.com INPUT/OUTPUT Enter main string: JntuHyderabad Enter sub string: ASReddy Enter position: 4 Main string: JntuHyderabad Sub string: ASReddy Main string: JntuASReddyHyderabad Sub string: ASReddy Enter main string: AravindReddyJNTUH Enter sub string: 12011U0502 Enter position: 12 Main string: AravindReddyJNTUH Sub string: 12011U0502 Main string: AravindReddy12011U0502JNTUH Sub string: 12011U0502 To delete n Characters from a given position in a given string. #include<stdio.h> void main() { char str[500]; int n,i,loc; printf("nEnter a string: "); scanf("%s",str); printf("nEnter number of characters to be deleted: "); scanf("%d",&n); printf("nEnter position from which deletion should be done: "); scanf("%d",&loc); if(loc+n>strlen(str)) { printf("nDeletion not possible"); printf("nToo many characters from the given location"); exit(0); } Srinivas Reddy Amedapu, Full Time Research Scholar, CSE Department NATIONAL INSTITUTE OF TECHNOLOGY, TRICHY, TAMIL NADU 17
  • 18. SrinivasReddyAmedapu@yahoo.com i=loc; while(str[i+n]) { str[i]=str[i+n]; i++; } str[i]=str[i+n]; printf("nString after deletion: %s",str); } INPUT/OUTPUT Enter a string: AravindReddyJNTU Enter number of characters to be deleted: 5 Enter position from which deletion should be done: 7 String after deletion: AravindJNTU Enter a string: AravindReddyNarmetta12011U0502 Enter number of characters to be deleted: 8 Enter position from which deletion should be done: 12 String after deletion: AravindReddy12011U0502 b) Write a C program to determine if the given string is a palindrome or not #include<stdio.h> #include<string.h> void main() { char str[500]; int n,i; printf("nEnter a string: "); scanf("%s",str); n=strlen(str); for(i=0;i<n/2;i++) if(str[i]!=str[n-i-1]) break; if(i==n/2) printf("n%s is palindrome",str); else printf("n%s is not palindrome",str); } Srinivas Reddy Amedapu, Full Time Research Scholar, CSE Department NATIONAL INSTITUTE OF TECHNOLOGY, TRICHY, TAMIL NADU 18
  • 19. SrinivasReddyAmedapu@yahoo.com Enter a string: madam madam is palindrome Enter a string: aravind aravind is not palindrome Enter a string: aravindnivara aravindnivara is palindrome Enter a string: jntutnj jntutnj is palindrome Enter a string: JNTUH JNTUH is not palindrome Week 7 a) 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. b) Write a C program to count the lines, words and characters in a given text. #include<stdio.h> void main() { char str[500],sub[100]; int n1,n2,i,j,loc; printf("nEnter main string: "); scanf("%s",str); printf("nEnter sub string: "); scanf("%s",sub); i=0; while(str[i]) { j=0; while(str[i+j]&&sub[j]&&str[i+j]==sub[j]) j++; if(sub[j]==NULL) break; i=i+1; } if(sub[j]==NULL) printf("nSub string available at %d location",i+1); else printf("nSub String not available : %d",-1); } Srinivas Reddy Amedapu, Full Time Research Scholar, CSE Department NATIONAL INSTITUTE OF TECHNOLOGY, TRICHY, TAMIL NADU 19
  • 20. SrinivasReddyAmedapu@yahoo.com INPUT/OUTPUT Enter main string: AravindReddy Enter sub string: Reddy Sub string available at 8 location Enter main string: AravindJNTUcse Enter sub string: JNTU Sub string available at 8 location Enter main string: SrinivasReddy Enter sub string: vas Sub string available at 6 location Enter main string: FirstYear Enter sub string: irt Sub String not available : -1 Week 7 (b) Write a C program to count the lines, words and characters in a given text. Week 8 (a) Write a program to generate Pascal’s triangle. First Model using Arrays #include<stdio.h> void main() { int x[50][50],i,j,spaces,l,n; printf("nThis is a program to generate Pascal triangle"); printf("nHow many lines you want : "); scanf("%d",&n); for(i=0;i<n;i++) for(j=0;j<=i;j++) if(j==0||j==i) x[i][j]=1; else x[i][j]=x[i-1][j-1]+x[i-1][j]; spaces=36; for(i=0;i<n;i++) { printf("nn"); for(l=0;l<=spaces;l++) printf(" "); for(j=0;j<=i;j++) printf("%4d",x[i][j]); spaces=spaces-2; } } Srinivas Reddy Amedapu, Full Time Research Scholar, CSE Department NATIONAL INSTITUTE OF TECHNOLOGY, TRICHY, TAMIL NADU 20
  • 21. SrinivasReddyAmedapu@yahoo.com This is a program to generate Pascal triangle How many lines you want : 7 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 1 5 10 10 5 1 1 6 15 20 15 6 1 Second Model Without Arrays #include<stdio.h> void main() { int i,j,l,n,ncr,spaces; printf("nEnter number of lines to be printed: "); scanf("%d",&n); spaces=38; for(i=0;i<=n;i++) { printf("nn"); for(l=1;l<=spaces;l++) printf(" "); for(j=0;j<=i;j++) { if(j==0||j==i) ncr=1; else ncr=fact(i)/(fact(i-j)*fact(j)); printf("%4d",ncr); } spaces=spaces-2; } } Srinivas Reddy Amedapu, Full Time Research Scholar, CSE Department NATIONAL INSTITUTE OF TECHNOLOGY, TRICHY, TAMIL NADU 21
  • 22. SrinivasReddyAmedapu@yahoo.com int fact(int n) { int i,f=1; for(i=1;i<=n;i++) f=f*i; return f; } INPUT/OUTPUT Enter number of lines to be printed: 5 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 1 5 10 10 5 1 Week 8 (b) Write a C program to construct a pyramid of numbers. (i) #include<stdio.h> void main() { int i,j,l,n,sp; printf("nHow many lines you want ? "); scanf("%d",&n); sp=35; for(i=1;i<=n;i++) { printf("n"); for(l=1;l<sp;l++) printf(" "); for(j=1;j<=i;j++) printf("%4d",1); sp=sp-2; } } Srinivas Reddy Amedapu, Full Time Research Scholar, CSE Department NATIONAL INSTITUTE OF TECHNOLOGY, TRICHY, TAMIL NADU 22
  • 23. SrinivasReddyAmedapu@yahoo.com How many lines you want ? 7 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 (ii) #include<stdio.h> void main() { int i,j,k,l,n,spaces; clrscr(); printf("nThis is a dymand pattern program"); printf("nEnter n value "); scanf("%d",&n); spaces=36; for(i=1;i<=n;i++) { printf("n"); for(l=1;l<=spaces;l++) printf(" "); for(j=1;j<=i;j++) printf("%4d",i); spaces-=2; } spaces=spaces+4; for(i=n-1;i>=1;i--) { printf("n"); for(l=1;l<=spaces;l++) printf(" "); for(j=1;j<=i;j++) printf("%4d",i); spaces+=2; } } Srinivas Reddy Amedapu, Full Time Research Scholar, CSE Department NATIONAL INSTITUTE OF TECHNOLOGY, TRICHY, TAMIL NADU 23
  • 24. SrinivasReddyAmedapu@yahoo.com This is a dymand pattern program Enter n value 7 1 2 2 3 3 3 4 4 4 4 5 5 5 5 5 6 6 6 6 6 6 7 7 7 7 7 7 7 6 6 6 6 6 6 5 5 5 5 5 4 4 4 4 3 3 3 2 2 1 (iii) void main() { int i,j,k,l,n,spaces; printf("nThis is a dymand pattern program"); printf("nEnter n value "); scanf("%d",&n); spaces=36; for(i=1;i<=n;i++) { printf("n"); for(l=1;l<=spaces;l++) printf(" "); for(j=1;j<=i;j++) printf("%4d",j); for(j=i-1;j>=1;j--) printf("%4d",j); spaces-=4; } spaces=spaces+8; for(i=n-1;i>=1;i--) { printf("n"); for(l=1;l<=spaces;l++) printf(" "); for(j=1;j<=i;j++) printf("%4d",j); for(j=i-1;j>=1;j--) printf("%4d",j); spaces+=4; } } Srinivas Reddy Amedapu, Full Time Research Scholar, CSE Department NATIONAL INSTITUTE OF TECHNOLOGY, TRICHY, TAMIL NADU 24
  • 25. SrinivasReddyAmedapu@yahoo.com This is a dymand pattern program Enter n value 7 1 1 2 1 1 2 3 2 1 1 2 3 4 3 2 1 1 2 3 4 5 4 3 2 1 1 2 3 4 5 6 5 4 3 2 1 1 2 3 4 5 6 7 6 5 4 3 2 1 1 2 3 4 5 6 5 4 3 2 1 1 2 3 4 5 4 3 2 1 1 2 3 4 3 2 1 1 2 3 2 1 1 2 1 1 Some more patterns void main() { int i,j,n; printf("nThis is a pattern program"); printf("nEnter how many lines you want : "); scanf("%d",&n); for(i=1;i<=n;i++) //Program done by Srinivas Reddy Amedapu { //SrinivasReddyAmedapu@yahoo.com printf("n"); // 9490 456 987 for(j=1;j<=i;j++) printf("%4d",j); } } This is a pattern program Enter how many lines you want : 7 1 1 2 1 2 3 1 2 3 4 1 2 3 4 5 1 2 3 4 5 6 1 2 3 4 5 6 7 Srinivas Reddy Amedapu, Full Time Research Scholar, CSE Department NATIONAL INSTITUTE OF TECHNOLOGY, TRICHY, TAMIL NADU 25
  • 26. SrinivasReddyAmedapu@yahoo.com void main() { int i,j,n; printf("nThis is a pattern program"); printf("nEnter how many lines you want : "); scanf("%d",&n); for(i=1;i<=n;i++) { printf("n"); for(j=1;j<=i;j++) printf("%4d",i); } } This is a pattern program Enter how many lines you want : 7 1 2 2 3 3 3 4 4 4 4 5 5 5 5 5 6 6 6 6 6 6 7 7 7 7 7 7 7 //Program done by Srinivas Reddy Amedapu //SrinivasReddyAmedapu@yahoo.com void main() // 9490 456 987 { int i,j,n,x; printf("nThis is a pattern program"); printf("nEnter how many lines you want : "); scanf("%d",&n); x=1; for(i=1;i<=n;i++) { printf("n"); for(j=1;j<=i;j++) { printf("%4d",x); x=x+1; } } } Srinivas Reddy Amedapu, Full Time Research Scholar, CSE Department NATIONAL INSTITUTE OF TECHNOLOGY, TRICHY, TAMIL NADU 26
  • 27. SrinivasReddyAmedapu@yahoo.com This is a pattern program Enter how many lines you want : 7 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 void main() { int i,j,n,x; printf("nThis is a pattern program"); printf("nEnter how many lines you want : "); scanf("%d",&n); x=n*(n+1)/2; for(i=1;i<=n;i++) { printf("n"); for(j=1;j<=i;j++) { printf("%4d",x); x=x-1; } } } //Program done by Srinivas Reddy Amedapu //SrinivasReddyAmedapu@yahoo.com This is a pattern program // 9490 456 987 Enter how many lines you want : 7 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 Srinivas Reddy Amedapu, Full Time Research Scholar, CSE Department NATIONAL INSTITUTE OF TECHNOLOGY, TRICHY, TAMIL NADU 27
  • 28. SrinivasReddyAmedapu@yahoo.com void main() { int i,j,n,x; printf("nThis is a pattern program"); printf("nEnter how many lines you want : "); scanf("%d",&n); x=n; for(i=1;i<=n;i++) { printf("n"); for(j=1;j<=i;j++) printf("%4d",x); x=x-1; } } This is a pattern program Enter how many lines you want : 7 7 6 6 5 5 5 4 4 4 4 3 3 3 3 3 2 2 2 2 2 2 1 1 1 1 1 1 1 //Program done by Srinivas Reddy Amedapu //SrinivasReddyAmedapu@yahoo.com void main() // 9490 456 987 { int i,j,n,x; printf("nThis is a pattern program"); printf("nEnter how many lines you want : "); scanf("%d",&n); x=n; for(i=1;i<=n;i++) { printf("n"); x=n-i+1; for(j=1;j<=i;j++) { printf("%4d",x); x=x+1; } } } Srinivas Reddy Amedapu, Full Time Research Scholar, CSE Department NATIONAL INSTITUTE OF TECHNOLOGY, TRICHY, TAMIL NADU 28
  • 29. SrinivasReddyAmedapu@yahoo.com This is a pattern program Enter how many lines you want : 7 7 6 7 5 6 7 4 5 6 7 3 4 5 6 7 2 3 4 5 6 7 1 2 3 4 5 6 7 void main() { int i,j,n,x; printf("nThis is a pattern program"); //Program done by Srinivas Reddy Amedapu printf("nEnter how many lines you want : "); //SrinivasReddyAmedapu@yahoo.com scanf("%d",&n); // 9490 456 987 x=n; for(i=1;i<=n;i++) { printf("n"); x=n; for(j=1;j<=i;j++) { printf("%4d",x); x=x-1; } } } This is a pattern program Enter how many lines you want : 7 7 7 6 7 6 5 7 6 5 4 7 6 5 4 3 7 6 5 4 3 2 7 6 5 4 3 2 1 Srinivas Reddy Amedapu, Full Time Research Scholar, CSE Department NATIONAL INSTITUTE OF TECHNOLOGY, TRICHY, TAMIL NADU 29
  • 30. SrinivasReddyAmedapu@yahoo.com void main() { int i,j,n,l,spaces; printf("nThis is a pattern program"); printf("nEnter how many lines you want : "); scanf("%d",&n); spaces=25; for(i=n;i>=1;i--) { printf("n"); for(l=1;l<=spaces;l++) //Program done by Srinivas Reddy Amedapu printf(" "); //SrinivasReddyAmedapu@yahoo.com for(j=1;j<=i;j++) // 9490 456 987 printf("%4d",j); spaces=spaces+4; } } This is a pattern program Enter how many lines you want : 7 1 2 3 4 5 6 7 1 2 3 4 5 6 1 2 3 4 5 1 2 3 4 1 2 3 1 2 1 void main() { int i,j,n; printf("nThis is a pattern program"); printf("nEnter how many lines you want : "); scanf("%d",&n); for(i=n;i>=1;i--) { printf("n"); for(j=1;j<=i;j++) printf("%4d",i); } } Srinivas Reddy Amedapu, Full Time Research Scholar, CSE Department NATIONAL INSTITUTE OF TECHNOLOGY, TRICHY, TAMIL NADU 30
  • 31. SrinivasReddyAmedapu@yahoo.com This is a pattern program Enter how many lines you want : 7 7 7 7 7 7 7 7 6 6 6 6 6 6 5 5 5 5 5 4 4 4 4 3 3 3 2 2 1 void main() { int i,j,n,x; //Program done by Srinivas Reddy Amedapu //SrinivasReddyAmedapu@yahoo.com printf("nThis is a pattern program"); // 9490 456 987 printf("nEnter how many lines you want : "); scanf("%d",&n); for(i=n;i>=1;i--) { printf("n"); x=i*(i+1)/2-i; for(j=1;j<=i;j++) { x=x+1; printf("%4d",x); } } } This is a pattern program Enter how many lines you want : 7 22 23 24 25 26 27 28 16 17 18 19 20 21 11 12 13 14 15 7 8 9 10 4 5 6 2 3 1 Srinivas Reddy Amedapu, Full Time Research Scholar, CSE Department NATIONAL INSTITUTE OF TECHNOLOGY, TRICHY, TAMIL NADU 31
  • 32. SrinivasReddyAmedapu@yahoo.com void main() { int i,j,n,x,diff,temp; printf("nThis is a pattern program"); printf("nEnter how many lines you want : "); scanf("%d",&n); temp=0; diff=n; for(i=n;i>=1;i--) { printf("n"); temp=temp+diff; //Program done by Srinivas Reddy Amedapu diff=diff-1; //SrinivasReddyAmedapu@yahoo.com x=temp; // 9490 456 987 for(j=1;j<=i;j++) { printf("%4d",x); x=x-1; } } } This is a pattern program Enter how many lines you want : 7 7 6 5 4 3 2 1 13 12 11 10 9 8 18 17 16 15 14 22 21 20 19 25 24 23 27 26 28 void main() { int i,j,n,x; printf("nThis is a pattern program"); printf("nEnter how many lines you want : "); scanf("%d",&n); x=1; for(i=n;i>=1;i--) { printf("n"); for(j=1;j<=i;j++) printf("%4d",x); x=x+1; } } Srinivas Reddy Amedapu, Full Time Research Scholar, CSE Department NATIONAL INSTITUTE OF TECHNOLOGY, TRICHY, TAMIL NADU 32
  • 33. SrinivasReddyAmedapu@yahoo.com This is a pattern program Enter how many lines you want : 7 1 1 1 1 1 1 1 2 2 2 2 2 2 //Program done by Srinivas Reddy Amedapu 3 3 3 3 3 //SrinivasReddyAmedapu@yahoo.com 4 4 4 4 // 9490 456 987 5 5 5 6 6 7 void main() { int i,j,n,x; printf("nThis is a pattern program"); printf("nEnter how many lines you want : "); scanf("%d",&n); for(i=n;i>=1;i--) { printf("n"); x=n; for(j=1;j<=i;j++) { printf("%4d",x); x=x-1; } } } This is a pattern program Enter how many lines you want : 7 7 6 5 4 3 2 1 7 6 5 4 3 2 7 6 5 4 3 7 6 5 4 7 6 5 7 6 7 Srinivas Reddy Amedapu, Full Time Research Scholar, CSE Department NATIONAL INSTITUTE OF TECHNOLOGY, TRICHY, TAMIL NADU 33
  • 34. SrinivasReddyAmedapu@yahoo.com void main() { int i,j,n,x; clrscr(); printf("nThis is a pattern program"); //Program done by Srinivas Reddy Amedapu printf("nEnter how many lines you want : "); //SrinivasReddyAmedapu@yahoo.com scanf("%d",&n); // 9490 456 987 for(i=n;i>=1;i--) { printf("n"); x=n-i+1; for(j=1;j<=i;j++) { printf("%4d",x); x=x+1; } } } This is a pattern program Enter how many lines you want : 7 1 2 3 4 5 6 7 2 3 4 5 6 7 3 4 5 6 7 4 5 6 7 5 6 7 6 7 7 void main() { int i,j,n,l,spaces,x; printf("nThis is a pattern program"); printf("nEnter how many lines you want : "); scanf("%d",&n); spaces=35; x=1; for(i=1;i<=n;i++) { printf("n"); for(l=1;l<=spaces;l++) printf(" "); for(j=1;j<=i;j++) //Program done by Srinivas Reddy Amedapu { //SrinivasReddyAmedapu@yahoo.com printf("%4d",x); // 9490 456 987 x=x+1; } Srinivas Reddy Amedapu, Full Time Research Scholar, CSE Department NATIONAL INSTITUTE OF TECHNOLOGY, TRICHY, TAMIL NADU 34
  • 35. SrinivasReddyAmedapu@yahoo.com spaces=spaces-2; } } This is a pattern program Enter how many lines you want : 4 1 2 3 4 5 6 7 8 9 10 void main() { int i,j,n,l,spaces; printf("nThis is a pattern program"); printf("nEnter how many lines you want : "); scanf("%d",&n); spaces=35; for(i=1;i<=n;i++) { printf("n"); for(l=1;l<=spaces;l++) printf(" "); for(j=1;j<=i*2-1;j++) printf("%4d",i); spaces=spaces-4; } } This is a pattern program Enter how many lines you want : 4 1 2 2 2 3 3 3 3 3 4 4 4 4 4 4 4 void main() { int i,j,n,l,spaces; printf("nThis is a pattern program"); //Program done by Srinivas Reddy Amedapu printf("nEnter how many lines you want : "); //SrinivasReddyAmedapu@yahoo.com scanf("%d",&n); // 9490 456 987 spaces=35; for(i=1;i<=n;i++) { Srinivas Reddy Amedapu, Full Time Research Scholar, CSE Department NATIONAL INSTITUTE OF TECHNOLOGY, TRICHY, TAMIL NADU 35
  • 36. SrinivasReddyAmedapu@yahoo.com printf("n"); for(l=1;l<=spaces;l++) printf(" "); for(j=1;j<=i;j++) printf("%4d",j); for(j=i-1;j>=1;j--) printf("%4d",j); spaces=spaces-4; } } This is a pattern program Enter how many lines you want : 4 1 1 2 1 1 2 3 2 1 1 2 3 4 3 2 1 Week 9 Write a C program to read in two numbers, x and n, and then compute the sum of this geometric progression: 1+x+x2+x3+………….+xn. For example: if n is 3 and x is 5, then the program computes 1+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. Have your program print an error message if n<0, then go back and read in the next pair of numbers of without computing the sum. Are any values of x also illegal ? If so, test for them too. Week 10 a) 2’s complement of a number is obtained by scanning it from right to left and complementing all the bits after the first appearance of a 1. Thus 2’s complement of 11100 is 00100. Write a C program to find the 2’s complement of a binary number. b) Write a C program to convert a Roman numeral to its decimal equivalent. Srinivas Reddy Amedapu, Full Time Research Scholar, CSE Department NATIONAL INSTITUTE OF TECHNOLOGY, TRICHY, TAMIL NADU 36
  • 37. SrinivasReddyAmedapu@yahoo.com Week 11 Write a C program that uses functions to perform the following operations: i) Reading a complex number ii) Writing a complex number iii) Addition of two complex numbers iv) Multiplication of two complex numbers (Note: represent complex number using a structure.) struct complex { int real; int imag; }; void main() { struct complex c1,c2,c3,c4; void read(),display(); struct complex add(),mult(); read(&c1); read(&c2); printf("nEntered complex numbers aren"); display(c1); display(c2); c3=add(c1,c2); c4=mult(c1,c2); printf("nAddition of two complex numbersn"); display(c3); printf("nMultiplication of two complex numbersn"); display(c4); } void read(struct complex *p) { printf("nEnter Complex number (real imaginary)"); scanf("%d%d",&p->real,&p->imag); } void display(struct complex c) { printf("nComplex number is "); printf("n%d %di",c.real,c.imag); } Srinivas Reddy Amedapu, Full Time Research Scholar, CSE Department NATIONAL INSTITUTE OF TECHNOLOGY, TRICHY, TAMIL NADU 37
  • 38. SrinivasReddyAmedapu@yahoo.com struct complex add(struct complex x, struct complex y) { struct complex z; z.real=x.real+y.real; z.imag=x.imag+y.imag; return z; } struct complex mult(struct complex x, struct complex y) { struct complex z; z.real=x.real*y.real-x.imag*y.imag; z.imag=x.imag*y.real+x.real*y.imag; return z; } Enter Complex number (real imaginary)2 3 Enter Complex number (real imaginary)4 7 Enter complex numbers are Complex number is 2 3i Complex number is 4 7i Addition of two complex numbers Complex number is 6 10i Multiplication of two complex numbers Complex number is -13 26i Srinivas Reddy Amedapu, Full Time Research Scholar, CSE Department NATIONAL INSTITUTE OF TECHNOLOGY, TRICHY, TAMIL NADU 38
  • 39. SrinivasReddyAmedapu@yahoo.com Week 12 a) Write a C program which copies one file to another. #include<stdio.h> void main(int argc,char* argv[]) { FILE *fp1,*fp2; char ch; if(argc!=3) { printf("nUse Command Properly"); printf("nCommand SourceFileName TargetFileName"); exit(0); } fp1=fopen(argv[1],"r"); if(fp1==NULL) { printf("nSource File Not Existing"); exit(1); } fp2=fopen(argv[2],"w"); ch=fgetc(fp1); while(ch!=EOF) { fputc(ch,fp2); ch=fgetc(fp1); } printf("nFile Copied"); fclose(fp1); fclose(fp2); } C:TCBIN>dir asrc*.* Volume in drive C has no label. Volume Serial Number is 60A8-805B Directory of C:TCBIN 01/05/2013 11:46 PM 485 ASRCPY.BAK 01/05/2013 11:46 PM 485 ASRCPY.C 01/05/2013 11:46 PM 12,280 ASRCPY.EXE 5 File(s) 15,883 bytes 0 Dir(s) 36,109,975,552 bytes free Srinivas Reddy Amedapu, Full Time Research Scholar, CSE Department NATIONAL INSTITUTE OF TECHNOLOGY, TRICHY, TAMIL NADU 39
  • 40. SrinivasReddyAmedapu@yahoo.com C:TCBIN>asrcpy asrcpy.c aravind.c File Copied C:TCBIN>asrcpy sss.c yyy.c Source File Not Existing C:TCBIN>asrcpy asrcpy.c yy.c zz.c Use Command Properly Command SourceFileName TargetFileName C:TCBIN>asrcpy aravind.c jntuh.c File Copied C:TCBIN>dir jnt*.* Volume in drive C has no label. Volume Serial Number is 60A8-805B Directory of C:TCBIN 01/05/2013 11:49 PM 485 JNTUH.C 1 File(s) 485 bytes 0 Dir(s) 36,109,844,480 bytes free C:TCBIN>exit b) 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<stdio.h> void main(int argc,char* argv[]) { FILE *fp; int n,n2; char ch; n=atoi(argv[2]); n2=n; fp=fopen(argv[1],"r"); fseek(fp,n+1,0); while(n>0) { fseek(fp,-2,1); ch=fgetc(fp); printf("%c",ch); n=n-1; } Srinivas Reddy Amedapu, Full Time Research Scholar, CSE Department NATIONAL INSTITUTE OF TECHNOLOGY, TRICHY, TAMIL NADU 40
  • 41. SrinivasReddyAmedapu@yahoo.com fseek(fp,n2,0); ch=fgetc(fp); while(ch!=EOF) { printf("%c",ch); ch=fgetc(fp); } fclose(fp); } INPUT/OUTPUT C:TCBIN>type text.dat This is Srinivas Reddy Amedapu, Full Time Research Scholar at NIT Trichy, TN. C:TCBIN>asrfile4 text.dat 25 mA yddeR savinirS si sihTedapu, Full Time Research Scholar at NIT Trichy, TN. C:TCBIN>asrfile4 text.dat 66 TIN ta ralohcS hcraeseR emiT lluF ,upademA yddeR savinirS si sihTTrichy, TN. C:TCBIN>asrfile4 text.dat 45 seR emiT lluF ,upademA yddeR savinirS si sihTearch Scholar at NIT Trichy, TN. C:TCBIN>type aravind.dat I am Aravind Reddy Ravula, studying B.Tech(+MBA) First Year, JNTU Hyderabad. C:TCBIN>asrfile4 aravind.dat 35 gniyduts ,aluvaR yddeR dnivarA ma I B.Tech(+MBA) First Year, JNTU Hyderabad. C:TCBIN>asrfile4 aravind.dat 55 tsriF )ABM+(hceT.B gniyduts ,aluvaR yddeR dnivarA ma IYear, JNTU Hyderabad. C:TCBIN>exit Week 13 a) Write a C programme to display the contents of a file. #include<stdio.h> void main(int argc,char* argv[]) { FILE *fp; char ch; if(argc!=2) { printf("nUse Command Properly"); printf("nCommand FileName"); exit(0); } Srinivas Reddy Amedapu, Full Time Research Scholar, CSE Department NATIONAL INSTITUTE OF TECHNOLOGY, TRICHY, TAMIL NADU 41
  • 42. SrinivasReddyAmedapu@yahoo.com fp=fopen(argv[1],"r"); if(fp==NULL) { printf("nSource File Not Existing"); exit(1); } ch=fgetc(fp); while(ch!=EOF) { printf("%c",ch); ch=fgetc(fp); } fclose(fp); } C:TCBIN>asrtype yy.c Source File Not Existing C:TCBIN>asrtype simple.c void main() { printf("nWelcome to JNTU--Aravind Reddy CSE"); } C:TCBIN>asrtype simple.c asrtype.c Use Command Properly Command FileName C:TCBIN>exit b) Write a C programme to merge two files into a third file ( i.e., the contents of the first file followed by those of the second are put in the third file) #include<stdio.h> void main(int argc,char* argv[]) { FILE *fp1,*fp2,*fp3; char ch; if(argc!=4) { printf("nUse Command Properly"); printf("nCommand SourceFileName1 SourceFileName2 TargetFileName"); exit(0); } Srinivas Reddy Amedapu, Full Time Research Scholar, CSE Department NATIONAL INSTITUTE OF TECHNOLOGY, TRICHY, TAMIL NADU 42
  • 43. SrinivasReddyAmedapu@yahoo.com fp1=fopen(argv[1],"r"); if(fp1==NULL) { printf("nSource File1 Not Existing"); exit(1); } fp3=fopen(argv[3],"w"); ch=fgetc(fp1); while(ch!=EOF) { fputc(ch,fp3); ch=fgetc(fp1); } fclose(fp1); fp2=fopen(argv[2],"r"); if(fp2==NULL) { printf("nSource File 2 Not Existing"); fclose(fp3); exit(2); } ch=fgetc(fp2); while(ch!=EOF) { fputc(ch,fp3); ch=fgetc(fp2); } fclose(fp2); fclose(fp3); } INPUT/OUTPUT C:TCBIN>asrmerg simple.c hworld.c aravind.c C:TCBIN>type simple.c void main() { printf("nWelcome to JNTU--Aravind Reddy CSE"); } Srinivas Reddy Amedapu, Full Time Research Scholar, CSE Department NATIONAL INSTITUTE OF TECHNOLOGY, TRICHY, TAMIL NADU 43
  • 44. SrinivasReddyAmedapu@yahoo.com C:TCBIN>type hworld.c #include<stdio.h> void main() { printf("nHello World!"); printf("nThis is Aravind Reddy"); printf("nRoll No. 12011U0502, CSE"); } C:TCBIN>type aravind.c void main() { printf("nWelcome to JNTU--Aravind Reddy CSE"); } #include<stdio.h> void main() { printf("nHello World!"); printf("nThis is Aravind Reddy"); printf("nRoll No. 12011U0502, CSE"); } C:TCBIN>exit Week 14 Write a C program that uses functions to perform the following operations on singly linked list.: i) Creation ii) Insertion iii) Deletion iv) Traversal #include<stdio.h> #include<alloc.h> struct node { int data; struct node *link; }; typedef struct node* nodeptr; void main() { int val,pos; nodeptr list; nodeptr create(); void print(),insertnth(nodeptr*,int,int); int deletenth(nodeptr*,int); Srinivas Reddy Amedapu, Full Time Research Scholar, CSE Department NATIONAL INSTITUTE OF TECHNOLOGY, TRICHY, TAMIL NADU 44
  • 45. SrinivasReddyAmedapu@yahoo.com list=create(); print(list); printf("nEnter Element to be inserted and position : "); scanf("%d%d",&val,&pos); insertnth(&list,val,pos); print(list); printf("nWhich position node you want to delete? "); scanf("%d",&pos); val=deletenth(&list,pos); printf("nDeleted node value is %d",val); print(list); } int deletenth(nodeptr *lp,int pos) { int val=-1; nodeptr p,q,r; if(*lp==NULL) printf("nLinked List is empty, delete not possible"); else { p=*lp; if(pos==1) { *lp=p->link; val=p->data; free(p); } else { pos=pos-2; while(p&&pos) { p=p->link; pos=pos-1; } if(p) { q=p->link; p->link=q->link; val=q->data; free(q); } else printf("nLess nodes than given node number"); } } return val; } Srinivas Reddy Amedapu, Full Time Research Scholar, CSE Department NATIONAL INSTITUTE OF TECHNOLOGY, TRICHY, TAMIL NADU 45
  • 46. SrinivasReddyAmedapu@yahoo.com void insertnth(nodeptr *lp,int val,int pos) { nodeptr p,q,r; nodeptr getnode(); q=getnode(); q->data=val; q->link=NULL; if(*lp==NULL) *lp=q; else { p=*lp; pos=pos-1; while(p&&pos) { r=p; p=p->link; pos=pos-1; } q->link=r->link; r->link=q; } } nodeptr create() { int val; nodeptr p,q,r; nodeptr getnode(); printf("nEnter 0 (zero) to stopn"); scanf("%d",&val); p=getnode(); r=p; while(val) { q=getnode(); q->data=val; p->link=q; p=q; scanf("%d",&val); } p->link=NULL; p=r->link; free(r); return p; } Srinivas Reddy Amedapu, Full Time Research Scholar, CSE Department NATIONAL INSTITUTE OF TECHNOLOGY, TRICHY, TAMIL NADU 46
  • 47. SrinivasReddyAmedapu@yahoo.com void print(nodeptr p) { printf("nContents of Linked List aren"); while(p) { printf(" %d",p->data); p=p->link; } } nodeptr getnode() { nodeptr p; p=(nodeptr)malloc(sizeof(struct node)); return p; } INPUT/OUTPUT Enter 0 (zero) to stop 11 22 33 44 55 66 77 88 99 0 Contents of Linked List are 11 22 33 44 55 66 77 88 99 Enter Element to be inserted and position : 678 6 Contents of Linked List are 11 22 33 44 55 678 66 77 88 99 Which position node you want to delete? 3 Deleted node value is 33 Contents of Linked List are 11 22 44 55 678 66 77 88 99 Srinivas Reddy Amedapu, Full Time Research Scholar, CSE Department NATIONAL INSTITUTE OF TECHNOLOGY, TRICHY, TAMIL NADU 47
  • 48. SrinivasReddyAmedapu@yahoo.com Week 15 Write C programs that implement stack (its operations) using i) Arrays ii) Pointers Arrays #include<stdio.h> #define MAX 100 void main() { int stack[MAX],top=-1,val,op; void push(),display(),options(); int pop(); clrscr(); options(); while(1) { printf("nSelect option : "); scanf("%d",&op); switch(op) { case 1: printf("nEnter value to be pushed : "); scanf("%d",&val); push(stack,&top,val); break; case 2: val=pop(stack,&top); printf("nValue poped is %d",val); break; case 3: display(stack,top); break; case 4: exit(0); break; //optional ie, non reachable code default:options(); break; //optional, last case } } } void push(int stk[],int *tp,int val) { if(*tp==MAX-1) printf("nStack full, %d not inserted",val); else { *tp=*tp+1; stk[*tp]=val; } } Srinivas Reddy Amedapu, Full Time Research Scholar, CSE Department NATIONAL INSTITUTE OF TECHNOLOGY, TRICHY, TAMIL NADU 48
  • 49. SrinivasReddyAmedapu@yahoo.com int pop(int stk[],int *tp) { int val=-1; if(*tp==-1) printf("nStack empty, no value deleted"); else { val=stk[*tp]; *tp=*tp-1; } return val; } void display(int stk[],int top) { int i; printf("nContents of Stack aren"); for(i=top;i>=0;i--) printf("ntt%4d",stk[i]); } void options() { printf("nAvailable optons aren"); printf("ntt0. Options"); printf("ntt1. Push"); printf("ntt2. Pop"); printf("ntt3. Display"); printf("ntt4. Exit"); } INPUT/OUTPUT Available optons are 0. Options 1. Push 2. Pop 3. Display 4. Exit Select option : 1 Enter value to be pushed : 11 Select option : 1 Enter value to be pushed : 99 Srinivas Reddy Amedapu, Full Time Research Scholar, CSE Department NATIONAL INSTITUTE OF TECHNOLOGY, TRICHY, TAMIL NADU 49
  • 50. SrinivasReddyAmedapu@yahoo.com Select option : 1 Enter value to be pushed : 88 Select option : 3 Contents of Stack are 88 99 11 Select option : 2 Value poped is 88 Select option : 2 Value poped is 99 Select option : 2 Value poped is 11 Select option : 2 Stack empty, no value deleted Value poped is -1 Select option : 4 Pointers #include<stdio.h> struct node { int data; struct node *link; }; typedef struct node* nodeptr; void main() { int op,val; nodeptr sp=NULL; void push(),display(),options(); int pop(); clrscr(); options(); while(1) { printf("nSelect option : "); scanf("%d",&op); Srinivas Reddy Amedapu, Full Time Research Scholar, CSE Department NATIONAL INSTITUTE OF TECHNOLOGY, TRICHY, TAMIL NADU 50
  • 51. SrinivasReddyAmedapu@yahoo.com switch(op) { case 1: printf("nEnter value to be pushed : "); scanf("%d",&val); push(&sp,val); break; case 2: val=pop(&sp); printf("nValue poped is %d",val); break; case 3: display(sp); break; case 4: exit(0); break; //optional ie, non reachable code default:options(); break; //optional, last case } } } void push(nodeptr *spp,int val) { nodeptr p; nodeptr getnode(); p=getnode(); p->data=val; p->link=*spp; *spp=p; } int pop(nodeptr *spp) { int val=-1; nodeptr p; if(*spp==NULL) printf("nStack Empty"); else { p=*spp; *spp=p->link; val=p->data; free(p); } return val; } Srinivas Reddy Amedapu, Full Time Research Scholar, CSE Department NATIONAL INSTITUTE OF TECHNOLOGY, TRICHY, TAMIL NADU 51
  • 52. SrinivasReddyAmedapu@yahoo.com void display(nodeptr p) { printf("nContents of Stack aren"); while(p) { printf("nt%4d",p->data); p=p->link; } } void options() { printf("nAvailable optons aren"); printf("nt0. Options"); printf("nt1. Push"); printf("nt2. Pop"); printf("nt3. Display"); printf("nt4. Exit"); } nodeptr getnode() { nodeptr p; p=(nodeptr)malloc(sizeof(struct node)); return p; } INPUT/OUTPUT Available optons are 0. Options 1. Push 2. Pop 3. Display 4. Exit Select option : 1 Enter value to be pushed : 11 Select option : 1 Enter value to be pushed : 22 Select option : 1 Enter value to be pushed : 44 Select option : 2 Value poped is 44 Srinivas Reddy Amedapu, Full Time Research Scholar, CSE Department NATIONAL INSTITUTE OF TECHNOLOGY, TRICHY, TAMIL NADU 52
  • 53. SrinivasReddyAmedapu@yahoo.com Select option : 3 Contents of Stack are 22 11 Select option : 2 Value poped is 22 Select option : 2 Value poped is 11 Select option : 2 Stack Empty Value poped is -1 Select option : 4 Week 16 Write C programs that implement Queue (its operations) using i) Arrays ii) Pointers Arrays #include<stdio.h> #define MAX 100 void main() { int val,op; int queue[MAX],front=0,rear=-1; int delet(); void insert(),display(),options(); options(); while(1) { printf("nSelect option: "); scanf("%d",&op); switch(op) { case 1: printf("nEnter value to be inserted: "); scanf("%d",&val); insert(queue,&rear,val); break; case 2: val=delet(queue,&front,rear); printf("nDeleted value is %d",val); break; Srinivas Reddy Amedapu, Full Time Research Scholar, CSE Department NATIONAL INSTITUTE OF TECHNOLOGY, TRICHY, TAMIL NADU 53
  • 54. SrinivasReddyAmedapu@yahoo.com case 3: display(queue,front,rear); break; case 4: exit(0); break; default: options(); break; } } } int delet(int q[],int *fp,int r) { int val=-1; if(*fp>r) printf("nQueue empty"); else { val=q[*fp]; *fp=*fp+1; } return val; } void insert(int q[],int *rp,int val) { if(*rp==MAX-1) printf("nQueue full"); else { *rp=*rp+1; q[*rp]=val; } } void display(int q[],int f,int r) { int i; printf("nContents of queue are:n"); for(i=f;i<=r;i++) printf(" %d",q[i]); } Srinivas Reddy Amedapu, Full Time Research Scholar, CSE Department NATIONAL INSTITUTE OF TECHNOLOGY, TRICHY, TAMIL NADU 54
  • 55. SrinivasReddyAmedapu@yahoo.com void options() { printf("nAvailable operations"); printf("nt1. Insert"); printf("nt2. Delete"); printf("nt3. Display"); printf("nt4. Exit"); } Available operations 1. Insert 2. Delete 3. Display 4. Exit Select option: 1 Enter value to be inserted: 11 Select option: 1 Enter value to be inserted: 66 Select option: 1 Enter value to be inserted: 88 Select option: 3 Contents of queue are: 11 66 88 Select option: 2 Deleted value is 11 Select option: 4 Pointers #include<stdio.h> #define MAX 100 struct node { int data; struct node *link; }; typedef struct node* nodeptr; Srinivas Reddy Amedapu, Full Time Research Scholar, CSE Department NATIONAL INSTITUTE OF TECHNOLOGY, TRICHY, TAMIL NADU 55
  • 56. SrinivasReddyAmedapu@yahoo.com void main() { int val,op; nodeptr front=NULL,rear=NULL; int delet(); void insert(),display(),options(); options(); while(1) { printf("nSelect option: "); scanf("%d",&op); switch(op) { case 1: printf("nEnter value to be inserted: "); scanf("%d",&val); insert(&front,&rear,val); break; case 2: val=delet(&front,&rear); printf("nDeleted value is %d",val); break; case 3: display(front); break; case 4: exit(0); break; default: options(); break; } } } int delet(nodeptr *fp,nodeptr *rp) { int val=-1; nodeptr p; if(*fp==NULL) printf("nQueue is Empty"); else { p=*fp; val=p->data; *fp=p->link; if(*fp==NULL) *rp=NULL; } return val; } Srinivas Reddy Amedapu, Full Time Research Scholar, CSE Department NATIONAL INSTITUTE OF TECHNOLOGY, TRICHY, TAMIL NADU 56
  • 57. SrinivasReddyAmedapu@yahoo.com void insert(nodeptr *fp,nodeptr *rp,int val) { nodeptr p; nodeptr getnode(); p=getnode(); p->data=val; p->link=NULL; if(*rp==NULL) *fp=*rp=p; else { (*rp)->link=p; *rp=p; } } void display(nodeptr p) { printf("nContents of queue are:n"); while(p) { printf(" %d",p->data); p=p->link; } } void options() { printf("nAvailable operations"); printf("nt1. Insert"); printf("nt2. Delete"); printf("nt3. Display"); printf("nt4. Exit"); } nodeptr getnode() { nodeptr p; p=(nodeptr)malloc(sizeof(struct node)); return p; } Srinivas Reddy Amedapu, Full Time Research Scholar, CSE Department NATIONAL INSTITUTE OF TECHNOLOGY, TRICHY, TAMIL NADU 57
  • 58. SrinivasReddyAmedapu@yahoo.com Available operations 1. Insert 2. Delete 3. Display 4. Exit Select option: 1 Enter value to be inserted: 11 Select option: 1 Enter value to be inserted: 12 Select option: 1 Enter value to be inserted: 14 Select option: 2 Deleted value is 11 Select option: 3 Contents of queue are: 12 14 Select option: 2 Deleted value is 12 Select option: 2 Deleted value is 14 Select option: 2 Queue is Empty Deleted value is -1 Select option: 3 Contents of queue are: Select option: 4 Srinivas Reddy Amedapu, Full Time Research Scholar, CSE Department NATIONAL INSTITUTE OF TECHNOLOGY, TRICHY, TAMIL NADU 58
  • 59. SrinivasReddyAmedapu@yahoo.com Week 17 Write a C program that uses Stack operations to perform the following: i) Converting infix expression into postfix expression ii) Evaluating the postfix expression Converting infix expression into postfix expression #include<math.h> #include<stdio.h> #include<alloc.h> #include<conio.h> struct node { char data; struct node* link; }; typedef struct node* nodeptr; void main() { char in[100],post[100]; int i,j; nodeptr sp=NULL; void push(); char pop(); printf("nEnter valid infix expression"); printf("nThis program will work for + - * / % ^ operatorsn"); scanf("%s",in); i=0,j=0; while(in[i]) { if(in[i]>='a'&&in[i]<='z') { post[j]=in[i]; j++; } else { if(in[i]=='+'||in[i]=='-'||in[i]=='*' ||in[i]=='/'||in[i]=='%'||in[i]=='^') { while(sp&&compare(in[i],sp->data)<=0) { post[j]=pop(&sp); j++; } push(&sp,in[i]); } Srinivas Reddy Amedapu, Full Time Research Scholar, CSE Department NATIONAL INSTITUTE OF TECHNOLOGY, TRICHY, TAMIL NADU 59
  • 60. SrinivasReddyAmedapu@yahoo.com else { printf("nInvalid Symbol in the expression"); exit(0); } } i++; } while(sp) { post[j]=pop(&sp); j++; } post[j]='0'; printf("nInfix expression: %s",in); printf("nPostfix expression: %s",post); } int compare(char sym1,char sym2) { int diff; diff=priority(sym1)-priority(sym2); return diff; } int priority(char sym) { int p; switch(sym) { case '+': case '-': p=1; break; case '*': case '/': p=2; break; case '%': p=3; break; case '^': p=4; break; } return p; } Srinivas Reddy Amedapu, Full Time Research Scholar, CSE Department NATIONAL INSTITUTE OF TECHNOLOGY, TRICHY, TAMIL NADU 60
  • 61. SrinivasReddyAmedapu@yahoo.com char pop(nodeptr *spp) { int val=-1; nodeptr p; p=*spp; *spp=p->link; val=p->data; free(p); return(val); } void push(nodeptr *spp,char val) { nodeptr p; nodeptr getnode(); p=getnode(); p->data=val; p->link=*spp; *spp=p; } nodeptr getnode() { nodeptr p; p=(nodeptr)malloc(sizeof(struct node)); // malloc -> alloc.h included return p; } INPUT/OUTPUT Enter valid infix expression This program will work for + - * / % ^ operators a+b*c/d-e%f^g Infix expression: a+b*c/d-e%f^g Postfix expression: abc*d/+efg^%- Enter valid infix expression This program will work for + - * / % ^ operators a+b@ Invalid Symbol in the expression Enter valid infix expression This program will work for + - * / % ^ operators a+b%c-d/f+g^h+i*j Infix expression: a+b%c-d/f+g^h+i*j Postfix expression: abc%+df/-gh^+ij*+ Srinivas Reddy Amedapu, Full Time Research Scholar, CSE Department NATIONAL INSTITUTE OF TECHNOLOGY, TRICHY, TAMIL NADU 61
  • 62. SrinivasReddyAmedapu@yahoo.com Evaluating the postfix expression #include<math.h> #include<stdio.h> #include<alloc.h> #include<conio.h> struct node { int data; struct node* link; }; typedef struct node* nodeptr; void main() { int i,val,val1,val2,temp; char post[100]; nodeptr sp=NULL; int evaluate(),pop(); void push(); printf("nEnter postfix expressionn"); scanf("%s",post); i=0; while(post[i]) { if(post[i]>='0'&&post[i]<='9') { temp=post[i]-'0'; push(&sp,temp); } else { if(post[i]=='+'||post[i]=='-'||post[i]=='*' ||post[i]=='/'||post[i]=='^') { val2=pop(&sp); val1=pop(&sp); if(val1==-1||val2==-1) { printf("nExpression Error"); exit(0); } val=evaluate(val1,val2,post[i]); push(&sp,val); } Srinivas Reddy Amedapu, Full Time Research Scholar, CSE Department NATIONAL INSTITUTE OF TECHNOLOGY, TRICHY, TAMIL NADU 62
  • 63. SrinivasReddyAmedapu@yahoo.com else { printf("nInvalid Symbol"); exit(1); } } i=i+1; } val=pop(&sp); printf("n%s = %d",post,val); getch(); // getch -> conio.h included } int evaluate(int a,int b,char sym) { int val; switch(sym) { case '+': val=a+b; break; case '-': val=a-b; break; case '*': val=a*b; break; case '/': val=a/b; break; case '^': val=pow(a,b); // pow -> math.h is included } return val; } int pop(nodeptr *spp) { int val=-1; nodeptr p; p=*spp; *spp=p->link; val=p->data; free(p); return(val); } void push(nodeptr *spp,int val) { nodeptr p; nodeptr getnode(); p=getnode(); p->data=val; p->link=*spp; *spp=p; } Srinivas Reddy Amedapu, Full Time Research Scholar, CSE Department NATIONAL INSTITUTE OF TECHNOLOGY, TRICHY, TAMIL NADU 63
  • 64. SrinivasReddyAmedapu@yahoo.com nodeptr getnode() { nodeptr p; p=(nodeptr)malloc(sizeof(struct node)); // malloc -> alloc.h included return p; } INPUT/OUTPUT Enter postfix expression 23+ 23+ = 5 Enter postfix expression 45+63/-42^+ 45+63/-42^+ = 23 Enter postfix expression 45* 45* = 20 Week 18 Write a C program that implements the following sorting methods to sort a given list of integers in ascending order i) Bubble sort ii) Selection sort Bubble Sort #include<stdio.h> #define MAX 100 void main() { int arr[MAX],n,temp,i,j; void read1D(),print1D(),bubble(); printf("nEnter number of terms: "); scanf("%d",&n); read1D(arr,n); bubble(arr,n); print1D(arr,n); } Srinivas Reddy Amedapu, Full Time Research Scholar, CSE Department NATIONAL INSTITUTE OF TECHNOLOGY, TRICHY, TAMIL NADU 64
  • 65. SrinivasReddyAmedapu@yahoo.com void bubble(int a[],int n) { int i,j,temp; for(i=0;i<n-1;i++) { for(j=0;j<n-i-1;j++) if(a[j]>a[j+1]) { temp=a[j]; a[j]=a[j+1]; a[j+1]=temp; } } } void read1D(int arr[],int n) { int i; printf("nEnter %d valuesn",n); for(i=0;i<n;i++) scanf("%d",&arr[i]); } void print1D(int arr[],int n) { int i; printf("nValues of array are:n"); for(i=0;i<n;i++) printf(" %d",arr[i]); } Enter number of terms: 7 Enter 7 values 11 66 33 99 88 22 44 Values of array are: 11 22 33 44 66 88 99 Enter number terms: 12 Enter 12 values 22 88 33 77 100 222 777 123 876 456 767 121 Values of array are: 22 33 77 88 100 121 123 222 456 767 777 876 Srinivas Reddy Amedapu, Full Time Research Scholar, CSE Department NATIONAL INSTITUTE OF TECHNOLOGY, TRICHY, TAMIL NADU 65
  • 66. SrinivasReddyAmedapu@yahoo.com Week 18 Write a C program that implements the following sorting methods to sort a given list of integers in ascending order ii) Selection sort Week 19 Write C programs that use both recursive and non recursive functions to perform the following searching operations for a Key value in a given list of integers : i) Linear search ii) Binary search Iterative Linear Search #include<stdio.h> void main() { int arr[100],n,val,loc; void read1D(); int lsearch(); printf("nHowmany elements you want to enter? "); scanf("%d",&n); read1D(arr,n); printf("nEnter element to be searched: "); scanf("%d",&val); loc=lsearch(arr,n,val); printf("n%d availabel at %d location",val,loc); } int lsearch(int arr[],int n,int val) { int i; for(i=0;i<n;i++) if(arr[i]==val) return i; return -1; } void read1D(int arr[],int n) { int i; printf("nEnter %d values:n",n); for(i=0;i<n;i++) scanf("%d",&arr[i]); } Srinivas Reddy Amedapu, Full Time Research Scholar, CSE Department NATIONAL INSTITUTE OF TECHNOLOGY, TRICHY, TAMIL NADU 66
  • 67. SrinivasReddyAmedapu@yahoo.com INPUT/OUTPUT Howmany elements you want to enter? 1 Enter 1 values: 1 Enter element to be searched: 1 1 availabel at 0 location Howmany elements you want to enter? 8 Enter 8 values: 11 55 33 77 89 98 22 66 Enter element to be searched: 89 89 availabel at 4 location Howmany elements you want to enter? 12 Enter 12 values: 12 56 89 65 32 11 66 44 99 92 23 48 Enter element to be searched: 10 10 availabel at -1 location Howmany elements you want to enter? 5 Enter 5 values: 12345 Enter element to be searched: 3 3 availabel at 2 location Iterative Binary Search #include<stdio.h> void main() { int arr[100],n,val,loc; void read1D(); int bsearch(); printf("nHowmany elements you want to enter? "); scanf("%d",&n); read1D(arr,n); printf("nEnter element to be searched: "); scanf("%d",&val); loc=bsearch(arr,0,n-1,val); printf("n%d availabel at %d location",val,loc); } Srinivas Reddy Amedapu, Full Time Research Scholar, CSE Department NATIONAL INSTITUTE OF TECHNOLOGY, TRICHY, TAMIL NADU 67
  • 68. SrinivasReddyAmedapu@yahoo.com int bsearch(int arr[],int lb,int ub,int val) { int mid; while(lb<=ub) { mid=(lb+ub)/2; if(arr[mid]==val) return mid; else if(arr[mid]<val) lb=mid+1; else ub=mid-1; } return -1; } void read1D(int arr[],int n) { int i; printf("nEnter %d values:n",n); for(i=0;i<n;i++) scanf("%d",&arr[i]); } INPUT/OUTPUT Howmany elements you want to enter? 7 Enter 7 values: 11 33 45 67 88 90 112 Enter element to be searched: 88 88 availabel at 4 location Howmany elements you want to enter? 5 Enter 5 values: 1 4 7 9 15 Enter element to be searched: 6 6 availabel at -1 location Howmany elements you want to enter? 10 Enter 10 values: 11 14 17 25 28 45 47 56 67 78 Enter element to be searched: 56 56 availabel at 7 location Srinivas Reddy Amedapu, Full Time Research Scholar, CSE Department NATIONAL INSTITUTE OF TECHNOLOGY, TRICHY, TAMIL NADU 68
  • 69. SrinivasReddyAmedapu@yahoo.com Recursive Binary Search #include<stdio.h> void main() { int arr[100],n,val,loc; void read1D(); int bsearch(); printf("nHowmany elements you want to enter? "); scanf("%d",&n); read1D(arr,n); printf("nEnter element to be searched: "); scanf("%d",&val); loc=bsearch(arr,0,n-1,val); printf("n%d availabel at %d location",val,loc); } int bsearch(int a[],int low,int high,int key) { int mid; if(low<=high) { mid=(low+high)/2; if(a[mid]==key) return mid; else if(key<a[mid]) return bsearch(a,low,mid-1,key); else if(key>a[mid]) return bsearch(a,mid+1,high,key); } else return -1; } void read1D(int arr[],int n) { int i; printf("nEnter %d values:n",n); for(i=0;i<n;i++) scanf("%d",&arr[i]); } Srinivas Reddy Amedapu, Full Time Research Scholar, CSE Department NATIONAL INSTITUTE OF TECHNOLOGY, TRICHY, TAMIL NADU 69
  • 70. SrinivasReddyAmedapu@yahoo.com Howmany elements you want to enter? 5 Enter 5 values: 11 22 33 44 55 Enter element to be searched: 22 22 availabel at 1 location Howmany elements you want to enter? 7 Enter 7 values: 12 23 34 45 56 67 78 Enter element to be searched: 66 66 availabel at -1 location Howmany elements you want to enter? 10 Enter 10 values: 10 20 30 40 50 60 70 80 90 100 Enter element to be searched: 80 80 availabel at 7 location Week 20 Write C program that implement the Quick sort method to sort a given list of integers in ascending order: #include<stdio.h> #define MAX 100 int split(int*,int,int); void getdata(int arr[],int n); void display(int arr[],int n); int main() { int arr[MAX],i,n; void quicksort(int*,int,int); printf("nEnter the total number of elements: "); scanf("%d",&n); getdata(arr,n); quicksort(arr,0,n-1); display(arr,n); return 0; } Srinivas Reddy Amedapu, Full Time Research Scholar, CSE Department NATIONAL INSTITUTE OF TECHNOLOGY, TRICHY, TAMIL NADU 70
  • 71. SrinivasReddyAmedapu@yahoo.com void getdata(int arr[],int n) { int i; printf("nEnter the elements which to be sort:n"); for(i=0;i<n;i++) scanf("%d",&arr[i]); } void display(int arr[],int n) { int i; printf("nAfter merge sorting elements are:n"); for(i=0;i<n;i++) printf("%d ",arr[i]); } void quicksort(int a[],int lower,int upper) { int i ; if(upper>lower) { i=split(a,lower,upper); quicksort(a,lower,i-1); quicksort(a,i+1,upper); } } int split(int x[10],int lower,int upper) { int pivot,j,temp,i; pivot=lower; i=lower; j=upper; while(i<j) { while(x[i]<=x[pivot]&&i<upper) i++; while(x[j]>x[pivot]) j--; if(i<j) { temp=x[i]; x[i]=x[j]; x[j]=temp; } } Srinivas Reddy Amedapu, Full Time Research Scholar, CSE Department NATIONAL INSTITUTE OF TECHNOLOGY, TRICHY, TAMIL NADU 71