Srikanth Technologies

C Language For Beginners

2017 Edition

2014 Edition
C Language For Beginners By Srikanth Pragada is a book meant for absolute beginners of programming. It teaches how to write programs using C Language.

How to compile and run C programs?

Watch the following video to understand how to use CodeBlocks IDE. This video explains how to download, install and use CodeBlocks IDE to compile and run C programs.

How to use CodeBlocks IDE for C Programming

How To Buy This Book?

Hard copy (printed version) of this book is available for sale at Srikanth Technologies.

The price of this book is 250 INR.

Kindle Edition (digital version) of this book in available in Amazon.

Answers For Exercises

1. Introduction To C

  1. Compiler or interpreter
  2. They use more operators, which make program very compact.
  3. Functions. Because C is function oriented language.

2. First C Program

  1. /* */
  2. \t
  3. main
  4. A
  5. Display your name and address in two different lines.
    // Program to print name and address in two different lines
    #include <stdio.h>
    void main()
    {
      printf("Srikanth Pragada");                         
      printf("\n304, Srikanth Technologies, Eswar Paradise, Dwarkanagar, Vizag-16");
    }
                                        
    
  6. Display your name on the first line and address on the second line. Separate each part of the address using tab.
    #include <stdio.h>
    void main()
    {
      printf("Srikanth Pragada");
      printf("\n304\tSrikanth Technologies\tEswar Paradise\tDwarkanagar\tVizag-16");
    }
    

3. Language Elements

  1. %u
  2. 8 bytes (may vary based on compiler)
  3. _ (underscore)
  4. Character
    1. Valid
    2. Valid
    3. Invalid - main is a keyword
    4. Valid
    5. Invalid – identifier must not start with a digit
    6. Valid
  5. Accept two integers and display octal equivalent of first and hex equivalent of second.
    #include <stdio.h>
    void main()
    {
       int  n1,n2;
    
         // Accept two numbers  
         printf("Enter two numbers :");
         scanf("%d%d",&n1,&n2);
      
         printf("Octal of %d = %o  Hex of %d = %x",n1,n1,n2,n2);
    }
    
  6. Accept amount and discount percentage and display net amount.
    #include <stdio.h>
    void main()
    {
       float  amt, disper,net;
    
         // accept amount and discount percentage  
    
         printf("Enter amount and discount percentage : ");
         scanf("%f%f", &amt,&disper);
      
         net =  amt  - ( amt * disper / 100 );
    
         printf("Net amount : %f ", net);
    }
    
  7. Take two numbers and display them in the reverse order of accepted order.
    #include <stdio.h>
    void main()
    {
       int n1,n2;
    
         // accept two numbers  
    
         printf("Enter two numbers  ");
         scanf("%d%d", &n1, &n2);
      
         // print numbers in the reverse order    
         printf("Numbers in reverse order : %d %d ", n2, n1);
    }
    

4. Operators

  1. &&
  2. 10 and store the result back in A
  3. a = b is assigning value of b to a, a == b is comparing the value of a with b for equality
  4. pre-fix notation
  5. An operator that takes only one operand, such as ++ and --.
  6. Take two integers and display sum, difference, product, quotient, and remainder.
    #include <stdio.h>
    void main()
    {
       int n1,n2;
    
         // accept two numbers  
         printf("Enter two numbers :");
         scanf("%d%d", &n1, &n2);
      
         // print sum, difference, product and quotient and remainder    
         printf("\nSum = %d ", n1 + n2);
         printf("\nDifference = %d ", n1 - n2);
         printf("\nProduct = %d ", n1 * n2);
         printf("\nQuotient = %d ", n1 / n2);
         printf("\nRemainder = %d ", n1 % n2);
    } 
  7. Take a number and display its square.
    #include <stdio.h>
    void main()
    {
       int n;
    
         // accept a number  
         printf("Enter a number ");
         scanf("%d",&n);
      
         printf("\nSquare of %d = %d ", n , n * n );
    }
    
  8. Take principal amount, rate of interest, number of years and display simple interest.
    #include <stdio.h>
    void main()
    {
       float pamt, rate, interest;
       int  ny;
       
         printf("Enter principal amount : ");
         scanf("%f",&pamt);
         printf("Enter interest rate    : ");
         scanf("%f",&rate);
         printf("Enter number of years  : ");
         scanf("%d",&ny);
     
         interest =  pamt * rate * ny / 100;
         printf("Total Simple Interest = %f", interest );
    } 
    
  9. Take values for 'a' and 'b' and then display the result for a2 + b2
    #include <stdio.h>
    void main()
    {
        int a,b;
       
         printf("Enter value for a and  b : ");
         scanf("%d%d",&a,&b);
         printf(" Result of  =  %d " ,  a * a + b * b);
    }
    

