Appendix F

Practice Problems

There are two sections in this problem set. In the first section, we present 30 short questions. The reader is suggested to test their skills developed so far. The answers to these problems have not been provided. The reader can get the answers by executing them directly in the machine.

In the next section, 40 programming exercises are given. These exercises are not graded, but mixed in nature. Except for a few of these programming problems, we have also provided the solutions (at the end a * is marked). The reader is suggested, not to look at these solutions before a sincere try. It is assumed that the reader will be able to write programs for those problems for which the solution is not provided.

F.1 SECTION — I

Short Questions

What are the outputs of the following code segments?

  1. int a;
    a = 9;
    while (a >= 0)
    {
    	a -= 2;
    	printf(“%d
    ”, a);
    }
  2. Int a;
    a = 9;
    do
    {
    	  a -= 2;
    	  printf(“%d
    ”, a);
    } while (a >= 1);
  3. int a = 9;
    if (a-- < 2)
           printf(“%d”, a);
    else if (a-- < 5)
           printf(“%d”, 2*a);
    else if (a-- < 8)
           printf(“%d”, 3*a);
    else if (a-- < 11)
           printf(“%d”, 4*a);
    else
           printf(“%d”, 5*a);
  4. int i;
    for (i = 1; i <= 15; i++)
    	   printf(“%d
    ”, i++);
    printf(“%d
    ”, i++);
  5. int j;
    j = 0;
    do {
    	   if (j < 5)
    	   {
    		   j += 2;
    		   printf(“%d
    ”, j);
    		   continue;
    	   }
    	   else {
    		    printf(“%d
    ”, ++j);
    		break;
    	   }
    } while (j < 7);
  6. int j;
    j = 0;
    while (j < 7)
    {
    	   if (j < 5)
    	   {
    		   j += 2;
    		   printf(“%d
    ”, j);
    		   continue;
    	   }
    	   else {
    		   printf(“%d
    ”, ++j);
    		break;
    	   }
    }
  7. int b = 15;
    if (!!b)
    	   printf(“b = %d”, !b);
    else
    	   printf(“b = %d”, b);
  8. int x = 3;
    switch(x)
    {
    	   case 1 : printf(“%d
    ”, 2*x);
    		    break;
    	   case 2 : printf(“%d
    ”, 3*x);
    		    break;
    	   case 3 : printf(“%d
    ”, 4*x);
    		    break;
    	   default : printf(“We have come to default
    ”);
    }
  9. int x = 2;
    switch(x)
    {
    	   case 1 : printf(“%d
    ”, 2*x);
    	   case 2 : printf(“%d
    ”, 3*x);
    	   case 3 : printf(“%d
    ”, 4*x);
    	   default : printf(“We have come to default
    ”);
    }
  10. int x = 3;
    switch(x)
    {
    	  default : printf(“We have come to default
    ”);
    		    break;
    	   case 1 : printf(“%d
    ”, 2*x);
    		    break;
    	   case 2 : printf(“%d
    ”, 3*x);
    		    break;
    	   case 3 : printf(“%d
    ”, 4*x);
    		    break;
    }
  11. int x = 3;
    switch(x)
    {
    	   default : printf(“We have come to default
    ”);
    	   case 1 : printf(“%d
    ”, 2*x);
    	   case 2 : printf(“%d
    ”, 3*x);
    		    break;
    	   case 3 : printf(“%d
    ”, 4*x);
    		    break;
    }
  12. int i, a[5];
    for (i = 0; i < 5; i++)
    		scanf(“%d”, &a[i]);
        /* consider input as 2 3 4 5 & 6 */
        for (i = 0; i < 5; i++)
    		printf( “%d”, ++a[i] );
        for (i = 0; i < 5; i++)
    		printf(“%d”, a[i++]);
    
        In case, it is not possible to provide the exact output, give reasons, why it is not possible to do so, and what will happen.
  13. main()
    {
    		int a, asqr;
    		scanf(“%d”, &a);
    		printf(“a = %d	a_square = %d
    ”, a, square(a));
    		return 0;
    }
    int square(int x)
    {
    		return x*x;
    }
  14. main()
    {
    		char a[] = “Dear I Always“;
    		char *ptr = “remember you”;
    		int m1, m2;
    		m1 = goodone(a);
    		m2 = goodone(ptr);
    		printf(“%d + %d = %d
    ”, m1, m2, m1 + m2);
    		return 0;
    }
    int goodone(char *pa)
    	{
    		char *ptr = pa;
    		while (*pa++ != ‘’);
    		return (pa - ptr - 1);
    }
  15. main()
    {
    		float *ptr1, *ptr2;
    		int x = 5000, y = 1000;
    		int funny(float *, float *);
    		ptr1 = (float *)(x);
    		ptr2 = (float *)(y);
    		printf(“funny value = %d
    ”, funny(ptr1, ptr2));
    		return 0;
    }
    int funny(float *pa, float *pb)
    {
    		int x;
    
    		x = (pa - pb)/2;
    		return x;
    }
  16. int fst = ‘a’;
    int lst = ‘z’;
    printf(“%c
    ”, fst >> 1);
    printf(“%d
    ”, fst >> 1);
    printf(“%c
    ”, lst << 1);
    printf(“%d
    ”, lst << 1);
  17. unsigned int p;
    int q, r;
    scanf(“%u”, &p);
    /* consider the input as 65 */
    	r > sizeof(int)*8;
    	for (q = 0; q < r; q++)
    		printf(“%d”, (m << p & 1 << (r-1))? 1 : 0);
  18. #define min(x,y) ((x)<=(y))? (x) : (y)
    #define max(x,y) ((x)==(y))? (x) : (y)
    int a = 14, b = 21, c = 54, d = 45;
    printf(“Large = %d	Small = %d
    ”, max(c,d)-1, min(a,b)+1);
  19. int x = 20;
    printf(“%d	%d	%d	%d
    ”, x++, ++x, x--, --x);
  20. int x = 5;
    char *ptr = “Language”;
    printf(x = 10 ? “%s” : “C Programming %s
    ”, ptr);
  21. main()
    {
    		main1();
    		return 0;
    }
    main1()
    {
    		static int i = 0;
    		i++;
    		i <= 5? main1() : i++;
    		printf(“%d”,i);
    }
  22. main()
    {
    		static int i;
    		while (i <= 8)
    			(i = 2)? i++ : i--;
    		printf(“%d”, i);
    }
  23. main()
    {
    		toogood();
    }
    toogood()
    {
    		int x;
    		if ((x = getchar()) ! = EOF)
    		{
    			toogood();
    			putchar(x);
    		}
    }
    Consider the input as a part to provide your result.
  24. main()
    {
    	static int m[] = {2, 4, 6};
    	printf(“%d
    ”, m[0]);
    	badone(m);
    	printf(“%d
    ”, m[0]);
    }
    	badone(int a [])
    	{
    		a[0] = 50;
    	}
  25. #include <stdio.h>
    #define N 5
    
    main()
    {
    	int i, j, a[N + 1][N + 1];
    	for (i = 1; i <= N; i++)
    	for (j = 1; j <= N; j++)
    	     a[i][j] = (i/j) * (j/i);
    	for (i = 1; i <= N; i++)
    	{
    		for (j = 1; j <= N; j++)
    			printf(“%d	”, a[i][j]);
    		putchar(‘
    ’);
    	}
    }
  26. What type of problems, if any, may occur with the following code segment? Give reasons.
         int x[SIZE];
         int *pi;
         for(pi = &x[0]; pi < &x[SIZE];)
    		*++pi = 0;
  27. Arrays in C are stored in a row-major order. When is this information relevant?
  28. What type of problems, if any, may occur with the following function? Explain.
            int getmax(int x[10])
    	{
    		int j, max = x[0];
    		for(j = 1; j <10; j++)
    			if (x[j] = max)
    				max = x[j];
    		return max;
    	}
  29. Are the expressions x[m+n] and m+n[x] equivalent? Give reasons for your answer.
  30. Consider the statement, ‘Whatever we can do using arrays, can also be done using pointers’. Do you agree or disagree? Give reasons.
F.2 SECTION — II

Programming Exercises

  1. Write a program that reads 10 integers and determines their standard deviation s, where s is given by
                 s=v(Sx)2 – Sx2
  2. Write a program that reads integers until end-of-file, and then, prints
    1. the largest and smallest values
    2. the largest and the second largest values
  3. Write a program to read a string of characters and print the sum of their ASCII values.
  4. Write a program that copies all characters from the standard input to the standard output, except that each newline character is preceded by two characters and each tab character by two , so that newlines and tabs become visible.
  5. Write a program that reads a sentence and prints the frequency of each of the vowels and the total count of consonants.
  6. Write a program to input the three angles of a triangle, and then, classify the triangle.
  7. Write a program to output the sum of the series 1 - 1/22 + 1/32 - 1/42+ 1/52 - … …
  8. Write a program to read an integer and print all prime factors of the integer, read.
  9. Write a program to print all perfect numbers between 1 and 1000. Prefect numbers are numbers that are same as the sum of all its factors except itself (e.g 6=1+2+3).*
  10. Write a program to output all Pythagorian triplets within a given range of positive integer values.
  11. Write a function that accepts two positive integers and returns the least common multiple (LCM) of these integers. One way of achieving this is to find the greatest common divisor (GCD) of the integers and dividing the product of the integers by this GCD. Try to find the LCM directly without using GCD.*
  12. Write a program that reads an integer, and then, forms the reverse of it in an integer variable. Finally, print this reverse integer.
  13. Write a function that prints all non-Fibonacci numbers within a given range of values. The function accepts the range as its arguments.*
  14. Write a function that accepts an integer and an array of characters of suitable size. The function converts the integer to its equivalent string form and stores it to the array.*
  15. Write a function in C that accepts a string as its argument and leaves the string with all its trailing blanks, tabs, and newlines removed from it.*
  16. Write a program that reads an integer (positive) and checks, if it is a Fibonacci number. If it is so, then, print the index of the corresponding term in the Fibonacci series. If not, then, output a proper message.
  17. Consider a positive integer p, which is of the form d1, d2 … … dn, where each di (i=1, 2, …n) corresponds to a digit. Clearly, the sum of all di's is another integer of the form h1, h2…. hk, where each h (i=1, 2, ….k) corresponds to a digit. We find the sum of all such hi’s, and so on. Finally, we get a single digit. If this digit is x, then, we say p is a magic_x number. Write a program that reads the single digit x(1–9), excluding zero(0), and outputs all magic_x numbers within the range from 1 to 1000.*
  18. Write a program to generate and print the values of p, q, and r, such that p*q=r, where p, q, and r, are of the form ab, cde, and efghi, respectively, that is, p is a two-digit integer, q is a three-digit integer, and r is a five digit integer. Note that the letters a, b, c, d, e, f, g, h, and i correspond to a distinct single digit.*
  19. Write a program that reads a text and converts all its uppercase characters to its lowercase, leaving non-uppercase characters unchanged.
  20. Write a program using recursion, to read a line of text and print it in reverse order.*
  21. Write a program that prints all twin primes (two prime numbers that differ by 2, e.g., 5 and 7) those are within a given range. The range is to be read as input to the program.*
  22. Write a program that will generate and print first n (to be read as input) prime Fibonacci numbers.*
  23. Write a program that reads a positive decimal integer, which is to be converted in to another base within 2 to 16. Read this base value and output the integer in the changed base.*
  24. Write a program that reads three integers (say x, y, and z) and rotates the values of the variables (i.e., value of x goes to y, value of y to z, and value of z to x). The program is very simple, if a temporary variable is taken. Write your program without any temporary storage.*
  25. A manufacturing company produces five types of products. They are numbered from 1 to 5. The company has four salespersons 1, 2, 3, and 4. Write a program to read the units sold by each salesperson of each product in a particular month. The company wants to have the following information:
    1. Total units of each product sold in the month
    2. Total units of all products sold by each salesperson
    3. Maximum unit sold of each product
    4. Which salesperson sold this maximum unit, so that incentive can be provided to that salesperson.

    Give the output in a suitable format.*

  26. Write a program to read a two-dimensional array of integers, and arrange the elements of it in such a way that each column of it is arranged in the ascending order.
  27. Write a program (validate) to check whether a given date is valid or not. In the command line, the date should be supplied as “validate 17-04-2009”. The output should look like “The date 17-04-2009 is valid”. For the command “validate 29-02-2009” the output is “The date 29-02-2009 is not valid".*
  28. Write a program to read two dates and output the number of days in between these dates. *
  29. Write a program to generate the Pascal triangle. Read an integer n within the range 1 to 20. Print the triangle with n lines. A triangle with 5 lines is as shown

     

    image

     

  30. Write a program to read a string of digits that is an amount in Rupees. For example, 235187615.89. The output should be in words. For the given input, the output will be as follows:

    Rupees Two Hundred Thirty Five Million One Hundred Eighty Seven Thousand Six Hundred Fifteen and paise Eighty Nine Only.*

  31. Write a program to read a date (dd, mm, yyyy) and output the corresponding day of the week.*
  32. An integer is divisible by 11 if the sum of the digits in odd position equates to the sum of the digits in even position of the integer. Write a program to find if an integer is divisible by 11 following the given rule.
  33. The Russian peasants have an interesting way of doing multiplication of integers (not very large numbers). The method can be illustrated by the following example. If the numbers 17 and 19 are to be multiplied, they are put at the top of two columns. The number at the left hand side is successively divided by 2 (integer division) while the other is successively multiplied by 2. The results are written one below the other in their respective columns. The process is repeated till the column containing the division results reaches 1. At this stage, all numbers in the right hand column are struck off, where as the numbers corresponding to them in the left hand column are even.

     

    image

     

    Now, the remaining numbers on the right hand side are added : namely, 19 + 304=323, which is equal to the product of 17 and 19.

    Write a program to accept two integers p and q consisting of two digits each, and use the above-mentioned method to obtain the product of p and q.*

  34. Write a program that reads an odd integer (say n) within the range from 3 to 15. Your program should generate and print a magic square of order n. In a magic square the row, column, and diagonal sums are identical.*
  35. Write a program to read a positive integer and output the integer in Roman numerals. The following table gives you the Roman characters corresponding to their integer values.

     

       Decimal Roman
       1 I
       4 IV
       5 V
       9 IX
       10 X
       40 XL
       50 L
       90 XC
       100 C
       400 CD
       500 D
       900 CM
       1000 M*

     

  36. Write a program to read a string of Roman numerals and output the corresponding integer values.*
  37. Write a program to read the length of a string (1 to 12) and output all possible permutations of the string (e.g., abcde… … ) of a given length.*
  38. Write a program to remove all the comments from a C-source code. Note that C comments do not nest. A comment starts with /* and terminates with */.*
  39. A complex number is of the form x + iy where x and y are integers. Write the functions for addition and multiplication operators that use complex numbers, and for displaying a complex number. Write a main function that uses the above functions to test if it is correct.*
  40. Write a program that prints the name of the program that is executing.*