5. Control Structures

  1. Accept a number and display whether it is an even number or odd number. Write two programs - one with normal if statement and another with conditional expression.
    #include <stdio.h>
    void main()
    {
        int n;
       
         printf("Enter a number  : ");
         scanf("%d",&n);
      
         if ( n % 2 == 0 )
             printf("%d is even number",n);
         else
             printf("%d is odd number",n);
    }                                   
    

    /* using conditional expression */
    #include <stdio.h>
    void main()
    {
        int n;
       
         printf("Enter a number  : ");
         scanf("%d",&n);
      
         printf("%d is %s ", n, n % 2 == 0 ? "Even" : "Odd");
    }
    
    
  2. Accept marks in subject and subject code (1 to 4) and display whether student passed or failed.
    Pass mark is based on subject code as follows. 1 - 40, 2 - 50 , 3 - 45 , 4 - 55.
    #include <stdio.h>
    void main()
    {
        int marks,pm,subject;
       
         printf("Enter subject code [1-4]: ");
         scanf("%d",&subject);
    
         printf("Enter marks : ");
         scanf("%d",&marks);
      
         switch(subject)
         {
           case 1: pm = 40; break;
           case 2: pm = 50; break;
           case 3: pm = 45; break;
           case 4: pm = 55; break;
         }
    
         if (marks >= pm)
            printf(" Passed");
         else
            printf(" Failed");
    }
    
    
  3. Accept two numbers and display the relationship between these two numbers. The output should display one of the messages: "Both numbers are equal", "First number is bigger" or "Second number is bigger".
    #include <stdio.h>
    void main()
    {
        int n1,n2;
       
         printf("Enter two numbers : ");
         scanf("%d%d",&n1,&n2);
    
         if (n1 == n2)
             printf("Both the numbers are equal");
         else
           if (n1 > n2)
             printf("First number is bigger");
           else
             printf("Second number is bigger");
    } 
    
  4. Accept three numbers from user and display the biggest of three numbers.
    #include <stdio.h>
    void main()
    {
        int n1,n2,n3,big;
       
         printf("Enter three numbers : ");
         scanf("%d%d%d",&n1,&n2,&n3);
    
         big = n1 > n2 ? n1 : n2;
         big = n3 > big ? n3: big;
    
         printf(" The biggest of %d %d %d is %d ", n1,n2,n3,big);
    }
    
    

6. Looping Structures

  1. do..while
  2. break
  3. initialization, condition and updation
  4. Display numbers from 100 to 1.
    #include <stdio.h>
    void main()
    {
      int i;
    
         for (i = 100 ; i > 0 ; i--)
            printf("%d\n", i);
    }
    
  5. Accept a number and display sum of numbers from 1 to that number.
    #include <stdio.h>
    void main()
    {
      int i,n,sum=0;
    
         printf("Enter a number: ");
         scanf("%d", &n);
    
         for (i = 1 ; i <= n ; i ++)
             sum += i;
    
         printf("Sum of 1 to %d = %d ", n,sum);
    }
    
  6. Display all even numbers in the range 100 to 200.
    #include <stdio.h>
    void main()
    {
      int i;
    
         for (i = 100 ; i <= 200 ; i += 2)
           printf("%d\n",i);
    }
    
  7. Take numbers from user until user enters 0 and display sum and average of accepted numbers.
    #include <stdio.h>
    void main()
    {
      int i=0,n;
      float sum=0;
    
     
         while (1)  /* always true loop */
         {
           printf("Enter a number [0 to stop] : ");
           scanf("%d", &n);
    
           if (n == 0)
               break;    /* terminate loop */
    
           sum += n;
           i++;  
         }
         printf("Sum = %f Average = %f ",sum, sum / i);      
    }
    
  8. Take 10 numbers and display the biggest and smallest of the given numbers.
    #include <stdio.h>
    void main()
    {
      int i,n,big,small;
    
         big = -32768;   /* set big to smallest possible number */
         small = 32767;  /* set small to biggest possible number */
        
         for (i=1; i <= 10 ; i++)
         {
             printf("Enter a number : ");
             scanf("%d", &n);
    
             if(n > big )
                 big = n;
    
             if ( n < small )
                  small = n;
         }
         printf(" The smallest = %d  and biggest = %d ", small, big);
    }
    
  9. Display table for 7 up to 20.
    Sample output:
    7 * 1 = 7
    7 * 2 = 14
    ...
    7 * 20  = 140
    
    #include <stdio.h>
    void main()
    {
      int i;
    
       for ( i = 1; i <= 20 ; i++)
         printf("7 * %2d  = %4d\n", i, 7 * i); 
    
    }
    
  10. Display numbers in the following format.
    1  2  3  4  5
    1  2  3  4  5  
    1  2  3  4  5 
    1  2  3  4  5
    1  2  3  4  5
    
    #include <stdio.h>
    void main()
    {
      int i,j;
    
       for(i=1; i <= 5 ; i++) 
       {
          printf("\n");
          for (j = 1 ; j <= 5 ; j ++)
            printf("%5d", j);
       }
    }
    

7. Character Handling

  1. 50
  2. iscntrl()
  3. Standard input device
  4. Echo
  5. The character will be read from the file on the disk.
  6. printf(). For example: printf("%d", 'A');
  7. Accept 10 characters and display number of uppercase letter, lowercase letters and digits.
    #include <ctype.h>
    #include <stdio.h>
    
    void main()
    {
      char ch;
      int  i,nu,nd,nl;
    
        nu = nd = nl = 0;
        for (i = 1 ; i <= 10 ; i ++)
        {
             ch = getchar();
             if (isupper(ch))
                  nu ++;
             else
               if (islower(ch))
                    nl ++;
               else
                if (isdigit(ch))
                      nd ++;
        }
        printf("Upper = %d, Lower = %d, Digits = %d",nu,nl,nd);
    }
  8. Accept a character and convert that character to uppercase if it is in lowercase or convert it to lowercase if it is in uppercase.
    #include <ctype.h>
    #include <stdio.h>
    void main()
    {
      char ch;
        
         printf("Enter a character : ");   
         ch = getchar();
    
         if (isupper(ch))
              putchar( tolower(ch));
         else
            if (islower(ch))
              putchar(toupper(ch));
    }
  9. Accept characters till the user inputs '*' and convert characters to lowercase.
    #include <ctype.h>
    #include <stdio.h>
    void main()
    {
      char ch;
       
        printf("Enter characters : ");   
        while (1)
        {
          ch = getch();
          if (ch == '*')
               break;
          putch(tolower(ch));
        }
    }    
    