SOLUTIONS FOR PROGRAMMING EXERCISES

9. Program to print perfect numbers.

    #include <stdio.h>
    main()
    {
	int p = 1, q = 1000;
	int n, nn, s, sq;
	for(n = p; n <= q; n++)
	{
		nn = n;
		s = 1;
		sq = sqrt(n);
		for(j = 2; j <= sq; j++)
			if (nn % j == 0)
				s += j + nn/j;
		if (s == n)
			printf(“%d	”, n);
	}
	return;
    }

11. The function to find the LCM of two positive integers is as follows. We assume the first argument is larger or equal to the second one.

     int lcm(int l, int s)
     {
	  int m = 2, result;
	  result = l;
	  while (result % s)
	  {
		result = l * m;
		m++;
	  }
	  return result;
    }

13. The following function prints non-Fibonacci numbers.

       non-fib(int from, int to)
       {
	   int last, last_but_one, fib, index = from;
	   last_but_one = last = 1;
	   fib = last_but_one + last;
	   while (index <= to)
	   {
		if (index == last)
			index++;
		while (index > last_but_one && index < fib &&
			   index <= to)
			printf(“%d	”, index++);
		last_but_one = last;
		last = fib;
		fib = last_but_one + last;
	}
	return;
    }

14. The following function itoa converts the integer given in its argument to a string, and stores it to the given string:

    itoa (int n, char s[])
    {
	int i, sign;
	if ((sign = n) < 0) /* stores integer in sign */
		n = –n; /* makes n as a positive integer */
	i = 0;
	do {
		s[i++] = n%10 + ‘0’; /* stores the digits of n in
        reverse order in the array */
	} while ((n /= 10) > 0);
	if (sign < 0)
		s[i++] =”–”; /* puts minus (–) if necessary */
	s[i] = ‘’; /* puts NULL character at last */
	reverse(s); /* reverses the string */
    }
    reverse(char s[])
    {
	int i, j;
	for (i = 0, j = strlen(s)–1; i < j; i ++, j--)
	{
           t = s[i];
           s[i] = s[j];
           s[j] = t;
        }
        return;
   }

15. The following function trim removes all the trailing blanks, tabs, and newlines from a string:

   int trim(char s[])
   {
	int i;
	for (i = strlen(s)–1; i>= 0; i--) /* trims from end
        of string */
		if (s[i] ! = “ “ && s[i] ! = ‘	’ && s[i] != “
”)
			break;
	s[i++] = ‘’;
	return i;
}

17. Generating and printing magic_x numbers.

    #include <stdio.h>
    main()
    {
	int x, j, c;
	printf(“Enter a digit(1–9):”);
	do{
		c = getchar();
		while(getchar() ! = EOF);
	} while (c < ’1’ || c=’9’);
	printf(“Magic_%c numbers are listed below:
”, c);
	for( x = c-’0’; x <= 1000; x += 9)
		printf(“%d	”, x);
    }