8. Arrays

  1. Accept 20 numbers into array and display the sum and average along with numbers.
    #include <stdio.h>
    void main()
    {
       int ar[20]; 
       int i, sum = 0;
    
          for(i = 0 ; i < 20 ; i++)
          {
             printf("Enter number for [%d] element : ",i);
             scanf("%d", &ar[i]);
             sum += ar[i];
          }
    
          printf("Entered Numbers \n");
          for (i = 0 ; i < 20 ; i++)
          {
             printf("%d\n", ar[i]);
          }    
          printf("Sum = %d  Average = %d ", sum, sum  / 20);
    }
    
  2. Take an array of 10 integers and accept values into it. Sort the array in descending order.
    #include <stdio.h>
    void main()
    {
       int ar[10]; 
       int i, j, temp;
    
          for (i = 0 ; i < 10 ; i++)
          {
             printf("Enter number for [%d] element : ",i);
             scanf("%d", &ar[i]);
          }
    
          /* sort array in descending order */
          for ( i = 0 ; i < 9 ; i++)
          {
               for ( j = i+1; j < 10 ; j ++)
               {
                 if ( ar[i] < ar[j])
                 {
                    /* interchange */
                    temp  =  ar[j];
                    ar[j] = ar[i];
                    ar[i] = temp;
                 }
               } /* end of  j loop */
          } /* end of i loop */
    
          /* display sorted array */
          printf("Entered Numbers \n");
          for (i = 0 ; i < 10 ; i++)
          {
             printf("%d\n", ar[i]);
          }    
    }    
    
  3. Accept 20 numbers into an array and display how many numbers are below the average of the array.
    #include <stdio.h>
    void main()
    {
       int ar[20]; 
       int i,avg,sum=0,count = 0;
    
          for (i = 0 ; i < 20 ; i++)
          {
             printf("Enter number for [%d] element : ",i);
             scanf("%d", &ar[i]);
             sum += ar[i];
          }
          avg =  sum / 10;
    
          /* Count values that are below average of the array */
          for (i = 0 ; i < 20 ; i++)
          {
               if (ar[i]  <  avg ) 
                      count ++;                  
          }
          printf("\nNo. of values below average : %d",count);
    }
    
  4. Create an array of 10 elements and fill 9 elements of the array. Accept a number and position and insert the number at the given position in the array.
    #include <stdio.h>
    void main()
    {
       int ar[10]; 
       int i,num, pos;
    
          for (i = 0 ; i < 9 ; i++)
          {
             printf("Enter number for [%d] element : ",i);
             scanf("%d", &ar[i]);
          }
    
          /* take number and position */
          printf("Enter position and number : " );
          scanf("%d%d", &pos, &num);
      
          /* push all numbers from position to right */
          for (i = 9 ; i > pos ; i-- )
                 ar[i] = ar [i - 1];
    
          /* insert new value at position */
          ar[pos] = num;
                  
          /* Display array after insertion */
          for(i = 0 ; i < 10 ; i++)
          {
              printf("%d \n", ar[i]);
          }
     }    
    
  5. Create an array of 10 elements and fill it. Interchange first 5 elements with last 5 elements.
    #include <stdio.h>
    void main()
    {
       int ar[10]; 
       int i,temp;
    
          for(i = 0 ; i < 10 ; i++)
          {
             printf("Enter number for [%d] element : ",i);
             scanf("%d", &ar[i]);
          }
    
          /* interchange first 5 elements with last 5 elements */
          for(i = 0 ; i < 5 ; i++)
          {
             temp = ar [i];
             ar[i] = ar [9-i];
             ar[9-i] = temp;
          }
    
          /* Display array after interchange */
          for (i = 0 ; i < 10 ; i++)
          {
               printf("%d \n", ar[i]);
          }
     }
    

9. Multidimensional Array

  1. Take an array of 5 * 5 ( 5 rows and 5 columns ) and accept values into it. Display the array in the form of a matrix.
    #include <stdio.h>
    void main()
    {
       int ar[5][5]; 
       int i,j;
    
          for (i = 0 ; i < 5 ; i++)
          {
            for( j = 0 ; j < 5 ; j ++)
            {
               printf("Enter number for [%d][%d] element : ",i,j);
               scanf("%d", &ar[i][j]);
            }
          }
    
          /* display array as a matrix */
          for (i = 0 ; i < 5 ; i++)
          {
            /* move to next line before each row */
            printf("\n");
    
            for( j = 0 ; j < 5 ; j ++)
            {
               printf("%5d",ar[i][j]);
            }
          }
     }    
    
  2. Take an array of 4 * 4. Place 1 in diagonal cells and 0 in remaining and display the array in matrix format.
    #include <stdio.h>
    void main()
    {
       int ar[4][4]; 
       int i,j;
    
          for (i = 0 ; i < 4 ; i++)
          {
            for( j = 0 ; j < 4 ; j ++)
            {
              if ( i == j )
                  ar[i][j] = 1;
              else
                  ar[i][j] = 0;
            }
          }
    
          /* display array as a matrix */
          for (i = 0 ; i < 4 ; i++)
          {
            /* move to next line before each row */
            printf("\n");
            for( j = 0 ; j < 4 ; j ++)
            {
               printf("%5d",ar[i][j]);
            }
          }
     }    
    
  3. Accept numbers into an array of 5 * 5. Accept a number. Display all the elements of the array that are greater than the accepted number.
    #include <stdio.h>
    void main()
    {
       int ar[5][5]; 
       int i,j,num;
    
          for (i = 0 ; i < 5 ; i++)
          {
            for( j = 0 ; j < 5 ; j ++)
            {
               printf("Enter number for [%d][%d] element : ",i,j);
               scanf("%d", &ar[i][j]);
            }
          }
    
          printf("Enter a number : ");
          scanf("%d", &num);
    
          /* display all elements that are greater than the  given number  */
          for (i = 0 ; i < 5 ; i++)
          {
            for( j = 0 ; j < 5 ; j ++)
            {
               if ( ar[i][j] > num )
                     printf("%d \n",ar[i][j]);
            }
         }
    }
    
  4. Store random numbers into an array of 6 * 6 and interchange first 3 rows with last three rows.
    #include <stdlib.h>
    void main()
    {
       int ar[6][6]; 
       int i,j,temp;
    
          srand(time(0)); // Initialize seed                             
          for (i = 0 ; i < 6 ; i++)
          {
            /* move to next line before each row */
            printf("\n");
    
            for(j = 0 ; j < 6 ; j ++)
            { 
               ar[i][j] = rand() % 100;
               printf("%5d",ar[i][j]);
            }
          }
    
          /* interchange */
          for (i = 0 ; i < 3 ; i++)
          {
            for(j = 0 ; j < 6 ; j ++)
            {
               temp = ar[i][j];
               ar[i][j] =  ar[5-i][j];
               ar[5-i][j] = temp;
            }
          }    
          
          printf("\n\n");
          for (i = 0 ; i < 6 ; i++)
          {
            /* move to next line before each row */
            printf("\n");
            for( j = 0 ; j < 6 ; j ++)
            {
               printf("%5d",ar[i][j]);
            }
          } /* end of i loop */
     } /* end of main */
        
    

10. String Handling

  1. stricmp()
  2. 2 bytes one for A and other one for null character.
  3. Because scanf() takes whitespace character as end of input for a field.
  4. Return value will be greater than 0 as first string is bigger than second string.
  5. printf("%s",name) will display the value of name and puts(name) will display name followed by new line.
  6. Accept a string and display each character in the string in opposite case.
    #include <stdio.h>
    void main()
    {
       char st[20];
       int i;
    
         /* accept a string */
         printf("Enter a string : ");
         gets(st);
    
         /* display it in opposite case */
         for ( i = 0 ; st[i] != '\0';  i++)
    	  if (islower(st[i]))
    	       putch(toupper(st[i]));
    	  else
     	       putch(tolower(st[i]));
    }
    
    
  7. Accept a string and display only uppercase letters in the string.
    #include <stdio.h>
    void main()
    {
       char st[20];
       int i;
    
         /* accept a string */
         printf("Enter a string : ");
         gets(st);
    
         for ( i = 0 ; st[i] != '\0';  i++) 
            if (isupper(st[i]))
                  putch(st[i]);
    }    
    
  8. Accept a string and a character.  Display how many times that character occurs in string.
    #include <stdio.h>
    void main()
    {
       char st[20];
       int i, count = 0;
       char ch;
    
         /* accept a string */
         printf("Enter a string : ");
         gets(st);
    
         /* accept character */
         printf("Enter a character : ");
         ch = getchar();
    
         /* count */
         for ( i = 0 ; st[i] != '\0';  i++)
    	  if ( st[i] == ch)
                  count ++;
    
         printf("Count  : %d", count);
    }    
    
  9. Take a sentence and display the number of words in it. You can assume that words are separated by only one space. Try to do this without this assumption also.
    #include <stdio.h>
    void main()
    {
       char st[100];
       int i,count =0;
    
         /* accept a string */
         printf("Enter a string : ");
         gets(st);
    
         /* count words  */
         for ( i = 0 ; st[i] != '\0';  i++)
    	  if (st[i] == ' ' )
    		   count ++;
    
         printf(" No. of words :  %d", count + 1);
    }
    
    Count no. of words without assuming there is only one space between words.

    #include <stdio.h>
    void main()
    {
       char st[100];
       int ch, i, inword = 0, wordcount = 0;
         
         printf("Enter string :");
         gets(st);
    
         for(i=0; st[i] != '\0'; i++)
         {
           if(st[i] != 32) // Non-space
           {
              if(!inword) // if it is first char in word then count it a word
              {
                  wordcount++;
                  inword = 1;
              }
           }
           else
           {
              inword = 0;
           }
        }
        printf("No. of words = %d",wordcount);  
    }
    
  10. Take a string, source character and target character. Replace every occurrence of source character with target character.
    #include <stdio.h>
    void main()
    {
       char st[20];
       int i;
       char sch,tch;
    
         /* accept a string */
         printf("Enter a string : ");
         gets(st);
    
         /* accept source and target characters */
         printf("\nEnter source character : ");
         sch = getche();
    
         printf("\nEnter target character : ");
         tch = getche();
                                        
         /* replace source with target */
         for (i = 0 ; st[i] != '\0';  i++)
    	  if (st[i] == sch)
    		  st[i] = tch;
    
         printf("\nString after conversion : %s", st);
    }    
    
  11. Accept 10 strings and display the biggest of 10 strings.
    #include <stdio.h>
    void main()
    {
       char  st[10][20];
       int i, hpos=0;
    
          /* take strings */
          for (i = 0 ; i < 10 ; i ++)
          {
    	   printf("Enter a string :");
    	   gets( st[i]);
    
    	   if(strcmp(st[i],st[hpos]) > 0 )
    	         hpos = i;
          }
          printf("%s is the biggest string",  st[hpos]);
    }
    
    

11. User-defined Functions

  1. only one
  2. return
  3. int
  4. Function declaration is optional
  5. Function declaration should be given first and then function definition.
  6. Recursion
  7. User-defined function can have any name whereas main is predefined name. Function main() is the first function to be automatically called whereas user-defined function is to be explicitly called.
  8. Write a function that takes a number as parameter and returns the next odd number.
    int  nextodd(int num)
    {
       if (num % 2 == 0)
           return  num + 1;
       else
           return  num + 2;
    }
    
    
  9. Write a function to take a string as parameter and display only non-blank characters of the given string.
     void nonblank(char st[100])
    {
      int i;
    
          for (i = 0 ; st[i] != '\0'; i ++)
               if (st[i] != 32)
                      putch(st[i]);
    }
    
    
  10. Write a function to take a number and return 1 if it is a prime number, otherwise 0.
    int  isprime(int num)
    {
       int i;
    
          for (i = 2; i <= num/2 ; i ++)
             if (num % i == 0 )         /* not a prime number */
                 return 0;
    
          /* if control comes here, it means prime number */
          return 1;
    } 
    
  11. Write a function to take a string and return the number of digits the string contains.
    int  nodigits(char st[100])
    {
      int count = 0, i;
    
          for (i = 0 ; st[i] != '\0'; i ++)
               if (isdigit (st[i]) )
                        count ++;
    
          return count;
    }
    
    
  12. Write a function to take a number and return factorial of the given number. Use recursion.
    #include <stdio.h>
    void main()
    {
        printf("Fact : %d ", fact(4));
    }
    
    int fact(int n)
    {
       if ( n > 1 )
           return (n * fact( n-1));
       else
           return 1;
    }
    
    

12. Storage Classes

  1. static
  2. scope
  3. extern
  4. static
  5. By declaring another variable in a block with the same name as the one to be hidden.
    fun()
    {
      int i;
       
         if (   )
         {
           int i;  /* outer i is hidden here */
    
         }
    }
    
    
  6. Yes

13. Pointers

  1. &
  2. *
  3. Generally 4 bytes. But it depends on system.
  4. A pointer
  5. Declare two int variables, take values into them and display the values and addresses of those variables.
    #include <stdio.h>                                        
    void main()
    {
      int n1,n2;
    
        printf("Enter two values : ");
        scanf("%d%d", &n1,&n2);
    
        printf("Values %d %d ", n1,n2);
        printf("\nAddresses %p %p", &n1,&n2);
    }
    
  6. Write a function that takes 2 numbers and sets both of them to the smallest of two. Use pass by reference.
    void settosmall(int * n1, int * n2)
    {
        if (*n1 < *n2)
             *n2 = *n1;
        else
             *n1 = *n2;
    }
    
    
  7. Write a function to take three numbers and return minimum and maximum values. Use pass by reference.
    #include <stdio.h> 
    void smallbig(int n1,int n2, int n3,int * big, int * small)
    {
    
        /* get biggest */
        *big = n2 > n1 ? n2 : n1;
        *big = n3 > *big ? n3 : *big;
    
        /* get samllest */
        *samll = n2 < n1 ? n2 : n1;
        *samll = n3 <  *samll ? n3 : *small;
    }
    
    void main()
    {
     int n1, n2, n3, small, big;
     
         smallbig(n1,n2,n3, &big, &small);
    } 
    
  8. Write a function to take an array and return smallest and largest values of the array. Use pass by reference.
    void smallbig(int * ar,int * big, int * small)
    {
     int i;
    
       *big = *small = ar[0];
    
       for( i = 1 ; i < 10 ; i ++)
       {
            if ( ar[i] > *big )
                 *big = ar[i];
               
            if ( ar[i]  < *small)
                 *small = ar[i];
       }                                                          
    }
    
    
  9. Write a function to take an array of 10 integers and set all of them to 0. Use pass by reference
    void settozeroes(int * ar)
    {
     int i;
    
       for(i = 0; i < 10 ; i ++)
       {
          ar[i] = 0;
       }
    }
    
    

14. Pointer vs. Array

  1. Write a function that takes an array and number of elements as parameters and sorts the array in the ascending order.
    #include <stdio.h> 
    void sortarray( int * ar, int nel)
    {
     int i,j,temp;
    
          /* sort array in descending order */
          for (i = 0 ; i < nel - 1 ; i++)
          {
               for (j = i+1; j < nel ; j ++)
               {
                 if ( ar[j] > ar[i])
                 {
                    /* interchange */
                    temp  = ar[j];
                    ar[j] = ar[i];
                    ar[i] = temp;
                 }
               } /* end of  j loop */
         } /* end of i loop */
    }
    
    void main()
    {
       int ar[10]; 
       int i, j, temp;
    
          for (i = 0 ; i < 10 ; i++)
          {
             printf("Enter number for [%d] element : ",i);
             scanf("%d", &ar[i]);
          }
          sortarray(ar,10);
    
          /* display sorted array */
          for ( i = 0 ; i < 10 ; i++)
          {
             printf("%d\n", ar[i]);
          }    
    }
    
  2. Take month number from user and display the name of the month. Use an array of strings, which contains the names of all months.
    #include <stdio.h> 
    void main()
    {
       int mn;
    
       char * months[] = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October",  "November", "December"};
    
       printf("Enter month number :");
       scanf("%d",&mn);
       printf(" Month name : %s", months[ mn - 1]);
    }
    
    
  3. Write a function that takes an array of 10 integers and a search number, and returns the address in the array where search number is found. If number is not found then it should return NULL.
    #include <stdio.h>
    int * search(int a[10], int sn)
    {
     int i;
     
          for (i = 0 ; i < 10 ; i++)
          {
              if(a[i] == sn)
                  return  &a[i];                                        
          } 
          return NULL;                                              
    }
    
    void main()
    {
       int ar[10],*p;
      
         // fill array
         p = search(ar,10); // look for 10
         if(p == NULL)
             printf("Not Found");
         else
             printf("Found at %d", p - ar); // Pointer Arithmetic                                            
    }
    

15. Structures

  1. Take details of 10 students ( student number, name, total marks) and display details in ascending order of total marks.
    #include <stdio.h>
    
    struct student
    {
       int no; 
       char name[30];
       int tm;
    };
    
    void main()
    {
      struct student  s[10], temp;
      int i,j;
      
         for ( i = 0 ; i < 10 ; i ++)
         {
            printf("Enter student number : ");
            scanf("%d", & s[i].no);
    
            fflush(stdin);
    
            printf("Enter student name   : ");
            gets( s[i].name);
    
            printf("Enter total marks    : ");
            scanf("%d",& s[i].tm);
        }
    
        /* sort the array */
    
        for ( i = 0 ; i < 9 ; i ++)
          for ( j = i + 1 ; j < 10 ; j ++)
               if ( s[i].tm > s[j].tm)
               {
                temp = s[i];
    	        s[i] = s[j];
    	        s[j] = temp;
               }
    
         /* display sorted details */
         for ( i = 0 ; i < 10 ; i ++)
         {
           printf("\n %5d %-20s %5d", s[i].no, s[i].name, s[i].tm);
         }
    } /* end of main*/
    
    
  2. Write a program to take 10 times ( HH:MM:SS) and display the smallest time. Allow user to enter time in HH:MM:SS format. Hint: Use %d:%d:%d with scanf().
    #include <stdio.h> 
    struct time
    {
        int h,m,s;
    };
    
    /* returns > 0 if t1 > t2
       < 0  if t1 < t2
       0  if t1 == t2 
    */
    int compare(struct time t1, struct time t2)
    {
        return   (t1.h * 60 * 60 + t1.m * 60 + t1.s) - (t2.h * 60 * 60 + t2.m * 60 + t2.s);
    
    }
    
    void main()
    {
      struct time t[10], st;
      int i;
    
    
         /* accept 10 times */
    
         for ( i = 0 ; i < 10 ; i ++)
         {
            printf("Enter time in hh:mm:ss format :");
            scanf("%d:%d:%d", & t[i].h, &t[i].m, &t[i].s);
         }
    
         /* get the smallest time */
    
         st = t[0];
    
         for ( i = 1;  i < 10 ; i ++)
         {
               if ( compare( t[i], st ) < 0 )  /* if time is less than smallest time */
                     st = t [i];
         }
    
         printf("Smallest Time : %d:%d:%d", st.h, st.m, st.s);
    }     
    
  3. Write a function to take a parameter of struct time and return the next second of the given time. Return value is also a struct time.
    struct time
    {
      int h,m,s;
    };
    
    struct time  nextsecond(struct time t)
    {
        t.s ++; /* increment seconds */
    
        if ( t.s > 59 )
        {
            t.s = 0;
            t.m ++;
        
            if ( t.m > 59 )
            {
               t.m = 0;
               t.h ++;
                
               if ( t.h > 23 )
                     t.h = 0;
            }  
        }
    
        return t;
    }
    
    
  4. (*p).x is to treat p as a pointer and then access structure pointed by p. Then it will access member x of that structure.
    *p.x is to take member x of structure variable p first, as .(member operator) has higher precedence over *, and then treat that member (x) as a pointer.
  5. In Structure declaration only members of the structure are declared. No space is allocated to member.
    In Structure variable declaration, we declare a variable of the structure and that variable is allocated memory.

16. Union, typedef and enumeration

  1. All members in a structure are allocated memory whereas only the largest member of a union is allocated memory.
  2. The value is assigned to the item instead of the default value. If nothing is specified enum starts assigning from zero onwards.
  3. typedef char * STRING;

17. Pre-processor commands

  1. In case of angle brakets (<>) C searches for the file only in standard include directory. In case of double quotes C searches for header file in the current directory first and if it is not found then searches for the file in the standard include directory.
  2. A macro will improve performance because it will not have the overheads of calling a function.
  3. Create a macro called odd to take a number and return 1 if it is odd and 0 if even.
    #define  odd(n)  n % 2 == 1
    
  4. Create a macro that takes a number as parameter and returns next even number after the parameter.
    #define nexteven(n)  n % 2 == 0 ? n + 2 : n + 1 

18. File handling

  1. fgets()
  2. NULL pointer
  3. r+
  4. char *
  5. stdio.h
  6. Accept a filename and display only uppercase characters of the file.
    #include <stdio.h>
    #include <ctype.h>
    
    void main()
    {
       char fn[30];
       int ch;
       FILE * fp;
    
         printf("Enter filename :");
         gets(fn);
    
         fp = fopen(fn,"r");
    
         if ( fp == NULL)
         {
             printf("File not found.");
             exit(1);
         }
    
         while (1)
         {
           ch = fgetc(fp);
           if(ch == EOF)
                break;
           if ( isupper(ch))
                 putchar(ch);
         }
    
         fclose(fp);
    } /* end of main */
        
    
  7. Accept source filename and target filename and copy the contents of source file to target file.
    #include <stdio.h>
    void main()
    {
       char sfn[30],tfn[30];
       int ch;
       FILE * sfp, * tfp;
    
         printf("Enter source filename :");
         gets(sfn);
    
         printf("Enter target filename :");
         gets(tfn);
    
         sfp = fopen(sfn,"r");
    
         if (sfp == NULL)
         {
             printf("Source file not found.");
             exit(1);
         }
    
         tfp = fopen(tfn,"w");
    
         if (tfp == NULL)
         {
             printf("Target file not found.");
             exit(1);
         }
    
         while (1)
         {
           ch = fgetc(sfp);
           if(ch == EOF)
                break;
           fputc(ch, tfp);
         }
    
         fclose(sfp);
         fclose(tfp);
    
    } /* end of main */    
    
  8. Accept filename and display the number of lines.
    #include <stdio.h>
    void main()
    {
       char fn[30];
       int ch;
       FILE * fp;
       int  lines=0;
    
         printf("Enter filename :");
         gets(fn);
    
         fp = fopen(fn,"r");
    
         if ( fp == NULL)
         {
             printf("File not found.");
             exit(1);
         }
    
         while (1)
         {
           ch = fgetc(fp);
           if(ch == EOF)
              break;
           if (ch == '\n')
                  lines ++;
         }
    
         fclose(fp);
         printf("No. of lines : %d", lines);
    } /* end of main */
        
    
  9. Accept lines from keyboard till END is given and write all lines into file called LINES.TXT.
    #include <stdio.h>
    void main()
    {
       char line[100];
       FILE * fp;
    
    
         fp = fopen("lines.txt","w");
         if ( fp == NULL)
         {
             printf("LINES.TXT could not be created.");
             exit(1);
         }
         while (1)
         {
           printf("Enter a line and END to stop :");
           gets(line);
           if ( strcmp(line,"END") == 0 )
                  break;
           fputs(line,fp);
         }
    
         fclose(fp);  /* close the file */
    } /* end of main */    
    
  10. Accept a file and display its content by displaying one space where multiple spaces are present in the file.
    #include <stdio.h>
    #include <ctype.h>
    
    void main()
    {
       char fn[30];
       int ch, inspace = 0;
       FILE * fp;
    
         printf("Enter filename :");
         gets(fn);
    
         fp = fopen(fn,"r");
    
         if (fp == NULL)
         {
             printf("File not found.");
             exit(1);
         }
    
         while (1)
         {
           ch = fgetc(fp);
           if(ch == EOF)
                break;
    
           if(ch == 32) //space
           {
              if(!inspace) // if it is first space then print otherwise ignore
              {
                 inspace = 1;
                 putch(ch);
              }
           }
           else
           {
             inspace = 0;
             putch(ch);
           }
         }
    
         fclose(fp);
    } /* end of main */                                     

19. Binary files and random access

  1. Accept details of a collection of students and write details into STUDENT.DAT.
     #include <stdio.h>
    
    struct student
    {
        int sno;
        char name[30];
        int  tf, fp;
    };
    
    void main()
    {
       struct student s;
       FILE * fp;
    
          fp = fopen("student.dat","wb");  /* open in write and binary mode */
          while(1)
          {
             fflush(stdin);
             printf("Enter student number [0 to stop]: ");
             scanf("%d", & s.sno);
    
             if ( s.sno == 0 )  
    	     	break;
    
             fflush(stdin);
    
             printf("Enter student name : ");
             gets(s.name);
    
             printf("Enter total fee    : ");
             scanf("%d", & s.tf); 
    
             printf("Enter fee paid     : ");
             scanf("%d", & s.fp);
    
             /* write record to file */
    
             fwrite(&s,sizeof(s),1,fp);
          }
          fclose(fp);
    }     
    
  2. Display the details of all students who have not paid complete amount by using the data in STUDENT.DAT.
    #include <stdio.h>
    struct student
    {
        int sno;
        char name[30];
        int  tf, fp;
    };
    
    void main()
    {
       struct student s;
       FILE * fp;
       int count;
    
          fp = fopen("student.dat","rb");  /* open in read and binary mode */
    
          /* read record */
          count = fread(&s,sizeof(s),1,fp);
    
          while( count != 0 )
          {
             if (s.tf > s.fp )
             printf("%d\t%s\t%d\t%d\n", s.sno, s.name, s.tf, s.fp);
             count = fread(&s,sizeof(s),1,fp);
          }
          fclose(fp);
    }
     
    
  3. Accept record number and display that record from STUDENT.DAT.
    #include <stdio.h>
    struct student
    {
        int sno;
        char name[30];
        int  tf, fp;
    };
    
    void main()
    {
       struct student s;
       FILE * fp;
       int recno;
    
          fp = fopen("student.dat","rb");  /* open in read and binary mode */
    
          /* read record number */
          printf("Enter record number. Record number starts with 0 : ");
          scanf("%d",&recno);
    
          /* move to the record with the given record number */
          fseek(fp,  sizeof(s) * recno , 0); 
    
          /* read the record */
          fread(&s,sizeof(s),1,fp);
    
          printf("%d %s %d %d", s.sno, s.name, s.tf, s.fp);
    
          fclose(fp);
    }     
    
  4. Accept record number, amount paid and increment fp (fee paid) in that record by amount paid. Hint: Open file in r+ (read and write) mode. Read record, change the data in memory, and write record back to file. But make sure you move record pointer back before you write modified record.
    #include <stdio.h>
    struct student
    {
        int sno;
        char name[30];
        int  tf, fp;
    };
    
    void main()
    {
       struct student s;
       FILE * fp;
       int recno, amt;
    
          fp = fopen("student.dat","r+b");  /* open in update and binary mode */
    
          /* read record number */
          printf("Enter record number. Record number starts with 0 : ");
          scanf("%d",&recno);
    
          printf("Enter Amount paid : ");
          scanf("%d",&amt);
    
          /* move to the record with the given record number */
          fseek ( fp,  sizeof(s) * recno , 0); 
    
          /* read the record */
          fread(&s,sizeof(s),1,fp);
    
          /* update structure in memory */
          s.fp += amt;
    
          /* move back to the previous record */
          fseek (fp,  sizeof(s) * -1l, 1); 
    
          /* write new record back to file */
          fwrite(&s,sizeof(s),1,fp);
    
          printf("Updation is complete");
    
          fclose(fp);
    }     
    

20. Command line arguments

  1. Take source file and target file on command line and place source file contents into target file after converting contents to lowercase.
    #include <stdio.h>
    void main(int argc, char * argv[] )
    {
       int ch;
       FILE * sfp, * tfp;
    
         if (argc < 3 )
         {
           /* display syntax of the program. Assuming file name is LOWER.C */
           printf("LOWER  source target"); 
           exit(1);
         }
    
         sfp = fopen(argv[1],"r");
         if ( sfp == NULL)
         {
             printf("Source file not found.");
             exit(2);
         }
    
         tfp = fopen(argv[2],"w");
         if ( tfp == NULL)
         {
             printf("Target file not found.");
             exit(3);
         }
    
         while (1)
         {
           ch = fgetc(sfp);
           if(ch == EOF)
               break;
           fputc( tolower(ch), tfp);
         }
    
         fclose(sfp);
         fclose(tfp);
    } 
    
    
  2. Take filename and a string on the command line and display all lines of the file that contain the given string along with line numbers.
    #include <stdio.h>
    void main()
    {
       FILE * fp;
       char line[100], word[30] , fn[30], *cp;
       int ln=1;
    
         /* take input from user */
         printf("Enter filename : ");
         gets(fn);
    
         printf("Enter string to search for : ");
         gets(word);
    
         /* open file */
         fp = fopen(fn,"r");
         ln = 1;
         while(1)
         {
    	  cp = fgets(line,100,fp);
              if (cp == NULL)
                  break;
    	  if (strstr(line,word) != NULL )
    	      printf("%4d:%s", ln, line);
    
    	  ln++;
         }
         fclose(fp);
    }
    
    
  3. Take a target file and source file(s) and place the contents of all source file(s) in target file.
    Example: c:\cprog>concat t.txt a.txt b.txt
    Places contents of a.txt and b.txt one after another into t.txt.
    #include <stdio.h>
    void main(int argc, char * argv[] )
    {
       int ch;
       FILE * sfp, * tfp;
       int i;
    
         if ( argc < 3 )
         {
           /* display syntax of the program. Assuming file name is COPYALL.C */
           printf("COPYALL  target  source ..."); 
           exit(1);
         }
    
         /* open target file */
         tfp = fopen(argv[1],"w");
         if ( tfp == NULL)
         {
             printf("Target file open error.");
             exit(2);
         }
    
         for (i = 2; i < argc ;i ++)
         {
           /* open source file */
           sfp = fopen( argv[i], "r");
           if ( sfp == NULL)
           {
             printf("Error while opening file %s ", argv[i]);
             exit(3);
           }
    
           while (1)
           {
             ch = fgetc(sfp);
             if(ch == EOF)
               break;
    
             fputc( ch, tfp);
           }
    
           /* close current source file */
           fclose(sfp);
         } /* end of for loop */
       
         fclose(tfp);   /* close target file */
    }    
    

21. Dynamic memory allocation

  1. void *
  2. free()
  3. No. of blocks, Size of block
  4. Because the default return type is void *, which is a pointer that points to no specific data type.

22. Linked list

  1. Write a program to take the content of a file into a linked list and display the content in the reverse order. Hint: Create a list that works like a stack and not a queue.
    #include <stdio.h>
    /* create a structure for node */
    
    typedef struct node
    {
       char line[100];
       struct node  * prev;
    } NODE;
    
    void main()
    {
      NODE * root= NULL ,*current;
      char fn[10],line[100];
      FILE * fp;
    
         printf("Enter filename :");
         gets(fn);
    
         fp = fopen(fn,"r");
         while (!feof(fp))
         {
           fgets(line,100,fp);
           
           current  = (NODE *) malloc(sizeof(NODE));
    
           if (current == NULL)
           {
    	     printf("Memory allocation error. ");
    	     exit(1);
           }
    
           /* copy data into node */
           strcpy( current -> line, line);
           current -> prev = root;
           root = current;
        } /* end of while */
    
        fclose(fp);
    
        /* display the content of the file */
        current = root;
        while(current != NULL)
        {
           printf(current-> line);
           current = current -> prev;
        }  /* end of while */
    } /* end of main */
    
    
  2. Write a program to create a linked list to take all lines from the given file. While creating the list ensure the nodes in the list are in the ascending order. Then display the sorted list.
    /* take the content of the file and sort it */
    #include <alloc.h>
    #include <stdio.h>
    
    struct node
    {
       char line[100];
       struct node * next;
    } * root;
    
    struct node * findpos(char *);
    
    void main()
    {
     struct node * cur, * prev;
     char fn[30],line[100];
     FILE * fp;
    
          printf("Enter filename : ");
          gets(fn);
     
          fp = fopen(fn,"rt");
          if ( fp == NULL)
          {
              printf("File not found. ");
              exit(1);
          }
    
          /* add a dummy node at the beginning */
          cur = (struct node * ) malloc(sizeof(struct node ));
          cur -> next = NULL;
          cur->line[0] = '\0';  /* value is empty string */
    
          root = cur;
          while ( fgets(line,100,fp) != NULL )
          {
    	    cur = ( struct node  *) malloc( sizeof(struct node));
    	    strcpy( cur-> line, line);
      	    prev = findpos(line);
    	    cur-> next = prev-> next;
    	    prev -> next = cur;
         }
    
         fclose(fp);
    
         /* display the list */
         cur = root;
         while ( cur != NULL)
         {
    	  printf("%s", cur->line);
    	  cur = cur -> next;
         }
    }
    
    struct node * findpos( char * line)
    {
       struct node * cur, * prev;
    
           prev =  root;
           cur = root -> next;
           while ( cur != NULL )
           {
    	   if ( strcmp(cur-> line, line) > 0 )
    	       break;
    	   prev = cur;
    	   cur = cur -> next;
           }
           return prev;
    }
    
    
  3. Create a function called search that takes the root node and the name to search for. It must return the address of the node if the name is found in the list otherwise NULL pointer.
    #include <alloc.h>
    
    /* create a structure for node */
    typedef struct node
    {
       char line[100];
       struct node  * next;
    } NODE;
    
    NODE * search(NODE * root, char name[20])
    {
     NODE *  current;
    
       current = root;
       while ( current != NULL)
       {
          if (strcmp( current-> line, name) == 0)
    		  return current;
    
          current = current -> next;
       }
       return NULL; /* value not found */
    } /* end of function */