18. Program to print p, q, and r, such that p*q=r, where p, q, and r are of the form ab, cde, and efghi, respectively, with the constraint that a, b, c, d, e, f, g, h, and i are distinct digits and ab*cde=efghi.

    #include <stdio.h>
    main()
    {
	int p, q, visit[10];
	long int r;
	int i, k;
	char ps[3], qs[4], rs[6], s[10];
	for(p = 10; p <= 98; p++)
    for(q = 102; q <=987; q++)
    {
	r = p * q;
	itoa(r, rs);
	if (strlen(rs) == 5)
	{
		itoa(p, ps);
		itoa(q, qs);
		s[0] =’’;
		strcat(s, ps);
		strcat(s, qs);
		strcat(s, rs);
		if (s[4] == s[5])
		{
			for(i = 0;i < 10; i++)
				visit[i] = 0;
			for(i = 0; i < 10; i++)
			{
				if (i == 4)
					i++;
				k = s[i] – ‘0’;
				if (visit[k])
					break;
				else
					visit[k] = 1;
			}
			if ( i == 10 )
				printf(“%d * %d = %ld
”, p, q, r);
		}
	}
  }
  return;
}
itoa (int n, char s[])
{
	int i, sign;
	if ((sign = n) < 0) /* stores integer in sign*/
		n = –n; /* makes n as a positive integer*/
	i = 0;
	do {
		s[i++] = n%10 + ‘0’; /* stores the digits of n in
reverse order in the array*/
	} while ((n /= 10) > 0);
	if (sign < 0)
		s[i++] = ‘–’; /* puts minus (–) if necessary*/
	s[i] = ‘’; /* puts NULL character at last*/
	reverse(s); /* reverses the string*/
}
reverse(char s[])
{
	int i, j;
	char t;
	for (i = 0, j = strlen(s)–1; i < j; i++, j--)
	{
		t = s[i];
		s[i] = s[j];
		s[j] = t;
	}
	return;
  }

20. Program to reverse a given line of test using recursion.

    #include <stdio.h>
    main()
    {
	printf(“Enter a line of text :
”);
	backwards();
    }
    backwards()
    {
	char c;
	if ((c = getchar()) != ‘
’)
		backwards();
	putchar(c);
	return;
    }

21. The program for twin primes within the range from l to h, where l and h are read as input to the program. Note that every prime is either one less or one greater than an integer divisible by 6.

    #include <stdio.h>
    main()
    {
	int l, h, p1, p2, y, i;
	printf(“Enter the range (low, high) :“);
	scanf(“%d, %d”, &l, &h);
	if (l == 1)
	{
		p1 = 3; p2 = 5;
		printf(“%d	%d	”, p1, p2);
	}
	y = h/6;
	for( i = l/6 + 1; i < y; i++)
	{
		t = i*6;
		p1 = t – 1;
		p2 = t + 1;
		if (prime(p1) && prime(p2))
			printf(“%d	%d	”, p1, p2);
	}
}
int prime(int n)
{
	int c, f = 1; k = 2;
	c = sqrt(n) +1;
	while (f == 1 && k <= c)
		if (n%k++ == 0)
			f = 0;
	return f;
    }

22. The following program prints first n(given) prime Fibonacci numbers.

    main()
    {
	int l, h, p1, p2, y, i;
	printf(“Enter the range (low, high) :“);
	scanf(“%d, %d”, &l, &h);
	if (l == 1)
	{
		p1 = 3; p2 = 5;
		printf(“%d	%d	”, p1, p2);
	}
	y = h/6;
	for( i = l/6 + 1; i < y; i++)
	{
		t = i*6;
		p1 = t – 1;
		p2 = t + 1;
		if (prime(p1) && prime(p2))
			printf(“%d	%d	”, p1, p2);
	}
    }
    int prime(int n)
    {
	int c, f = 1; k = 2;
	c = sqrt(n) +1;
	while (f == 1 && k <= c)
		if (n%k++ == 0)
			f = 0;
	return f;
    }

23. The base change program follows:

    #include <stdio.h>
    #include <string.h>
    #define MAX 100
    main()

    {
        int n,base;
        char *p, *convert();
        printf(“Enter the positive decimal integer to be changed :”);
        scanf(“%d”, &n);
        printf(“Enter base value:”);
        scanf(“%d”, &base);
        p = convert(n,base);
        printf(“The decimal integer %d in base %d is %s
”,n,base,p);
        return;
    }
    char *convert(int n, int base)
    {
      char str[MAX];
      int remainder,c,i = 0;
      while(n)
      {
         remainder = n % base;
         switch(remainder)
         {
         case 0:
         case 1:
         case 2:
         case 3:
         case 4:
         case 5:
         case 6:
         case 7:
         case 8:
         case 9: c = remainder + ’0’; break;
         case 10:
         case 11:
         case 12:
         case 13:
         case 14:
         case 15: c = remainder -10 + ’A’; break;
         }
         str[i++] = c;
         n /= base;
   }
   str[i] = ’’;
   reverse(str);
   return(str);
}
reverse(char s[])
{
   int i,j,t;
   for(i = 0,j = strlen(s)-1; i ` j; i++,j--)
   {
      t = s[i];
      s[i] = s[j];
      s[j] = t;
   }
   return;
}

24. Rotating three variables without any extra storage.

    #include <stdio.h>
    main()
    {
	int x, y, z;
	printf(“Enter three integers separated by blanks:”);
	scanf(“%d%d%d
”, &x, &y, &z);
	printf(“Before Rotation: %d %d %d
”, x, y, z);
	rotate(&x,&y,&z);
	printf(“After Rotation: %d %d %d”, x, y, z);
    }
    rotate(int *px, int *py, int *pz)
    {
	*px = *px + *py + *pz;
	*py = *px - (*py + *pz);
	*pz = *px - (*py + *pz);
	*px = *px - (*py + *pz);
    }

25. Following C program solves the problem.

    #include <stdio.h>
    #define NPERSON 4
    #define NPROD 5
    main()
    {
	int a[NPERSON][NPROD];
	int rowtot[NPERSON]; /* Totals of each row */
	int coltot[NPROD]; /* Totals of each column */
	int maxcol[NPROD]; /* Maximum sale of each product */
	int person[NPROD]; /* Salesperson sold maximum amount */
	int grandtot = 0;
	int i,j;
	for (i = 0; i < NPERSON; i++)
		for(j = 0; j < NPROD; j++)
			scanf(“%d“, &a[i][j]);
	for (i = 0; i < NPERSON; i++)
	{
		rowtot[i] = 0;
		for (j = 0; j < NPROD; j++)
			rowtot[i] += a[i][j];
	}
	for (j = 0; j < NPROD; j++)
	{
		coltot[j] = 0;
		for (i = 0; i < NPERSON; i++)
			coltot[j] += a[i][j];
	}
	for (j = 0; j < NPROD; j++)
	{
		maxcol[j] = a[0][j];
		person[j] = 1;
		for (i = 1; i < NPERSON; i++)
			if ( a[i][j] = maxcol[j] )
			{
				maxcol[j] = a[i][j];
				person[j] = i+1;
			}
	}
	table1(); /* Print table with row and column totals */
	table2(); /* Print table showing salesperson performances */
	return;
    }
    table1()
    {
	heading1();
	for (i = 0; i < NPERSON; i++)
	{
		printf(“Salesperson #%d:“, i+1);
		for (j = 0; j < NPROD; j++)
			printf(“%5d	”,a[i][j]);
		printf(“%5d
”,rowtot[i]);
		grandtot += rowtot[i];
	}
	printf(“		”);
	for (j = 0; j < NPROD; j++)
		printf(“===	”);
	printf(“===
”);
	printf(“T O T A L S :“);
	for (j = 0; j < NPROD; j++)
		printf(“%5d	”,coltot[j]);
	printf(“%5d
”,grandtot);
	return;
    }
    heading1()
    {
	printf(“Salesperson_Product Table
”);
	printf(“=========================
”);
	printf(“
	”);
	for (j = 0; j < NPROD; j++)
		printf(“	Product”);
	printf(“	 Totals”);
	printf(“
	”);
	for (j = 0; j < NPROD; j++)
		printf(“	 %d”, j+1);
	printf(“
	”);
	for (j = 0; j <= NPROD; j++)
		printf(“	=======”);
	printf(“
”);
	return;
    }
    table2()
    {
	printf(“
 Performance Table
”);
	printf(“=================
”);
	printf(“
		Maximum Unit Sold	Salesperson”);
	printf(“
		=================	===========
”);
	for (j = 0; j < NPROD; j++)
		printf(“Product #%d:		%d		 #%d
”, j + 1,
			   maxcol[j], person[j]);
	return;
    }

27. The C code for validity of a date is the following:

    #include <stdio.h>
    main(int argc, char *argv[])
    {
	int d,m,y;
	int leap;
	if (--argc > 0)
	{
		convert(++argv, &d, &m, &y);
		leap = y % 4 == 0 && y % 100! = 0 || y % 400 == 0;
		printf(“The date %s is %s
”,*argv,(valid(d,m,y,leap))
			   ?”valid”:
			   ”not valid”);
	}
	else
		printf(“Usage:: VALIDATE <dd-mm-yyyy>
”);
	return;
    }
    convert(char **ptrarr, int *pd, int *pm, int *py)
    {
	char *curptr;
	char c;
	int n;
	curptr = *ptrarr; /* points to date string */
	for(n = 0; ((c = *curptr) >= ‘0’ && c <= ‘9’); curptr++)
		n = 10 * n + (c - ‘0’);
	*pd = n;
	++curptr;
	for(n = 0; ((c = *curptr) >= ‘0’ && c <= ‘9’); curptr++)
		n = 10 * n + (c - ‘0’);
	*pm = n;
	++curptr;
	for(n = 0; ((c = *curptr) >= ‘0’ && c <= ‘9’); curptr++)
		n = 10 * n + (c - ‘0’);
	*py = n;
	return;
    }
    valid(int d, int m, int y, int leap)
    {
	if (d <= 0 || d > 31 || m <= 0 || m > 12 || y <= 0 || y > 3000)
		return 0;
	if ((m == 4 || m == 6 || m == 9 || m == 11) && d > 30)
		return 0;
	if (m == 2 && d > 29)
		return 0;
	if (m == 2 && leap == 0 && d > 28)
		return 0;
	return 1;
    }

28. The program for the number of days within two dates:

    #include <stdio.h>
    int day_tab[2][13] = {
	       {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
	       {0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
      };
    main()
    {
	int d1,m1,y1,d2,m2,y2;
	int n1,n2,i,leap;
	printf(“Enter the dates :
”);
	scanf(“%d%d%d%d%d%d”,&d1,&m1,&y1,&d2,&m2,&y2);
	n1 = yearday(d1,m1,y1);
	n2 = yearday(d2,m2,y2);
	printf(“***** %d ======= %d
”, n1,n2);
	for(i = y1; i < y2; i++)
	{
		leap = (i%4 == 0 && i%100! = 0) || i%400 == 0;
		n2 += (365 + leap);
	}
	printf(“The days between the dates = %d 
”, n2-n1);
    }
    yearday(int d, int m, int y)
    {
	int leap,i;
	leap = (y%4 == 0 && y%100! = 0) || y%400 == 0;
	for(i = 1; i < m; i++)
		d += day_tab[leap][i];
	return d;
    }

29. The program for Pascal triangle follows:

    #include <stdio.h>
    main()
    {
	int n, a[21], index,s,i,j;
	printf(“Enter number of lines :“);
        /* assume n lise between 1 and 20*/
	scanf(“%d”, &n);
	for (i = 0; i <= 21; i++)
		a[i] = 0;
	index = 2;
	s = 40;
	ahead(s);
	a[1] = 1;
	for (i = 1; i <= n; i++)
	{
		for (j = 1; j <= i; j++)
			printf(“%d“, a[j]);
		putchar(‘
’);
		if (i != n)
		{
			for (j = index; j > 1; j--)
				a[j] += a[j-1];
			s = s-3;
			ahead(s);
			index++;
		}
	}
	return;
    }
    ahead(int s)
    {
	while (--s)
		putchar(‘ ‘);
	return;
    }

30. The program for cheque printing is as follows:

   #include <stdio.h>
   #include <ctype.h>
   #define MA× 13
   char *p[]={“One”,“Two”,“Three”,“Four”,“Five”,“Six”,“Seven”,
   “Eight”,“Nine”};
   char *q[]={“Eleven”,“Twelve”,“Thirteen”,“Fourteen”,“Fifteen”,
   “Sixteen”,“Seventeen”,“Eighteen”,“Nineteen”};
   char *r[]={“Ten”,“Twenty”,“Thirty”,“Forty”,“Fifty”,“Sixty”,
   “Seventy”,“Eighty”,“Ninty”};
   
   char *place[]={“Rupees”,“and paisa”,“only.”};
   int x[13];
   int y[10];
   int dot=0;
   main()
   {
         int i,n,len,group;
         char line[255];

         for(i=1; i < 10; ++i)
               y[i]=0;
         line[0]=‘’;
         len=getnum(MA×);
         if(len) {
                 for (i=9; i > 0; —i)
                 y[i]=x[i];

                 strcat(line, *place);
                 if (len > 6)
                 group=3;
                 else if (len > 3)
                 group=2;
                 else
                 group=1;

                 produce(group, line);
         }
         if(dot)
         {
                 group=1;
                 for(i=1; i < 10;
                      y[i]=0;
                 for (n=0, i=9; i > 7;--i)
                 {
                      y[i]=x[i+3];
                      n=n*10 + y[i];
                 }
                 if (n) {
                        strcat(line, *(place+1));
                        produce(group, line);
                 }
         }
         strcat(line, *(place + 2));
         printf(“%s
”, line);
         return;
   }

   getnum(int lim)

  {
         int c, i, j;

         i=0;
         while (--lim-3 >= 0 && isdigit(c=getchar()) && c !=EOF 
         && c! =‘
’)
               x[++i]=c-’0’;
         if (c == ‘.’)
         {
            x[++i]=c;
            dot=1;
            for (j=0; j < 2 0;j++)
            {
                 c=getchar();
                 x[++i]=((isdigit(c)) ? c-’0’ : 0);
            }
         }
         i=adjust(i);
         return (i);
   
   }

   adjust(int i)

   {

   
      int begin, len;

      begin=((dot) ? 12 : 9);
      while(i > 0)
      {
            x[begin]=x[i];
            begin-- ;
            i-- ;
      }
      len=9-begin;
      while (begin)
            x[begin-- ]=0;
      return (len);
   
   }

   char *v[]={“Million”, “Thousand”};
   produce(int g, char ps[])
   {
      int start;
      switch (g)
      {
      case 3: start=1;
              process(start, ps);
              strcat(ps, *v);
      case 2: start=4;
              process(start, ps);
              strcat(ps, *(v + 1));
      case 1: start=7;
              process(start, ps);
      };
      return;
   }
   process(int s, char *ps) 
   {
      char *h=“Hundred”;
      if (y[s])
      {
              strcat(ps, p[y[s]-1]);
              strcat(ps, h);
      }
      if (y[s + 1] == 1)
          if (y[s + 2])
              strcat(ps, q[y[s + 2]-1]);
          else
              strcat(ps, r[y[s + 1]-1]);
      else
      {
          if (y[s + 1])
              strcat(ps, r[y[s + 1]-1]);
          if (y[s + 2])
              strcat(ps, p[y[s + 2]-1]);
      }
      return;
   }

31. The following program prints the day corresponding to a given date.

   #include <stdio.h>
   main()
   {
        int d, m, y;
        int leap, day;
        long int totdays;

        printf(“Enter date, month, year :”);
        scanf(“%d %d %d”, &d, &m, &y);

        leap=y % 4 == 0 && y % 100 != 0 || y % 400 == 0;

        if (valid(d, m, y, leap))
        {
              totdays=(long)(y-1)*365 + (long)((y-1)/4)-(long)
              ((y-1)/100) + (long)((y-1)/400);
              switch (m) 
              {
              case 12 : totdays += 301;
              case 11 : totdays += 31l;
              case 10 : totdays += 301;
              case 9 : totdays += 31l;
              case 8 : totdays += 31l;
              case 7 : totdays += 30l;
              case 6 : totdays += 31l;
              case 5 : totdays += 30l;
              case 4 : totdays += 31l;
              case 3 : totdays += (long)(28l+leap);
              case 2 : totdays += 31l;
              case 1 : totdays += (long)d;
              }
              day=(int)(totdays % 7l);
              printf(“The date %d-%d-%d is supposed to be a ”, d, m, y);
              switch (day)
              {
              case 0 : printf(“SUNDAY”);
                       break;
              case 1 : printf(“MONDAY”);
                       break;
              case 2 : printf(“TUESDAY”);
                       break;
              case 3 : printf(“WEDNESDAY”);
                       break;
              case 4 : printf(“THURSDAY”);
                       break;
              case 5 : printf(“FRIDAY”);
                       break;
              case 6 : printf(“SATURDAY”);
                       break;
              }
              printf(“
”); 
        }else printf(“Given date is not valid
”);
        return;
   }

   valid(int d, int m, int y, int leap)

   {

        if (d <= 0 || d > 31 || m <= 0 || m > 12 || y <= 1940 ||
        y > 3000)
              return 0;
        if ((m == 4 || m == 6 || m == 9 || m == 11) && d > 30)
              return 0;
        if (m == 2 && d > 29)
              return 0;
        if (m == 2 && leap == 0 && d > 28)
              return 0;
        return 1;
   }

33. Russian multiplication algorithm:

   #include <stdio.h>

   main() 
   {
         int m, n, result=0;

         printf(“Enter two positive integers(m, n):”); 
         scanf(“%d, %d”, <m, <n);

         while (m > 0)
         {
               if (m%2 != 0)
                    result += n; 
               m >>= 1; /* m /= 2; */  
               n <<= 1; /* n *= 2; */
         }
         printf(“Product of %d and %d is=%d
”, m, n, result);
   }

34. The program to generate and print a magic square of odd order follows:

   #include <stdio.h>

   int a[20][20];
   int i, r, c, m, n, k, j, nsq;

   main() 
   {
        printf(“Enter no. of rows of the magic square :”);
        scanf(“%d”, &n);/* assume n > 0 and odd */

        m=n/2+1; i=1;
        r=1;
        c=m;
        a[r][c]=i;i++;
        nsq=n*n;
        while (i <= nsq) 
        {
              set();
              i++;
        }
        for (k=1; k <= n; k++)
        {
              putchar(‘×t’);
              for (j=1; j <= n;
                   printf(“%d	”, a[k][j]); 
              putchar(‘×n’);
        }
        return;
   }
   set()
   {
        if (r == 1 && c > 1)
        {
              r=n;
              c--;
              a[r][c]=i;
        }
        else if (r > 1 && c == 1)
        {
              r-- ;
              c=n;
              a[r][c]=i;
        }
        else if (r == 1 && c == 1)
        {
              r++;
              a[r][c]=i;
        }
        else if (r > 1 && c > 1)
        {
              r-- ;
              c-- ;
              if (a[r][c] == 0)
                    a[r][c]=i;
              else 
              {
                    r += 2;
                    c++;
                    a[r][c]=i;
              }
        }
        return;
   }

35. Decimal/Arabic to Roman conversion:

  /*

   Decimal       Roman
   1              I
   4              IV
   5              V
   9              IX
   10             X
   40             XL
   50             L
   90             XC
   100            C
   400            CD
   500            D
   900            CM
   1000           M

   */
   #include <stdio.h>
   main()
   {
	unsigned int x;
	char *r_str;
	printf(“Enter a positive integer:”);
	scanf(“%d”, &x);
	r_str = dec_to_romanstr(x);
	printf(“The Roman equivalent of the integer %d is %s
”,
		   x, r_str);
	return;
   }
   char *dec_to_romanstr(unsigned int n)
   {
	struct correspond
	{
		char *roman_str;
		unsigned int dec_Val;
	};
	static struct correspond conv_tab[]=
	{
		{“M”, 1000},
		{“CM”, 900},
		{“D”, 500},
				{“CD”, 400},
				{“C”, 100},
				{“XC”, 90},
				{“L”, 50},
				{“XL”, 40},
				{“X”, 10},
				{“IX”, 9},
				{“V”, 5},
				{“IV”, 4},
				{“I”, 1},
	};
	char roman[50];
	int i;
	roman[0] = '';
	for (i = 0; n && i < sizeof(conv_tab)/sizeof(conv_tab[0]); i++)
	{
		while (n >= conv_tab[i].dec_val)
		{
			strcat(roman, conv_tab[i].roman_str);
			n -= conv_tab[i].dec_val;
		}
	}
	return roman;
   }

36. Roman to Arabic/decimal conversion:

   #include <stdio.h>
   #include <string.h>
   #include <stdlib.h>
   main()
   {
	unsigned int x;
	char r_str[50];
	unsigned int romanstr_to_dec(char *roman_str);
	printf(“Enter a Roman Numeral string in Capital Letters Only:”);
	scanf(“%s”, r_str);
	x = romanstr_to_dec( r_str);
	printf(“The integer corresponding to the Roman equivalent
		   of %sis %d
”, r_str, x);
	return 0;
   }
   unsigned int romanstr_to_dec(char *roman_str)
   {
	struct correspond
	{
		char *roman_str;
		unsigned int dec_val;
	};
	static struct correspond conv_tab[]=
	{
		{“M”, 1000},
		{“CM”, 900},
		{“D”, 500},
		{“CD”, 400},
		{“C”, 100},
		{“XC”, 90},
		{“L”, 50},
		{“XL”, 40},
		{“X”, 10},
		{“IX”, 9},
		{“V”, 5},
		{“IV”, 4},
		{“I”, 1},
	};
	unsigned int n = 0;
	int i = 0, flag = 0,cnt, len = strlen(roman_str);
	while (i < len && roman_str[i] == 'M') /* Consider all M's */
	{
		n += conv_tab[0].dec_val;
		i++;
	}
	if (i+1 < len && roman_str[i] == 'C' && roman_str[i+1] ==
		  'M') /* Next consider one CM */
	{
		n += conv_tab[1].dec_val;
		i += 2; flag = 9; /* sets flag = 9 if 900 appears */
	}
	if (i < len && roman_str[i] == 'D' && flag != 9)
	{
		n += conv_tab[2].dec_val;
		i++; flag = 5; /* sets flag = 5 if 500 appears */
	}
	if (i+1 < len && flag != 9 && flag != 5 && roman_str[i] ==
		  'C' && roman_str[i+1] == 'D')
	{
				n += conv_tab[3].dec_val; /* One cannot have CD
                                                             after a CM or D */
		i += 2; flag = 4; /* sets flag = 4 if 400
                                     appears */
	}
	cnt = 0; /* counts number of c's i.e 100's */
	while ( i < len && roman_str[i] == 'C') /* Consider
all C's */
	{
		n += conv_tab[4].dec_val;
		i++; cnt++;
	}
	if (((flag == 9 || flag == 4) && cnt > 0) || (flag == 5 &&
		cnt > 3))
	{
		printf(“The Roman string is malformed ……
”);
		exit (1);;
	}
   /* Now a XC may come */
	flag = 0;
	if (i+1 < len && roman_str[i] == 'X' && roman_str[i+1] ==
		  'C') /* Next consider one XC */
	{
		n += conv_tab[5].dec_val;
		i += 2; flag = 9; /* sets flag = 9 if 90 appears */
	}
	if (i < len && roman_str[i] == 'L' && flag != 9)
	{
		n += conv_tab[6].dec_val;
		i++; flag = 5; /* sets flag = 5 if 50 appears */
	}
	if (i+1 < len && flag != 9 && flag != 5 && roman_str[i] ==
		  'X' && roman_str[i+1] == 'L')
	{
		n += conv_tab[7].dec_val; /* One cannot have XL
                                             after a XC or L */
		i += 2; flag = 4; /* sets flag = 4 if 40 appears */
	}
	cnt = 0; /* counts number of X's i.e 10's */
	while (i < len && roman_str[i] == 'X') /* Consider all X's */
	{
		n += conv_tab[8].dec_val;
		i++; cnt++;
	}
			if (((flag == 9 || flag == 4) && cnt > 0) || (flag == 5 && cnt > 3) )
	{
		printf(“The Roman string is malformed ……
”);
		exit(1);
	}
   /* Now a IX may come */
	flag = 0;
	if (i+1 < Len && roman_str[i] == 'I' && roman_str[i+1] ==
		  'X') /* Next consider one IX */
	{
		n += conv_tab[9].dec_val;
		i += 2; flag = 9; /* sets flag = 9 if 9 appears */
	}
	if (i < len && roman_str[i] == 'V' && flag != 9)
	{
		n += conv_tab[10].dec_val;
		i++; flag = 5; /* sets flag = 5 if 5 appears */
	}
	if (i+1 < len && flag != 9 && flag != 5 && roman_str[i] ==
		  'I' && roman_str[i+1] == 'V')
	{
		n += conv_tab[11].dec_val; /* One cannot have IV
                                               after a IX or V */
		i += 2; flag = 4; /* sets flag = 4 if 4 appears */
	}
	cnt = 0; /* counts number of I's i.e 1's */
	while (i < len && roman_str[i] == 'I') /* Consider all X's */
	{
		n += conv_tab[12].dec_val;
		i++; cnt++;
	}
	if (((flag == 9 || flag == 4) && cnt > 0) || (flag == 5
		&& cnt > 3))
	{
		printf(“The Roman string is malformed ……
”);
		exit(1);
	}
	if(i < len)
	{
		printf(“The Roman string is malformed ……
”);
		exit (1);
	}
	return n;
   }

37. Program to find all the possible permutations appears below:

   #include <stdio.h>
   #define N 13

   unsigned long fact[N];
   main()
   {
	char p[N], ps[N+1];
	int i,len;
	for(i = 0; i < N; i++) /* Set factorial table *
              fact[i] = factorial(i);
	printf(“Enter string length to permute(1 to 12):”);
	scanf(“%d”, &len);
	for (i = 0; i < len; i++) /* Form the string in p array */
              p[i]='a'+ i;
	for (i = 0; i < fact[len]; i++)
	{
		reverse_map(p, ps, len, i);
		printf(“%s	”, ps);
	}
	putchar('
'),
	return;
   }
   unsigned long factorial(int n)
   {
	unsigned long prod = 1l;
	int i;
	for (i = 1; i <= n; i++)
		prod *= i;
	return prod;
   }
   reverse_map(char s[], char p_rank[], int size, int rank)
   {
	int visit[N];
	int x, y, i, j;
	for (i = 0; i < size; i++)
		visit[i] = 0;
			for(i = 0; i < size; i++)
	{
		y = rank / fact[size - 1 - i]; /* get index of i_th
                                                  character */
		rank %= fact[size - 1 - i]; /* set rank of remaining
                                               permutation */
		j = 0; x = 0;
		while(j < y)
			if (visit[x++] == 0)
				j++;
		while (visit[x] == 1)
			x++;
		p_rank[i] = s[x];
		visit[x] = 1;
	}
	p_rank[size] = '';
   }

38. Program to suppress all the comments from a C source program is as given.

   #include <stdio.h>

   main(int argc, char *argv[])
   {
	FILE *fopen(), *fp;
	if (argc !> 2) {
		printf(“Usage: SUPPRESS filename
”);
		exit(1);
	}
	if ((fp = fopen(*++argv, “r”)) == NULL) /* open file */
		printf(“Can't open file %s
”, *argv);
	else {
		filecopy(fp); /* Copy the source code without
                                 comments */
		fclose(fp);
	}
	return;
   }
   /* FUNCTION filecopy follows */
   filecopy(FILE *fp)
   {
	int c;
	while ((c = getc(fp)) != EOF)
		if (c != '/')
			putc(c, stdout); /* Copy charater to stdout */
		else
					skip(fp, c); /* Skip comment if appeared */
	return;
   }
   /* FUNCTION skip follows */
   skip(FILE *fp, int c)
   {
	int cc;
	if ((cc = getc(fp)) == '*')
		do {
			while ((cc = getc(fp)) != '*'),
			if ((cc = getc(fp)) == '/')
				break;
		} while (cc != EOF);
	else {
		putc(c, stdout);
		putc(cc, stdout);
	}
	return;
   }

39. Program for complex number arithmetic is as given.

   #include <stdio.h>

   enum { re, im };
   typedef int cp[2];
   neg_cp(cp x)
   {
	x[re] = -x[re];
	x[im] = -x[im];
   }
   add_cp(cp x, cp y, cp z)
   {
	z[re] = x[re] + y[re];
	z[im] = x[im] + y[im];
   }
   mul_cp(cp x, cp y, cp z)
   {
	cp aux;
	aux[re] = x[re]* y[re] - x[im]* y[im];
	aux[im] = x[re]* y[im] + y[re]* x[im];
	z[re] = aux[re];
	z[im] = aux[im];
   }
   raise_cp(cp x, int p, cp z)
   {
	cp aux;
	aux[re] = x[re];
	aux[im] = x[im];
	z[re] = 1;
	z[im] = 0;
	while (p > 0)
	{
		if (p & 1)
			mul_cp(z, aux, z);
		mul_cp(aux, aux, aux);
		p = p >> 1;
	}
   }
   display_cp(cp x)
   {
	printf(“(%d + i%d)”, x[re], x[im]);
   }
   main()
   {
	cp a, b, c;
	a[re] = 5; a[im] = 7;
	b[re] = 8; b[im] = 9;
	display_cp(a);
	putchar(' + '),
	display_cp(b);
	putchar(' = '),
	add_cp(a, b, c);
	display_cp(c);
	putchar('
'),
	display_cp(a);
	putchar(' * '),
	display_cp(b);
	putchar(' = '),
	mul_cp(a, b, c);
	display_cp(c);
	putchar('
'),
	display_cp(a);
	printf(“raised 7”);
	putchar(' = '),
	raise_cp(a, 7, c);
	display_cp(c);
			putchar('
'),
	return;
   }

40. The program to print the name of a program that is executing is as given.

   #include <stdio.h>

   main(int argc, char *argv[])
   {
	if (argc > 1)
		printf(“There are extra arguments in command line
”);
	printf(“program name is %s
”, *argv);
	return;
   }
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset